Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(282)

Side by Side Diff: base/test/test_suite.h

Issue 3026055: Cleanup in base. This moves the implementation (and a bunch of header file... (Closed) Base URL: svn://chrome-svn/chrome/trunk/src/
Patch Set: Created 10 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2009 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #ifndef BASE_TEST_TEST_SUITE_H_ 5 #ifndef BASE_TEST_TEST_SUITE_H_
6 #define BASE_TEST_TEST_SUITE_H_ 6 #define BASE_TEST_TEST_SUITE_H_
7 #pragma once 7 #pragma once
8 8
9 // Defines a basic test suite framework for running gtest based tests. You can 9 // Defines a basic test suite framework for running gtest based tests. You can
10 // instantiate this class in your main function and call its Run method to run 10 // instantiate this class in your main function and call its Run method to run
11 // any gtest based tests that are linked into your executable. 11 // any gtest based tests that are linked into your executable.
12 12
13 #include <string>
14
13 #include "base/at_exit.h" 15 #include "base/at_exit.h"
14 #include "base/base_paths.h"
15 #include "base/debug_on_start.h"
16 #include "base/debug_util.h"
17 #include "base/file_path.h"
18 #include "base/i18n/icu_util.h"
19 #include "base/multiprocess_test.h"
20 #include "base/nss_util.h"
21 #include "base/path_service.h"
22 #include "base/process_util.h"
23 #include "base/scoped_nsautorelease_pool.h"
24 #include "base/scoped_ptr.h"
25 #include "base/time.h"
26 #include "testing/gtest/include/gtest/gtest.h"
27 #include "testing/multiprocess_func_list.h"
28 16
29 #if defined(OS_POSIX) && !defined(OS_MACOSX) 17 namespace testing {
30 #include <gtk/gtk.h> 18 class TestInfo;
31 #endif 19 }
32 20
33 // A command-line flag that makes a test failure always result in a non-zero 21 namespace base {
34 // process exit code.
35 const char kStrictFailureHandling[] = "strict_failure_handling";
36
37 // Match function used by the GetTestCount method.
38 typedef bool (*TestMatch)(const testing::TestInfo&);
39
40 // By setting up a shadow AtExitManager, this test event listener ensures that
41 // no state is carried between tests (like singletons, lazy instances, etc).
42 // Of course it won't help if the code under test corrupts memory.
43 class TestIsolationEnforcer : public testing::EmptyTestEventListener {
44 public:
45 virtual void OnTestStart(const testing::TestInfo& test_info) {
46 ASSERT_FALSE(exit_manager_.get());
47 exit_manager_.reset(new base::ShadowingAtExitManager());
48 }
49
50 virtual void OnTestEnd(const testing::TestInfo& test_info) {
51 ASSERT_TRUE(exit_manager_.get());
52 exit_manager_.reset();
53 }
54
55 private:
56 scoped_ptr<base::ShadowingAtExitManager> exit_manager_;
57 };
58 22
59 class TestSuite { 23 class TestSuite {
60 public: 24 public:
61 TestSuite(int argc, char** argv) { 25 // Match function used by the GetTestCount method.
62 base::EnableTerminationOnHeapCorruption(); 26 typedef bool (*TestMatch)(const testing::TestInfo&);
63 CommandLine::Init(argc, argv);
64 testing::InitGoogleTest(&argc, argv);
65 #if defined(OS_POSIX) && !defined(OS_MACOSX)
66 g_thread_init(NULL);
67 gtk_init_check(&argc, &argv);
68 #endif // defined(OS_LINUX)
69 // Don't add additional code to this constructor. Instead add it to
70 // Initialize(). See bug 6436.
71 }
72 27
73 virtual ~TestSuite() { 28 TestSuite(int argc, char** argv);
74 CommandLine::Reset(); 29 virtual ~TestSuite();
75 }
76 30
77 // Returns true if the test is marked as flaky. 31 // Returns true if the test is marked as flaky.
78 static bool IsMarkedFlaky(const testing::TestInfo& test) { 32 static bool IsMarkedFlaky(const testing::TestInfo& test);
79 return strncmp(test.name(), "FLAKY_", 6) == 0;
80 }
81 33
82 // Returns true if the test is marked as failing. 34 // Returns true if the test is marked as failing.
83 static bool IsMarkedFailing(const testing::TestInfo& test) { 35 static bool IsMarkedFailing(const testing::TestInfo& test);
84 return strncmp(test.name(), "FAILS_", 6) == 0;
85 }
86 36
87 // Returns true if the test is marked as "MAYBE_". 37 // Returns true if the test is marked as "MAYBE_".
88 // When using different prefixes depending on platform, we use MAYBE_ and 38 // When using different prefixes depending on platform, we use MAYBE_ and
89 // preprocessor directives to replace MAYBE_ with the target prefix. 39 // preprocessor directives to replace MAYBE_ with the target prefix.
90 static bool IsMarkedMaybe(const testing::TestInfo& test) { 40 static bool IsMarkedMaybe(const testing::TestInfo& test);
91 return strncmp(test.name(), "MAYBE_", 6) == 0;
92 }
93 41
94 // Returns true if the test failure should be ignored. 42 // Returns true if the test failure should be ignored.
95 static bool ShouldIgnoreFailure(const testing::TestInfo& test) { 43 static bool ShouldIgnoreFailure(const testing::TestInfo& test);
96 if (CommandLine::ForCurrentProcess()->HasSwitch(kStrictFailureHandling))
97 return false;
98 return IsMarkedFlaky(test) || IsMarkedFailing(test);
99 }
100 44
101 // Returns true if the test failed and the failure shouldn't be ignored. 45 // Returns true if the test failed and the failure shouldn't be ignored.
102 static bool NonIgnoredFailures(const testing::TestInfo& test) { 46 static bool NonIgnoredFailures(const testing::TestInfo& test);
103 return test.should_run() && test.result()->Failed() &&
104 !ShouldIgnoreFailure(test);
105 }
106 47
107 // Returns the number of tests where the match function returns true. 48 // Returns the number of tests where the match function returns true.
108 int GetTestCount(TestMatch test_match) { 49 int GetTestCount(TestMatch test_match);
109 testing::UnitTest* instance = testing::UnitTest::GetInstance();
110 int count = 0;
111
112 for (int i = 0; i < instance->total_test_case_count(); ++i) {
113 const testing::TestCase& test_case = *instance->GetTestCase(i);
114 for (int j = 0; j < test_case.total_test_count(); ++j) {
115 if (test_match(*test_case.GetTestInfo(j))) {
116 count++;
117 }
118 }
119 }
120
121 return count;
122 }
123 50
124 // TODO(phajdan.jr): Enforce isolation for all tests once it's stable. 51 // TODO(phajdan.jr): Enforce isolation for all tests once it's stable.
125 void EnforceTestIsolation() { 52 void EnforceTestIsolation();
126 testing::TestEventListeners& listeners =
127 testing::UnitTest::GetInstance()->listeners();
128 listeners.Append(new TestIsolationEnforcer);
129 }
130 53
131 void CatchMaybeTests() { 54 void CatchMaybeTests();
132 testing::TestEventListeners& listeners =
133 testing::UnitTest::GetInstance()->listeners();
134 listeners.Append(new MaybeTestDisabler);
135 }
136 55
137 // Don't add additional code to this method. Instead add it to 56 int Run();
138 // Initialize(). See bug 6436.
139 int Run() {
140 base::ScopedNSAutoreleasePool scoped_pool;
141
142 Initialize();
143 std::string client_func =
144 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
145 kRunClientProcess);
146 // Check to see if we are being run as a client process.
147 if (!client_func.empty())
148 return multi_process_function_list::InvokeChildProcessTest(client_func);
149 int result = RUN_ALL_TESTS();
150
151 // If there are failed tests, see if we should ignore the failures.
152 if (result != 0 && GetTestCount(&TestSuite::NonIgnoredFailures) == 0)
153 result = 0;
154
155 // Display the number of flaky tests.
156 int flaky_count = GetTestCount(&TestSuite::IsMarkedFlaky);
157 if (flaky_count) {
158 printf(" YOU HAVE %d FLAKY %s\n\n", flaky_count,
159 flaky_count == 1 ? "TEST" : "TESTS");
160 }
161
162 // Display the number of tests with ignored failures (FAILS).
163 int failing_count = GetTestCount(&TestSuite::IsMarkedFailing);
164 if (failing_count) {
165 printf(" YOU HAVE %d %s with ignored failures (FAILS prefix)\n\n",
166 failing_count, failing_count == 1 ? "test" : "tests");
167 }
168
169 // This MUST happen before Shutdown() since Shutdown() tears down
170 // objects (such as NotificationService::current()) that Cocoa
171 // objects use to remove themselves as observers.
172 scoped_pool.Recycle();
173
174 Shutdown();
175
176 return result;
177 }
178 57
179 protected: 58 protected:
180 class MaybeTestDisabler : public testing::EmptyTestEventListener {
181 public:
182 virtual void OnTestStart(const testing::TestInfo& test_info) {
183 ASSERT_FALSE(TestSuite::IsMarkedMaybe(test_info))
184 << "Probably the OS #ifdefs don't include all of the necessary "
185 "platforms.\nPlease ensure that no tests have the MAYBE_ prefix "
186 "after the code is preprocessed.";
187 }
188 };
189
190 // By default fatal log messages (e.g. from DCHECKs) result in error dialogs 59 // By default fatal log messages (e.g. from DCHECKs) result in error dialogs
191 // which gum up buildbots. Use a minimalistic assert handler which just 60 // which gum up buildbots. Use a minimalistic assert handler which just
192 // terminates the process. 61 // terminates the process.
193 static void UnitTestAssertHandler(const std::string& str) { 62 static void UnitTestAssertHandler(const std::string& str);
194 RAW_LOG(FATAL, str.c_str());
195 }
196 63
197 // Disable crash dialogs so that it doesn't gum up the buildbot 64 // Disable crash dialogs so that it doesn't gum up the buildbot
198 virtual void SuppressErrorDialogs() { 65 virtual void SuppressErrorDialogs();
199 #if defined(OS_WIN)
200 UINT new_flags = SEM_FAILCRITICALERRORS |
201 SEM_NOGPFAULTERRORBOX |
202 SEM_NOOPENFILEERRORBOX;
203
204 // Preserve existing error mode, as discussed at
205 // http://blogs.msdn.com/oldnewthing/archive/2004/07/27/198410.aspx
206 UINT existing_flags = SetErrorMode(new_flags);
207 SetErrorMode(existing_flags | new_flags);
208 #endif // defined(OS_WIN)
209 }
210 66
211 // Override these for custom initialization and shutdown handling. Use these 67 // Override these for custom initialization and shutdown handling. Use these
212 // instead of putting complex code in your constructor/destructor. 68 // instead of putting complex code in your constructor/destructor.
213 69
214 virtual void Initialize() { 70 virtual void Initialize();
215 // Initialize logging. 71 virtual void Shutdown();
216 FilePath exe;
217 PathService::Get(base::FILE_EXE, &exe);
218 FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL("log"));
219 logging::InitLogging(log_filename.value().c_str(),
220 logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
221 logging::LOCK_LOG_FILE,
222 logging::DELETE_OLD_LOG_FILE);
223 // We want process and thread IDs because we may have multiple processes.
224 // Note: temporarily enabled timestamps in an effort to catch bug 6361.
225 logging::SetLogItems(true, true, true, true);
226
227 CHECK(base::EnableInProcessStackDumping());
228 #if defined(OS_WIN)
229 // Make sure we run with high resolution timer to minimize differences
230 // between production code and test code.
231 base::Time::EnableHighResolutionTimer(true);
232 #endif // defined(OS_WIN)
233
234 // In some cases, we do not want to see standard error dialogs.
235 if (!DebugUtil::BeingDebugged() &&
236 !CommandLine::ForCurrentProcess()->HasSwitch("show-error-dialogs")) {
237 SuppressErrorDialogs();
238 DebugUtil::SuppressDialogs();
239 logging::SetLogAssertHandler(UnitTestAssertHandler);
240 }
241
242 icu_util::Initialize();
243
244 #if defined(USE_NSS)
245 // Trying to repeatedly initialize and cleanup NSS and NSPR may result in
246 // a deadlock. Such repeated initialization will happen when using test
247 // isolation. Prevent problems by initializing NSS here, so that the cleanup
248 // will be done only on process exit.
249 base::EnsureNSSInit();
250 #endif // defined(USE_NSS)
251
252 CatchMaybeTests();
253 }
254
255 virtual void Shutdown() {
256 }
257 72
258 // Make sure that we setup an AtExitManager so Singleton objects will be 73 // Make sure that we setup an AtExitManager so Singleton objects will be
259 // destroyed. 74 // destroyed.
260 base::AtExitManager at_exit_manager_; 75 base::AtExitManager at_exit_manager_;
76
77 DISALLOW_COPY_AND_ASSIGN(TestSuite);
261 }; 78 };
262 79
80 } // namespace base
81
263 #endif // BASE_TEST_TEST_SUITE_H_ 82 #endif // BASE_TEST_TEST_SUITE_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698