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"
34 #include "base/test/test_listener_ios.h"
38 #if defined(OS_ANDROID)
39 #include "base/test/test_support_android.h"
43 #include "base/test/test_support_ios.h"
48 class MaybeTestDisabler
: public testing::EmptyTestEventListener
{
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
{
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_
;
73 base::CommandLine old_command_line_
;
75 DISALLOW_COPY_AND_ASSIGN(TestClientInitializer
);
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
)));
90 TestSuite::TestSuite(int argc
, char** argv
) : initialized_command_line_(false) {
92 InitializeFromCommandLine(argc
, argv
);
96 TestSuite::TestSuite(int argc
, wchar_t** argv
)
97 : initialized_command_line_(false) {
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
);
120 InitIOSRunHook(this, argc
, argv
);
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
) {
135 testing::GTEST_FLAG(catch_exceptions
) = false;
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
);
152 // Don't add additional code to this function. Instead add it to
153 // Initialize(). See bug 6436.
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
)) {
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.";
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() {
204 RunTestsFromIOSApp();
207 #if defined(OS_MACOSX)
208 base::mac::ScopedNSAutoreleasePool scoped_pool
;
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
);
220 base::test_listener_ios::RegisterTestEndListener();
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();
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
243 const ::testing::TestInfo
* const test_info
=
244 ::testing::UnitTest::GetInstance()->current_test_info();
246 LOG(ERROR
) << "Currently running: " << test_info
->test_case_name() << "."
247 << test_info
->name();
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.
257 void TestSuite::SuppressErrorDialogs() {
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() {
280 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
281 switches::kWaitForDebugger
)) {
282 base::debug::WaitForDebugger(60, true);
287 InitIOSTestMessageLoop();
290 #if defined(OS_ANDROID)
293 // Initialize logging.
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());
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();
327 AddTestLauncherResultPrinter();
329 TestTimeouts::Initialize();
331 trace_to_file_
.BeginTracingFromCommandLineOptions();
334 void TestSuite::Shutdown() {