Roll src/third_party/WebKit 57aef96:a1089e6 (svn 201978:201979)
[chromium-blink-merge.git] / base / test / test_suite.cc
blobfee7b6879505ef326bce200dccd5e046b4165896
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/launch.h"
21 #include "base/process/memory.h"
22 #include "base/test/gtest_xml_unittest_result_printer.h"
23 #include "base/test/gtest_xml_util.h"
24 #include "base/test/launcher/unit_test_launcher.h"
25 #include "base/test/multiprocess_test.h"
26 #include "base/test/test_switches.h"
27 #include "base/test/test_timeouts.h"
28 #include "base/time/time.h"
29 #include "testing/gmock/include/gmock/gmock.h"
30 #include "testing/gtest/include/gtest/gtest.h"
31 #include "testing/multiprocess_func_list.h"
33 #if defined(OS_MACOSX)
34 #include "base/mac/scoped_nsautorelease_pool.h"
35 #if defined(OS_IOS)
36 #include "base/test/test_listener_ios.h"
37 #endif // OS_IOS
38 #endif // OS_MACOSX
40 #if !defined(OS_WIN)
41 #include "base/i18n/rtl.h"
42 #if !defined(OS_IOS)
43 #include "base/strings/string_util.h"
44 #include "third_party/icu/source/common/unicode/uloc.h"
45 #endif
46 #endif
48 #if defined(OS_ANDROID)
49 #include "base/test/test_support_android.h"
50 #endif
52 #if defined(OS_IOS)
53 #include "base/test/test_support_ios.h"
54 #endif
56 namespace base {
58 namespace {
60 class MaybeTestDisabler : public testing::EmptyTestEventListener {
61 public:
62 void OnTestStart(const testing::TestInfo& test_info) override {
63 ASSERT_FALSE(TestSuite::IsMarkedMaybe(test_info))
64 << "Probably the OS #ifdefs don't include all of the necessary "
65 "platforms.\nPlease ensure that no tests have the MAYBE_ prefix "
66 "after the code is preprocessed.";
70 class TestClientInitializer : public testing::EmptyTestEventListener {
71 public:
72 TestClientInitializer()
73 : old_command_line_(CommandLine::NO_PROGRAM) {
76 void OnTestStart(const testing::TestInfo& test_info) override {
77 old_command_line_ = *CommandLine::ForCurrentProcess();
80 void OnTestEnd(const testing::TestInfo& test_info) override {
81 *CommandLine::ForCurrentProcess() = old_command_line_;
84 private:
85 CommandLine old_command_line_;
87 DISALLOW_COPY_AND_ASSIGN(TestClientInitializer);
90 } // namespace
92 int RunUnitTestsUsingBaseTestSuite(int argc, char **argv) {
93 TestSuite test_suite(argc, argv);
94 return LaunchUnitTests(argc, argv,
95 Bind(&TestSuite::Run, Unretained(&test_suite)));
98 TestSuite::TestSuite(int argc, char** argv) : initialized_command_line_(false) {
99 PreInitialize(true);
100 InitializeFromCommandLine(argc, argv);
103 #if defined(OS_WIN)
104 TestSuite::TestSuite(int argc, wchar_t** argv)
105 : initialized_command_line_(false) {
106 PreInitialize(true);
107 InitializeFromCommandLine(argc, argv);
109 #endif // defined(OS_WIN)
111 TestSuite::TestSuite(int argc, char** argv, bool create_at_exit_manager)
112 : initialized_command_line_(false) {
113 PreInitialize(create_at_exit_manager);
114 InitializeFromCommandLine(argc, argv);
117 TestSuite::~TestSuite() {
118 if (initialized_command_line_)
119 CommandLine::Reset();
122 void TestSuite::InitializeFromCommandLine(int argc, char** argv) {
123 initialized_command_line_ = CommandLine::Init(argc, argv);
124 testing::InitGoogleTest(&argc, argv);
125 testing::InitGoogleMock(&argc, argv);
127 #if defined(OS_IOS)
128 InitIOSRunHook(this, argc, argv);
129 #endif
132 #if defined(OS_WIN)
133 void TestSuite::InitializeFromCommandLine(int argc, wchar_t** argv) {
134 // Windows CommandLine::Init ignores argv anyway.
135 initialized_command_line_ = CommandLine::Init(argc, NULL);
136 testing::InitGoogleTest(&argc, argv);
137 testing::InitGoogleMock(&argc, argv);
139 #endif // defined(OS_WIN)
141 void TestSuite::PreInitialize(bool create_at_exit_manager) {
142 #if defined(OS_WIN)
143 testing::GTEST_FLAG(catch_exceptions) = false;
144 #endif
145 EnableTerminationOnHeapCorruption();
146 #if defined(OS_LINUX) && defined(USE_AURA)
147 // When calling native char conversion functions (e.g wrctomb) we need to
148 // have the locale set. In the absence of such a call the "C" locale is the
149 // default. In the gtk code (below) gtk_init() implicitly sets a locale.
150 setlocale(LC_ALL, "");
151 #endif // defined(OS_LINUX) && defined(USE_AURA)
153 // On Android, AtExitManager is created in
154 // testing/android/native_test_wrapper.cc before main() is called.
155 #if !defined(OS_ANDROID)
156 if (create_at_exit_manager)
157 at_exit_manager_.reset(new AtExitManager);
158 #endif
160 // Don't add additional code to this function. Instead add it to
161 // Initialize(). See bug 6436.
165 // static
166 bool TestSuite::IsMarkedMaybe(const testing::TestInfo& test) {
167 return strncmp(test.name(), "MAYBE_", 6) == 0;
170 void TestSuite::CatchMaybeTests() {
171 testing::TestEventListeners& listeners =
172 testing::UnitTest::GetInstance()->listeners();
173 listeners.Append(new MaybeTestDisabler);
176 void TestSuite::ResetCommandLine() {
177 testing::TestEventListeners& listeners =
178 testing::UnitTest::GetInstance()->listeners();
179 listeners.Append(new TestClientInitializer);
182 void TestSuite::AddTestLauncherResultPrinter() {
183 // Only add the custom printer if requested.
184 if (!CommandLine::ForCurrentProcess()->HasSwitch(
185 switches::kTestLauncherOutput)) {
186 return;
189 FilePath output_path(CommandLine::ForCurrentProcess()->GetSwitchValuePath(
190 switches::kTestLauncherOutput));
192 // Do not add the result printer if output path already exists. It's an
193 // indicator there is a process printing to that file, and we're likely
194 // its child. Do not clobber the results in that case.
195 if (PathExists(output_path)) {
196 LOG(WARNING) << "Test launcher output path " << output_path.AsUTF8Unsafe()
197 << " exists. Not adding test launcher result printer.";
198 return;
201 XmlUnitTestResultPrinter* printer = new XmlUnitTestResultPrinter;
202 CHECK(printer->Initialize(output_path));
203 testing::TestEventListeners& listeners =
204 testing::UnitTest::GetInstance()->listeners();
205 listeners.Append(printer);
208 // Don't add additional code to this method. Instead add it to
209 // Initialize(). See bug 6436.
210 int TestSuite::Run() {
211 #if defined(OS_IOS)
212 RunTestsFromIOSApp();
213 #endif
215 #if defined(OS_MACOSX)
216 mac::ScopedNSAutoreleasePool scoped_pool;
217 #endif
219 Initialize();
220 std::string client_func =
221 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
222 switches::kTestChildProcess);
224 // Check to see if we are being run as a client process.
225 if (!client_func.empty())
226 return multi_process_function_list::InvokeChildProcessTest(client_func);
227 #if defined(OS_IOS)
228 test_listener_ios::RegisterTestEndListener();
229 #endif
230 int result = RUN_ALL_TESTS();
232 #if defined(OS_MACOSX)
233 // This MUST happen before Shutdown() since Shutdown() tears down
234 // objects (such as NotificationService::current()) that Cocoa
235 // objects use to remove themselves as observers.
236 scoped_pool.Recycle();
237 #endif
239 Shutdown();
241 return result;
244 // static
245 void TestSuite::UnitTestAssertHandler(const std::string& str) {
246 #if defined(OS_ANDROID)
247 // Correlating test stdio with logcat can be difficult, so we emit this
248 // helpful little hint about what was running. Only do this for Android
249 // because other platforms don't separate out the relevant logs in the same
250 // way.
251 const ::testing::TestInfo* const test_info =
252 ::testing::UnitTest::GetInstance()->current_test_info();
253 if (test_info) {
254 LOG(ERROR) << "Currently running: " << test_info->test_case_name() << "."
255 << test_info->name();
256 fflush(stderr);
258 #endif // defined(OS_ANDROID)
260 // The logging system actually prints the message before calling the assert
261 // handler. Just exit now to avoid printing too many stack traces.
262 _exit(1);
265 void TestSuite::SuppressErrorDialogs() {
266 #if defined(OS_WIN)
267 UINT new_flags = SEM_FAILCRITICALERRORS |
268 SEM_NOGPFAULTERRORBOX |
269 SEM_NOOPENFILEERRORBOX;
271 // Preserve existing error mode, as discussed at
272 // http://blogs.msdn.com/oldnewthing/archive/2004/07/27/198410.aspx
273 UINT existing_flags = SetErrorMode(new_flags);
274 SetErrorMode(existing_flags | new_flags);
276 #if defined(_DEBUG) && defined(_HAS_EXCEPTIONS) && (_HAS_EXCEPTIONS == 1)
277 // Suppress the "Debug Assertion Failed" dialog.
278 // TODO(hbono): remove this code when gtest has it.
279 // http://groups.google.com/d/topic/googletestframework/OjuwNlXy5ac/discussion
280 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
281 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
282 #endif // defined(_DEBUG) && defined(_HAS_EXCEPTIONS) && (_HAS_EXCEPTIONS == 1)
283 #endif // defined(OS_WIN)
286 void TestSuite::Initialize() {
287 #if !defined(OS_IOS)
288 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kWaitForDebugger)) {
289 debug::WaitForDebugger(60, true);
291 #endif
293 #if defined(OS_IOS)
294 InitIOSTestMessageLoop();
295 #endif // OS_IOS
297 #if defined(OS_ANDROID)
298 InitAndroidTest();
299 #else
300 // Initialize logging.
301 FilePath exe;
302 PathService::Get(FILE_EXE, &exe);
303 FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL("log"));
304 logging::LoggingSettings settings;
305 settings.logging_dest = logging::LOG_TO_ALL;
306 settings.log_file = log_filename.value().c_str();
307 settings.delete_old = logging::DELETE_OLD_LOG_FILE;
308 logging::InitLogging(settings);
309 // We want process and thread IDs because we may have multiple processes.
310 // Note: temporarily enabled timestamps in an effort to catch bug 6361.
311 logging::SetLogItems(true, true, true, true);
312 #endif // else defined(OS_ANDROID)
314 CHECK(debug::EnableInProcessStackDumping());
315 #if defined(OS_WIN)
316 RouteStdioToConsole(true);
317 // Make sure we run with high resolution timer to minimize differences
318 // between production code and test code.
319 Time::EnableHighResolutionTimer(true);
320 #endif // defined(OS_WIN)
322 // In some cases, we do not want to see standard error dialogs.
323 if (!debug::BeingDebugged() &&
324 !CommandLine::ForCurrentProcess()->HasSwitch("show-error-dialogs")) {
325 SuppressErrorDialogs();
326 debug::SetSuppressDebugUI(true);
327 logging::SetLogAssertHandler(UnitTestAssertHandler);
330 i18n::InitializeICU();
331 // On the Mac OS X command line, the default locale is *_POSIX. In Chromium,
332 // the locale is set via an OS X locale API and is never *_POSIX.
333 // Some tests (such as those involving word break iterator) will behave
334 // differently and fail if we use *POSIX locale. Setting it to en_US here
335 // does not affect tests that explicitly overrides the locale for testing.
336 // This can be an issue on all platforms other than Windows.
337 // TODO(jshin): Should we set the locale via an OS X locale API here?
338 #if !defined(OS_WIN)
339 #if defined(OS_IOS)
340 i18n::SetICUDefaultLocale("en_US");
341 #else
342 std::string default_locale(uloc_getDefault());
343 if (EndsWith(default_locale, "POSIX", CompareCase::INSENSITIVE_ASCII))
344 i18n::SetICUDefaultLocale("en_US");
345 #endif
346 #endif
348 CatchMaybeTests();
349 ResetCommandLine();
350 AddTestLauncherResultPrinter();
352 TestTimeouts::Initialize();
354 trace_to_file_.BeginTracingFromCommandLineOptions();
357 void TestSuite::Shutdown() {
360 } // namespace base