Update comments of TabObserver#onLoadStarted and rename onContentChanged
[chromium-blink-merge.git] / base / test / test_suite.cc
blob6c766ebd8fa35c3d2f9c65b11ef4ce2563a6072c
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_WIN)
39 #include "base/i18n/rtl.h"
40 #if !defined(OS_IOS)
41 #include "base/strings/string_util.h"
42 #include "third_party/icu/source/common/unicode/uloc.h"
43 #endif
44 #endif
46 #if defined(OS_ANDROID)
47 #include "base/test/test_support_android.h"
48 #endif
50 #if defined(OS_IOS)
51 #include "base/test/test_support_ios.h"
52 #endif
54 namespace base {
56 namespace {
58 class MaybeTestDisabler : public testing::EmptyTestEventListener {
59 public:
60 void OnTestStart(const testing::TestInfo& test_info) override {
61 ASSERT_FALSE(TestSuite::IsMarkedMaybe(test_info))
62 << "Probably the OS #ifdefs don't include all of the necessary "
63 "platforms.\nPlease ensure that no tests have the MAYBE_ prefix "
64 "after the code is preprocessed.";
68 class TestClientInitializer : public testing::EmptyTestEventListener {
69 public:
70 TestClientInitializer()
71 : old_command_line_(CommandLine::NO_PROGRAM) {
74 void OnTestStart(const testing::TestInfo& test_info) override {
75 old_command_line_ = *CommandLine::ForCurrentProcess();
78 void OnTestEnd(const testing::TestInfo& test_info) override {
79 *CommandLine::ForCurrentProcess() = old_command_line_;
82 private:
83 CommandLine old_command_line_;
85 DISALLOW_COPY_AND_ASSIGN(TestClientInitializer);
88 } // namespace
90 int RunUnitTestsUsingBaseTestSuite(int argc, char **argv) {
91 TestSuite test_suite(argc, argv);
92 return LaunchUnitTests(argc, argv,
93 Bind(&TestSuite::Run, Unretained(&test_suite)));
96 TestSuite::TestSuite(int argc, char** argv) : initialized_command_line_(false) {
97 PreInitialize(true);
98 InitializeFromCommandLine(argc, argv);
101 #if defined(OS_WIN)
102 TestSuite::TestSuite(int argc, wchar_t** argv)
103 : initialized_command_line_(false) {
104 PreInitialize(true);
105 InitializeFromCommandLine(argc, argv);
107 #endif // defined(OS_WIN)
109 TestSuite::TestSuite(int argc, char** argv, bool create_at_exit_manager)
110 : initialized_command_line_(false) {
111 PreInitialize(create_at_exit_manager);
112 InitializeFromCommandLine(argc, argv);
115 TestSuite::~TestSuite() {
116 if (initialized_command_line_)
117 CommandLine::Reset();
120 void TestSuite::InitializeFromCommandLine(int argc, char** argv) {
121 initialized_command_line_ = CommandLine::Init(argc, argv);
122 testing::InitGoogleTest(&argc, argv);
123 testing::InitGoogleMock(&argc, argv);
125 #if defined(OS_IOS)
126 InitIOSRunHook(this, argc, argv);
127 #endif
130 #if defined(OS_WIN)
131 void TestSuite::InitializeFromCommandLine(int argc, wchar_t** argv) {
132 // Windows CommandLine::Init ignores argv anyway.
133 initialized_command_line_ = CommandLine::Init(argc, NULL);
134 testing::InitGoogleTest(&argc, argv);
135 testing::InitGoogleMock(&argc, argv);
137 #endif // defined(OS_WIN)
139 void TestSuite::PreInitialize(bool create_at_exit_manager) {
140 #if defined(OS_WIN)
141 testing::GTEST_FLAG(catch_exceptions) = false;
142 #endif
143 EnableTerminationOnHeapCorruption();
144 #if defined(OS_LINUX) && defined(USE_AURA)
145 // When calling native char conversion functions (e.g wrctomb) we need to
146 // have the locale set. In the absence of such a call the "C" locale is the
147 // default. In the gtk code (below) gtk_init() implicitly sets a locale.
148 setlocale(LC_ALL, "");
149 #endif // defined(OS_LINUX) && defined(USE_AURA)
151 // On Android, AtExitManager is created in
152 // testing/android/native_test_wrapper.cc before main() is called.
153 #if !defined(OS_ANDROID)
154 if (create_at_exit_manager)
155 at_exit_manager_.reset(new AtExitManager);
156 #endif
158 // Don't add additional code to this function. Instead add it to
159 // Initialize(). See bug 6436.
163 // static
164 bool TestSuite::IsMarkedMaybe(const testing::TestInfo& test) {
165 return strncmp(test.name(), "MAYBE_", 6) == 0;
168 void TestSuite::CatchMaybeTests() {
169 testing::TestEventListeners& listeners =
170 testing::UnitTest::GetInstance()->listeners();
171 listeners.Append(new MaybeTestDisabler);
174 void TestSuite::ResetCommandLine() {
175 testing::TestEventListeners& listeners =
176 testing::UnitTest::GetInstance()->listeners();
177 listeners.Append(new TestClientInitializer);
180 void TestSuite::AddTestLauncherResultPrinter() {
181 // Only add the custom printer if requested.
182 if (!CommandLine::ForCurrentProcess()->HasSwitch(
183 switches::kTestLauncherOutput)) {
184 return;
187 FilePath output_path(CommandLine::ForCurrentProcess()->GetSwitchValuePath(
188 switches::kTestLauncherOutput));
190 // Do not add the result printer if output path already exists. It's an
191 // indicator there is a process printing to that file, and we're likely
192 // its child. Do not clobber the results in that case.
193 if (PathExists(output_path)) {
194 LOG(WARNING) << "Test launcher output path " << output_path.AsUTF8Unsafe()
195 << " exists. Not adding test launcher result printer.";
196 return;
199 XmlUnitTestResultPrinter* printer = new XmlUnitTestResultPrinter;
200 CHECK(printer->Initialize(output_path));
201 testing::TestEventListeners& listeners =
202 testing::UnitTest::GetInstance()->listeners();
203 listeners.Append(printer);
206 // Don't add additional code to this method. Instead add it to
207 // Initialize(). See bug 6436.
208 int TestSuite::Run() {
209 #if defined(OS_IOS)
210 RunTestsFromIOSApp();
211 #endif
213 #if defined(OS_MACOSX)
214 mac::ScopedNSAutoreleasePool scoped_pool;
215 #endif
217 Initialize();
218 std::string client_func =
219 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
220 switches::kTestChildProcess);
222 // Check to see if we are being run as a client process.
223 if (!client_func.empty())
224 return multi_process_function_list::InvokeChildProcessTest(client_func);
225 #if defined(OS_IOS)
226 test_listener_ios::RegisterTestEndListener();
227 #endif
228 int result = RUN_ALL_TESTS();
230 #if defined(OS_MACOSX)
231 // This MUST happen before Shutdown() since Shutdown() tears down
232 // objects (such as NotificationService::current()) that Cocoa
233 // objects use to remove themselves as observers.
234 scoped_pool.Recycle();
235 #endif
237 Shutdown();
239 return result;
242 // static
243 void TestSuite::UnitTestAssertHandler(const std::string& str) {
244 #if defined(OS_ANDROID)
245 // Correlating test stdio with logcat can be difficult, so we emit this
246 // helpful little hint about what was running. Only do this for Android
247 // because other platforms don't separate out the relevant logs in the same
248 // way.
249 const ::testing::TestInfo* const test_info =
250 ::testing::UnitTest::GetInstance()->current_test_info();
251 if (test_info) {
252 LOG(ERROR) << "Currently running: " << test_info->test_case_name() << "."
253 << test_info->name();
254 fflush(stderr);
256 #endif // defined(OS_ANDROID)
258 // The logging system actually prints the message before calling the assert
259 // handler. Just exit now to avoid printing too many stack traces.
260 _exit(1);
263 void TestSuite::SuppressErrorDialogs() {
264 #if defined(OS_WIN)
265 UINT new_flags = SEM_FAILCRITICALERRORS |
266 SEM_NOGPFAULTERRORBOX |
267 SEM_NOOPENFILEERRORBOX;
269 // Preserve existing error mode, as discussed at
270 // http://blogs.msdn.com/oldnewthing/archive/2004/07/27/198410.aspx
271 UINT existing_flags = SetErrorMode(new_flags);
272 SetErrorMode(existing_flags | new_flags);
274 #if defined(_DEBUG) && defined(_HAS_EXCEPTIONS) && (_HAS_EXCEPTIONS == 1)
275 // Suppress the "Debug Assertion Failed" dialog.
276 // TODO(hbono): remove this code when gtest has it.
277 // http://groups.google.com/d/topic/googletestframework/OjuwNlXy5ac/discussion
278 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
279 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
280 #endif // defined(_DEBUG) && defined(_HAS_EXCEPTIONS) && (_HAS_EXCEPTIONS == 1)
281 #endif // defined(OS_WIN)
284 void TestSuite::Initialize() {
285 #if !defined(OS_IOS)
286 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kWaitForDebugger)) {
287 debug::WaitForDebugger(60, true);
289 #endif
291 #if defined(OS_IOS)
292 InitIOSTestMessageLoop();
293 #endif // OS_IOS
295 #if defined(OS_ANDROID)
296 InitAndroidTest();
297 #else
298 // Initialize logging.
299 FilePath exe;
300 PathService::Get(FILE_EXE, &exe);
301 FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL("log"));
302 logging::LoggingSettings settings;
303 settings.logging_dest = logging::LOG_TO_ALL;
304 settings.log_file = log_filename.value().c_str();
305 settings.delete_old = logging::DELETE_OLD_LOG_FILE;
306 logging::InitLogging(settings);
307 // We want process and thread IDs because we may have multiple processes.
308 // Note: temporarily enabled timestamps in an effort to catch bug 6361.
309 logging::SetLogItems(true, true, true, true);
310 #endif // else defined(OS_ANDROID)
312 CHECK(debug::EnableInProcessStackDumping());
313 #if defined(OS_WIN)
314 // Make sure we run with high resolution timer to minimize differences
315 // between production code and test code.
316 Time::EnableHighResolutionTimer(true);
317 #endif // defined(OS_WIN)
319 // In some cases, we do not want to see standard error dialogs.
320 if (!debug::BeingDebugged() &&
321 !CommandLine::ForCurrentProcess()->HasSwitch("show-error-dialogs")) {
322 SuppressErrorDialogs();
323 debug::SetSuppressDebugUI(true);
324 logging::SetLogAssertHandler(UnitTestAssertHandler);
327 i18n::InitializeICU();
328 // On the Mac OS X command line, the default locale is *_POSIX. In Chromium,
329 // the locale is set via an OS X locale API and is never *_POSIX.
330 // Some tests (such as those involving word break iterator) will behave
331 // differently and fail if we use *POSIX locale. Setting it to en_US here
332 // does not affect tests that explicitly overrides the locale for testing.
333 // This can be an issue on all platforms other than Windows.
334 // TODO(jshin): Should we set the locale via an OS X locale API here?
335 #if !defined(OS_WIN)
336 #if defined(OS_IOS)
337 i18n::SetICUDefaultLocale("en_US");
338 #else
339 std::string default_locale(uloc_getDefault());
340 if (EndsWith(default_locale, "POSIX", false))
341 i18n::SetICUDefaultLocale("en_US");
342 #endif
343 #endif
345 CatchMaybeTests();
346 ResetCommandLine();
347 AddTestLauncherResultPrinter();
349 TestTimeouts::Initialize();
351 trace_to_file_.BeginTracingFromCommandLineOptions();
354 void TestSuite::Shutdown() {
357 } // namespace base