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.

449 lines
20 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, check_results/3]).
  5. -export([expand_deps/2, flat_deps/1, top_level_deps/1]).
  6. -export([create_app/4, create_eunit_app/4, create_empty_app/4,
  7. create_config/2, create_config/3, package_app/3]).
  8. -export([create_random_name/1, create_random_vsn/0, write_src_file/2]).
  9. %%%%%%%%%%%%%%
  10. %%% Public %%%
  11. %%%%%%%%%%%%%%
  12. %% @doc {@see init_rebar_state/2}
  13. init_rebar_state(Config) -> init_rebar_state(Config, "apps_dir1_").
  14. %% @doc Takes a common test config and a name (string) and sets up
  15. %% a basic OTP app directory with a pre-configured rebar state to
  16. %% run tests with.
  17. init_rebar_state(Config, Name) ->
  18. application:load(rebar),
  19. DataDir = ?config(priv_dir, Config),
  20. AppsDir = filename:join([DataDir, create_random_name(Name)]),
  21. CheckoutsDir = filename:join([AppsDir, "_checkouts"]),
  22. ok = ec_file:mkdir_p(AppsDir),
  23. ok = ec_file:mkdir_p(CheckoutsDir),
  24. Verbosity = rebar3:log_level(),
  25. rebar_log:init(command_line, Verbosity),
  26. GlobalDir = filename:join([DataDir, "cache"]),
  27. State = rebar_state:new([{base_dir, filename:join([AppsDir, "_build"])}
  28. ,{global_rebar_dir, GlobalDir}
  29. ,{root_dir, AppsDir}]),
  30. [{apps, AppsDir}, {checkouts, CheckoutsDir}, {state, State} | Config].
  31. %% @doc Takes common test config, a rebar config ([] if empty), a command to
  32. %% run ("install_deps", "compile", etc.), and a list of expected applications
  33. %% and/or dependencies to be present, and verifies whether they are all in
  34. %% place.
  35. %%
  36. %% The expectation list takes elements of the form:
  37. %% - `{app, Name :: string()}': checks that the app is properly built.
  38. %% - `{dep, Name :: string()}': checks that the dependency has been fetched.
  39. %% Ignores the build status of the dependency.
  40. %% - `{dep, Name :: string(), Vsn :: string()}': checks that the dependency
  41. %% has been fetched, and that a given version has been chosen. Useful to
  42. %% test for conflict resolution. Also ignores the build status of the
  43. %% dependency.
  44. %%
  45. %% This function assumes `init_rebar_state/1-2' has run before, in order to
  46. %% fetch the `apps' and `state' values from the CT config.
  47. run_and_check(Config, RebarConfig, Command, Expect) ->
  48. %% Assumes init_rebar_state has run first
  49. AppDir = ?config(apps, Config),
  50. State = ?config(state, Config),
  51. try
  52. Res = rebar3:run(rebar_state:new(State, RebarConfig, AppDir), Command),
  53. case Expect of
  54. {error, Reason} ->
  55. ?assertEqual({error, Reason}, Res);
  56. {ok, Expected} ->
  57. {ok, _} = Res,
  58. check_results(AppDir, Expected, "*"),
  59. Res;
  60. {ok, Expected, ProfileRun} ->
  61. {ok, _} = Res,
  62. check_results(AppDir, Expected, ProfileRun),
  63. Res;
  64. return ->
  65. Res
  66. end
  67. catch
  68. rebar_abort when Expect =:= rebar_abort -> rebar_abort
  69. end.
  70. %% @doc Creates a dummy application including:
  71. %% - src/<file>.erl
  72. %% - src/<file>.app.src
  73. %% And returns a `rebar_app_info' object.
  74. create_app(AppDir, Name, Vsn, Deps) ->
  75. write_src_file(AppDir, Name ++ ".erl"),
  76. write_src_file(AppDir, "not_a_real_src_" ++ Name ++ ".erl"),
  77. write_app_src_file(AppDir, Name, Vsn, Deps),
  78. rebar_app_info:new(Name, Vsn, AppDir, Deps).
  79. %% @doc Creates a dummy application including:
  80. %% - src/<file>.erl
  81. %% - src/<file>.app.src
  82. %% - test/<file>_tests.erl
  83. %% And returns a `rebar_app_info' object.
  84. create_eunit_app(AppDir, Name, Vsn, Deps) ->
  85. write_eunitized_src_file(AppDir, Name),
  86. write_eunit_suite_file(AppDir, Name),
  87. write_app_src_file(AppDir, Name, Vsn, Deps),
  88. rebar_app_info:new(Name, Vsn, AppDir, Deps).
  89. %% @doc Creates a dummy application including:
  90. %% - ebin/<file>.app
  91. %% And returns a `rebar_app_info' object.
  92. create_empty_app(AppDir, Name, Vsn, Deps) ->
  93. write_app_file(AppDir, Name, Vsn, Deps),
  94. rebar_app_info:new(Name, Vsn, AppDir, Deps).
  95. %% @doc Creates a rebar.config file. The function accepts a list of terms,
  96. %% each of which will be dumped as a consult file. For example, the list
  97. %% `[a, b, c]' will return the consult file `a. b. c.'.
  98. create_config(AppDir, Contents) ->
  99. ConfFilename = filename:join([AppDir, "rebar.config"]),
  100. create_config(AppDir, ConfFilename, Contents).
  101. create_config(_AppDir, ConfFilename, Contents) ->
  102. ok = filelib:ensure_dir(ConfFilename),
  103. Config = lists:flatten([io_lib:fwrite("~p.~n", [Term]) || Term <- Contents]),
  104. ok = ec_file:write(ConfFilename, Config),
  105. ConfFilename.
  106. %% @doc Util to create a random variation of a given name.
  107. create_random_name(Name) ->
  108. random_seed(),
  109. Name ++ erlang:integer_to_list(random:uniform(1000000)).
  110. %% @doc Util to create a random variation of a given version.
  111. create_random_vsn() ->
  112. random_seed(),
  113. lists:flatten([erlang:integer_to_list(random:uniform(100)),
  114. ".", erlang:integer_to_list(random:uniform(100)),
  115. ".", erlang:integer_to_list(random:uniform(100))]).
  116. random_seed() ->
  117. <<A:32, B:32, C:32>> = crypto:rand_bytes(12),
  118. random:seed({A,B,C}).
  119. expand_deps(_, []) -> [];
  120. expand_deps(git, [{Name, Deps} | Rest]) ->
  121. Dep = {Name, ".*", {git, "https://example.org/user/"++Name++".git", "master"}},
  122. [{Dep, expand_deps(git, Deps)} | expand_deps(git, Rest)];
  123. expand_deps(git, [{Name, Vsn, Deps} | Rest]) ->
  124. Dep = {Name, Vsn, {git, "https://example.org/user/"++Name++".git", {tag, Vsn}}},
  125. [{Dep, expand_deps(git, Deps)} | expand_deps(git, Rest)];
  126. expand_deps(pkg, [{Name, Deps} | Rest]) ->
  127. Dep = {pkg, Name, "0.0.0"},
  128. [{Dep, expand_deps(pkg, Deps)} | expand_deps(pkg, Rest)];
  129. expand_deps(pkg, [{Name, Vsn, Deps} | Rest]) ->
  130. Dep = {pkg, Name, Vsn},
  131. [{Dep, expand_deps(pkg, Deps)} | expand_deps(pkg, Rest)];
  132. expand_deps(mixed, [{Name, Deps} | Rest]) ->
  133. Dep = if hd(Name) >= $a, hd(Name) =< $z ->
  134. {pkg, string:to_upper(Name), "0.0.0"}
  135. ; hd(Name) >= $A, hd(Name) =< $Z ->
  136. {Name, ".*", {git, "https://example.org/user/"++Name++".git", "master"}}
  137. end,
  138. [{Dep, expand_deps(mixed, Deps)} | expand_deps(mixed, Rest)];
  139. expand_deps(mixed, [{Name, Vsn, Deps} | Rest]) ->
  140. Dep = if hd(Name) >= $a, hd(Name) =< $z ->
  141. {pkg, string:to_upper(Name), Vsn}
  142. ; hd(Name) >= $A, hd(Name) =< $Z ->
  143. {Name, Vsn, {git, "https://example.org/user/"++Name++".git", {tag, Vsn}}}
  144. end,
  145. [{Dep, expand_deps(mixed, Deps)} | expand_deps(mixed, Rest)].
  146. %% Source deps can depend on both source and package dependencies;
  147. %% package deps can only depend on package deps.
  148. %% For things to work we have to go down the dep tree and find all
  149. %% lineages of pkg deps and return them, whereas the source deps
  150. %% can be left as is.
  151. flat_deps(Deps) -> flat_deps(Deps, [], []).
  152. flat_deps([], Src, Pkg) -> {Src, Pkg};
  153. flat_deps([{{pkg, Name, Vsn}, PkgDeps} | Rest], Src, Pkg) ->
  154. Current = {{iolist_to_binary(Name), iolist_to_binary(Vsn)},
  155. top_level_deps(PkgDeps)},
  156. {[], FlatPkgDeps} = flat_deps(PkgDeps),
  157. flat_deps(Rest,
  158. Src,
  159. Pkg ++ [Current | FlatPkgDeps]);
  160. flat_deps([{{Name,_Vsn,Ref}, Deps} | Rest], Src, Pkg) ->
  161. Current = {{Name,vsn_from_ref(Ref)}, top_level_deps(Deps)},
  162. {FlatDeps, FlatPkgDeps} = flat_deps(Deps),
  163. flat_deps(Rest,
  164. Src ++ [Current | FlatDeps],
  165. Pkg ++ FlatPkgDeps).
  166. vsn_from_ref({git, _, {_, Vsn}}) -> Vsn;
  167. vsn_from_ref({git, _, Vsn}) -> Vsn.
  168. top_level_deps([]) -> [];
  169. top_level_deps([{{pkg, Name, Vsn}, _} | Deps]) ->
  170. [{list_to_atom(Name), Vsn} | top_level_deps(Deps)];
  171. top_level_deps([{{Name, Vsn, Ref}, _} | Deps]) ->
  172. [{list_to_atom(Name), Vsn, Ref} | top_level_deps(Deps)].
  173. %%%%%%%%%%%%%%%
  174. %%% Helpers %%%
  175. %%%%%%%%%%%%%%%
  176. check_results(AppDir, Expected, ProfileRun) ->
  177. BuildDirs = filelib:wildcard(filename:join([AppDir, "_build", ProfileRun, "lib", "*"])),
  178. PluginDirs = filelib:wildcard(filename:join([AppDir, "_build", ProfileRun, "plugins", "*"])),
  179. GlobalPluginDirs = filelib:wildcard(filename:join([AppDir, "global", "plugins", "*"])),
  180. CheckoutsDir = filename:join([AppDir, "_checkouts", "*"]),
  181. LockFile = filename:join([AppDir, "rebar.lock"]),
  182. Locks = lists:flatten(rebar_config:consult_lock_file(LockFile)),
  183. InvalidApps = rebar_app_discover:find_apps(BuildDirs, invalid),
  184. ValidApps = rebar_app_discover:find_apps(BuildDirs, valid),
  185. InvalidDepsNames = [{ec_cnv:to_list(rebar_app_info:name(App)), App} || App <- InvalidApps],
  186. ValidDepsNames = [{ec_cnv:to_list(rebar_app_info:name(App)), App} || App <- ValidApps],
  187. Deps = rebar_app_discover:find_apps(BuildDirs, all),
  188. DepsNames = [{ec_cnv:to_list(rebar_app_info:name(App)), App} || App <- Deps],
  189. Checkouts = rebar_app_discover:find_apps([CheckoutsDir], all),
  190. CheckoutsNames = [{ec_cnv:to_list(rebar_app_info:name(App)), App} || App <- Checkouts],
  191. Plugins = rebar_app_discover:find_apps(PluginDirs, all),
  192. PluginsNames = [{ec_cnv:to_list(rebar_app_info:name(App)), App} || App <- Plugins],
  193. GlobalPlugins = rebar_app_discover:find_apps(GlobalPluginDirs, all),
  194. GlobalPluginsNames = [{ec_cnv:to_list(rebar_app_info:name(App)), App} || App <- GlobalPlugins],
  195. lists:foreach(
  196. fun({app, Name}) ->
  197. ct:pal("App Name: ~p", [Name]),
  198. case lists:keyfind(Name, 1, DepsNames) of
  199. false ->
  200. error({app_not_found, Name});
  201. {Name, _App} ->
  202. ok
  203. end
  204. ; ({app, Name, invalid}) ->
  205. ct:pal("Invalid Name: ~p", [Name]),
  206. case lists:keyfind(Name, 1, InvalidDepsNames) of
  207. false ->
  208. error({app_not_found, Name});
  209. {Name, _App} ->
  210. ok
  211. end
  212. ; ({app, Name, valid}) ->
  213. ct:pal("Valid Name: ~p", [Name]),
  214. case lists:keyfind(Name, 1, ValidDepsNames) of
  215. false ->
  216. error({app_not_found, Name});
  217. {Name, _App} ->
  218. ok
  219. end
  220. ; ({dep_not_exist, Name}) ->
  221. ct:pal("App Not Exist Name: ~p", [Name]),
  222. case lists:keyfind(Name, 1, DepsNames) of
  223. false ->
  224. ok;
  225. {Name, _App} ->
  226. error({app_found, Name})
  227. end
  228. ; ({checkout, Name}) ->
  229. ct:pal("Checkout Name: ~p", [Name]),
  230. ?assertNotEqual(false, lists:keyfind(Name, 1, CheckoutsNames))
  231. ; ({dep, Name}) ->
  232. ct:pal("Dep Name: ~p", [Name]),
  233. ?assertNotEqual(false, lists:keyfind(Name, 1, DepsNames))
  234. ; ({dep, Name, Vsn}) ->
  235. ct:pal("Dep Name: ~p, Vsn: ~p", [Name, Vsn]),
  236. case lists:keyfind(Name, 1, DepsNames) of
  237. false ->
  238. error({dep_not_found, Name});
  239. {Name, App} ->
  240. ?assertEqual(iolist_to_binary(Vsn),
  241. iolist_to_binary(rebar_app_info:original_vsn(App)))
  242. end
  243. ; ({plugin, Name}) ->
  244. ct:pal("Plugin Name: ~p", [Name]),
  245. ?assertNotEqual(false, lists:keyfind(Name, 1, PluginsNames))
  246. ; ({plugin, Name, Vsn}) ->
  247. ct:pal("Plugin Name: ~p, Vsn: ~p", [Name, Vsn]),
  248. case lists:keyfind(Name, 1, PluginsNames) of
  249. false ->
  250. error({plugin_not_found, Name});
  251. {Name, App} ->
  252. ?assertEqual(iolist_to_binary(Vsn),
  253. iolist_to_binary(rebar_app_info:original_vsn(App)))
  254. end
  255. ; ({global_plugin, Name}) ->
  256. ct:pal("Global Plugin Name: ~p", [Name]),
  257. ?assertNotEqual(false, lists:keyfind(Name, 1, GlobalPluginsNames))
  258. ; ({global_plugin, Name, Vsn}) ->
  259. ct:pal("Global Plugin Name: ~p, Vsn: ~p", [Name, Vsn]),
  260. case lists:keyfind(Name, 1, GlobalPluginsNames) of
  261. false ->
  262. error({global_plugin_not_found, Name});
  263. {Name, App} ->
  264. ?assertEqual(iolist_to_binary(Vsn),
  265. iolist_to_binary(rebar_app_info:original_vsn(App)))
  266. end
  267. ; ({lock, Name}) ->
  268. ct:pal("Lock Name: ~p", [Name]),
  269. ?assertNotEqual(false, lists:keyfind(iolist_to_binary(Name), 1, Locks))
  270. ; ({lock, Name, Vsn}) ->
  271. ct:pal("Lock Name: ~p, Vsn: ~p", [Name, Vsn]),
  272. case lists:keyfind(iolist_to_binary(Name), 1, Locks) of
  273. false ->
  274. error({lock_not_found, Name});
  275. {_LockName, {pkg, _, LockVsn}, _} ->
  276. ?assertEqual(iolist_to_binary(Vsn),
  277. iolist_to_binary(LockVsn));
  278. {_LockName, {_, _, {ref, LockVsn}}, _} ->
  279. ?assertEqual(iolist_to_binary(Vsn),
  280. iolist_to_binary(LockVsn))
  281. end
  282. ; ({lock, pkg, Name, Vsn}) ->
  283. ct:pal("Pkg Lock Name: ~p, Vsn: ~p", [Name, Vsn]),
  284. case lists:keyfind(iolist_to_binary(Name), 1, Locks) of
  285. false ->
  286. error({lock_not_found, Name});
  287. {_LockName, {pkg, _, LockVsn}, _} ->
  288. ?assertEqual(iolist_to_binary(Vsn),
  289. iolist_to_binary(LockVsn));
  290. {_LockName, {_, _, {ref, LockVsn}}, _} ->
  291. error({source_lock, {Name, LockVsn}})
  292. end
  293. ; ({lock, src, Name, Vsn}) ->
  294. ct:pal("Src Lock Name: ~p, Vsn: ~p", [Name, Vsn]),
  295. case lists:keyfind(iolist_to_binary(Name), 1, Locks) of
  296. false ->
  297. error({lock_not_found, Name});
  298. {_LockName, {pkg, _, LockVsn}, _} ->
  299. error({pkg_lock, {Name, LockVsn}});
  300. {_LockName, {_, _, {ref, LockVsn}}, _} ->
  301. ?assertEqual(iolist_to_binary(Vsn),
  302. iolist_to_binary(LockVsn))
  303. end
  304. ; ({release, Name, Vsn, ExpectedDevMode}) ->
  305. ct:pal("Release: ~p-~s", [Name, Vsn]),
  306. {ok, Cwd} = file:get_cwd(),
  307. try
  308. file:set_cwd(AppDir),
  309. [ReleaseDir] = filelib:wildcard(filename:join([AppDir, "_build", "*", "rel"])),
  310. RelxState = rlx_state:new("", [], []),
  311. RelxState1 = rlx_state:base_output_dir(RelxState, ReleaseDir),
  312. {ok, RelxState2} = rlx_prv_app_discover:do(RelxState1),
  313. {ok, RelxState3} = rlx_prv_rel_discover:do(RelxState2),
  314. LibDir = filename:join([ReleaseDir, Name, "lib"]),
  315. {ok, RelLibs} = rebar_utils:list_dir(LibDir),
  316. IsSymLinkFun =
  317. fun(X) ->
  318. ec_file:is_symlink(filename:join(LibDir, X))
  319. end,
  320. DevMode = lists:all(IsSymLinkFun, RelLibs),
  321. ?assertEqual(ExpectedDevMode, DevMode),
  322. %% throws not_found if it doesn't exist
  323. rlx_state:get_realized_release(RelxState3, Name, Vsn)
  324. catch
  325. _ ->
  326. ct:fail(release_not_found)
  327. after
  328. file:set_cwd(Cwd)
  329. end
  330. ; ({tar, Name, Vsn}) ->
  331. ct:pal("Tarball: ~s-~s", [Name, Vsn]),
  332. Tarball = filename:join([AppDir, "_build", "rel", Name, Name++"-"++Vsn++".tar.gz"]),
  333. ?assertNotEqual([], filelib:is_file(Tarball))
  334. ; ({file, Filename}) ->
  335. ct:pal("Filename: ~s", [Filename]),
  336. ?assert(filelib:is_file(Filename))
  337. ; ({dir, Dirname}) ->
  338. ct:pal("Directory: ~s", [Dirname]),
  339. ?assert(filelib:is_dir(Dirname))
  340. end, Expected).
  341. write_src_file(Dir, Name) ->
  342. Erl = filename:join([Dir, "src", Name]),
  343. ok = filelib:ensure_dir(Erl),
  344. ok = ec_file:write(Erl, erl_src_file(Name)).
  345. write_eunitized_src_file(Dir, Name) ->
  346. Erl = filename:join([Dir, "src", "not_a_real_src_" ++ Name ++ ".erl"]),
  347. ok = filelib:ensure_dir(Erl),
  348. ok = ec_file:write(Erl, erl_eunitized_src_file("not_a_real_src_" ++ Name ++ ".erl")).
  349. write_eunit_suite_file(Dir, Name) ->
  350. Erl = filename:join([Dir, "test", "not_a_real_src_" ++ Name ++ "_tests.erl"]),
  351. ok = filelib:ensure_dir(Erl),
  352. ok = ec_file:write(Erl, erl_eunit_suite_file("not_a_real_src_" ++ Name ++ ".erl")).
  353. write_app_file(Dir, Name, Version, Deps) ->
  354. Filename = filename:join([Dir, "ebin", Name ++ ".app"]),
  355. ok = filelib:ensure_dir(Filename),
  356. ok = ec_file:write_term(Filename, get_app_metadata(ec_cnv:to_list(Name), Version, Deps)).
  357. write_app_src_file(Dir, Name, Version, Deps) ->
  358. Filename = filename:join([Dir, "src", Name ++ ".app.src"]),
  359. ok = filelib:ensure_dir(Filename),
  360. ok = ec_file:write_term(Filename, get_app_metadata(ec_cnv:to_list(Name), Version, Deps)).
  361. erl_src_file(Name) ->
  362. io_lib:format("-module('~s').\n"
  363. "-export([main/0]).\n"
  364. "main() -> ok.\n", [filename:basename(Name, ".erl")]).
  365. erl_eunitized_src_file(Name) ->
  366. io_lib:format("-module('~s').\n"
  367. "-export([main/0]).\n"
  368. "main() -> ok.\n"
  369. "-ifdef(TEST).\n"
  370. "-include_lib(\"eunit/include/eunit.hrl\").\n"
  371. "some_test_() -> ?_assertEqual(ok, main()).\n"
  372. "-endif.\n", [filename:basename(Name, ".erl")]).
  373. erl_eunit_suite_file(Name) ->
  374. BaseName = filename:basename(Name, ".erl"),
  375. io_lib:format("-module('~s_tests').\n"
  376. "-compile(export_all).\n"
  377. "-ifndef(some_define).\n"
  378. "-define(some_define, false).\n"
  379. "-endif.\n"
  380. "-ifdef(TEST).\n"
  381. "-include_lib(\"eunit/include/eunit.hrl\").\n"
  382. "some_test_() -> ?_assertEqual(ok, ~s:main()).\n"
  383. "define_test_() -> ?_assertEqual(true, ?some_define).\n"
  384. "-endif.\n", [BaseName, BaseName]).
  385. get_app_metadata(Name, Vsn, Deps) ->
  386. {application, erlang:list_to_atom(Name),
  387. [{description, ""},
  388. {vsn, Vsn},
  389. {modules, []},
  390. {included_applications, []},
  391. {registered, []},
  392. {applications, Deps}]}.
  393. package_app(AppDir, DestDir, PkgName) ->
  394. Name = PkgName++".tar",
  395. {ok, Fs} = rebar_utils:list_dir(AppDir),
  396. ok = erl_tar:create(filename:join(DestDir, "contents.tar.gz"),
  397. lists:zip(Fs, [filename:join(AppDir,F) || F <- Fs]),
  398. [compressed]),
  399. ok = file:write_file(filename:join(DestDir, "metadata.config"), "who cares"),
  400. ok = file:write_file(filename:join(DestDir, "VERSION"), "3"),
  401. {ok, Contents} = file:read_file(filename:join(DestDir, "contents.tar.gz")),
  402. Blob = <<"3who cares", Contents/binary>>,
  403. <<X:256/big-unsigned>> = crypto:hash(sha256, Blob),
  404. BinChecksum = list_to_binary(string:to_upper(lists:flatten(io_lib:format("~64.16.0b", [X])))),
  405. ok = file:write_file(filename:join(DestDir, "CHECKSUM"), BinChecksum),
  406. PkgFiles = ["contents.tar.gz", "VERSION", "metadata.config", "CHECKSUM"],
  407. Archive = filename:join(DestDir, Name),
  408. ok = erl_tar:create(Archive,
  409. lists:zip(PkgFiles, [filename:join(DestDir,F) || F <- PkgFiles])),
  410. {ok, BinFull} = file:read_file(Archive),
  411. <<E:128/big-unsigned-integer>> = crypto:hash(md5, BinFull),
  412. Etag = string:to_lower(lists:flatten(io_lib:format("~32.16.0b", [E]))),
  413. {BinChecksum, Etag}.