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

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

Issue 3035062: Revert 55400 - Cleanup in base. This moves the implementation (and a bunch of... (Closed) Base URL: svn://svn.chromium.org/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
« no previous file with comments | « base/test/run_all_unittests.cc ('k') | base/test/test_suite.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2009 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
15 #include "base/at_exit.h" 13 #include "base/at_exit.h"
16 14 #include "base/base_paths.h"
17 namespace testing { 15 #include "base/debug_on_start.h"
18 class TestInfo; 16 #include "base/debug_util.h"
19 } 17 #include "base/file_path.h"
20 18 #include "base/i18n/icu_util.h"
21 namespace base { 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
29 #if defined(TOOLKIT_USES_GTK)
30 #include <gtk/gtk.h>
31 #endif
32
33 // A command-line flag that makes a test failure always result in a non-zero
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 };
22 58
23 class TestSuite { 59 class TestSuite {
24 public: 60 public:
25 // Match function used by the GetTestCount method. 61 TestSuite(int argc, char** argv) {
26 typedef bool (*TestMatch)(const testing::TestInfo&); 62 base::EnableTerminationOnHeapCorruption();
27 63 CommandLine::Init(argc, argv);
28 TestSuite(int argc, char** argv); 64 testing::InitGoogleTest(&argc, argv);
29 virtual ~TestSuite(); 65 #if defined(TOOLKIT_USES_GTK)
66 g_thread_init(NULL);
67 gtk_init_check(&argc, &argv);
68 #endif // defined(TOOLKIT_USES_GTK)
69 // Don't add additional code to this constructor. Instead add it to
70 // Initialize(). See bug 6436.
71 }
72
73 virtual ~TestSuite() {
74 CommandLine::Reset();
75 }
30 76
31 // Returns true if the test is marked as flaky. 77 // Returns true if the test is marked as flaky.
32 static bool IsMarkedFlaky(const testing::TestInfo& test); 78 static bool IsMarkedFlaky(const testing::TestInfo& test) {
79 return strncmp(test.name(), "FLAKY_", 6) == 0;
80 }
33 81
34 // Returns true if the test is marked as failing. 82 // Returns true if the test is marked as failing.
35 static bool IsMarkedFailing(const testing::TestInfo& test); 83 static bool IsMarkedFailing(const testing::TestInfo& test) {
84 return strncmp(test.name(), "FAILS_", 6) == 0;
85 }
36 86
37 // Returns true if the test is marked as "MAYBE_". 87 // Returns true if the test is marked as "MAYBE_".
38 // When using different prefixes depending on platform, we use MAYBE_ and 88 // When using different prefixes depending on platform, we use MAYBE_ and
39 // preprocessor directives to replace MAYBE_ with the target prefix. 89 // preprocessor directives to replace MAYBE_ with the target prefix.
40 static bool IsMarkedMaybe(const testing::TestInfo& test); 90 static bool IsMarkedMaybe(const testing::TestInfo& test) {
91 return strncmp(test.name(), "MAYBE_", 6) == 0;
92 }
41 93
42 // Returns true if the test failure should be ignored. 94 // Returns true if the test failure should be ignored.
43 static bool ShouldIgnoreFailure(const testing::TestInfo& test); 95 static bool ShouldIgnoreFailure(const testing::TestInfo& test) {
96 if (CommandLine::ForCurrentProcess()->HasSwitch(kStrictFailureHandling))
97 return false;
98 return IsMarkedFlaky(test) || IsMarkedFailing(test);
99 }
44 100
45 // Returns true if the test failed and the failure shouldn't be ignored. 101 // Returns true if the test failed and the failure shouldn't be ignored.
46 static bool NonIgnoredFailures(const testing::TestInfo& test); 102 static bool NonIgnoredFailures(const testing::TestInfo& test) {
103 return test.should_run() && test.result()->Failed() &&
104 !ShouldIgnoreFailure(test);
105 }
47 106
48 // Returns the number of tests where the match function returns true. 107 // Returns the number of tests where the match function returns true.
49 int GetTestCount(TestMatch test_match); 108 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 }
50 123
51 // TODO(phajdan.jr): Enforce isolation for all tests once it's stable. 124 // TODO(phajdan.jr): Enforce isolation for all tests once it's stable.
52 void EnforceTestIsolation(); 125 void EnforceTestIsolation() {
53 126 testing::TestEventListeners& listeners =
54 void CatchMaybeTests(); 127 testing::UnitTest::GetInstance()->listeners();
55 128 listeners.Append(new TestIsolationEnforcer);
56 int Run(); 129 }
57 130
58 // A command-line flag that makes a test failure always result in a non-zero 131 void CatchMaybeTests() {
59 // process exit code. 132 testing::TestEventListeners& listeners =
60 static const char kStrictFailureHandling[]; 133 testing::UnitTest::GetInstance()->listeners();
134 listeners.Append(new MaybeTestDisabler);
135 }
136
137 // Don't add additional code to this method. Instead add it to
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 }
61 178
62 protected: 179 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
63 // By default fatal log messages (e.g. from DCHECKs) result in error dialogs 190 // By default fatal log messages (e.g. from DCHECKs) result in error dialogs
64 // which gum up buildbots. Use a minimalistic assert handler which just 191 // which gum up buildbots. Use a minimalistic assert handler which just
65 // terminates the process. 192 // terminates the process.
66 static void UnitTestAssertHandler(const std::string& str); 193 static void UnitTestAssertHandler(const std::string& str) {
194 RAW_LOG(FATAL, str.c_str());
195 }
67 196
68 // Disable crash dialogs so that it doesn't gum up the buildbot 197 // Disable crash dialogs so that it doesn't gum up the buildbot
69 virtual void SuppressErrorDialogs(); 198 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 }
70 210
71 // Override these for custom initialization and shutdown handling. Use these 211 // Override these for custom initialization and shutdown handling. Use these
72 // instead of putting complex code in your constructor/destructor. 212 // instead of putting complex code in your constructor/destructor.
73 213
74 virtual void Initialize(); 214 virtual void Initialize() {
75 virtual void Shutdown(); 215 // Initialize logging.
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 }
76 257
77 // Make sure that we setup an AtExitManager so Singleton objects will be 258 // Make sure that we setup an AtExitManager so Singleton objects will be
78 // destroyed. 259 // destroyed.
79 base::AtExitManager at_exit_manager_; 260 base::AtExitManager at_exit_manager_;
80
81 DISALLOW_COPY_AND_ASSIGN(TestSuite);
82 }; 261 };
83 262
84 } // namespace base
85
86 // TODO(brettw) remove this. This is a temporary hack to allow WebKit to compile
87 // until we can update it to use "base::" (preventing a two-sided patch).
88 using base::TestSuite;
89
90 #endif // BASE_TEST_TEST_SUITE_H_ 263 #endif // BASE_TEST_TEST_SUITE_H_
OLDNEW
« no previous file with comments | « base/test/run_all_unittests.cc ('k') | base/test/test_suite.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698