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 "chrome/test/automation/proxy_launcher.h"
9 #include "base/environment.h"
10 #include "base/file_util.h"
11 #include "base/files/file_enumerator.h"
12 #include "base/process/kill.h"
13 #include "base/process/launch.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/test/test_file_util.h"
19 #include "base/test/test_timeouts.h"
20 #include "chrome/app/chrome_command_ids.h"
21 #include "chrome/common/automation_constants.h"
22 #include "chrome/common/chrome_constants.h"
23 #include "chrome/common/chrome_switches.h"
24 #include "chrome/common/logging_chrome.h"
25 #include "chrome/common/url_constants.h"
26 #include "chrome/test/automation/automation_proxy.h"
27 #include "chrome/test/base/chrome_process_util.h"
28 #include "chrome/test/base/test_launcher_utils.h"
29 #include "chrome/test/base/test_switches.h"
30 #include "chrome/test/ui/ui_test.h"
31 #include "content/public/common/process_type.h"
32 #include "ipc/ipc_channel.h"
33 #include "ipc/ipc_descriptors.h"
34 #include "sql/connection.h"
38 #include "base/posix/global_descriptors.h"
43 // Passed as value of kTestType.
44 const char kUITestType
[] = "ui";
46 // Copies the contents of the given source directory to the given dest
47 // directory. This is somewhat different than CopyDirectory in base which will
48 // copies "source/" to "dest/source/". This version will copy "source/*" to
49 // "dest/*", overwriting existing files as necessary.
51 // This also kicks the files out of the memory cache for the startup tests.
52 // TODO(brettw) bug 237904: This is the wrong place for this code. It means all
53 // startup tests other than the "cold" ones run more slowly than necessary.
54 bool CopyDirectoryContentsNoCache(const base::FilePath
& source
,
55 const base::FilePath
& dest
) {
56 base::FileEnumerator
en(source
, false,
57 base::FileEnumerator::FILES
| base::FileEnumerator::DIRECTORIES
);
58 for (base::FilePath cur
= en
.Next(); !cur
.empty(); cur
= en
.Next()) {
59 base::FileEnumerator::FileInfo info
= en
.GetInfo();
60 if (info
.IsDirectory()) {
61 if (!base::CopyDirectory(cur
, dest
, true))
64 if (!base::CopyFile(cur
, dest
.Append(cur
.BaseName())))
69 // Kick out the profile files, this must happen after SetUp which creates the
70 // profile. It might be nicer to use EvictFileFromSystemCacheWrapper from
71 // UITest which will retry on failure.
72 base::FileEnumerator
kickout(dest
, true, base::FileEnumerator::FILES
);
73 for (base::FilePath cur
= kickout
.Next(); !cur
.empty(); cur
= kickout
.Next())
74 base::EvictFileFromSystemCacheWithRetry(cur
);
78 // We want to have a current history database when we start the browser so
79 // things like the NTP will have thumbnails. This method updates the dates
80 // in the history to be more recent.
81 void UpdateHistoryDates(const base::FilePath
& user_data_dir
) {
82 // Migrate the times in the segment_usage table to yesterday so we get
83 // actual thumbnails on the NTP.
85 base::FilePath history
=
86 user_data_dir
.AppendASCII("Default").AppendASCII("History");
87 // Not all test profiles have a history file.
88 if (!base::PathExists(history
))
91 ASSERT_TRUE(db
.Open(history
));
92 base::Time yesterday
= base::Time::Now() - base::TimeDelta::FromDays(1);
93 std::string yesterday_str
= base::Int64ToString(yesterday
.ToInternalValue());
94 std::string query
= base::StringPrintf(
95 "UPDATE segment_usage "
97 "WHERE id IN (SELECT id FROM segment_usage WHERE time_slot > 0);",
98 yesterday_str
.c_str());
99 ASSERT_TRUE(db
.Execute(query
.c_str()));
101 file_util::EvictFileFromSystemCache(history
);
106 // ProxyLauncher functions
109 const char ProxyLauncher::kDefaultInterfaceId
[] = "ChromeTestingInterface";
110 #elif defined(OS_POSIX)
111 const char ProxyLauncher::kDefaultInterfaceId
[] =
112 "/var/tmp/ChromeTestingInterface";
115 ProxyLauncher::ProxyLauncher()
116 : process_(base::kNullProcessHandle
),
118 shutdown_type_(WINDOW_CLOSE
),
119 no_sandbox_(CommandLine::ForCurrentProcess()->HasSwitch(
120 switches::kNoSandbox
)),
121 full_memory_dump_(CommandLine::ForCurrentProcess()->HasSwitch(
122 switches::kFullMemoryCrashReport
)),
123 show_error_dialogs_(CommandLine::ForCurrentProcess()->HasSwitch(
124 switches::kEnableErrorDialogs
)),
125 silent_dump_on_dcheck_(CommandLine::ForCurrentProcess()->HasSwitch(
126 switches::kSilentDumpOnDCHECK
)),
127 disable_breakpad_(CommandLine::ForCurrentProcess()->HasSwitch(
128 switches::kDisableBreakpad
)),
129 js_flags_(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
130 switches::kJavaScriptFlags
)),
131 log_level_(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
132 switches::kLoggingLevel
)) {
135 ProxyLauncher::~ProxyLauncher() {}
137 bool ProxyLauncher::WaitForBrowserLaunch(bool wait_for_initial_loads
) {
138 AutomationLaunchResult app_launched
= automation_proxy_
->WaitForAppLaunch();
139 EXPECT_EQ(AUTOMATION_SUCCESS
, app_launched
)
140 << "Error while awaiting automation ping from browser process";
141 if (app_launched
!= AUTOMATION_SUCCESS
)
144 if (wait_for_initial_loads
) {
145 if (!automation_proxy_
->WaitForInitialLoads()) {
146 LOG(ERROR
) << "WaitForInitialLoads failed.";
151 // TODO(phajdan.jr): Get rid of this Sleep when logging_chrome_uitest
152 // stops "relying" on it.
153 base::PlatformThread::Sleep(TestTimeouts::action_timeout());
160 bool ProxyLauncher::LaunchBrowserAndServer(const LaunchState
& state
,
161 bool wait_for_initial_loads
) {
162 // Set up IPC testing interface as a server.
163 automation_proxy_
.reset(CreateAutomationProxy(
164 TestTimeouts::action_max_timeout()));
166 if (!LaunchBrowser(state
))
169 if (!WaitForBrowserLaunch(wait_for_initial_loads
))
175 bool ProxyLauncher::ConnectToRunningBrowser(bool wait_for_initial_loads
) {
176 // Set up IPC testing interface as a client.
177 automation_proxy_
.reset(CreateAutomationProxy(
178 TestTimeouts::action_max_timeout()));
180 return WaitForBrowserLaunch(wait_for_initial_loads
);
183 void ProxyLauncher::CloseBrowserAndServer() {
186 // Suppress spammy failures that seem to be occurring when running
187 // the UI tests in single-process mode.
188 // TODO(jhughes): figure out why this is necessary at all, and fix it
191 "Unable to quit all browser processes. Original PID %d",
194 DisconnectFromRunningBrowser();
197 void ProxyLauncher::DisconnectFromRunningBrowser() {
198 automation_proxy_
.reset(); // Shut down IPC testing interface.
201 bool ProxyLauncher::LaunchBrowser(const LaunchState
& state
) {
202 if (state
.clear_profile
|| !temp_profile_dir_
.IsValid()) {
203 if (temp_profile_dir_
.IsValid() && !temp_profile_dir_
.Delete()) {
204 LOG(ERROR
) << "Failed to delete temporary directory.";
208 if (!temp_profile_dir_
.CreateUniqueTempDir()) {
209 LOG(ERROR
) << "Failed to create temporary directory.";
213 if (!test_launcher_utils::OverrideUserDataDir(user_data_dir())) {
214 LOG(ERROR
) << "Failed to override user data directory.";
219 if (!state
.template_user_data
.empty()) {
220 // Recursively copy the template directory to the user_data_dir.
221 if (!CopyDirectoryContentsNoCache(state
.template_user_data
,
223 LOG(ERROR
) << "Failed to copy user data directory template.";
227 // Update the history file to include recent dates.
228 UpdateHistoryDates(user_data_dir());
231 // Optionally do any final setup of the test environment.
232 if (!state
.setup_profile_callback
.is_null())
233 state
.setup_profile_callback
.Run();
235 if (!LaunchBrowserHelper(state
, true, false, &process_
)) {
236 LOG(ERROR
) << "LaunchBrowserHelper failed.";
239 process_id_
= base::GetProcId(process_
);
244 void ProxyLauncher::QuitBrowser() {
245 // If we have already finished waiting for the browser to exit
246 // (or it hasn't launched at all), there's nothing to do here.
247 if (process_
== base::kNullProcessHandle
|| !automation_proxy_
.get())
250 if (SESSION_ENDING
== shutdown_type_
) {
255 base::TimeTicks quit_start
= base::TimeTicks::Now();
257 if (WINDOW_CLOSE
== shutdown_type_
) {
258 int window_count
= 0;
259 EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count
));
261 // Synchronously close all but the last browser window. Closing them
262 // one-by-one may help with stability.
263 while (window_count
> 1) {
264 scoped_refptr
<BrowserProxy
> browser_proxy
=
265 automation()->GetBrowserWindow(0);
266 EXPECT_TRUE(browser_proxy
.get());
267 if (browser_proxy
.get()) {
268 EXPECT_TRUE(browser_proxy
->RunCommand(IDC_CLOSE_WINDOW
));
269 EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count
));
275 // Close the last window asynchronously, because the browser may
276 // shutdown faster than it will be able to send a synchronous response
278 scoped_refptr
<BrowserProxy
> browser_proxy
=
279 automation()->GetBrowserWindow(0);
280 EXPECT_TRUE(browser_proxy
.get());
281 if (browser_proxy
.get()) {
282 EXPECT_TRUE(browser_proxy
->is_valid());
283 EXPECT_TRUE(browser_proxy
->ApplyAccelerator(IDC_CLOSE_WINDOW
));
284 browser_proxy
= NULL
;
286 } else if (USER_QUIT
== shutdown_type_
) {
287 scoped_refptr
<BrowserProxy
> browser_proxy
=
288 automation()->GetBrowserWindow(0);
289 EXPECT_TRUE(browser_proxy
.get());
290 if (browser_proxy
.get()) {
291 EXPECT_TRUE(browser_proxy
->RunCommandAsync(IDC_EXIT
));
294 NOTREACHED() << "Invalid shutdown type " << shutdown_type_
;
297 ChromeProcessList processes
= GetRunningChromeProcesses(process_id_
);
299 // Now, drop the automation IPC channel so that the automation provider in
300 // the browser notices and drops its reference to the browser process.
301 if (automation_proxy_
.get())
302 automation_proxy_
->Disconnect();
304 // Wait for the browser process to quit. It should quit once all tabs have
307 EXPECT_TRUE(WaitForBrowserProcessToQuit(
308 TestTimeouts::action_max_timeout(), &exit_code
));
309 EXPECT_EQ(0, exit_code
); // Expect a clean shutdown.
311 browser_quit_time_
= base::TimeTicks::Now() - quit_start
;
313 // Ensure no child processes are left dangling.
314 TerminateAllChromeProcesses(processes
);
317 void ProxyLauncher::TerminateBrowser() {
318 // If we have already finished waiting for the browser to exit
319 // (or it hasn't launched at all), there's nothing to do here.
320 if (process_
== base::kNullProcessHandle
|| !automation_proxy_
.get())
323 base::TimeTicks quit_start
= base::TimeTicks::Now();
325 ChromeProcessList processes
= GetRunningChromeProcesses(process_id_
);
327 // Now, drop the automation IPC channel so that the automation provider in
328 // the browser notices and drops its reference to the browser process.
329 if (automation_proxy_
.get())
330 automation_proxy_
->Disconnect();
332 #if defined(OS_POSIX)
333 EXPECT_EQ(kill(process_
, SIGTERM
), 0);
337 EXPECT_TRUE(WaitForBrowserProcessToQuit(
338 TestTimeouts::action_max_timeout(), &exit_code
));
339 EXPECT_EQ(0, exit_code
); // Expect a clean shutdown.
341 browser_quit_time_
= base::TimeTicks::Now() - quit_start
;
343 // Ensure no child processes are left dangling.
344 TerminateAllChromeProcesses(processes
);
347 void ProxyLauncher::AssertAppNotRunning(const std::string
& error_message
) {
348 std::string
final_error_message(error_message
);
350 ChromeProcessList processes
= GetRunningChromeProcesses(process_id_
);
351 if (!processes
.empty()) {
352 final_error_message
+= " Leftover PIDs: [";
353 for (ChromeProcessList::const_iterator it
= processes
.begin();
354 it
!= processes
.end(); ++it
) {
355 final_error_message
+= base::StringPrintf(" %d", *it
);
357 final_error_message
+= " ]";
359 ASSERT_TRUE(processes
.empty()) << final_error_message
;
362 bool ProxyLauncher::WaitForBrowserProcessToQuit(
363 base::TimeDelta timeout
,
365 #ifdef WAIT_FOR_DEBUGGER_ON_OPEN
366 timeout
= base::TimeDelta::FromSeconds(500);
368 bool success
= false;
370 // Only wait for exit if the "browser, please terminate" message had a
371 // chance of making it through.
372 if (!automation_proxy_
->channel_disconnected_on_failure())
373 success
= base::WaitForExitCodeWithTimeout(process_
, exit_code
, timeout
);
375 base::CloseProcessHandle(process_
);
376 process_
= base::kNullProcessHandle
;
382 void ProxyLauncher::PrepareTestCommandline(CommandLine
* command_line
,
383 bool include_testing_id
) {
384 // Add any explicit command line flags passed to the process.
385 CommandLine::StringType extra_chrome_flags
=
386 CommandLine::ForCurrentProcess()->GetSwitchValueNative(
387 switches::kExtraChromeFlags
);
388 if (!extra_chrome_flags
.empty()) {
389 // Split by spaces and append to command line.
390 std::vector
<CommandLine::StringType
> flags
;
391 base::SplitStringAlongWhitespace(extra_chrome_flags
, &flags
);
392 for (size_t i
= 0; i
< flags
.size(); ++i
)
393 command_line
->AppendArgNative(flags
[i
]);
396 // Also look for extra flags in environment.
397 scoped_ptr
<base::Environment
> env(base::Environment::Create());
398 std::string extra_from_env
;
399 if (env
->GetVar("EXTRA_CHROME_FLAGS", &extra_from_env
)) {
400 std::vector
<std::string
> flags
;
401 base::SplitStringAlongWhitespace(extra_from_env
, &flags
);
402 for (size_t i
= 0; i
< flags
.size(); ++i
)
403 command_line
->AppendArg(flags
[i
]);
406 // No default browser check, it would create an info-bar (if we are not the
407 // default browser) that could conflicts with some tests expectations.
408 command_line
->AppendSwitch(switches::kNoDefaultBrowserCheck
);
410 // This is a UI test.
411 command_line
->AppendSwitchASCII(switches::kTestType
, kUITestType
);
413 // Tell the browser to use a temporary directory just for this test
414 // if it is not already set.
415 if (command_line
->GetSwitchValuePath(switches::kUserDataDir
).empty()) {
416 command_line
->AppendSwitchPath(switches::kUserDataDir
, user_data_dir());
419 if (include_testing_id
)
420 command_line
->AppendSwitchASCII(switches::kTestingChannelID
,
421 PrefixedChannelID());
423 if (!show_error_dialogs_
)
424 command_line
->AppendSwitch(switches::kNoErrorDialogs
);
426 command_line
->AppendSwitch(switches::kNoSandbox
);
427 if (full_memory_dump_
)
428 command_line
->AppendSwitch(switches::kFullMemoryCrashReport
);
429 if (silent_dump_on_dcheck_
)
430 command_line
->AppendSwitch(switches::kSilentDumpOnDCHECK
);
431 if (disable_breakpad_
)
432 command_line
->AppendSwitch(switches::kDisableBreakpad
);
434 if (!js_flags_
.empty())
435 command_line
->AppendSwitchASCII(switches::kJavaScriptFlags
, js_flags_
);
436 if (!log_level_
.empty())
437 command_line
->AppendSwitchASCII(switches::kLoggingLevel
, log_level_
);
439 command_line
->AppendSwitch(switches::kMetricsRecordingOnly
);
441 if (!CommandLine::ForCurrentProcess()->HasSwitch(
442 switches::kEnableErrorDialogs
))
443 command_line
->AppendSwitch(switches::kEnableLogging
);
445 #ifdef WAIT_FOR_DEBUGGER_ON_OPEN
446 command_line
->AppendSwitch(switches::kDebugOnStart
);
449 // Force the app to always exit when the last browser window is closed.
450 command_line
->AppendSwitch(switches::kDisableZeroBrowsersOpenForTests
);
452 // Allow file:// access on ChromeOS.
453 command_line
->AppendSwitch(switches::kAllowFileAccess
);
455 // The tests assume that file:// URIs can freely access other file:// URIs.
456 command_line
->AppendSwitch(switches::kAllowFileAccessFromFiles
);
459 bool ProxyLauncher::LaunchBrowserHelper(const LaunchState
& state
,
462 base::ProcessHandle
* process
) {
463 CommandLine
command_line(state
.command
);
465 // Add command line arguments that should be applied to all UI tests.
466 PrepareTestCommandline(&command_line
, state
.include_testing_id
);
468 // Sometimes one needs to run the browser under a special environment
469 // (e.g. valgrind) without also running the test harness (e.g. python)
470 // under the special environment. Provide a way to wrap the browser
471 // commandline with a special prefix to invoke the special environment.
472 const char* browser_wrapper
= getenv("BROWSER_WRAPPER");
473 if (browser_wrapper
) {
475 command_line
.PrependWrapper(base::ASCIIToWide(browser_wrapper
));
476 #elif defined(OS_POSIX)
477 command_line
.PrependWrapper(browser_wrapper
);
479 VLOG(1) << "BROWSER_WRAPPER was set, prefixing command_line with "
484 browser_launch_time_
= base::TimeTicks::Now();
486 base::LaunchOptions options
;
490 options
.start_hidden
= !state
.show_window
;
491 #elif defined(OS_POSIX)
493 file_util::ScopedFD
ipcfd_closer(&ipcfd
);
494 base::FileHandleMappingVector fds
;
495 if (main_launch
&& automation_proxy_
.get()) {
496 ipcfd
= automation_proxy_
->channel()->TakeClientFileDescriptor();
497 fds
.push_back(std::make_pair(ipcfd
,
498 kPrimaryIPCChannel
+ base::GlobalDescriptors::kBaseDescriptor
));
499 options
.fds_to_remap
= &fds
;
503 return base::LaunchProcess(command_line
, options
, process
);
506 AutomationProxy
* ProxyLauncher::automation() const {
507 EXPECT_TRUE(automation_proxy_
.get());
508 return automation_proxy_
.get();
511 base::FilePath
ProxyLauncher::user_data_dir() const {
512 EXPECT_TRUE(temp_profile_dir_
.IsValid());
513 return temp_profile_dir_
.path();
516 base::ProcessHandle
ProxyLauncher::process() const {
520 base::ProcessId
ProxyLauncher::process_id() const {
524 base::TimeTicks
ProxyLauncher::browser_launch_time() const {
525 return browser_launch_time_
;
528 base::TimeDelta
ProxyLauncher::browser_quit_time() const {
529 return browser_quit_time_
;
532 // NamedProxyLauncher functions
534 NamedProxyLauncher::NamedProxyLauncher(const std::string
& channel_id
,
536 bool disconnect_on_failure
)
537 : channel_id_(channel_id
),
538 launch_browser_(launch_browser
),
539 disconnect_on_failure_(disconnect_on_failure
) {
542 AutomationProxy
* NamedProxyLauncher::CreateAutomationProxy(
543 base::TimeDelta execution_timeout
) {
544 AutomationProxy
* proxy
= new AutomationProxy(execution_timeout
,
545 disconnect_on_failure_
);
546 proxy
->InitializeChannel(channel_id_
, true);
550 bool NamedProxyLauncher::InitializeConnection(const LaunchState
& state
,
551 bool wait_for_initial_loads
) {
552 if (launch_browser_
) {
553 #if defined(OS_POSIX)
554 // Because we are waiting on the existence of the testing file below,
555 // make sure there isn't one already there before browser launch.
556 if (!base::DeleteFile(base::FilePath(channel_id_
), false)) {
557 LOG(ERROR
) << "Failed to delete " << channel_id_
;
562 if (!LaunchBrowser(state
)) {
563 LOG(ERROR
) << "Failed to LaunchBrowser";
568 // Wait for browser to be ready for connections.
569 bool channel_initialized
= false;
570 base::TimeDelta sleep_time
= base::TimeDelta::FromMilliseconds(
571 automation::kSleepTime
);
572 for (base::TimeDelta wait_time
= base::TimeDelta();
573 wait_time
< TestTimeouts::action_max_timeout();
574 wait_time
+= sleep_time
) {
575 channel_initialized
= IPC::Channel::IsNamedServerInitialized(channel_id_
);
576 if (channel_initialized
)
578 base::PlatformThread::Sleep(sleep_time
);
580 if (!channel_initialized
) {
581 LOG(ERROR
) << "Failed to wait for testing channel presence.";
585 if (!ConnectToRunningBrowser(wait_for_initial_loads
)) {
586 LOG(ERROR
) << "Failed to ConnectToRunningBrowser";
592 void NamedProxyLauncher::TerminateConnection() {
594 CloseBrowserAndServer();
596 DisconnectFromRunningBrowser();
599 std::string
NamedProxyLauncher::PrefixedChannelID() const {
600 std::string channel_id
;
601 channel_id
.append(automation::kNamedInterfacePrefix
).append(channel_id_
);
605 // AnonymousProxyLauncher functions
607 AnonymousProxyLauncher::AnonymousProxyLauncher(bool disconnect_on_failure
)
608 : disconnect_on_failure_(disconnect_on_failure
) {
609 channel_id_
= AutomationProxy::GenerateChannelID();
612 AutomationProxy
* AnonymousProxyLauncher::CreateAutomationProxy(
613 base::TimeDelta execution_timeout
) {
614 AutomationProxy
* proxy
= new AutomationProxy(execution_timeout
,
615 disconnect_on_failure_
);
616 proxy
->InitializeChannel(channel_id_
, false);
620 bool AnonymousProxyLauncher::InitializeConnection(const LaunchState
& state
,
621 bool wait_for_initial_loads
) {
622 return LaunchBrowserAndServer(state
, wait_for_initial_loads
);
625 void AnonymousProxyLauncher::TerminateConnection() {
626 CloseBrowserAndServer();
629 std::string
AnonymousProxyLauncher::PrefixedChannelID() const {