You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

342 lines
14 KiB

  1. -module(rebar_test_utils).
  2. -include_lib("common_test/include/ct.hrl").
  3. -include_lib("eunit/include/eunit.hrl").
  4. -export([init_rebar_state/1, init_rebar_state/2, run_and_check/4]).
  5. -export([expand_deps/2, flat_deps/1, flat_pkgdeps/1, top_level_deps/1]).
  6. -export([create_app/4, create_eunit_app/4, create_empty_app/4, create_config/2]).
  7. -export([create_random_name/1, create_random_vsn/0]).
  8. %%%%%%%%%%%%%%
  9. %%% Public %%%
  10. %%%%%%%%%%%%%%
  11. %% @doc {@see init_rebar_state/2}
  12. init_rebar_state(Config) -> init_rebar_state(Config, "apps_dir1_").
  13. %% @doc Takes a common test config and a name (string) and sets up
  14. %% a basic OTP app directory with a pre-configured rebar state to
  15. %% run tests with.
  16. init_rebar_state(Config, Name) ->
  17. application:load(rebar),
  18. DataDir = ?config(priv_dir, Config),
  19. AppsDir = filename:join([DataDir, create_random_name(Name)]),
  20. CheckoutsDir = filename:join([AppsDir, "_checkouts"]),
  21. ok = ec_file:mkdir_p(AppsDir),
  22. ok = ec_file:mkdir_p(CheckoutsDir),
  23. Verbosity = rebar3:log_level(),
  24. rebar_log:init(command_line, Verbosity),
  25. State = rebar_state:new([{base_dir, filename:join([AppsDir, "_build"])}
  26. ,{root_dir, AppsDir}]),
  27. [{apps, AppsDir}, {checkouts, CheckoutsDir}, {state, State} | Config].
  28. %% @doc Takes common test config, a rebar config ([] if empty), a command to
  29. %% run ("install_deps", "compile", etc.), and a list of expected applications
  30. %% and/or dependencies to be present, and verifies whether they are all in
  31. %% place.
  32. %%
  33. %% The expectation list takes elements of the form:
  34. %% - `{app, Name :: string()}': checks that the app is properly built.
  35. %% - `{dep, Name :: string()}': checks that the dependency has been fetched.
  36. %% Ignores the build status of the dependency.
  37. %% - `{dep, Name :: string(), Vsn :: string()}': checks that the dependency
  38. %% has been fetched, and that a given version has been chosen. Useful to
  39. %% test for conflict resolution. Also ignores the build status of the
  40. %% dependency.
  41. %%
  42. %% This function assumes `init_rebar_state/1-2' has run before, in order to
  43. %% fetch the `apps' and `state' values from the CT config.
  44. run_and_check(Config, RebarConfig, Command, Expect) ->
  45. %% Assumes init_rebar_state has run first
  46. AppDir = ?config(apps, Config),
  47. State = ?config(state, Config),
  48. try
  49. Res = rebar3:run(rebar_state:new(State, RebarConfig, AppDir), Command),
  50. case Expect of
  51. {error, Reason} ->
  52. ?assertEqual({error, Reason}, Res);
  53. {ok, Expected} ->
  54. {ok, _} = Res,
  55. check_results(AppDir, Expected);
  56. return ->
  57. Res
  58. end
  59. catch
  60. rebar_abort when Expect =:= rebar_abort -> rebar_abort
  61. end.
  62. %% @doc Creates a dummy application including:
  63. %% - src/<file>.erl
  64. %% - src/<file>.app.src
  65. %% And returns a `rebar_app_info' object.
  66. create_app(AppDir, Name, Vsn, Deps) ->
  67. write_src_file(AppDir, Name),
  68. write_app_src_file(AppDir, Name, Vsn, Deps),
  69. rebar_app_info:new(Name, Vsn, AppDir, Deps).
  70. %% @doc Creates a dummy application including:
  71. %% - src/<file>.erl
  72. %% - src/<file>.app.src
  73. %% - test/<file>_tests.erl
  74. %% And returns a `rebar_app_info' object.
  75. create_eunit_app(AppDir, Name, Vsn, Deps) ->
  76. write_eunitized_src_file(AppDir, Name),
  77. write_eunit_suite_file(AppDir, Name),
  78. write_app_src_file(AppDir, Name, Vsn, Deps),
  79. rebar_app_info:new(Name, Vsn, AppDir, Deps).
  80. %% @doc Creates a dummy application including:
  81. %% - ebin/<file>.app
  82. %% And returns a `rebar_app_info' object.
  83. create_empty_app(AppDir, Name, Vsn, Deps) ->
  84. write_app_file(AppDir, Name, Vsn, Deps),
  85. rebar_app_info:new(Name, Vsn, AppDir, Deps).
  86. %% @doc Creates a rebar.config file. The function accepts a list of terms,
  87. %% each of which will be dumped as a consult file. For example, the list
  88. %% `[a, b, c]' will return the consult file `a. b. c.'.
  89. create_config(AppDir, Contents) ->
  90. Conf = filename:join([AppDir, "rebar.config"]),
  91. ok = filelib:ensure_dir(Conf),
  92. Config = lists:flatten([io_lib:fwrite("~p.~n", [Term]) || Term <- Contents]),
  93. ok = ec_file:write(Conf, Config),
  94. Conf.
  95. %% @doc Util to create a random variation of a given name.
  96. create_random_name(Name) ->
  97. random:seed(erlang:now()),
  98. Name ++ erlang:integer_to_list(random:uniform(1000000)).
  99. %% @doc Util to create a random variation of a given version.
  100. create_random_vsn() ->
  101. random:seed(erlang:now()),
  102. lists:flatten([erlang:integer_to_list(random:uniform(100)),
  103. ".", erlang:integer_to_list(random:uniform(100)),
  104. ".", erlang:integer_to_list(random:uniform(100))]).
  105. expand_deps(_, []) -> [];
  106. expand_deps(git, [{Name, Deps} | Rest]) ->
  107. Dep = {Name, ".*", {git, "https://example.org/user/"++Name++".git", "master"}},
  108. [{Dep, expand_deps(git, Deps)} | expand_deps(git, Rest)];
  109. expand_deps(git, [{Name, Vsn, Deps} | Rest]) ->
  110. Dep = {Name, Vsn, {git, "https://example.org/user/"++Name++".git", {tag, Vsn}}},
  111. [{Dep, expand_deps(git, Deps)} | expand_deps(git, Rest)];
  112. expand_deps(pkg, [{Name, Deps} | Rest]) ->
  113. Dep = {pkg, Name, "0.0.0"},
  114. [{Dep, expand_deps(pkg, Deps)} | expand_deps(pkg, Rest)];
  115. expand_deps(pkg, [{Name, Vsn, Deps} | Rest]) ->
  116. Dep = {pkg, Name, Vsn},
  117. [{Dep, expand_deps(pkg, Deps)} | expand_deps(pkg, Rest)].
  118. flat_deps([]) -> [];
  119. flat_deps([{{Name,_Vsn,Ref}, Deps} | Rest]) ->
  120. [{{Name,vsn_from_ref(Ref)}, top_level_deps(Deps)}]
  121. ++
  122. flat_deps(Deps)
  123. ++
  124. flat_deps(Rest).
  125. flat_pkgdeps([]) -> [];
  126. flat_pkgdeps([{{pkg, Name, Vsn}, Deps} | Rest]) ->
  127. [{{iolist_to_binary(Name),iolist_to_binary(Vsn)}, top_level_deps(Deps)}]
  128. ++
  129. flat_pkgdeps(Deps)
  130. ++
  131. flat_pkgdeps(Rest).
  132. vsn_from_ref({git, _, {_, Vsn}}) -> Vsn;
  133. vsn_from_ref({git, _, Vsn}) -> Vsn.
  134. top_level_deps([]) -> [];
  135. top_level_deps([{{pkg, Name, Vsn}, _} | Deps]) ->
  136. [{list_to_atom(Name), Vsn} | top_level_deps(Deps)];
  137. top_level_deps([{{Name, Vsn, Ref}, _} | Deps]) ->
  138. [{list_to_atom(Name), Vsn, Ref} | top_level_deps(Deps)].
  139. %%%%%%%%%%%%%%%
  140. %%% Helpers %%%
  141. %%%%%%%%%%%%%%%
  142. check_results(AppDir, Expected) ->
  143. BuildDirs = filelib:wildcard(filename:join([AppDir, "_build", "*", "lib"])),
  144. PluginDirs = filelib:wildcard(filename:join([AppDir, "_build", "*", "plugins"])),
  145. CheckoutsDir = filename:join([AppDir, "_checkouts"]),
  146. LockFile = filename:join([AppDir, "rebar.lock"]),
  147. Locks = lists:flatten(rebar_config:consult_file(LockFile)),
  148. InvalidApps = rebar_app_discover:find_apps(BuildDirs, invalid),
  149. ValidApps = rebar_app_discover:find_apps(BuildDirs, valid),
  150. InvalidDepsNames = [{ec_cnv:to_list(rebar_app_info:name(App)), App} || App <- InvalidApps],
  151. ValidDepsNames = [{ec_cnv:to_list(rebar_app_info:name(App)), App} || App <- ValidApps],
  152. Deps = rebar_app_discover:find_apps(BuildDirs, all),
  153. DepsNames = [{ec_cnv:to_list(rebar_app_info:name(App)), App} || App <- Deps],
  154. Checkouts = rebar_app_discover:find_apps([CheckoutsDir], all),
  155. CheckoutsNames = [{ec_cnv:to_list(rebar_app_info:name(App)), App} || App <- Checkouts],
  156. Plugins = rebar_app_discover:find_apps(PluginDirs, all),
  157. PluginsNames = [{ec_cnv:to_list(rebar_app_info:name(App)), App} || App <- Plugins],
  158. lists:foreach(
  159. fun({app, Name}) ->
  160. ct:pal("Name: ~p", [Name]),
  161. case lists:keyfind(Name, 1, DepsNames) of
  162. false ->
  163. error({app_not_found, Name});
  164. {Name, _App} ->
  165. ok
  166. end
  167. ; ({app, Name, invalid}) ->
  168. ct:pal("Name: ~p", [Name]),
  169. case lists:keyfind(Name, 1, InvalidDepsNames) of
  170. false ->
  171. error({app_not_found, Name});
  172. {Name, _App} ->
  173. ok
  174. end
  175. ; ({app, Name, valid}) ->
  176. ct:pal("Name: ~p", [Name]),
  177. case lists:keyfind(Name, 1, ValidDepsNames) of
  178. false ->
  179. error({app_not_found, Name});
  180. {Name, _App} ->
  181. ok
  182. end
  183. ; ({checkout, Name}) ->
  184. ct:pal("Name: ~p", [Name]),
  185. ?assertNotEqual(false, lists:keyfind(Name, 1, CheckoutsNames))
  186. ; ({dep, Name}) ->
  187. ct:pal("Name: ~p", [Name]),
  188. ?assertNotEqual(false, lists:keyfind(Name, 1, DepsNames))
  189. ; ({dep, Name, Vsn}) ->
  190. ct:pal("Name: ~p, Vsn: ~p", [Name, Vsn]),
  191. case lists:keyfind(Name, 1, DepsNames) of
  192. false ->
  193. error({dep_not_found, Name});
  194. {Name, App} ->
  195. ?assertEqual(iolist_to_binary(Vsn),
  196. iolist_to_binary(rebar_app_info:original_vsn(App)))
  197. end
  198. ; ({plugin, Name}) ->
  199. ct:pal("Name: ~p", [Name]),
  200. ?assertNotEqual(false, lists:keyfind(Name, 1, PluginsNames))
  201. ; ({plugin, Name, Vsn}) ->
  202. ct:pal("Name: ~p, Vsn: ~p", [Name, Vsn]),
  203. case lists:keyfind(Name, 1, PluginsNames) of
  204. false ->
  205. error({dep_not_found, Name});
  206. {Name, App} ->
  207. ?assertEqual(iolist_to_binary(Vsn),
  208. iolist_to_binary(rebar_app_info:original_vsn(App)))
  209. end
  210. ; ({lock, Name}) ->
  211. ct:pal("Name: ~p", [Name]),
  212. ?assertNotEqual(false, lists:keyfind(iolist_to_binary(Name), 1, Locks))
  213. ; ({lock, Name, Vsn}) ->
  214. ct:pal("Name: ~p, Vsn: ~p", [Name, Vsn]),
  215. case lists:keyfind(iolist_to_binary(Name), 1, Locks) of
  216. false ->
  217. error({lock_not_found, Name});
  218. {_LockName, {pkg, _, LockVsn}, _} ->
  219. ?assertEqual(iolist_to_binary(Vsn),
  220. iolist_to_binary(LockVsn));
  221. {_LockName, {_, _, {ref, LockVsn}}, _} ->
  222. ?assertEqual(iolist_to_binary(Vsn),
  223. iolist_to_binary(LockVsn))
  224. end
  225. ; ({release, Name, Vsn, ExpectedDevMode}) ->
  226. ct:pal("Release: ~p-~s", [Name, Vsn]),
  227. {ok, Cwd} = file:get_cwd(),
  228. try
  229. file:set_cwd(AppDir),
  230. [ReleaseDir] = filelib:wildcard(filename:join([AppDir, "_build", "*", "rel"])),
  231. RelxState = rlx_state:new("", [], []),
  232. RelxState1 = rlx_state:base_output_dir(RelxState, ReleaseDir),
  233. {ok, RelxState2} = rlx_prv_app_discover:do(RelxState1),
  234. {ok, RelxState3} = rlx_prv_rel_discover:do(RelxState2),
  235. LibDir = filename:join([ReleaseDir, Name, "lib"]),
  236. {ok, RelLibs} = file:list_dir(LibDir),
  237. IsSymLinkFun =
  238. fun(X) ->
  239. ec_file:is_symlink(filename:join(LibDir, X))
  240. end,
  241. DevMode = lists:all(IsSymLinkFun, RelLibs),
  242. ?assertEqual(ExpectedDevMode, DevMode),
  243. %% throws not_found if it doesn't exist
  244. rlx_state:get_realized_release(RelxState3, Name, Vsn)
  245. catch
  246. _ ->
  247. ct:fail(release_not_found)
  248. after
  249. file:set_cwd(Cwd)
  250. end
  251. ; ({tar, Name, Vsn}) ->
  252. ct:pal("Tarball: ~s-~s", [Name, Vsn]),
  253. Tarball = filename:join([AppDir, "_build", "rel", Name, Name++"-"++Vsn++".tar.gz"]),
  254. ?assertNotEqual([], filelib:is_file(Tarball))
  255. ; ({file, Filename}) ->
  256. ct:pal("Filename: ~s", [Filename]),
  257. ?assert(filelib:is_file(Filename))
  258. end, Expected).
  259. write_src_file(Dir, Name) ->
  260. Erl = filename:join([Dir, "src", "not_a_real_src_" ++ Name ++ ".erl"]),
  261. ok = filelib:ensure_dir(Erl),
  262. ok = ec_file:write(Erl, erl_src_file("not_a_real_src_" ++ Name ++ ".erl")).
  263. write_eunitized_src_file(Dir, Name) ->
  264. Erl = filename:join([Dir, "src", "not_a_real_src_" ++ Name ++ ".erl"]),
  265. ok = filelib:ensure_dir(Erl),
  266. ok = ec_file:write(Erl, erl_eunitized_src_file("not_a_real_src_" ++ Name ++ ".erl")).
  267. write_eunit_suite_file(Dir, Name) ->
  268. Erl = filename:join([Dir, "test", "not_a_real_src_" ++ Name ++ "_tests.erl"]),
  269. ok = filelib:ensure_dir(Erl),
  270. ok = ec_file:write(Erl, erl_eunit_suite_file("not_a_real_src_" ++ Name ++ ".erl")).
  271. write_app_file(Dir, Name, Version, Deps) ->
  272. Filename = filename:join([Dir, "ebin", Name ++ ".app"]),
  273. ok = filelib:ensure_dir(Filename),
  274. ok = ec_file:write_term(Filename, get_app_metadata(ec_cnv:to_list(Name), Version, Deps)).
  275. write_app_src_file(Dir, Name, Version, Deps) ->
  276. Filename = filename:join([Dir, "src", Name ++ ".app.src"]),
  277. ok = filelib:ensure_dir(Filename),
  278. ok = ec_file:write_term(Filename, get_app_metadata(ec_cnv:to_list(Name), Version, Deps)).
  279. erl_src_file(Name) ->
  280. io_lib:format("-module(~s).\n"
  281. "-export([main/0]).\n"
  282. "main() -> ok.\n", [filename:basename(Name, ".erl")]).
  283. erl_eunitized_src_file(Name) ->
  284. io_lib:format("-module(~s).\n"
  285. "-export([main/0]).\n"
  286. "main() -> ok.\n"
  287. "-ifdef(TEST).\n"
  288. "-include_lib(\"eunit/include/eunit.hrl\").\n"
  289. "some_test_() -> ?_assertEqual(ok, main()).\n"
  290. "-endif.\n", [filename:basename(Name, ".erl")]).
  291. erl_eunit_suite_file(Name) ->
  292. BaseName = filename:basename(Name, ".erl"),
  293. io_lib:format("-module(~s_tests).\n"
  294. "-compile(export_all).\n"
  295. "-ifndef(some_define).\n"
  296. "-define(some_define, false).\n"
  297. "-endif.\n"
  298. "-ifdef(TEST).\n"
  299. "-include_lib(\"eunit/include/eunit.hrl\").\n"
  300. "some_test_() -> ?_assertEqual(ok, ~s:main()).\n"
  301. "define_test_() -> ?_assertEqual(true, ?some_define).\n"
  302. "-endif.\n", [BaseName, BaseName]).
  303. get_app_metadata(Name, Vsn, Deps) ->
  304. {application, erlang:list_to_atom(Name),
  305. [{description, ""},
  306. {vsn, Vsn},
  307. {modules, []},
  308. {included_applications, []},
  309. {registered, []},
  310. {applications, Deps}]}.