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.

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