test_launcher.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_TEST_LAUNCHER_TEST_LAUNCHER_H_
  5. #define BASE_TEST_LAUNCHER_TEST_LAUNCHER_H_
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <memory>
  9. #include <set>
  10. #include <string>
  11. #include <vector>
  12. #include "base/command_line.h"
  13. #include "base/compiler_specific.h"
  14. #include "base/macros.h"
  15. #include "base/process/launch.h"
  16. #include "base/test/gtest_util.h"
  17. #include "base/test/launcher/test_result.h"
  18. #include "base/test/launcher/test_results_tracker.h"
  19. #include "base/threading/thread_checker.h"
  20. #include "base/time/time.h"
  21. #include "base/timer/timer.h"
  22. #include "build/build_config.h"
  23. namespace base {
  24. // Constants for GTest command-line flags.
  25. extern const char kGTestFilterFlag[];
  26. extern const char kGTestFlagfileFlag[];
  27. extern const char kGTestHelpFlag[];
  28. extern const char kGTestListTestsFlag[];
  29. extern const char kGTestRepeatFlag[];
  30. extern const char kGTestRunDisabledTestsFlag[];
  31. extern const char kGTestOutputFlag[];
  32. extern const char kGTestShuffleFlag[];
  33. extern const char kGTestRandomSeedFlag[];
  34. extern const char kIsolatedScriptRunDisabledTestsFlag[];
  35. extern const char kIsolatedScriptTestFilterFlag[];
  36. extern const char kIsolatedScriptTestRepeatFlag[];
  37. // Interface for use with LaunchTests that abstracts away exact details
  38. // which tests and how are run.
  39. class TestLauncherDelegate {
  40. public:
  41. // Called to get names of tests available for running. The delegate
  42. // must put the result in |output| and return true on success.
  43. virtual bool GetTests(std::vector<TestIdentifier>* output) = 0;
  44. // Additional delegate TestResult processing.
  45. virtual void ProcessTestResults(std::vector<TestResult>& test_results,
  46. TimeDelta elapsed_time) {}
  47. // Called to get the command line for the specified tests.
  48. // |output_file_| is populated with the path to the result file, and must
  49. // be inside |temp_dir|.
  50. virtual CommandLine GetCommandLine(const std::vector<std::string>& test_names,
  51. const FilePath& temp_dir,
  52. FilePath* output_file) = 0;
  53. // Invoked when a test process exceeds its runtime, immediately before it is
  54. // terminated. |command_line| is the command line used to launch the process.
  55. // NOTE: this method is invoked on the thread the process is launched on.
  56. virtual void OnTestTimedOut(const CommandLine& cmd_line) {}
  57. // Returns the delegate specific wrapper for command line.
  58. // If it is not empty, it is prepended to the final command line.
  59. virtual std::string GetWrapper() = 0;
  60. // Returns the delegate specific flags for launch options.
  61. // The flags are specified in LaunchChildGTestProcessFlags.
  62. virtual int GetLaunchOptions() = 0;
  63. // Returns the delegate specific timeout per test.
  64. virtual TimeDelta GetTimeout() = 0;
  65. // Returns the delegate specific batch size.
  66. virtual size_t GetBatchSize() = 0;
  67. // Returns true if test should run.
  68. virtual bool ShouldRunTest(const TestIdentifier& test);
  69. protected:
  70. virtual ~TestLauncherDelegate();
  71. };
  72. // Launches tests using a TestLauncherDelegate.
  73. class TestLauncher {
  74. public:
  75. // Flags controlling behavior of LaunchChildGTestProcess.
  76. enum LaunchChildGTestProcessFlags {
  77. // Allows usage of job objects on Windows. Helps properly clean up child
  78. // processes.
  79. USE_JOB_OBJECTS = (1 << 0),
  80. // Allows breakaway from job on Windows. May result in some child processes
  81. // not being properly terminated after launcher dies if these processes
  82. // fail to cooperate.
  83. ALLOW_BREAKAWAY_FROM_JOB = (1 << 1),
  84. };
  85. // Enum for subprocess stdio redirect.
  86. enum StdioRedirect { AUTO, ALWAYS, NEVER };
  87. struct LaunchOptions {
  88. LaunchOptions();
  89. LaunchOptions(const LaunchOptions& other);
  90. ~LaunchOptions();
  91. int flags = 0;
  92. // These mirror values in base::LaunchOptions, see it for details.
  93. #if defined(OS_WIN)
  94. base::LaunchOptions::Inherit inherit_mode =
  95. base::LaunchOptions::Inherit::kSpecific;
  96. base::HandlesToInheritVector handles_to_inherit;
  97. #else
  98. FileHandleMappingVector fds_to_remap;
  99. #endif
  100. };
  101. // Constructor. |parallel_jobs| is the limit of simultaneous parallel test
  102. // jobs. |retry_limit| is the default limit of retries for bots or all tests.
  103. TestLauncher(TestLauncherDelegate* launcher_delegate,
  104. size_t parallel_jobs,
  105. size_t retry_limit = 1U);
  106. // virtual to mock in testing.
  107. virtual ~TestLauncher();
  108. // Runs the launcher. Must be called at most once.
  109. // command_line is null by default.
  110. // if null, uses command line for current process.
  111. bool Run(CommandLine* command_line = nullptr) WARN_UNUSED_RESULT;
  112. // Launches a child process (assumed to be gtest-based binary) which runs
  113. // tests indicated by |test_names|.
  114. // |task_runner| is used to post results back to the launcher on the main
  115. // thread. |task_temp_dir| is used for child process files such as user data,
  116. // result file, and flag_file. |child_temp_dir|, if not empty, specifies a
  117. // directory (within task_temp_dir) that the child process will use as its
  118. // process-wide temporary directory.
  119. // virtual to mock in testing.
  120. virtual void LaunchChildGTestProcess(
  121. scoped_refptr<TaskRunner> task_runner,
  122. const std::vector<std::string>& test_names,
  123. const FilePath& task_temp_dir,
  124. const FilePath& child_temp_dir);
  125. // Called when a test has finished running.
  126. void OnTestFinished(const TestResult& result);
  127. // Returns true if child test processes should have dedicated temporary
  128. // directories.
  129. static constexpr bool SupportsPerChildTempDirs() {
  130. #if defined(OS_WIN)
  131. return true;
  132. #else
  133. // TODO(https://crbug.com/1038857): Enable for macOS, Linux, and Fuchsia.
  134. return false;
  135. #endif
  136. }
  137. private:
  138. bool Init(CommandLine* command_line) WARN_UNUSED_RESULT;
  139. // Gets tests from the delegate, and converts to TestInfo objects.
  140. // Catches and logs uninstantiated parameterized tests.
  141. // Returns false if delegate fails to return tests.
  142. bool InitTests();
  143. // Some of the TestLauncherDelegate implementations don't call into gtest
  144. // until they've already split into test-specific processes. This results
  145. // in gtest's native shuffle implementation attempting to shuffle one test.
  146. // Shuffling the list of tests in the test launcher (before the delegate
  147. // gets involved) ensures that the entire shard is shuffled.
  148. bool ShuffleTests(CommandLine* command_line);
  149. // Move all PRE_ tests prior to the final test in order.
  150. // Validate tests names. This includes no name conflict between tests
  151. // without DISABLED_ prefix, and orphaned PRE_ tests.
  152. // Add all tests and disabled tests names to result tracker.
  153. // Filter Disabled tests if not flagged to run.
  154. // Returns false if any violation is found.
  155. bool ProcessAndValidateTests();
  156. // Runs all tests in current iteration.
  157. void RunTests();
  158. // Print test names that almost match a filter (matches *<filter>*).
  159. void PrintFuzzyMatchingTestNames();
  160. // Retry to run tests that failed during RunTests.
  161. // Returns false if retry still fails or unable to start.
  162. bool RunRetryTests();
  163. void CombinePositiveTestFilters(std::vector<std::string> filter_a,
  164. std::vector<std::string> filter_b);
  165. // Rest counters, retry tests list, and test result tracker.
  166. void OnTestIterationStart();
  167. #if defined(OS_POSIX)
  168. void OnShutdownPipeReadable();
  169. #endif
  170. // Saves test results summary as JSON if requested from command line.
  171. void MaybeSaveSummaryAsJSON(const std::vector<std::string>& additional_tags);
  172. // Called when a test iteration is finished.
  173. void OnTestIterationFinished();
  174. // Called by the delay timer when no output was made for a while.
  175. void OnOutputTimeout();
  176. // Creates and starts a ThreadPoolInstance with |num_parallel_jobs| dedicated
  177. // to foreground blocking tasks (corresponds to the traits used to launch and
  178. // wait for child processes). virtual to mock in testing.
  179. virtual void CreateAndStartThreadPool(int num_parallel_jobs);
  180. // Callback to receive result of a test.
  181. // |result_file| is a path to xml file written by child process.
  182. // It contains information about test and failed
  183. // EXPECT/ASSERT/DCHECK statements. Test launcher parses that
  184. // file to get additional information about test run (status,
  185. // error-messages, stack-traces and file/line for failures).
  186. // |leaked_items| is the number of files and/or directories remaining in the
  187. // child process's temporary directory upon its termination.
  188. void ProcessTestResults(const std::vector<std::string>& test_names,
  189. const FilePath& result_file,
  190. const std::string& output,
  191. TimeDelta elapsed_time,
  192. int exit_code,
  193. bool was_timeout,
  194. int leaked_items);
  195. std::vector<std::string> CollectTests();
  196. // Make sure we don't accidentally call the wrong methods e.g. on the worker
  197. // pool thread. Should be the first member so that it's destroyed last: when
  198. // destroying other members, especially the worker pool, we may check the code
  199. // is running on the correct thread.
  200. ThreadChecker thread_checker_;
  201. TestLauncherDelegate* launcher_delegate_;
  202. // Support for outer sharding, just like gtest does.
  203. int32_t total_shards_; // Total number of outer shards, at least one.
  204. int32_t shard_index_; // Index of shard the launcher is to run.
  205. int cycles_; // Number of remaining test iterations, or -1 for infinite.
  206. // Test filters (empty means no filter).
  207. bool has_at_least_one_positive_filter_;
  208. std::vector<std::string> positive_test_filter_;
  209. std::vector<std::string> negative_test_filter_;
  210. // Class to encapsulate gtest information.
  211. class TestInfo;
  212. // Tests to use (cached result of TestLauncherDelegate::GetTests).
  213. std::vector<TestInfo> tests_;
  214. // Threshold for number of broken tests.
  215. size_t broken_threshold_;
  216. // Number of tests started in this iteration.
  217. size_t test_started_count_;
  218. // Number of tests finished in this iteration.
  219. size_t test_finished_count_;
  220. // Number of tests successfully finished in this iteration.
  221. size_t test_success_count_;
  222. // Number of tests either timing out or having an unknown result,
  223. // likely indicating a more systemic problem if widespread.
  224. size_t test_broken_count_;
  225. // Maximum number of retries per iteration.
  226. size_t retry_limit_;
  227. // If true will not early exit nor skip retries even if too many tests are
  228. // broken.
  229. bool force_run_broken_tests_;
  230. // Tests to retry in this iteration.
  231. std::unordered_set<std::string> tests_to_retry_;
  232. TestResultsTracker results_tracker_;
  233. // Watchdog timer to make sure we do not go without output for too long.
  234. DelayTimer watchdog_timer_;
  235. // Number of jobs to run in parallel.
  236. size_t parallel_jobs_;
  237. // Switch to control tests stdio :{auto, always, never}
  238. StdioRedirect print_test_stdio_;
  239. // Skip disabled tests unless explicitly requested.
  240. bool skip_diabled_tests_;
  241. // Stop test iterations due to failure.
  242. bool stop_on_failure_;
  243. // Path to JSON summary result file.
  244. FilePath summary_path_;
  245. // Path to trace file.
  246. FilePath trace_path_;
  247. // redirect stdio of subprocess
  248. bool redirect_stdio_;
  249. // Number of times all tests should be repeated during each iteration.
  250. // 1 if gtest_repeat is not specified or gtest_break_on_failure is specified.
  251. // Otherwise it matches gtest_repeat value.
  252. int repeats_per_iteration_ = 1;
  253. DISALLOW_COPY_AND_ASSIGN(TestLauncher);
  254. };
  255. // Return the number of parallel jobs to use, or 0U in case of error.
  256. size_t NumParallelJobs(unsigned int cores_per_job);
  257. // Extract part from |full_output| that applies to |result|.
  258. std::string GetTestOutputSnippet(const TestResult& result,
  259. const std::string& full_output);
  260. } // namespace base
  261. #endif // BASE_TEST_LAUNCHER_TEST_LAUNCHER_H_