您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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