• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
5 #ifndef BASE_TEST_LAUNCHER_TEST_LAUNCHER_H_
6 #define BASE_TEST_LAUNCHER_TEST_LAUNCHER_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <memory>
12 #include <set>
13 #include <string>
14 #include <vector>
15 
16 #include "base/compiler_specific.h"
17 #include "base/macros.h"
18 #include "base/process/launch.h"
19 #include "base/test/gtest_util.h"
20 #include "base/test/launcher/test_result.h"
21 #include "base/test/launcher/test_results_tracker.h"
22 #include "base/threading/thread_checker.h"
23 #include "base/time/time.h"
24 #include "base/timer/timer.h"
25 #include "build/build_config.h"
26 
27 namespace base {
28 
29 class CommandLine;
30 struct LaunchOptions;
31 class TestLauncher;
32 
33 // Constants for GTest command-line flags.
34 extern const char kGTestFilterFlag[];
35 extern const char kGTestFlagfileFlag[];
36 extern const char kGTestHelpFlag[];
37 extern const char kGTestListTestsFlag[];
38 extern const char kGTestRepeatFlag[];
39 extern const char kGTestRunDisabledTestsFlag[];
40 extern const char kGTestOutputFlag[];
41 extern const char kGTestShuffleFlag[];
42 extern const char kGTestRandomSeedFlag[];
43 
44 // Interface for use with LaunchTests that abstracts away exact details
45 // which tests and how are run.
46 class TestLauncherDelegate {
47  public:
48   // Called to get names of tests available for running. The delegate
49   // must put the result in |output| and return true on success.
50   virtual bool GetTests(std::vector<TestIdentifier>* output) = 0;
51 
52   // Called before a test is considered for running. If it returns false,
53   // the test is not run. If it returns true, the test will be run provided
54   // it is part of the current shard.
55   virtual bool ShouldRunTest(const std::string& test_case_name,
56                              const std::string& test_name) = 0;
57 
58   // Called to make the delegate run the specified tests. The delegate must
59   // return the number of actual tests it's going to run (can be smaller,
60   // equal to, or larger than size of |test_names|). It must also call
61   // |test_launcher|'s OnTestFinished method once per every run test,
62   // regardless of its success.
63   virtual size_t RunTests(TestLauncher* test_launcher,
64                           const std::vector<std::string>& test_names) = 0;
65 
66   // Called to make the delegate retry the specified tests. The delegate must
67   // return the number of actual tests it's going to retry (can be smaller,
68   // equal to, or larger than size of |test_names|). It must also call
69   // |test_launcher|'s OnTestFinished method once per every retried test,
70   // regardless of its success.
71   virtual size_t RetryTests(TestLauncher* test_launcher,
72                             const std::vector<std::string>& test_names) = 0;
73 
74  protected:
75   virtual ~TestLauncherDelegate();
76 };
77 
78 // An observer of child process lifetime events generated by
79 // LaunchChildGTestProcess.
80 class ProcessLifetimeObserver {
81  public:
82   virtual ~ProcessLifetimeObserver() = default;
83 
84   // Invoked once the child process is started. |handle| is a handle to the
85   // child process and |id| is its pid. NOTE: this method is invoked on the
86   // thread the process is launched on immediately after it is launched. The
87   // caller owns the ProcessHandle.
OnLaunched(ProcessHandle handle,ProcessId id)88   virtual void OnLaunched(ProcessHandle handle, ProcessId id) {}
89 
90   // Invoked when a test process exceeds its runtime, immediately before it is
91   // terminated. |command_line| is the command line used to launch the process.
92   // NOTE: this method is invoked on the thread the process is launched on.
OnTimedOut(const CommandLine & command_line)93   virtual void OnTimedOut(const CommandLine& command_line) {}
94 
95   // Invoked after a child process finishes, reporting the process |exit_code|,
96   // child process |elapsed_time|, whether or not the process was terminated as
97   // a result of a timeout, and the output of the child (stdout and stderr
98   // together). NOTE: this method is invoked on the same thread as
99   // LaunchChildGTestProcess.
OnCompleted(int exit_code,TimeDelta elapsed_time,bool was_timeout,const std::string & output)100   virtual void OnCompleted(int exit_code,
101                            TimeDelta elapsed_time,
102                            bool was_timeout,
103                            const std::string& output) {}
104 
105  protected:
106   ProcessLifetimeObserver() = default;
107 
108  private:
109   DISALLOW_COPY_AND_ASSIGN(ProcessLifetimeObserver);
110 };
111 
112 // Launches tests using a TestLauncherDelegate.
113 class TestLauncher {
114  public:
115   // Flags controlling behavior of LaunchChildGTestProcess.
116   enum LaunchChildGTestProcessFlags {
117     // Allows usage of job objects on Windows. Helps properly clean up child
118     // processes.
119     USE_JOB_OBJECTS = (1 << 0),
120 
121     // Allows breakaway from job on Windows. May result in some child processes
122     // not being properly terminated after launcher dies if these processes
123     // fail to cooperate.
124     ALLOW_BREAKAWAY_FROM_JOB = (1 << 1),
125   };
126 
127   struct LaunchOptions {
128     LaunchOptions();
129     LaunchOptions(const LaunchOptions& other);
130     ~LaunchOptions();
131 
132     int flags = 0;
133     // These mirror values in base::LaunchOptions, see it for details.
134 #if defined(OS_WIN)
135     base::LaunchOptions::Inherit inherit_mode =
136         base::LaunchOptions::Inherit::kSpecific;
137     base::HandlesToInheritVector handles_to_inherit;
138 #else
139     FileHandleMappingVector fds_to_remap;
140 #endif
141   };
142 
143   // Constructor. |parallel_jobs| is the limit of simultaneous parallel test
144   // jobs.
145   TestLauncher(TestLauncherDelegate* launcher_delegate, size_t parallel_jobs);
146   ~TestLauncher();
147 
148   // Runs the launcher. Must be called at most once.
149   bool Run() WARN_UNUSED_RESULT;
150 
151   // Launches a child process (assumed to be gtest-based binary) using
152   // |command_line|. If |wrapper| is not empty, it is prepended to the final
153   // command line. |observer|, if not null, is used to convey process lifetime
154   // events to the caller. |observer| is destroyed after its OnCompleted
155   // method is invoked.
156   void LaunchChildGTestProcess(
157       const CommandLine& command_line,
158       const std::string& wrapper,
159       TimeDelta timeout,
160       const LaunchOptions& options,
161       std::unique_ptr<ProcessLifetimeObserver> observer);
162 
163   // Called when a test has finished running.
164   void OnTestFinished(const TestResult& result);
165 
166  private:
167   bool Init() WARN_UNUSED_RESULT;
168 
169   // Runs all tests in current iteration.
170   void RunTests();
171 
172   void CombinePositiveTestFilters(std::vector<std::string> filter_a,
173                                   std::vector<std::string> filter_b);
174 
175   void RunTestIteration();
176 
177 #if defined(OS_POSIX)
178   void OnShutdownPipeReadable();
179 #endif
180 
181   // Saves test results summary as JSON if requested from command line.
182   void MaybeSaveSummaryAsJSON(const std::vector<std::string>& additional_tags);
183 
184   // Called when a test iteration is finished.
185   void OnTestIterationFinished();
186 
187   // Called by the delay timer when no output was made for a while.
188   void OnOutputTimeout();
189 
190   // Make sure we don't accidentally call the wrong methods e.g. on the worker
191   // pool thread.  Should be the first member so that it's destroyed last: when
192   // destroying other members, especially the worker pool, we may check the code
193   // is running on the correct thread.
194   ThreadChecker thread_checker_;
195 
196   TestLauncherDelegate* launcher_delegate_;
197 
198   // Support for outer sharding, just like gtest does.
199   int32_t total_shards_;  // Total number of outer shards, at least one.
200   int32_t shard_index_;   // Index of shard the launcher is to run.
201 
202   int cycles_;  // Number of remaining test iterations, or -1 for infinite.
203 
204   // Test filters (empty means no filter).
205   bool has_at_least_one_positive_filter_;
206   std::vector<std::string> positive_test_filter_;
207   std::vector<std::string> negative_test_filter_;
208 
209   // Tests to use (cached result of TestLauncherDelegate::GetTests).
210   std::vector<TestIdentifier> tests_;
211 
212   // Number of tests found in this binary.
213   size_t test_found_count_;
214 
215   // Number of tests started in this iteration.
216   size_t test_started_count_;
217 
218   // Number of tests finished in this iteration.
219   size_t test_finished_count_;
220 
221   // Number of tests successfully finished in this iteration.
222   size_t test_success_count_;
223 
224   // Number of tests either timing out or having an unknown result,
225   // likely indicating a more systemic problem if widespread.
226   size_t test_broken_count_;
227 
228   // Number of retries in this iteration.
229   size_t retry_count_;
230 
231   // Maximum number of retries per iteration.
232   size_t retry_limit_;
233 
234   // If true will not early exit nor skip retries even if too many tests are
235   // broken.
236   bool force_run_broken_tests_;
237 
238   // Tests to retry in this iteration.
239   std::set<std::string> tests_to_retry_;
240 
241   // Result to be returned from Run.
242   bool run_result_;
243 
244   // Support for test shuffling, just like gtest does.
245   bool shuffle_;
246   uint32_t shuffle_seed_;
247 
248   TestResultsTracker results_tracker_;
249 
250   // Watchdog timer to make sure we do not go without output for too long.
251   DelayTimer watchdog_timer_;
252 
253   // Number of jobs to run in parallel.
254   size_t parallel_jobs_;
255 
256   DISALLOW_COPY_AND_ASSIGN(TestLauncher);
257 };
258 
259 // Return the number of parallel jobs to use, or 0U in case of error.
260 size_t NumParallelJobs();
261 
262 // Extract part from |full_output| that applies to |result|.
263 std::string GetTestOutputSnippet(const TestResult& result,
264                                  const std::string& full_output);
265 
266 }  // namespace base
267 
268 #endif  // BASE_TEST_LAUNCHER_TEST_LAUNCHER_H_
269