Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

507 řádky
20 KiB

  1. %% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
  2. %% ex: ts=4 sw=4 et
  3. -module(rebar_prv_eunit).
  4. -behaviour(provider).
  5. -export([init/1,
  6. do/1,
  7. format_error/1]).
  8. %% exported solely for tests
  9. -export([prepare_tests/1, eunit_opts/1, validate_tests/2]).
  10. -include("rebar.hrl").
  11. -include_lib("providers/include/providers.hrl").
  12. -define(PROVIDER, eunit).
  13. %% we need to modify app_info state before compile
  14. -define(DEPS, [lock]).
  15. -define(DEFAULT_TEST_REGEX, "^(?!\\._).*\\.erl\$").
  16. %% ===================================================================
  17. %% Public API
  18. %% ===================================================================
  19. -spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
  20. init(State) ->
  21. Provider = providers:create([{name, ?PROVIDER},
  22. {module, ?MODULE},
  23. {deps, ?DEPS},
  24. {bare, true},
  25. {example, "rebar3 eunit"},
  26. {short_desc, "Run EUnit Tests."},
  27. {desc, "Run EUnit Tests."},
  28. {opts, eunit_opts(State)},
  29. {profiles, [test]}]),
  30. State1 = rebar_state:add_provider(State, Provider),
  31. {ok, State1}.
  32. -spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
  33. do(State) ->
  34. Tests = prepare_tests(State),
  35. %% inject `eunit_first_files`, `eunit_compile_opts` and any
  36. %% directories required by tests into the applications
  37. NewState = inject_eunit_state(State, Tests),
  38. case compile(NewState) of
  39. %% successfully compiled apps
  40. {ok, S} -> do(S, Tests);
  41. Error -> Error
  42. end.
  43. do(State, Tests) ->
  44. ?INFO("Performing EUnit tests...", []),
  45. setup_name(State),
  46. rebar_paths:set_paths([deps, plugins], State),
  47. %% Run eunit provider prehooks
  48. Providers = rebar_state:providers(State),
  49. Cwd = rebar_dir:get_cwd(),
  50. rebar_hooks:run_project_and_app_hooks(Cwd, pre, ?PROVIDER, Providers, State),
  51. case validate_tests(State, Tests) of
  52. {ok, T} ->
  53. case run_tests(State, T) of
  54. {ok, State1} ->
  55. %% Run eunit provider posthooks
  56. rebar_hooks:run_project_and_app_hooks(Cwd, post, ?PROVIDER, Providers, State1),
  57. rebar_paths:set_paths([plugins, deps], State),
  58. {ok, State1};
  59. Error ->
  60. rebar_paths:set_paths([plugins, deps], State),
  61. Error
  62. end;
  63. Error ->
  64. rebar_paths:set_paths([plugins, deps], State),
  65. Error
  66. end.
  67. run_tests(State, Tests) ->
  68. T = translate_paths(State, Tests),
  69. EUnitOpts = resolve_eunit_opts(State),
  70. ?DEBUG("eunit_tests ~p", [T]),
  71. ?DEBUG("eunit_opts ~p", [EUnitOpts]),
  72. try eunit:test(T, EUnitOpts) of
  73. Result ->
  74. ok = maybe_write_coverdata(State),
  75. case handle_results(Result) of
  76. {error, Reason} ->
  77. ?PRV_ERROR(Reason);
  78. ok ->
  79. {ok, State}
  80. end
  81. catch error:badarg -> ?PRV_ERROR({error, badarg})
  82. end.
  83. -spec format_error(any()) -> iolist().
  84. format_error(unknown_error) ->
  85. io_lib:format("Error running tests", []);
  86. format_error({error_running_tests, Reason}) ->
  87. io_lib:format("Error running tests: ~p", [Reason]);
  88. format_error({eunit_test_errors, Errors}) ->
  89. io_lib:format(lists:concat(["Error Running EUnit Tests:"] ++
  90. lists:map(fun(Error) -> "~n " ++ Error end, Errors)), []);
  91. format_error({badconfig, {Msg, {Value, Key}}}) ->
  92. io_lib:format(Msg, [Value, Key]);
  93. format_error({error, Error}) ->
  94. format_error({error_running_tests, Error}).
  95. %% ===================================================================
  96. %% Internal functions
  97. %% ===================================================================
  98. setup_name(State) ->
  99. {Long, Short, Opts} = rebar_dist_utils:find_options(State),
  100. rebar_dist_utils:either(Long, Short, Opts).
  101. prepare_tests(State) ->
  102. %% parse and translate command line tests
  103. CmdTests = resolve_tests(State),
  104. CfgTests = cfg_tests(State),
  105. ProjectApps = rebar_state:project_apps(State),
  106. %% prioritize tests to run first trying any command line specified
  107. %% tests falling back to tests specified in the config file finally
  108. %% running a default set if no other tests are present
  109. select_tests(State, ProjectApps, CmdTests, CfgTests).
  110. resolve_tests(State) ->
  111. {RawOpts, _} = rebar_state:command_parsed_args(State),
  112. Apps = resolve(app, application, RawOpts),
  113. Applications = resolve(application, RawOpts),
  114. Dirs = resolve(dir, RawOpts),
  115. Files = resolve(file, RawOpts),
  116. Modules = resolve(module, RawOpts),
  117. Suites = resolve(suite, module, RawOpts),
  118. Apps ++ Applications ++ Dirs ++ Files ++ Modules ++ Suites.
  119. resolve(Flag, RawOpts) -> resolve(Flag, Flag, RawOpts).
  120. resolve(Flag, EUnitKey, RawOpts) ->
  121. case proplists:get_value(Flag, RawOpts) of
  122. undefined -> [];
  123. Args -> lists:map(fun(Arg) -> normalize(EUnitKey, Arg) end,
  124. rebar_string:lexemes(Args, [$,]))
  125. end.
  126. normalize(Key, Value) when Key == dir; Key == file -> {Key, Value};
  127. normalize(Key, Value) -> {Key, list_to_atom(Value)}.
  128. cfg_tests(State) ->
  129. case rebar_state:get(State, eunit_tests, []) of
  130. Tests when is_list(Tests) ->
  131. lists:map(fun({app, App}) -> {application, App}; (T) -> T end, Tests);
  132. Wrong ->
  133. %% probably a single non list term
  134. ?PRV_ERROR({badconfig, {"Value `~p' of option `~p' must be a list", {Wrong, eunit_tests}}})
  135. end.
  136. select_tests(_State, _ProjectApps, _, {error, _} = Error) -> Error;
  137. select_tests(State, ProjectApps, [], []) -> {ok, default_tests(State, ProjectApps)};
  138. select_tests(_State, _ProjectApps, [], Tests) -> {ok, Tests};
  139. select_tests(_State, _ProjectApps, Tests, _) -> {ok, Tests}.
  140. default_tests(State, Apps) ->
  141. %% use `{application, App}` for each app in project
  142. AppTests = set_apps(Apps),
  143. %% additional test modules in `test` dir of each app
  144. ModTests = set_modules(Apps, State),
  145. AppTests ++ ModTests.
  146. set_apps(Apps) -> set_apps(Apps, []).
  147. set_apps([], Acc) -> Acc;
  148. set_apps([App|Rest], Acc) ->
  149. AppName = list_to_atom(binary_to_list(rebar_app_info:name(App))),
  150. set_apps(Rest, [{application, AppName}|Acc]).
  151. set_modules(Apps, State) -> set_modules(Apps, State, {[], []}).
  152. set_modules([], State, {AppAcc, TestAcc}) ->
  153. Regex = rebar_state:get(State, eunit_test_regex, ?DEFAULT_TEST_REGEX),
  154. BareTestDir = [filename:join([rebar_state:dir(State), "test"])],
  155. TestSrc = gather_src(BareTestDir, Regex),
  156. dedupe_tests({AppAcc, TestAcc ++ TestSrc});
  157. set_modules([App|Rest], State, {AppAcc, TestAcc}) ->
  158. F = fun(Dir) -> filename:join([rebar_app_info:dir(App), Dir]) end,
  159. AppDirs = lists:map(F, rebar_dir:src_dirs(rebar_app_info:opts(App), ["src"])),
  160. Regex = rebar_state:get(State, eunit_test_regex, ?DEFAULT_TEST_REGEX),
  161. AppSrc = gather_src(AppDirs, Regex),
  162. TestDirs = [filename:join([rebar_app_info:dir(App), "test"])],
  163. TestSrc = gather_src(TestDirs, Regex),
  164. set_modules(Rest, State, {AppSrc ++ AppAcc, TestSrc ++ TestAcc}).
  165. gather_src(Dirs, Regex) -> gather_src(Dirs, Regex, []).
  166. gather_src([], _Regex, Srcs) -> Srcs;
  167. gather_src([Dir|Rest], Regex, Srcs) ->
  168. gather_src(Rest, Regex, Srcs ++ rebar_utils:find_files(Dir, Regex, true)).
  169. dedupe_tests({AppMods, TestMods}) ->
  170. UniqueTestMods = lists:usort(TestMods) -- AppMods,
  171. %% for each modules in TestMods create a test if there is not a module
  172. %% in AppMods that will trigger it
  173. F = fun(TestMod) ->
  174. M = filename:rootname(filename:basename(TestMod)),
  175. MatchesTest = fun(AppMod) -> filename:rootname(filename:basename(AppMod)) ++ "_tests" == M end,
  176. case lists:any(MatchesTest, AppMods) of
  177. false -> {true, {module, list_to_atom(M)}};
  178. true -> false
  179. end
  180. end,
  181. rebar_utils:filtermap(F, UniqueTestMods).
  182. inject_eunit_state(State, {ok, Tests}) ->
  183. Apps = rebar_state:project_apps(State),
  184. case inject_eunit_state(State, Apps, []) of
  185. {ok, {NewState, ModdedApps}} ->
  186. test_dirs(NewState, ModdedApps, Tests);
  187. {error, _} = Error -> Error
  188. end;
  189. inject_eunit_state(_State, Error) -> Error.
  190. inject_eunit_state(State, [App|Rest], Acc) ->
  191. case inject(rebar_app_info:opts(App)) of
  192. {error, _} = Error -> Error;
  193. NewOpts ->
  194. NewApp = rebar_app_info:opts(App, NewOpts),
  195. inject_eunit_state(State, Rest, [NewApp|Acc])
  196. end;
  197. inject_eunit_state(State, [], Acc) ->
  198. case inject(rebar_state:opts(State)) of
  199. {error, _} = Error -> Error;
  200. NewOpts -> {ok, {rebar_state:opts(State, NewOpts), lists:reverse(Acc)}}
  201. end.
  202. opts(Opts, Key, Default) ->
  203. case rebar_opts:get(Opts, Key, Default) of
  204. Vs when is_list(Vs) -> Vs;
  205. Wrong ->
  206. ?PRV_ERROR({badconfig, {"Value `~p' of option `~p' must be a list", {Wrong, Key}}})
  207. end.
  208. inject(Opts) -> erl_opts(Opts).
  209. erl_opts(Opts) ->
  210. %% append `eunit_compile_opts` to app defined `erl_opts`
  211. ErlOpts = opts(Opts, erl_opts, []),
  212. EUnitOpts = opts(Opts, eunit_compile_opts, []),
  213. case append(EUnitOpts, ErlOpts) of
  214. {error, _} = Error -> Error;
  215. NewErlOpts -> first_files(rebar_opts:set(Opts, erl_opts, NewErlOpts))
  216. end.
  217. first_files(Opts) ->
  218. %% append `eunit_first_files` to app defined `erl_first_files`
  219. FirstFiles = opts(Opts, erl_first_files, []),
  220. EUnitFirstFiles = opts(Opts, eunit_first_files, []),
  221. case append(EUnitFirstFiles, FirstFiles) of
  222. {error, _} = Error -> Error;
  223. NewFirstFiles -> eunit_macro(rebar_opts:set(Opts, erl_first_files, NewFirstFiles))
  224. end.
  225. eunit_macro(Opts) ->
  226. ErlOpts = opts(Opts, erl_opts, []),
  227. NewOpts = safe_define_eunit_macro(ErlOpts),
  228. rebar_opts:set(Opts, erl_opts, NewOpts).
  229. safe_define_eunit_macro(Opts) ->
  230. %% defining a compile macro twice results in an exception so
  231. %% make sure 'EUNIT' is only defined once
  232. case test_defined(Opts) of
  233. true -> Opts;
  234. false -> [{d, 'EUNIT'}|Opts]
  235. end.
  236. test_defined([{d, 'EUNIT'}|_]) -> true;
  237. test_defined([{d, 'EUNIT', true}|_]) -> true;
  238. test_defined([_|Rest]) -> test_defined(Rest);
  239. test_defined([]) -> false.
  240. append({error, _} = Error, _) -> Error;
  241. append(_, {error, _} = Error) -> Error;
  242. append(A, B) -> A ++ B.
  243. test_dirs(State, Apps, []) -> rebar_state:project_apps(State, Apps);
  244. test_dirs(State, Apps, [{dir, Dir}|Rest]) ->
  245. %% insert `Dir` into an app if relative, or the base state if not
  246. %% app relative but relative to the root or not at all if outside
  247. %% project scope
  248. {NewState, NewApps} = maybe_inject_test_dir(State, [], Apps, Dir),
  249. test_dirs(NewState, NewApps, Rest);
  250. test_dirs(State, Apps, [{file, File}|Rest]) ->
  251. Dir = filename:dirname(File),
  252. {NewState, NewApps} = maybe_inject_test_dir(State, [], Apps, Dir),
  253. test_dirs(NewState, NewApps, Rest);
  254. test_dirs(State, Apps, [_|Rest]) -> test_dirs(State, Apps, Rest).
  255. maybe_inject_test_dir(State, AppAcc, [App|Rest], Dir) ->
  256. case rebar_file_utils:path_from_ancestor(Dir, rebar_app_info:dir(App)) of
  257. {ok, Path} ->
  258. Opts = inject_test_dir(rebar_app_info:opts(App), Path),
  259. {State, AppAcc ++ [rebar_app_info:opts(App, Opts)] ++ Rest};
  260. {error, badparent} ->
  261. maybe_inject_test_dir(State, AppAcc ++ [App], Rest, Dir)
  262. end;
  263. maybe_inject_test_dir(State, AppAcc, [], Dir) ->
  264. case rebar_file_utils:path_from_ancestor(Dir, rebar_state:dir(State)) of
  265. {ok, Path} ->
  266. Opts = inject_test_dir(rebar_state:opts(State), Path),
  267. {rebar_state:opts(State, Opts), AppAcc};
  268. {error, badparent} ->
  269. {State, AppAcc}
  270. end.
  271. inject_test_dir(Opts, Dir) ->
  272. %% append specified test targets to app defined `extra_src_dirs`
  273. ExtraSrcDirs = rebar_opts:get(Opts, extra_src_dirs, []),
  274. rebar_opts:set(Opts, extra_src_dirs, ExtraSrcDirs ++ [Dir]).
  275. compile({error, _} = Error) -> Error;
  276. compile(State) ->
  277. {ok, S} = rebar_prv_compile:do(State),
  278. ok = maybe_cover_compile(S),
  279. {ok, S}.
  280. validate_tests(State, {ok, Tests}) ->
  281. gather_tests(fun(Elem) -> validate(State, Elem) end, Tests, []);
  282. validate_tests(_State, Error) -> Error.
  283. gather_tests(_F, [], Acc) -> {ok, lists:reverse(Acc)};
  284. gather_tests(F, [Test|Rest], Acc) ->
  285. case F(Test) of
  286. ok -> gather_tests(F, Rest, [Test|Acc]);
  287. %% failure mode, switch to gathering errors
  288. {error, Error} -> gather_errors(F, Rest, [Error])
  289. end.
  290. gather_errors(_F, [], Acc) -> ?PRV_ERROR({eunit_test_errors, lists:reverse(Acc)});
  291. gather_errors(F, [Test|Rest], Acc) ->
  292. case F(Test) of
  293. ok -> gather_errors(F, Rest, Acc);
  294. {error, Error} -> gather_errors(F, Rest, [Error|Acc])
  295. end.
  296. validate(State, {application, App}) ->
  297. validate_app(State, App);
  298. validate(State, {dir, Dir}) ->
  299. validate_dir(State, Dir);
  300. validate(State, {file, File}) ->
  301. validate_file(State, File);
  302. validate(State, {module, Module}) ->
  303. validate_module(State, Module);
  304. validate(State, {suite, Module}) ->
  305. validate_module(State, Module);
  306. validate(State, Module) when is_atom(Module) ->
  307. validate_module(State, Module);
  308. validate(State, Path) when is_list(Path) ->
  309. case ec_file:is_dir(Path) of
  310. true -> validate(State, {dir, Path});
  311. false -> validate(State, {file, Path})
  312. end;
  313. %% unrecognized tests should be included. if they're invalid eunit will error
  314. %% and rebar.config may contain arbitrarily complex tests that are effectively
  315. %% unvalidatable
  316. validate(_State, _Test) -> ok.
  317. validate_app(State, AppName) ->
  318. ProjectApps = rebar_state:project_apps(State),
  319. validate_app(State, ProjectApps, AppName).
  320. validate_app(_State, [], AppName) ->
  321. {error, lists:concat(["Application `", AppName, "' not found in project."])};
  322. validate_app(State, [App|Rest], AppName) ->
  323. case AppName == binary_to_atom(rebar_app_info:name(App), unicode) of
  324. true -> ok;
  325. false -> validate_app(State, Rest, AppName)
  326. end.
  327. validate_dir(State, Dir) ->
  328. case ec_file:is_dir(filename:join([rebar_state:dir(State), Dir])) of
  329. true -> ok;
  330. false -> {error, lists:concat(["Directory `", Dir, "' not found."])}
  331. end.
  332. validate_file(State, File) ->
  333. case ec_file:exists(filename:join([rebar_state:dir(State), File])) of
  334. true -> ok;
  335. false -> {error, lists:concat(["File `", File, "' not found."])}
  336. end.
  337. validate_module(_State, Module) ->
  338. case code:which(Module) of
  339. non_existing -> {error, lists:concat(["Module `", Module, "' not found in project."])};
  340. _ -> ok
  341. end.
  342. resolve_eunit_opts(State) ->
  343. {Opts, _} = rebar_state:command_parsed_args(State),
  344. EUnitOpts = rebar_state:get(State, eunit_opts, []),
  345. EUnitOpts1 = case proplists:get_value(verbose, Opts, false) of
  346. true -> set_verbose(EUnitOpts);
  347. false -> EUnitOpts
  348. end,
  349. IsVerbose = lists:member(verbose, EUnitOpts1),
  350. case proplists:get_value(eunit_formatters, EUnitOpts1, not IsVerbose) of
  351. true -> custom_eunit_formatters(EUnitOpts1);
  352. false -> EUnitOpts1
  353. end.
  354. custom_eunit_formatters(Opts) ->
  355. %% If `report` is already set then treat that like `eunit_formatters` is false
  356. case lists:keymember(report, 1, Opts) of
  357. true -> Opts;
  358. false -> [no_tty, {report, {eunit_progress, [colored, profile]}} | Opts]
  359. end.
  360. set_verbose(Opts) ->
  361. %% if `verbose` is already set don't set it again
  362. case lists:member(verbose, Opts) of
  363. true -> Opts;
  364. false -> [verbose] ++ Opts
  365. end.
  366. translate_paths(State, Tests) -> translate_paths(State, Tests, []).
  367. translate_paths(_State, [], Acc) -> lists:reverse(Acc);
  368. translate_paths(State, [{K, _} = Path|Rest], Acc) when K == file; K == dir ->
  369. Apps = rebar_state:project_apps(State),
  370. translate_paths(State, Rest, [translate(State, Apps, Path)|Acc]);
  371. translate_paths(State, [Test|Rest], Acc) ->
  372. translate_paths(State, Rest, [Test|Acc]).
  373. translate(State, [App|Rest], {dir, Dir}) ->
  374. case rebar_file_utils:path_from_ancestor(Dir, rebar_app_info:dir(App)) of
  375. {ok, Path} -> {dir, filename:join([rebar_app_info:out_dir(App), Path])};
  376. {error, badparent} -> translate(State, Rest, {dir, Dir})
  377. end;
  378. translate(State, [App|Rest], {file, FilePath}) ->
  379. Dir = filename:dirname(FilePath),
  380. File = filename:basename(FilePath),
  381. case rebar_file_utils:path_from_ancestor(Dir, rebar_app_info:dir(App)) of
  382. {ok, Path} -> {file, filename:join([rebar_app_info:out_dir(App), Path, File])};
  383. {error, badparent} -> translate(State, Rest, {file, FilePath})
  384. end;
  385. translate(State, [], {dir, Dir}) ->
  386. case rebar_file_utils:path_from_ancestor(Dir, rebar_state:dir(State)) of
  387. {ok, Path} -> {dir, filename:join([rebar_dir:base_dir(State), "extras", Path])};
  388. %% not relative, leave as is
  389. {error, badparent} -> {dir, Dir}
  390. end;
  391. translate(State, [], {file, FilePath}) ->
  392. Dir = filename:dirname(FilePath),
  393. File = filename:basename(FilePath),
  394. case rebar_file_utils:path_from_ancestor(Dir, rebar_state:dir(State)) of
  395. {ok, Path} -> {file, filename:join([rebar_dir:base_dir(State), "extras", Path, File])};
  396. %% not relative, leave as is
  397. {error, badparent} -> {file, FilePath}
  398. end.
  399. maybe_cover_compile(State) ->
  400. {RawOpts, _} = rebar_state:command_parsed_args(State),
  401. State1 = case proplists:get_value(cover, RawOpts, false) of
  402. true -> rebar_state:set(State, cover_enabled, true);
  403. false -> State
  404. end,
  405. rebar_prv_cover:maybe_cover_compile(State1).
  406. maybe_write_coverdata(State) ->
  407. {RawOpts, _} = rebar_state:command_parsed_args(State),
  408. State1 = case proplists:get_value(cover, RawOpts, false) of
  409. true -> rebar_state:set(State, cover_enabled, true);
  410. false -> State
  411. end,
  412. Name = proplists:get_value(cover_export_name, RawOpts, ?PROVIDER),
  413. rebar_prv_cover:maybe_write_coverdata(State1, Name).
  414. handle_results(ok) -> ok;
  415. handle_results(error) ->
  416. {error, unknown_error};
  417. handle_results({error, Reason}) ->
  418. {error, {error_running_tests, Reason}}.
  419. eunit_opts(_State) ->
  420. [{app, undefined, "app", string, help(app)},
  421. {application, undefined, "application", string, help(app)},
  422. {cover, $c, "cover", boolean, help(cover)},
  423. {cover_export_name, undefined, "cover_export_name", string, help(cover_export_name)},
  424. {dir, $d, "dir", string, help(dir)},
  425. {file, $f, "file", string, help(file)},
  426. {module, $m, "module", string, help(module)},
  427. {suite, $s, "suite", string, help(module)},
  428. {verbose, $v, "verbose", boolean, help(verbose)},
  429. {name, undefined, "name", atom, help(name)},
  430. {sname, undefined, "sname", atom, help(sname)},
  431. {setcookie, undefined, "setcookie", atom, help(setcookie)}].
  432. help(app) -> "Comma separated list of application test suites to run. Equivalent to `[{application, App}]`.";
  433. help(cover) -> "Generate cover data. Defaults to false.";
  434. help(cover_export_name) -> "Base name of the coverdata file to write";
  435. help(dir) -> "Comma separated list of dirs to load tests from. Equivalent to `[{dir, Dir}]`.";
  436. help(file) -> "Comma separated list of files to load tests from. Equivalent to `[{file, File}]`.";
  437. help(module) -> "Comma separated list of modules to load tests from. Equivalent to `[{module, Module}]`.";
  438. help(verbose) -> "Verbose output. Defaults to false.";
  439. help(name) -> "Gives a long name to the node";
  440. help(sname) -> "Gives a short name to the node";
  441. help(setcookie) -> "Sets the cookie if the node is distributed".