Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / test / remoting / remote_desktop_browsertest.cc
1 // Copyright 2013 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/remoting/remote_desktop_browsertest.h"
6
7 #include "base/command_line.h"
8 #include "base/files/file_util.h"
9 #include "base/json/json_reader.h"
10 #include "base/path_service.h"
11 #include "chrome/browser/extensions/extension_service.h"
12 #include "chrome/browser/extensions/unpacked_installer.h"
13 #include "chrome/browser/ui/extensions/application_launch.h"
14 #include "chrome/common/chrome_switches.h"
15 #include "chrome/test/remoting/key_code_conv.h"
16 #include "chrome/test/remoting/page_load_notification_observer.h"
17 #include "chrome/test/remoting/waiter.h"
18 #include "content/public/browser/native_web_keyboard_event.h"
19 #include "content/public/browser/render_view_host.h"
20 #include "content/public/test/test_utils.h"
21 #include "extensions/common/constants.h"
22 #include "extensions/common/extension.h"
23 #include "extensions/common/extension_set.h"
24 #include "extensions/common/switches.h"
25 #include "ui/base/window_open_disposition.h"
26
27 namespace remoting {
28
29 RemoteDesktopBrowserTest::RemoteDesktopBrowserTest()
30     : extension_(NULL) {
31 }
32
33 RemoteDesktopBrowserTest::~RemoteDesktopBrowserTest() {}
34
35 void RemoteDesktopBrowserTest::SetUp() {
36   ParseCommandLine();
37   PlatformAppBrowserTest::SetUp();
38 }
39
40 void RemoteDesktopBrowserTest::SetUpOnMainThread() {
41   PlatformAppBrowserTest::SetUpOnMainThread();
42
43   // Pushing the initial WebContents instance onto the stack before
44   // RunTestOnMainThread() and after |InProcessBrowserTest::browser_|
45   // is initialized in InProcessBrowserTest::RunTestOnMainThreadLoop()
46   web_contents_stack_.push_back(
47       browser()->tab_strip_model()->GetActiveWebContents());
48 }
49
50 // Change behavior of the default host resolver to avoid DNS lookup errors,
51 // so we can make network calls.
52 void RemoteDesktopBrowserTest::SetUpInProcessBrowserTestFixture() {
53   // The resolver object lifetime is managed by sync_test_setup, not here.
54   EnableDNSLookupForThisTest(
55       new net::RuleBasedHostResolverProc(host_resolver()));
56 }
57
58 void RemoteDesktopBrowserTest::TearDownInProcessBrowserTestFixture() {
59   DisableDNSLookupForThisTest();
60 }
61
62 void RemoteDesktopBrowserTest::VerifyInternetAccess() {
63   ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
64       browser(), GURL("http://www.google.com"), 1);
65
66   EXPECT_EQ(GetCurrentURL().host(), "www.google.com");
67 }
68
69 void RemoteDesktopBrowserTest::OpenClientBrowserPage() {
70   // Open the client browser page in a new tab
71   ui_test_utils::NavigateToURLWithDisposition(
72       browser(),
73       GURL(http_server() + "/clientpage.html"),
74       NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
75
76   // Save this web content for later reference
77   client_web_content_ = browser()->tab_strip_model()->GetActiveWebContents();
78
79   // Go back to the previous tab that has chromoting opened
80   browser()->tab_strip_model()->SelectPreviousTab();
81 }
82
83 bool RemoteDesktopBrowserTest::HtmlElementVisible(const std::string& name) {
84   _ASSERT_TRUE(HtmlElementExists(name));
85
86   ExecuteScript(
87       "function isElementVisible(name) {"
88       "  var element = document.getElementById(name);"
89       "  /* The existence of the element has already been ASSERTed. */"
90       "  do {"
91       "    if (element.hidden) {"
92       "      return false;"
93       "    }"
94       "    element = element.parentNode;"
95       "  } while (element != null);"
96       "  return true;"
97       "};");
98
99   return ExecuteScriptAndExtractBool(
100       "isElementVisible(\"" + name + "\")");
101 }
102
103 void RemoteDesktopBrowserTest::InstallChromotingAppCrx() {
104   ASSERT_TRUE(!is_unpacked());
105
106   base::FilePath install_dir(WebAppCrxPath());
107   scoped_refptr<const Extension> extension(InstallExtensionWithUIAutoConfirm(
108       install_dir, 1, browser()));
109
110   EXPECT_FALSE(extension.get() == NULL);
111
112   extension_ = extension.get();
113 }
114
115 void RemoteDesktopBrowserTest::InstallChromotingAppUnpacked() {
116   ASSERT_TRUE(is_unpacked());
117
118   scoped_refptr<extensions::UnpackedInstaller> installer =
119       extensions::UnpackedInstaller::Create(extension_service());
120   installer->set_prompt_for_plugins(false);
121
122   content::WindowedNotificationObserver observer(
123       extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
124       content::NotificationService::AllSources());
125
126   installer->Load(webapp_unpacked_);
127
128   observer.Wait();
129 }
130
131 void RemoteDesktopBrowserTest::UninstallChromotingApp() {
132   UninstallExtension(ChromotingID());
133   extension_ = NULL;
134 }
135
136 void RemoteDesktopBrowserTest::VerifyChromotingLoaded(bool expected) {
137   const extensions::ExtensionSet* extensions =
138       extension_service()->extensions();
139   scoped_refptr<const extensions::Extension> extension;
140   bool installed = false;
141
142   for (extensions::ExtensionSet::const_iterator iter = extensions->begin();
143        iter != extensions->end(); ++iter) {
144     extension = *iter;
145     // Is there a better way to recognize the chromoting extension
146     // than name comparison?
147     if (extension->name() == extension_name_) {
148       installed = true;
149       break;
150     }
151   }
152
153   if (installed) {
154     if (extension_)
155       EXPECT_EQ(extension.get(), extension_);
156     else
157       extension_ = extension.get();
158
159     // Either a V1 (TYPE_LEGACY_PACKAGED_APP) or a V2 (TYPE_PLATFORM_APP ) app.
160     extensions::Manifest::Type type = extension->GetType();
161     EXPECT_TRUE(type == extensions::Manifest::TYPE_PLATFORM_APP ||
162                 type == extensions::Manifest::TYPE_LEGACY_PACKAGED_APP);
163
164     EXPECT_TRUE(extension->ShouldDisplayInAppLauncher());
165   }
166
167   ASSERT_EQ(installed, expected);
168 }
169
170 void RemoteDesktopBrowserTest::LaunchChromotingApp() {
171   ASSERT_TRUE(extension_);
172
173   GURL chromoting_main = Chromoting_Main_URL();
174   // We cannot simply wait for any page load because the first page
175   // loaded could be the generated background page. We need to wait
176   // till the chromoting main page is loaded.
177   PageLoadNotificationObserver observer(chromoting_main);
178
179   OpenApplication(AppLaunchParams(
180       browser()->profile(),
181       extension_,
182       is_platform_app() ? extensions::LAUNCH_CONTAINER_NONE :
183           extensions::LAUNCH_CONTAINER_TAB,
184       is_platform_app() ? NEW_WINDOW : CURRENT_TAB));
185
186   observer.Wait();
187
188
189   // The active WebContents instance should be the source of the LOAD_STOP
190   // notification.
191   content::NavigationController* controller =
192       content::Source<content::NavigationController>(observer.source()).ptr();
193
194   content::WebContents* web_contents = controller->GetWebContents();
195   if (web_contents != active_web_contents())
196     web_contents_stack_.push_back(web_contents);
197
198   app_web_content_ = web_contents;
199
200   if (is_platform_app()) {
201     EXPECT_EQ(GetFirstAppWindowWebContents(), active_web_contents());
202   } else {
203     // For apps v1 only, the DOMOperationObserver is not ready at the LOAD_STOP
204     // event. A half second wait is necessary for the subsequent javascript
205     // injection to work.
206     // TODO(weitaosu): Find out whether there is a more appropriate notification
207     // to wait for so we can get rid of this wait.
208     ASSERT_TRUE(TimeoutWaiter(base::TimeDelta::FromSeconds(5)).Wait());
209   }
210
211   EXPECT_EQ(Chromoting_Main_URL(), GetCurrentURL());
212 }
213
214 void RemoteDesktopBrowserTest::Authorize() {
215   // The chromoting extension should be installed.
216   ASSERT_TRUE(extension_);
217
218   // The chromoting main page should be loaded in the current tab
219   // and isAuthenticated() should be false (auth dialog visible).
220   ASSERT_EQ(Chromoting_Main_URL(), GetCurrentURL());
221   ASSERT_FALSE(IsAuthenticated());
222
223   // The second observer monitors the loading of the Google login page.
224   // Unfortunately we cannot specify a source in this observer because
225   // we can't get a handle of the new window until the first observer
226   // has finished waiting. But we will assert that the source of the
227   // load stop event is indeed the newly created browser window.
228   content::WindowedNotificationObserver observer(
229       content::NOTIFICATION_LOAD_STOP,
230       content::NotificationService::AllSources());
231
232   ClickOnControl("auth-button");
233
234   observer.Wait();
235
236   content::NavigationController* controller =
237       content::Source<content::NavigationController>(observer.source()).ptr();
238
239   web_contents_stack_.push_back(controller->GetWebContents());
240
241   // Verify the active tab is at the "Google Accounts" login page.
242   EXPECT_EQ("accounts.google.com", GetCurrentURL().host());
243   EXPECT_TRUE(HtmlElementExists("Email"));
244   EXPECT_TRUE(HtmlElementExists("Passwd"));
245 }
246
247 void RemoteDesktopBrowserTest::Authenticate() {
248   // The chromoting extension should be installed.
249   ASSERT_TRUE(extension_);
250
251   // The active tab should have the "Google Accounts" login page loaded.
252   ASSERT_EQ("accounts.google.com", GetCurrentURL().host());
253   ASSERT_TRUE(HtmlElementExists("Email"));
254   ASSERT_TRUE(HtmlElementExists("Passwd"));
255
256   // Now log in using the username and password passed in from the command line.
257   ExecuteScriptAndWaitForAnyPageLoad(
258       "document.getElementById(\"Email\").value = \"" + username_ + "\";" +
259       "document.getElementById(\"Passwd\").value = \"" + password_ +"\";" +
260       "document.forms[\"gaia_loginform\"].submit();");
261
262   // TODO(weitaosu): Is there a better way to verify we are on the
263   // "Request for Permission" page?
264   // V2 app won't ask for approval here because the chromoting test account
265   // has already been granted permissions.
266   if (!is_platform_app()) {
267     EXPECT_EQ(GetCurrentURL().host(), "accounts.google.com");
268     EXPECT_TRUE(HtmlElementExists("submit_approve_access"));
269   }
270 }
271
272 void RemoteDesktopBrowserTest::Approve() {
273   // The chromoting extension should be installed.
274   ASSERT_TRUE(extension_);
275
276   if (is_platform_app()) {
277     // Popping the login window off the stack to return to the chromoting
278     // window.
279     web_contents_stack_.pop_back();
280
281     // There is nothing for the V2 app to approve because the chromoting test
282     // account has already been granted permissions.
283     // TODO(weitaosu): Revoke the permission at the beginning of the test so
284     // that we can test first-time experience here.
285     ConditionalTimeoutWaiter waiter(
286         base::TimeDelta::FromSeconds(7),
287         base::TimeDelta::FromSeconds(1),
288         base::Bind(
289             &RemoteDesktopBrowserTest::IsAuthenticatedInWindow,
290             active_web_contents()));
291
292     ASSERT_TRUE(waiter.Wait());
293   } else {
294     ASSERT_EQ("accounts.google.com", GetCurrentURL().host());
295
296     // Is there a better way to verify we are on the "Request for Permission"
297     // page?
298     ASSERT_TRUE(HtmlElementExists("submit_approve_access"));
299
300     const GURL chromoting_main = Chromoting_Main_URL();
301
302     // active_web_contents() is still the login window but the observer
303     // should be set up to observe the chromoting window because that is
304     // where we'll receive the message from the login window and reload the
305     // chromoting app.
306     content::WindowedNotificationObserver observer(
307         content::NOTIFICATION_LOAD_STOP,
308           base::Bind(
309               &RemoteDesktopBrowserTest::IsAuthenticatedInWindow,
310               browser()->tab_strip_model()->GetActiveWebContents()));
311
312     // Click to Approve the web-app.
313     ClickOnControl("submit_approve_access");
314
315     observer.Wait();
316
317     // Popping the login window off the stack to return to the chromoting
318     // window.
319     web_contents_stack_.pop_back();
320   }
321
322   ASSERT_TRUE(GetCurrentURL() == Chromoting_Main_URL());
323
324   EXPECT_TRUE(IsAuthenticated());
325 }
326
327 void RemoteDesktopBrowserTest::ExpandMe2Me() {
328   // The chromoting extension should be installed.
329   ASSERT_TRUE(extension_);
330
331   // The active tab should have the chromoting app loaded.
332   ASSERT_EQ(Chromoting_Main_URL(), GetCurrentURL());
333   EXPECT_TRUE(IsAuthenticated());
334
335   // The Me2Me host list should be hidden.
336   ASSERT_FALSE(HtmlElementVisible("me2me-content"));
337   // The Me2Me "Get Start" button should be visible.
338   ASSERT_TRUE(HtmlElementVisible("get-started-me2me"));
339
340   // Starting Me2Me.
341   ExecuteScript("remoting.showMe2MeUiAndSave();");
342
343   EXPECT_TRUE(HtmlElementVisible("me2me-content"));
344   EXPECT_FALSE(HtmlElementVisible("me2me-first-run"));
345 }
346
347 void RemoteDesktopBrowserTest::DisconnectMe2Me() {
348   // The chromoting extension should be installed.
349   ASSERT_TRUE(extension_);
350
351   ASSERT_TRUE(RemoteDesktopBrowserTest::IsSessionConnected());
352
353   ClickOnControl("toolbar-stub");
354
355   EXPECT_TRUE(HtmlElementVisible("session-toolbar"));
356
357   ClickOnControl("toolbar-disconnect");
358
359   EXPECT_TRUE(HtmlElementVisible("client-dialog"));
360   EXPECT_TRUE(HtmlElementVisible("client-reconnect-button"));
361   EXPECT_TRUE(HtmlElementVisible("client-finished-me2me-button"));
362
363   ClickOnControl("client-finished-me2me-button");
364
365   EXPECT_FALSE(HtmlElementVisible("client-dialog"));
366 }
367
368 void RemoteDesktopBrowserTest::SimulateKeyPressWithCode(
369     ui::KeyboardCode keyCode,
370     const char* code) {
371   SimulateKeyPressWithCode(keyCode, code, false, false, false, false);
372 }
373
374 void RemoteDesktopBrowserTest::SimulateKeyPressWithCode(
375     ui::KeyboardCode keyCode,
376     const char* code,
377     bool control,
378     bool shift,
379     bool alt,
380     bool command) {
381   content::SimulateKeyPressWithCode(
382       active_web_contents(),
383       keyCode,
384       code,
385       control,
386       shift,
387       alt,
388       command);
389 }
390
391 void RemoteDesktopBrowserTest::SimulateCharInput(char c) {
392   const char* code;
393   ui::KeyboardCode keyboard_code;
394   bool shift;
395   GetKeyValuesFromChar(c, &code, &keyboard_code, &shift);
396   ASSERT_TRUE(code != NULL);
397   SimulateKeyPressWithCode(keyboard_code, code, false, shift, false, false);
398 }
399
400 void RemoteDesktopBrowserTest::SimulateStringInput(const std::string& input) {
401   for (size_t i = 0; i < input.length(); ++i)
402     SimulateCharInput(input[i]);
403 }
404
405 void RemoteDesktopBrowserTest::SimulateMouseLeftClickAt(int x, int y) {
406   SimulateMouseClickAt(0, blink::WebMouseEvent::ButtonLeft, x, y);
407 }
408
409 void RemoteDesktopBrowserTest::SimulateMouseClickAt(
410     int modifiers, blink::WebMouseEvent::Button button, int x, int y) {
411   // TODO(weitaosu): The coordinate translation doesn't work correctly for
412   // apps v2.
413   ExecuteScript(
414       "var clientPluginElement = "
415            "document.getElementById('session-client-plugin');"
416       "var clientPluginRect = clientPluginElement.getBoundingClientRect();");
417
418   int top = ExecuteScriptAndExtractInt("clientPluginRect.top");
419   int left = ExecuteScriptAndExtractInt("clientPluginRect.left");
420   int width = ExecuteScriptAndExtractInt("clientPluginRect.width");
421   int height = ExecuteScriptAndExtractInt("clientPluginRect.height");
422
423   ASSERT_GT(x, 0);
424   ASSERT_LT(x, width);
425   ASSERT_GT(y, 0);
426   ASSERT_LT(y, height);
427
428   content::SimulateMouseClickAt(
429       browser()->tab_strip_model()->GetActiveWebContents(),
430       modifiers,
431       button,
432       gfx::Point(left + x, top + y));
433 }
434
435 void RemoteDesktopBrowserTest::Install() {
436   if (!NoInstall()) {
437     VerifyChromotingLoaded(false);
438     if (is_unpacked())
439       InstallChromotingAppUnpacked();
440     else
441       InstallChromotingAppCrx();
442   }
443
444   VerifyChromotingLoaded(true);
445 }
446
447 void RemoteDesktopBrowserTest::Cleanup() {
448   // TODO(weitaosu): Remove this hack by blocking on the appropriate
449   // notification.
450   // The browser may still be loading images embedded in the webapp. If we
451   // uinstall it now those load will fail.
452   ASSERT_TRUE(TimeoutWaiter(base::TimeDelta::FromSeconds(2)).Wait());
453
454   if (!NoCleanup()) {
455     UninstallChromotingApp();
456     VerifyChromotingLoaded(false);
457   }
458
459   // TODO(chaitali): Remove this additional timeout after we figure out
460   // why this is needed for the v1 app to work.
461   // Without this timeout the test fail with a "CloseWebContents called for
462   // tab not in our strip" error for the v1 app.
463   ASSERT_TRUE(TimeoutWaiter(base::TimeDelta::FromSeconds(2)).Wait());
464 }
465
466 void RemoteDesktopBrowserTest::SetUpTestForMe2Me() {
467   VerifyInternetAccess();
468   Install();
469   LaunchChromotingApp();
470   Auth();
471   LoadScript(app_web_content(), FILE_PATH_LITERAL("browser_test.js"));
472   ExpandMe2Me();
473   EnsureRemoteConnectionEnabled();
474 }
475
476 void RemoteDesktopBrowserTest::Auth() {
477   // For this test, we must be given the user-name and password.
478   ASSERT_TRUE(!username_.empty() && !password_.empty());
479
480   Authorize();
481   Authenticate();
482   Approve();
483 }
484
485 void RemoteDesktopBrowserTest::EnsureRemoteConnectionEnabled() {
486   // browser_test.ensureRemoteConnectionEnabled is defined in
487   // browser_test.js, which must be loaded before calling this function.
488   // TODO(kelvinp): This function currently only works on linux when the user is
489   // already part of the chrome-remote-desktop group.  Extend this functionality
490   // to Mac (https://crbug.com/397576) and Windows (https://crbug.com/397575).
491   bool result;
492   EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
493       app_web_content(),
494       "browserTest.ensureRemoteConnectionEnabled(" + me2me_pin() + ")",
495       &result));
496   EXPECT_TRUE(result) << "Cannot start the host with Pin:" << me2me_pin();
497 }
498
499 void RemoteDesktopBrowserTest::ConnectToLocalHost(bool remember_pin) {
500   // Verify that the local host is online.
501   ASSERT_TRUE(ExecuteScriptAndExtractBool(
502       "remoting.hostList.localHost_.hostName && "
503       "remoting.hostList.localHost_.hostId && "
504       "remoting.hostList.localHost_.status && "
505       "remoting.hostList.localHost_.status == 'ONLINE'"));
506
507   // Connect.
508   ClickOnControl("this-host-connect");
509
510   // Enter the pin # passed in from the command line.
511   EnterPin(me2me_pin(), remember_pin);
512
513   WaitForConnection();
514 }
515
516 void RemoteDesktopBrowserTest::ConnectToRemoteHost(
517     const std::string& host_name, bool remember_pin) {
518   std::string host_id = ExecuteScriptAndExtractString(
519       "remoting.hostList.getHostIdForName('" + host_name + "')");
520
521   EXPECT_FALSE(host_id.empty());
522   std::string element_id = "host_" + host_id;
523
524   // Verify the host is online.
525   std::string host_div_class = ExecuteScriptAndExtractString(
526       "document.getElementById('" + element_id + "').parentNode.className");
527   EXPECT_NE(std::string::npos, host_div_class.find("host-online"));
528
529   ClickOnControl(element_id);
530
531   // Enter the pin # passed in from the command line.
532   EnterPin(me2me_pin(), remember_pin);
533
534   WaitForConnection();
535 }
536
537 void RemoteDesktopBrowserTest::EnableDNSLookupForThisTest(
538     net::RuleBasedHostResolverProc* host_resolver) {
539   // mock_host_resolver_override_ takes ownership of the resolver.
540   scoped_refptr<net::RuleBasedHostResolverProc> resolver =
541       new net::RuleBasedHostResolverProc(host_resolver);
542   resolver->AllowDirectLookup("*.google.com");
543   // On Linux, we use Chromium's NSS implementation which uses the following
544   // hosts for certificate verification. Without these overrides, running the
545   // integration tests on Linux causes errors as we make external DNS lookups.
546   resolver->AllowDirectLookup("*.thawte.com");
547   resolver->AllowDirectLookup("*.geotrust.com");
548   resolver->AllowDirectLookup("*.gstatic.com");
549   resolver->AllowDirectLookup("*.googleapis.com");
550   mock_host_resolver_override_.reset(
551       new net::ScopedDefaultHostResolverProc(resolver.get()));
552 }
553
554 void RemoteDesktopBrowserTest::DisableDNSLookupForThisTest() {
555   mock_host_resolver_override_.reset();
556 }
557
558 void RemoteDesktopBrowserTest::ParseCommandLine() {
559   CommandLine* command_line = CommandLine::ForCurrentProcess();
560
561   // The test framework overrides any command line user-data-dir
562   // argument with a /tmp/.org.chromium.Chromium.XXXXXX directory.
563   // That happens in the ChromeTestLauncherDelegate, and affects
564   // all unit tests (no opt out available). It intentionally erases
565   // any --user-data-dir switch if present and appends a new one.
566   // Re-override the default data dir if override-user-data-dir
567   // is specified.
568   if (command_line->HasSwitch(kOverrideUserDataDir)) {
569     const base::FilePath& override_user_data_dir =
570         command_line->GetSwitchValuePath(kOverrideUserDataDir);
571
572     ASSERT_FALSE(override_user_data_dir.empty());
573
574     command_line->AppendSwitchPath(switches::kUserDataDir,
575                                    override_user_data_dir);
576   }
577
578   CommandLine::StringType accounts_file =
579       command_line->GetSwitchValueNative(kAccountsFile);
580   std::string account_type = command_line->GetSwitchValueASCII(kAccountType);
581   if (!accounts_file.empty()) {
582     // We've been passed in a file containing accounts information.
583     // In this case, we'll obtain the user-name and password information from
584     // the specified file, even if user-name and password have been specified
585     // on the command-line.
586     base::FilePath accounts_file_path((base::FilePath(accounts_file)));
587     ASSERT_FALSE(account_type.empty());
588     ASSERT_TRUE(base::PathExists((base::FilePath(accounts_file))));
589     SetUserNameAndPassword((base::FilePath(accounts_file)), account_type);
590   } else {
591     // No file for accounts specified. Read user-name and password from command
592     // line.
593     username_ = command_line->GetSwitchValueASCII(kUserName);
594     password_ = command_line->GetSwitchValueASCII(kUserPassword);
595   }
596
597   me2me_pin_ = command_line->GetSwitchValueASCII(kMe2MePin);
598   remote_host_name_ = command_line->GetSwitchValueASCII(kRemoteHostName);
599   extension_name_ = command_line->GetSwitchValueASCII(kExtensionName);
600   http_server_ = command_line->GetSwitchValueASCII(kHttpServer);
601
602   no_cleanup_ = command_line->HasSwitch(kNoCleanup);
603   no_install_ = command_line->HasSwitch(kNoInstall);
604
605   if (!no_install_) {
606     webapp_crx_ = command_line->GetSwitchValuePath(kWebAppCrx);
607     webapp_unpacked_ = command_line->GetSwitchValuePath(kWebAppUnpacked);
608     // One and only one of these two arguments should be provided.
609     ASSERT_NE(webapp_crx_.empty(), webapp_unpacked_.empty());
610   }
611
612   // Run with "enable-web-based-signin" flag to enforce web-based sign-in,
613   // rather than inline signin. This ensures we use the same authentication
614   // page, regardless of whether we are testing the v1 or v2 web-app.
615   command_line->AppendSwitch(switches::kEnableWebBasedSignin);
616
617   // Enable experimental extensions; this is to allow adding the LG extensions
618   command_line->AppendSwitch(
619     extensions::switches::kEnableExperimentalExtensionApis);
620 }
621
622 void RemoteDesktopBrowserTest::ExecuteScript(const std::string& script) {
623   ASSERT_TRUE(content::ExecuteScript(active_web_contents(), script));
624 }
625
626 void RemoteDesktopBrowserTest::ExecuteScriptAndWaitForAnyPageLoad(
627     const std::string& script) {
628   content::WindowedNotificationObserver observer(
629       content::NOTIFICATION_LOAD_STOP,
630       content::Source<content::NavigationController>(
631           &active_web_contents()->
632               GetController()));
633
634   ExecuteScript(script);
635
636   observer.Wait();
637 }
638
639 // static
640 bool RemoteDesktopBrowserTest::ExecuteScriptAndExtractBool(
641     content::WebContents* web_contents, const std::string& script) {
642   bool result;
643   EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
644       web_contents,
645       "window.domAutomationController.send(" + script + ");",
646       &result));
647
648   return result;
649 }
650
651 // static
652 int RemoteDesktopBrowserTest::ExecuteScriptAndExtractInt(
653     content::WebContents* web_contents, const std::string& script) {
654   int result;
655   _ASSERT_TRUE(content::ExecuteScriptAndExtractInt(
656       web_contents,
657       "window.domAutomationController.send(" + script + ");",
658       &result));
659
660   return result;
661 }
662
663 // static
664 std::string RemoteDesktopBrowserTest::ExecuteScriptAndExtractString(
665     content::WebContents* web_contents, const std::string& script) {
666   std::string result;
667   _ASSERT_TRUE(content::ExecuteScriptAndExtractString(
668       web_contents,
669       "window.domAutomationController.send(" + script + ");",
670       &result));
671
672   return result;
673 }
674
675 // static
676 bool RemoteDesktopBrowserTest::LoadScript(
677     content::WebContents* web_contents,
678     const base::FilePath::StringType& path) {
679   std::string script;
680   base::FilePath src_dir;
681   _ASSERT_TRUE(PathService::Get(base::DIR_EXE, &src_dir));
682   base::FilePath script_path = src_dir.Append(path);
683
684   if (!base::ReadFileToString(script_path, &script)) {
685     LOG(ERROR) << "Failed to load script " << script_path.value();
686     return false;
687   }
688
689   return content::ExecuteScript(web_contents, script);
690 }
691
692 // static
693 void RemoteDesktopBrowserTest::RunJavaScriptTest(
694     content::WebContents* web_contents,
695     const std::string& testName,
696     const std::string& testData) {
697   std::string result;
698   std::string script = "browserTest.runTest(browserTest." + testName + ", " +
699                        testData + ");";
700
701   LOG(INFO) << "Executing " << script;
702
703   ASSERT_TRUE(
704       content::ExecuteScriptAndExtractString(web_contents, script, &result));
705
706   // Read in the JSON
707   base::JSONReader reader;
708   scoped_ptr<base::Value> value;
709   value.reset(reader.Read(result, base::JSON_ALLOW_TRAILING_COMMAS));
710
711   // Convert to dictionary
712   base::DictionaryValue* dict_value = NULL;
713   ASSERT_TRUE(value->GetAsDictionary(&dict_value));
714
715   bool succeeded;
716   std::string error_message;
717   std::string stack_trace;
718
719   // Extract the fields
720   ASSERT_TRUE(dict_value->GetBoolean("succeeded", &succeeded));
721   ASSERT_TRUE(dict_value->GetString("error_message", &error_message));
722   ASSERT_TRUE(dict_value->GetString("stack_trace", &stack_trace));
723
724   EXPECT_TRUE(succeeded) << error_message << "\n" << stack_trace;
725 }
726
727 void RemoteDesktopBrowserTest::ClickOnControl(const std::string& name) {
728   ASSERT_TRUE(HtmlElementVisible(name));
729
730   std::string has_disabled_attribute =
731     "document.getElementById('" + name + "').hasAttribute('disabled')";
732
733   if (ExecuteScriptAndExtractBool(active_web_contents(),
734                                   has_disabled_attribute)) {
735     // This element has a disabled attribute. Wait for it become enabled.
736     ConditionalTimeoutWaiter waiter(
737           base::TimeDelta::FromSeconds(5),
738           base::TimeDelta::FromMilliseconds(500),
739           base::Bind(&RemoteDesktopBrowserTest::IsEnabled,
740             active_web_contents(), name));
741     ASSERT_TRUE(waiter.Wait());
742   }
743
744   ExecuteScript("document.getElementById(\"" + name + "\").click();");
745 }
746
747 void RemoteDesktopBrowserTest::EnterPin(const std::string& pin,
748                                         bool remember_pin) {
749   // Wait for the pin-form to be displayed. This can take a while.
750   // We also need to dismiss the host-needs-update dialog if it comes up.
751   // TODO(weitaosu) 1: Instead of polling, can we register a callback to be
752   // called when the pin-form is ready?
753   // TODO(weitaosu) 2: Instead of blindly dismiss the host-needs-update dialog,
754   // we should verify that it only pops up at the right circumstance. That
755   // probably belongs in a separate test case though.
756   ConditionalTimeoutWaiter waiter(
757       base::TimeDelta::FromSeconds(30),
758       base::TimeDelta::FromSeconds(1),
759       base::Bind(&RemoteDesktopBrowserTest::IsPinFormVisible, this));
760   EXPECT_TRUE(waiter.Wait());
761
762   ExecuteScript(
763       "document.getElementById(\"pin-entry\").value = \"" + pin + "\";");
764
765   if (remember_pin) {
766     EXPECT_TRUE(HtmlElementVisible("remember-pin"));
767     EXPECT_FALSE(ExecuteScriptAndExtractBool(
768         "document.getElementById('remember-pin-checkbox').checked"));
769     ClickOnControl("remember-pin");
770     EXPECT_TRUE(ExecuteScriptAndExtractBool(
771         "document.getElementById('remember-pin-checkbox').checked"));
772   }
773
774   ClickOnControl("pin-connect-button");
775 }
776
777 void RemoteDesktopBrowserTest::WaitForConnection() {
778   // Wait until the client has connected to the server.
779   // This can take a while.
780   // TODO(weitaosu): Instead of polling, can we register a callback to
781   // remoting.clientSession.onStageChange_?
782   ConditionalTimeoutWaiter waiter(
783       base::TimeDelta::FromSeconds(30),
784       base::TimeDelta::FromSeconds(1),
785       base::Bind(&RemoteDesktopBrowserTest::IsSessionConnected, this));
786   EXPECT_TRUE(waiter.Wait());
787
788   // The client is not yet ready to take input when the session state becomes
789   // CONNECTED. Wait for 2 seconds for the client to become ready.
790   // TODO(weitaosu): Find a way to detect when the client is truly ready.
791   TimeoutWaiter(base::TimeDelta::FromSeconds(2)).Wait();
792 }
793
794 bool RemoteDesktopBrowserTest::IsLocalHostReady() {
795   // TODO(weitaosu): Instead of polling, can we register a callback to
796   // remoting.hostList.setLocalHost_?
797   return ExecuteScriptAndExtractBool("remoting.hostList.localHost_ != null");
798 }
799
800 bool RemoteDesktopBrowserTest::IsSessionConnected() {
801   // If some form of PINless authentication is enabled, the host version
802   // warning may appear while waiting for the session to connect.
803   DismissHostVersionWarningIfVisible();
804
805   return ExecuteScriptAndExtractBool(
806       "remoting.clientSession != null && "
807       "remoting.clientSession.getState() == "
808       "remoting.ClientSession.State.CONNECTED");
809 }
810
811 bool RemoteDesktopBrowserTest::IsPinFormVisible() {
812   DismissHostVersionWarningIfVisible();
813   return HtmlElementVisible("pin-form");
814 }
815
816 void RemoteDesktopBrowserTest::DismissHostVersionWarningIfVisible() {
817   if (HtmlElementVisible("host-needs-update-connect-button"))
818     ClickOnControl("host-needs-update-connect-button");
819 }
820
821 void RemoteDesktopBrowserTest::SetUserNameAndPassword(
822     const base::FilePath &accounts_file_path, const std::string& account_type) {
823
824   // Read contents of accounts file, using its absolute path.
825   base::FilePath absolute_path = base::MakeAbsoluteFilePath(accounts_file_path);
826   std::string accounts_info;
827   ASSERT_TRUE(base::ReadFileToString(absolute_path, &accounts_info));
828
829   // Get the root dictionary from the input json file contents.
830   scoped_ptr<base::Value> root(
831       base::JSONReader::Read(accounts_info, base::JSON_ALLOW_TRAILING_COMMAS));
832
833   const base::DictionaryValue* root_dict = NULL;
834   ASSERT_TRUE(root.get() && root->GetAsDictionary(&root_dict));
835
836   // Now get the dictionary for the specified account type.
837   const base::DictionaryValue* account_dict = NULL;
838   ASSERT_TRUE(root_dict->GetDictionary(account_type, &account_dict));
839   ASSERT_TRUE(account_dict->GetString(kUserName, &username_));
840   ASSERT_TRUE(account_dict->GetString(kUserPassword, &password_));
841 }
842
843 // static
844 bool RemoteDesktopBrowserTest::IsAuthenticatedInWindow(
845     content::WebContents* web_contents) {
846   return ExecuteScriptAndExtractBool(
847       web_contents, "remoting.identity.isAuthenticated()");
848 }
849
850 // static
851 bool RemoteDesktopBrowserTest::IsHostActionComplete(
852     content::WebContents* client_web_content,
853     std::string host_action_var) {
854   return ExecuteScriptAndExtractBool(
855       client_web_content,
856       host_action_var);
857 }
858
859 // static
860 bool RemoteDesktopBrowserTest::IsEnabled(
861     content::WebContents* client_web_content,
862     const std::string& element_name) {
863   return !ExecuteScriptAndExtractBool(
864     client_web_content,
865     "document.getElementById(\"" + element_name + "\").disabled");
866 }
867
868 }  // namespace remoting