Reland "Don't refcount tracking id -> slot id mapping."
[chromium-blink-merge.git] / base / test / test_suite.cc
blob903e93ea07a7b8aba49e66f49603dcda88bdae89
1 // Copyright (c) 2012 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.
5 #include "base/test/test_suite.h"
7 #include "base/at_exit.h"
8 #include "base/base_paths.h"
9 #include "base/base_switches.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/debug/debugger.h"
13 #include "base/debug/stack_trace.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/i18n/icu_util.h"
17 #include "base/logging.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/path_service.h"
20 #include "base/process/memory.h"
21 #include "base/test/gtest_xml_util.h"
22 #include "base/test/launcher/unit_test_launcher.h"
23 #include "base/test/multiprocess_test.h"
24 #include "base/test/test_switches.h"
25 #include "base/test/test_timeouts.h"
26 #include "base/time/time.h"
27 #include "testing/gmock/include/gmock/gmock.h"
28 #include "testing/gtest/include/gtest/gtest.h"
29 #include "testing/multiprocess_func_list.h"
31 #if defined(OS_MACOSX)
32 #include "base/mac/scoped_nsautorelease_pool.h"
33 #if defined(OS_IOS)
34 #include "base/test/test_listener_ios.h"
35 #endif // OS_IOS
36 #endif // OS_MACOSX
38 #if defined(OS_ANDROID)
39 #include "base/test/test_support_android.h"
40 #endif
42 #if defined(OS_IOS)
43 #include "base/test/test_support_ios.h"
44 #endif
46 namespace {
48 class MaybeTestDisabler : public testing::EmptyTestEventListener {
49 public:
50 virtual void OnTestStart(const testing::TestInfo& test_info) override {
51 ASSERT_FALSE(TestSuite::IsMarkedMaybe(test_info))
52 << "Probably the OS #ifdefs don't include all of the necessary "
53 "platforms.\nPlease ensure that no tests have the MAYBE_ prefix "
54 "after the code is preprocessed.";
58 class TestClientInitializer : public testing::EmptyTestEventListener {
59 public:
60 TestClientInitializer()
61 : old_command_line_(base::CommandLine::NO_PROGRAM) {
64 virtual void OnTestStart(const testing::TestInfo& test_info) override {
65 old_command_line_ = *base::CommandLine::ForCurrentProcess();
68 virtual void OnTestEnd(const testing::TestInfo& test_info) override {
69 *base::CommandLine::ForCurrentProcess() = old_command_line_;
72 private:
73 base::CommandLine old_command_line_;
75 DISALLOW_COPY_AND_ASSIGN(TestClientInitializer);
78 } // namespace
80 namespace base {
82 int RunUnitTestsUsingBaseTestSuite(int argc, char **argv) {
83 TestSuite test_suite(argc, argv);
84 return base::LaunchUnitTests(
85 argc, argv, Bind(&TestSuite::Run, Unretained(&test_suite)));
88 } // namespace base
90 TestSuite::TestSuite(int argc, char** argv) : initialized_command_line_(false) {
91 PreInitialize(true);
92 InitializeFromCommandLine(argc, argv);
95 #if defined(OS_WIN)
96 TestSuite::TestSuite(int argc, wchar_t** argv)
97 : initialized_command_line_(false) {
98 PreInitialize(true);
99 InitializeFromCommandLine(argc, argv);
101 #endif // defined(OS_WIN)
103 TestSuite::TestSuite(int argc, char** argv, bool create_at_exit_manager)
104 : initialized_command_line_(false) {
105 PreInitialize(create_at_exit_manager);
106 InitializeFromCommandLine(argc, argv);
109 TestSuite::~TestSuite() {
110 if (initialized_command_line_)
111 base::CommandLine::Reset();
114 void TestSuite::InitializeFromCommandLine(int argc, char** argv) {
115 initialized_command_line_ = base::CommandLine::Init(argc, argv);
116 testing::InitGoogleTest(&argc, argv);
117 testing::InitGoogleMock(&argc, argv);
119 #if defined(OS_IOS)
120 InitIOSRunHook(this, argc, argv);
121 #endif
124 #if defined(OS_WIN)
125 void TestSuite::InitializeFromCommandLine(int argc, wchar_t** argv) {
126 // Windows CommandLine::Init ignores argv anyway.
127 initialized_command_line_ = base::CommandLine::Init(argc, NULL);
128 testing::InitGoogleTest(&argc, argv);
129 testing::InitGoogleMock(&argc, argv);
131 #endif // defined(OS_WIN)
133 void TestSuite::PreInitialize(bool create_at_exit_manager) {
134 #if defined(OS_WIN)
135 testing::GTEST_FLAG(catch_exceptions) = false;
136 #endif
137 base::EnableTerminationOnHeapCorruption();
138 #if defined(OS_LINUX) && defined(USE_AURA)
139 // When calling native char conversion functions (e.g wrctomb) we need to
140 // have the locale set. In the absence of such a call the "C" locale is the
141 // default. In the gtk code (below) gtk_init() implicitly sets a locale.
142 setlocale(LC_ALL, "");
143 #endif // defined(OS_LINUX) && defined(USE_AURA)
145 // On Android, AtExitManager is created in
146 // testing/android/native_test_wrapper.cc before main() is called.
147 #if !defined(OS_ANDROID)
148 if (create_at_exit_manager)
149 at_exit_manager_.reset(new base::AtExitManager);
150 #endif
152 // Don't add additional code to this function. Instead add it to
153 // Initialize(). See bug 6436.
157 // static
158 bool TestSuite::IsMarkedMaybe(const testing::TestInfo& test) {
159 return strncmp(test.name(), "MAYBE_", 6) == 0;
162 void TestSuite::CatchMaybeTests() {
163 testing::TestEventListeners& listeners =
164 testing::UnitTest::GetInstance()->listeners();
165 listeners.Append(new MaybeTestDisabler);
168 void TestSuite::ResetCommandLine() {
169 testing::TestEventListeners& listeners =
170 testing::UnitTest::GetInstance()->listeners();
171 listeners.Append(new TestClientInitializer);
174 void TestSuite::AddTestLauncherResultPrinter() {
175 // Only add the custom printer if requested.
176 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
177 switches::kTestLauncherOutput)) {
178 return;
181 FilePath output_path(base::CommandLine::ForCurrentProcess()->
182 GetSwitchValuePath(switches::kTestLauncherOutput));
184 // Do not add the result printer if output path already exists. It's an
185 // indicator there is a process printing to that file, and we're likely
186 // its child. Do not clobber the results in that case.
187 if (PathExists(output_path)) {
188 LOG(WARNING) << "Test launcher output path " << output_path.AsUTF8Unsafe()
189 << " exists. Not adding test launcher result printer.";
190 return;
193 XmlUnitTestResultPrinter* printer = new XmlUnitTestResultPrinter;
194 CHECK(printer->Initialize(output_path));
195 testing::TestEventListeners& listeners =
196 testing::UnitTest::GetInstance()->listeners();
197 listeners.Append(printer);
200 // Don't add additional code to this method. Instead add it to
201 // Initialize(). See bug 6436.
202 int TestSuite::Run() {
203 #if defined(OS_IOS)
204 RunTestsFromIOSApp();
205 #endif
207 #if defined(OS_MACOSX)
208 base::mac::ScopedNSAutoreleasePool scoped_pool;
209 #endif
211 Initialize();
212 std::string client_func =
213 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
214 switches::kTestChildProcess);
216 // Check to see if we are being run as a client process.
217 if (!client_func.empty())
218 return multi_process_function_list::InvokeChildProcessTest(client_func);
219 #if defined(OS_IOS)
220 base::test_listener_ios::RegisterTestEndListener();
221 #endif
222 int result = RUN_ALL_TESTS();
224 #if defined(OS_MACOSX)
225 // This MUST happen before Shutdown() since Shutdown() tears down
226 // objects (such as NotificationService::current()) that Cocoa
227 // objects use to remove themselves as observers.
228 scoped_pool.Recycle();
229 #endif
231 Shutdown();
233 return result;
236 // static
237 void TestSuite::UnitTestAssertHandler(const std::string& str) {
238 #if defined(OS_ANDROID)
239 // Correlating test stdio with logcat can be difficult, so we emit this
240 // helpful little hint about what was running. Only do this for Android
241 // because other platforms don't separate out the relevant logs in the same
242 // way.
243 const ::testing::TestInfo* const test_info =
244 ::testing::UnitTest::GetInstance()->current_test_info();
245 if (test_info) {
246 LOG(ERROR) << "Currently running: " << test_info->test_case_name() << "."
247 << test_info->name();
248 fflush(stderr);
250 #endif // defined(OS_ANDROID)
252 // The logging system actually prints the message before calling the assert
253 // handler. Just exit now to avoid printing too many stack traces.
254 _exit(1);
257 void TestSuite::SuppressErrorDialogs() {
258 #if defined(OS_WIN)
259 UINT new_flags = SEM_FAILCRITICALERRORS |
260 SEM_NOGPFAULTERRORBOX |
261 SEM_NOOPENFILEERRORBOX;
263 // Preserve existing error mode, as discussed at
264 // http://blogs.msdn.com/oldnewthing/archive/2004/07/27/198410.aspx
265 UINT existing_flags = SetErrorMode(new_flags);
266 SetErrorMode(existing_flags | new_flags);
268 #if defined(_DEBUG) && defined(_HAS_EXCEPTIONS) && (_HAS_EXCEPTIONS == 1)
269 // Suppress the "Debug Assertion Failed" dialog.
270 // TODO(hbono): remove this code when gtest has it.
271 // http://groups.google.com/d/topic/googletestframework/OjuwNlXy5ac/discussion
272 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
273 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
274 #endif // defined(_DEBUG) && defined(_HAS_EXCEPTIONS) && (_HAS_EXCEPTIONS == 1)
275 #endif // defined(OS_WIN)
278 void TestSuite::Initialize() {
279 #if !defined(OS_IOS)
280 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
281 switches::kWaitForDebugger)) {
282 base::debug::WaitForDebugger(60, true);
284 #endif
286 #if defined(OS_IOS)
287 InitIOSTestMessageLoop();
288 #endif // OS_IOS
290 #if defined(OS_ANDROID)
291 InitAndroidTest();
292 #else
293 // Initialize logging.
294 base::FilePath exe;
295 PathService::Get(base::FILE_EXE, &exe);
296 base::FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL("log"));
297 logging::LoggingSettings settings;
298 settings.logging_dest = logging::LOG_TO_ALL;
299 settings.log_file = log_filename.value().c_str();
300 settings.delete_old = logging::DELETE_OLD_LOG_FILE;
301 logging::InitLogging(settings);
302 // We want process and thread IDs because we may have multiple processes.
303 // Note: temporarily enabled timestamps in an effort to catch bug 6361.
304 logging::SetLogItems(true, true, true, true);
305 #endif // else defined(OS_ANDROID)
307 CHECK(base::debug::EnableInProcessStackDumping());
308 #if defined(OS_WIN)
309 // Make sure we run with high resolution timer to minimize differences
310 // between production code and test code.
311 base::Time::EnableHighResolutionTimer(true);
312 #endif // defined(OS_WIN)
314 // In some cases, we do not want to see standard error dialogs.
315 if (!base::debug::BeingDebugged() &&
316 !base::CommandLine::ForCurrentProcess()->HasSwitch(
317 "show-error-dialogs")) {
318 SuppressErrorDialogs();
319 base::debug::SetSuppressDebugUI(true);
320 logging::SetLogAssertHandler(UnitTestAssertHandler);
323 base::i18n::InitializeICU();
325 CatchMaybeTests();
326 ResetCommandLine();
327 AddTestLauncherResultPrinter();
329 TestTimeouts::Initialize();
331 trace_to_file_.BeginTracingFromCommandLineOptions();
334 void TestSuite::Shutdown() {