Home | History | Annotate | Download | only in automation
      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.
      4 
      5 #include "chrome/test/automation/proxy_launcher.h"
      6 
      7 #include <vector>
      8 
      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"
     35 
     36 #if defined(OS_POSIX)
     37 #include <signal.h>
     38 #include "base/posix/global_descriptors.h"
     39 #endif
     40 
     41 namespace {
     42 
     43 // Passed as value of kTestType.
     44 const char kUITestType[] = "ui";
     45 
     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.
     50 //
     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))
     62         return false;
     63     } else {
     64       if (!base::CopyFile(cur, dest.Append(cur.BaseName())))
     65         return false;
     66     }
     67   }
     68 
     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);
     75   return true;
     76 }
     77 
     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.
     84   sql::Connection db;
     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))
     89     return;
     90 
     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 "
     96       "SET time_slot = %s "
     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()));
    100   db.Close();
    101   file_util::EvictFileFromSystemCache(history);
    102 }
    103 
    104 }  // namespace
    105 
    106 // ProxyLauncher functions
    107 
    108 #if defined(OS_WIN)
    109 const char ProxyLauncher::kDefaultInterfaceId[] = "ChromeTestingInterface";
    110 #elif defined(OS_POSIX)
    111 const char ProxyLauncher::kDefaultInterfaceId[] =
    112     "/var/tmp/ChromeTestingInterface";
    113 #endif
    114 
    115 ProxyLauncher::ProxyLauncher()
    116     : process_(base::kNullProcessHandle),
    117       process_id_(-1),
    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       enable_dcheck_(CommandLine::ForCurrentProcess()->HasSwitch(
    126                          switches::kEnableDCHECK)),
    127       silent_dump_on_dcheck_(CommandLine::ForCurrentProcess()->HasSwitch(
    128                                  switches::kSilentDumpOnDCHECK)),
    129       disable_breakpad_(CommandLine::ForCurrentProcess()->HasSwitch(
    130                             switches::kDisableBreakpad)),
    131       js_flags_(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
    132                     switches::kJavaScriptFlags)),
    133       log_level_(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
    134                      switches::kLoggingLevel)) {
    135 }
    136 
    137 ProxyLauncher::~ProxyLauncher() {}
    138 
    139 bool ProxyLauncher::WaitForBrowserLaunch(bool wait_for_initial_loads) {
    140   AutomationLaunchResult app_launched = automation_proxy_->WaitForAppLaunch();
    141   EXPECT_EQ(AUTOMATION_SUCCESS, app_launched)
    142       << "Error while awaiting automation ping from browser process";
    143   if (app_launched != AUTOMATION_SUCCESS)
    144     return false;
    145 
    146   if (wait_for_initial_loads) {
    147     if (!automation_proxy_->WaitForInitialLoads()) {
    148       LOG(ERROR) << "WaitForInitialLoads failed.";
    149       return false;
    150     }
    151   } else {
    152 #if defined(OS_WIN)
    153     // TODO(phajdan.jr): Get rid of this Sleep when logging_chrome_uitest
    154     // stops "relying" on it.
    155     base::PlatformThread::Sleep(TestTimeouts::action_timeout());
    156 #endif
    157   }
    158 
    159   return true;
    160 }
    161 
    162 bool ProxyLauncher::LaunchBrowserAndServer(const LaunchState& state,
    163                                            bool wait_for_initial_loads) {
    164   // Set up IPC testing interface as a server.
    165   automation_proxy_.reset(CreateAutomationProxy(
    166       TestTimeouts::action_max_timeout()));
    167 
    168   if (!LaunchBrowser(state))
    169     return false;
    170 
    171   if (!WaitForBrowserLaunch(wait_for_initial_loads))
    172     return false;
    173 
    174   return true;
    175 }
    176 
    177 bool ProxyLauncher::ConnectToRunningBrowser(bool wait_for_initial_loads) {
    178   // Set up IPC testing interface as a client.
    179   automation_proxy_.reset(CreateAutomationProxy(
    180                               TestTimeouts::action_max_timeout()));
    181 
    182   return WaitForBrowserLaunch(wait_for_initial_loads);
    183 }
    184 
    185 void ProxyLauncher::CloseBrowserAndServer() {
    186   QuitBrowser();
    187 
    188   // Suppress spammy failures that seem to be occurring when running
    189   // the UI tests in single-process mode.
    190   // TODO(jhughes): figure out why this is necessary at all, and fix it
    191   AssertAppNotRunning(
    192       base::StringPrintf(
    193           "Unable to quit all browser processes. Original PID %d",
    194           process_id_));
    195 
    196   DisconnectFromRunningBrowser();
    197 }
    198 
    199 void ProxyLauncher::DisconnectFromRunningBrowser() {
    200   automation_proxy_.reset();  // Shut down IPC testing interface.
    201 }
    202 
    203 bool ProxyLauncher::LaunchBrowser(const LaunchState& state) {
    204   if (state.clear_profile || !temp_profile_dir_.IsValid()) {
    205     if (temp_profile_dir_.IsValid() && !temp_profile_dir_.Delete()) {
    206       LOG(ERROR) << "Failed to delete temporary directory.";
    207       return false;
    208     }
    209 
    210     if (!temp_profile_dir_.CreateUniqueTempDir()) {
    211       LOG(ERROR) << "Failed to create temporary directory.";
    212       return false;
    213     }
    214 
    215     if (!test_launcher_utils::OverrideUserDataDir(user_data_dir())) {
    216       LOG(ERROR) << "Failed to override user data directory.";
    217       return false;
    218     }
    219   }
    220 
    221   if (!state.template_user_data.empty()) {
    222     // Recursively copy the template directory to the user_data_dir.
    223     if (!CopyDirectoryContentsNoCache(state.template_user_data,
    224                                       user_data_dir())) {
    225       LOG(ERROR) << "Failed to copy user data directory template.";
    226       return false;
    227     }
    228 
    229     // Update the history file to include recent dates.
    230     UpdateHistoryDates(user_data_dir());
    231   }
    232 
    233   // Optionally do any final setup of the test environment.
    234   if (!state.setup_profile_callback.is_null())
    235     state.setup_profile_callback.Run();
    236 
    237   if (!LaunchBrowserHelper(state, true, false, &process_)) {
    238     LOG(ERROR) << "LaunchBrowserHelper failed.";
    239     return false;
    240   }
    241   process_id_ = base::GetProcId(process_);
    242 
    243   return true;
    244 }
    245 
    246 void ProxyLauncher::QuitBrowser() {
    247   // If we have already finished waiting for the browser to exit
    248   // (or it hasn't launched at all), there's nothing to do here.
    249   if (process_ == base::kNullProcessHandle || !automation_proxy_.get())
    250     return;
    251 
    252   if (SESSION_ENDING == shutdown_type_) {
    253     TerminateBrowser();
    254     return;
    255   }
    256 
    257   base::TimeTicks quit_start = base::TimeTicks::Now();
    258 
    259   if (WINDOW_CLOSE == shutdown_type_) {
    260     int window_count = 0;
    261     EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count));
    262 
    263     // Synchronously close all but the last browser window. Closing them
    264     // one-by-one may help with stability.
    265     while (window_count > 1) {
    266       scoped_refptr<BrowserProxy> browser_proxy =
    267           automation()->GetBrowserWindow(0);
    268       EXPECT_TRUE(browser_proxy.get());
    269       if (browser_proxy.get()) {
    270         EXPECT_TRUE(browser_proxy->RunCommand(IDC_CLOSE_WINDOW));
    271         EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count));
    272       } else {
    273         break;
    274       }
    275     }
    276 
    277     // Close the last window asynchronously, because the browser may
    278     // shutdown faster than it will be able to send a synchronous response
    279     // to our message.
    280     scoped_refptr<BrowserProxy> browser_proxy =
    281         automation()->GetBrowserWindow(0);
    282     EXPECT_TRUE(browser_proxy.get());
    283     if (browser_proxy.get()) {
    284       EXPECT_TRUE(browser_proxy->is_valid());
    285       EXPECT_TRUE(browser_proxy->ApplyAccelerator(IDC_CLOSE_WINDOW));
    286       browser_proxy = NULL;
    287     }
    288   } else if (USER_QUIT == shutdown_type_) {
    289     scoped_refptr<BrowserProxy> browser_proxy =
    290         automation()->GetBrowserWindow(0);
    291     EXPECT_TRUE(browser_proxy.get());
    292     if (browser_proxy.get()) {
    293       EXPECT_TRUE(browser_proxy->RunCommandAsync(IDC_EXIT));
    294     }
    295   } else {
    296     NOTREACHED() << "Invalid shutdown type " << shutdown_type_;
    297   }
    298 
    299   ChromeProcessList processes = GetRunningChromeProcesses(process_id_);
    300 
    301   // Now, drop the automation IPC channel so that the automation provider in
    302   // the browser notices and drops its reference to the browser process.
    303   if (automation_proxy_.get())
    304     automation_proxy_->Disconnect();
    305 
    306   // Wait for the browser process to quit. It should quit once all tabs have
    307   // been closed.
    308   int exit_code = -1;
    309   EXPECT_TRUE(WaitForBrowserProcessToQuit(
    310                   TestTimeouts::action_max_timeout(), &exit_code));
    311   EXPECT_EQ(0, exit_code);  // Expect a clean shutdown.
    312 
    313   browser_quit_time_ = base::TimeTicks::Now() - quit_start;
    314 
    315   // Ensure no child processes are left dangling.
    316   TerminateAllChromeProcesses(processes);
    317 }
    318 
    319 void ProxyLauncher::TerminateBrowser() {
    320   // If we have already finished waiting for the browser to exit
    321   // (or it hasn't launched at all), there's nothing to do here.
    322   if (process_ == base::kNullProcessHandle || !automation_proxy_.get())
    323     return;
    324 
    325   base::TimeTicks quit_start = base::TimeTicks::Now();
    326 
    327 #if defined(OS_WIN) && !defined(USE_AURA)
    328   scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
    329   ASSERT_TRUE(browser.get());
    330   ASSERT_TRUE(browser->TerminateSession());
    331 #endif  // defined(OS_WIN)
    332 
    333   ChromeProcessList processes = GetRunningChromeProcesses(process_id_);
    334 
    335   // Now, drop the automation IPC channel so that the automation provider in
    336   // the browser notices and drops its reference to the browser process.
    337   if (automation_proxy_.get())
    338     automation_proxy_->Disconnect();
    339 
    340 #if defined(OS_POSIX)
    341   EXPECT_EQ(kill(process_, SIGTERM), 0);
    342 #endif  // OS_POSIX
    343 
    344   int exit_code = -1;
    345   EXPECT_TRUE(WaitForBrowserProcessToQuit(
    346                   TestTimeouts::action_max_timeout(), &exit_code));
    347   EXPECT_EQ(0, exit_code);  // Expect a clean shutdown.
    348 
    349   browser_quit_time_ = base::TimeTicks::Now() - quit_start;
    350 
    351   // Ensure no child processes are left dangling.
    352   TerminateAllChromeProcesses(processes);
    353 }
    354 
    355 void ProxyLauncher::AssertAppNotRunning(const std::string& error_message) {
    356   std::string final_error_message(error_message);
    357 
    358   ChromeProcessList processes = GetRunningChromeProcesses(process_id_);
    359   if (!processes.empty()) {
    360     final_error_message += " Leftover PIDs: [";
    361     for (ChromeProcessList::const_iterator it = processes.begin();
    362          it != processes.end(); ++it) {
    363       final_error_message += base::StringPrintf(" %d", *it);
    364     }
    365     final_error_message += " ]";
    366   }
    367   ASSERT_TRUE(processes.empty()) << final_error_message;
    368 }
    369 
    370 bool ProxyLauncher::WaitForBrowserProcessToQuit(
    371     base::TimeDelta timeout,
    372     int* exit_code) {
    373 #ifdef WAIT_FOR_DEBUGGER_ON_OPEN
    374   timeout = base::TimeDelta::FromSeconds(500);
    375 #endif
    376   bool success = false;
    377 
    378   // Only wait for exit if the "browser, please terminate" message had a
    379   // chance of making it through.
    380   if (!automation_proxy_->channel_disconnected_on_failure())
    381     success = base::WaitForExitCodeWithTimeout(process_, exit_code, timeout);
    382 
    383   base::CloseProcessHandle(process_);
    384   process_ = base::kNullProcessHandle;
    385   process_id_ = -1;
    386 
    387   return success;
    388 }
    389 
    390 void ProxyLauncher::PrepareTestCommandline(CommandLine* command_line,
    391                                            bool include_testing_id) {
    392   // Add any explicit command line flags passed to the process.
    393   CommandLine::StringType extra_chrome_flags =
    394       CommandLine::ForCurrentProcess()->GetSwitchValueNative(
    395           switches::kExtraChromeFlags);
    396   if (!extra_chrome_flags.empty()) {
    397     // Split by spaces and append to command line.
    398     std::vector<CommandLine::StringType> flags;
    399     base::SplitStringAlongWhitespace(extra_chrome_flags, &flags);
    400     for (size_t i = 0; i < flags.size(); ++i)
    401       command_line->AppendArgNative(flags[i]);
    402   }
    403 
    404   // Also look for extra flags in environment.
    405   scoped_ptr<base::Environment> env(base::Environment::Create());
    406   std::string extra_from_env;
    407   if (env->GetVar("EXTRA_CHROME_FLAGS", &extra_from_env)) {
    408     std::vector<std::string> flags;
    409     base::SplitStringAlongWhitespace(extra_from_env, &flags);
    410     for (size_t i = 0; i < flags.size(); ++i)
    411       command_line->AppendArg(flags[i]);
    412   }
    413 
    414   // No default browser check, it would create an info-bar (if we are not the
    415   // default browser) that could conflicts with some tests expectations.
    416   command_line->AppendSwitch(switches::kNoDefaultBrowserCheck);
    417 
    418   // This is a UI test.
    419   command_line->AppendSwitchASCII(switches::kTestType, kUITestType);
    420 
    421   // Tell the browser to use a temporary directory just for this test
    422   // if it is not already set.
    423   if (command_line->GetSwitchValuePath(switches::kUserDataDir).empty()) {
    424     command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir());
    425   }
    426 
    427   if (include_testing_id)
    428     command_line->AppendSwitchASCII(switches::kTestingChannelID,
    429                                     PrefixedChannelID());
    430 
    431   if (!show_error_dialogs_)
    432     command_line->AppendSwitch(switches::kNoErrorDialogs);
    433   if (no_sandbox_)
    434     command_line->AppendSwitch(switches::kNoSandbox);
    435   if (full_memory_dump_)
    436     command_line->AppendSwitch(switches::kFullMemoryCrashReport);
    437   if (enable_dcheck_)
    438     command_line->AppendSwitch(switches::kEnableDCHECK);
    439   if (silent_dump_on_dcheck_)
    440     command_line->AppendSwitch(switches::kSilentDumpOnDCHECK);
    441   if (disable_breakpad_)
    442     command_line->AppendSwitch(switches::kDisableBreakpad);
    443 
    444   if (!js_flags_.empty())
    445     command_line->AppendSwitchASCII(switches::kJavaScriptFlags, js_flags_);
    446   if (!log_level_.empty())
    447     command_line->AppendSwitchASCII(switches::kLoggingLevel, log_level_);
    448 
    449   command_line->AppendSwitch(switches::kMetricsRecordingOnly);
    450 
    451   if (!CommandLine::ForCurrentProcess()->HasSwitch(
    452           switches::kEnableErrorDialogs))
    453     command_line->AppendSwitch(switches::kEnableLogging);
    454 
    455 #ifdef WAIT_FOR_DEBUGGER_ON_OPEN
    456   command_line->AppendSwitch(switches::kDebugOnStart);
    457 #endif
    458 
    459   // Force the app to always exit when the last browser window is closed.
    460   command_line->AppendSwitch(switches::kDisableZeroBrowsersOpenForTests);
    461 
    462   // Allow file:// access on ChromeOS.
    463   command_line->AppendSwitch(switches::kAllowFileAccess);
    464 
    465   // The tests assume that file:// URIs can freely access other file:// URIs.
    466   command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);
    467 }
    468 
    469 bool ProxyLauncher::LaunchBrowserHelper(const LaunchState& state,
    470                                         bool main_launch,
    471                                         bool wait,
    472                                         base::ProcessHandle* process) {
    473   CommandLine command_line(state.command);
    474 
    475   // Add command line arguments that should be applied to all UI tests.
    476   PrepareTestCommandline(&command_line, state.include_testing_id);
    477 
    478   // Sometimes one needs to run the browser under a special environment
    479   // (e.g. valgrind) without also running the test harness (e.g. python)
    480   // under the special environment.  Provide a way to wrap the browser
    481   // commandline with a special prefix to invoke the special environment.
    482   const char* browser_wrapper = getenv("BROWSER_WRAPPER");
    483   if (browser_wrapper) {
    484 #if defined(OS_WIN)
    485     command_line.PrependWrapper(ASCIIToWide(browser_wrapper));
    486 #elif defined(OS_POSIX)
    487     command_line.PrependWrapper(browser_wrapper);
    488 #endif
    489     VLOG(1) << "BROWSER_WRAPPER was set, prefixing command_line with "
    490             << browser_wrapper;
    491   }
    492 
    493   if (main_launch)
    494     browser_launch_time_ = base::TimeTicks::Now();
    495 
    496   base::LaunchOptions options;
    497   options.wait = wait;
    498 
    499 #if defined(OS_WIN)
    500   options.start_hidden = !state.show_window;
    501 #elif defined(OS_POSIX)
    502   int ipcfd = -1;
    503   file_util::ScopedFD ipcfd_closer(&ipcfd);
    504   base::FileHandleMappingVector fds;
    505   if (main_launch && automation_proxy_.get()) {
    506     ipcfd = automation_proxy_->channel()->TakeClientFileDescriptor();
    507     fds.push_back(std::make_pair(ipcfd,
    508         kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor));
    509     options.fds_to_remap = &fds;
    510   }
    511 #endif
    512 
    513   return base::LaunchProcess(command_line, options, process);
    514 }
    515 
    516 AutomationProxy* ProxyLauncher::automation() const {
    517   EXPECT_TRUE(automation_proxy_.get());
    518   return automation_proxy_.get();
    519 }
    520 
    521 base::FilePath ProxyLauncher::user_data_dir() const {
    522   EXPECT_TRUE(temp_profile_dir_.IsValid());
    523   return temp_profile_dir_.path();
    524 }
    525 
    526 base::ProcessHandle ProxyLauncher::process() const {
    527   return process_;
    528 }
    529 
    530 base::ProcessId ProxyLauncher::process_id() const {
    531   return process_id_;
    532 }
    533 
    534 base::TimeTicks ProxyLauncher::browser_launch_time() const {
    535   return browser_launch_time_;
    536 }
    537 
    538 base::TimeDelta ProxyLauncher::browser_quit_time() const {
    539   return browser_quit_time_;
    540 }
    541 
    542 // NamedProxyLauncher functions
    543 
    544 NamedProxyLauncher::NamedProxyLauncher(const std::string& channel_id,
    545                                        bool launch_browser,
    546                                        bool disconnect_on_failure)
    547     : channel_id_(channel_id),
    548       launch_browser_(launch_browser),
    549       disconnect_on_failure_(disconnect_on_failure) {
    550 }
    551 
    552 AutomationProxy* NamedProxyLauncher::CreateAutomationProxy(
    553     base::TimeDelta execution_timeout) {
    554   AutomationProxy* proxy = new AutomationProxy(execution_timeout,
    555                                                disconnect_on_failure_);
    556   proxy->InitializeChannel(channel_id_, true);
    557   return proxy;
    558 }
    559 
    560 bool NamedProxyLauncher::InitializeConnection(const LaunchState& state,
    561                                               bool wait_for_initial_loads) {
    562   if (launch_browser_) {
    563 #if defined(OS_POSIX)
    564     // Because we are waiting on the existence of the testing file below,
    565     // make sure there isn't one already there before browser launch.
    566     if (!base::DeleteFile(base::FilePath(channel_id_), false)) {
    567       LOG(ERROR) << "Failed to delete " << channel_id_;
    568       return false;
    569     }
    570 #endif
    571 
    572     if (!LaunchBrowser(state)) {
    573       LOG(ERROR) << "Failed to LaunchBrowser";
    574       return false;
    575     }
    576   }
    577 
    578   // Wait for browser to be ready for connections.
    579   bool channel_initialized = false;
    580   base::TimeDelta sleep_time = base::TimeDelta::FromMilliseconds(
    581       automation::kSleepTime);
    582   for (base::TimeDelta wait_time = base::TimeDelta();
    583        wait_time < TestTimeouts::action_max_timeout();
    584        wait_time += sleep_time) {
    585     channel_initialized = IPC::Channel::IsNamedServerInitialized(channel_id_);
    586     if (channel_initialized)
    587       break;
    588     base::PlatformThread::Sleep(sleep_time);
    589   }
    590   if (!channel_initialized) {
    591     LOG(ERROR) << "Failed to wait for testing channel presence.";
    592     return false;
    593   }
    594 
    595   if (!ConnectToRunningBrowser(wait_for_initial_loads)) {
    596     LOG(ERROR) << "Failed to ConnectToRunningBrowser";
    597     return false;
    598   }
    599   return true;
    600 }
    601 
    602 void NamedProxyLauncher::TerminateConnection() {
    603   if (launch_browser_)
    604     CloseBrowserAndServer();
    605   else
    606     DisconnectFromRunningBrowser();
    607 }
    608 
    609 std::string NamedProxyLauncher::PrefixedChannelID() const {
    610   std::string channel_id;
    611   channel_id.append(automation::kNamedInterfacePrefix).append(channel_id_);
    612   return channel_id;
    613 }
    614 
    615 // AnonymousProxyLauncher functions
    616 
    617 AnonymousProxyLauncher::AnonymousProxyLauncher(bool disconnect_on_failure)
    618     : disconnect_on_failure_(disconnect_on_failure) {
    619   channel_id_ = AutomationProxy::GenerateChannelID();
    620 }
    621 
    622 AutomationProxy* AnonymousProxyLauncher::CreateAutomationProxy(
    623     base::TimeDelta execution_timeout) {
    624   AutomationProxy* proxy = new AutomationProxy(execution_timeout,
    625                                                disconnect_on_failure_);
    626   proxy->InitializeChannel(channel_id_, false);
    627   return proxy;
    628 }
    629 
    630 bool AnonymousProxyLauncher::InitializeConnection(const LaunchState& state,
    631                                                   bool wait_for_initial_loads) {
    632   return LaunchBrowserAndServer(state, wait_for_initial_loads);
    633 }
    634 
    635 void AnonymousProxyLauncher::TerminateConnection() {
    636   CloseBrowserAndServer();
    637 }
    638 
    639 std::string AnonymousProxyLauncher::PrefixedChannelID() const {
    640   return channel_id_;
    641 }
    642