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.
5 #include "chrome/test/remoting/remote_desktop_browsertest.h"
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"
29 RemoteDesktopBrowserTest::RemoteDesktopBrowserTest()
33 RemoteDesktopBrowserTest::~RemoteDesktopBrowserTest() {}
35 void RemoteDesktopBrowserTest::SetUp() {
37 PlatformAppBrowserTest::SetUp();
40 void RemoteDesktopBrowserTest::SetUpOnMainThread() {
41 PlatformAppBrowserTest::SetUpOnMainThread();
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());
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()));
58 void RemoteDesktopBrowserTest::TearDownInProcessBrowserTestFixture() {
59 DisableDNSLookupForThisTest();
62 void RemoteDesktopBrowserTest::VerifyInternetAccess() {
63 ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
64 browser(), GURL("http://www.google.com"), 1);
66 EXPECT_EQ(GetCurrentURL().host(), "www.google.com");
69 void RemoteDesktopBrowserTest::OpenClientBrowserPage() {
70 // Open the client browser page in a new tab
71 ui_test_utils::NavigateToURLWithDisposition(
73 GURL(http_server() + "/clientpage.html"),
74 NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
76 // Save this web content for later reference
77 client_web_content_ = browser()->tab_strip_model()->GetActiveWebContents();
79 // Go back to the previous tab that has chromoting opened
80 browser()->tab_strip_model()->SelectPreviousTab();
83 bool RemoteDesktopBrowserTest::HtmlElementVisible(const std::string& name) {
84 _ASSERT_TRUE(HtmlElementExists(name));
87 "function isElementVisible(name) {"
88 " var element = document.getElementById(name);"
89 " /* The existence of the element has already been ASSERTed. */"
91 " if (element.hidden) {"
94 " element = element.parentNode;"
95 " } while (element != null);"
99 return ExecuteScriptAndExtractBool(
100 "isElementVisible(\"" + name + "\")");
103 void RemoteDesktopBrowserTest::InstallChromotingAppCrx() {
104 ASSERT_TRUE(!is_unpacked());
106 base::FilePath install_dir(WebAppCrxPath());
107 scoped_refptr<const Extension> extension(InstallExtensionWithUIAutoConfirm(
108 install_dir, 1, browser()));
110 EXPECT_FALSE(extension.get() == NULL);
112 extension_ = extension.get();
115 void RemoteDesktopBrowserTest::InstallChromotingAppUnpacked() {
116 ASSERT_TRUE(is_unpacked());
118 scoped_refptr<extensions::UnpackedInstaller> installer =
119 extensions::UnpackedInstaller::Create(extension_service());
120 installer->set_prompt_for_plugins(false);
122 content::WindowedNotificationObserver observer(
123 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
124 content::NotificationService::AllSources());
126 installer->Load(webapp_unpacked_);
131 void RemoteDesktopBrowserTest::UninstallChromotingApp() {
132 UninstallExtension(ChromotingID());
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;
142 for (extensions::ExtensionSet::const_iterator iter = extensions->begin();
143 iter != extensions->end(); ++iter) {
145 // Is there a better way to recognize the chromoting extension
146 // than name comparison?
147 if (extension->name() == extension_name_) {
155 EXPECT_EQ(extension.get(), extension_);
157 extension_ = extension.get();
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);
164 EXPECT_TRUE(extension->ShouldDisplayInAppLauncher());
167 ASSERT_EQ(installed, expected);
170 void RemoteDesktopBrowserTest::LaunchChromotingApp() {
171 ASSERT_TRUE(extension_);
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);
179 OpenApplication(AppLaunchParams(
180 browser()->profile(),
182 is_platform_app() ? extensions::LAUNCH_CONTAINER_NONE :
183 extensions::LAUNCH_CONTAINER_TAB,
184 is_platform_app() ? NEW_WINDOW : CURRENT_TAB));
189 // The active WebContents instance should be the source of the LOAD_STOP
191 content::NavigationController* controller =
192 content::Source<content::NavigationController>(observer.source()).ptr();
194 content::WebContents* web_contents = controller->GetWebContents();
195 if (web_contents != active_web_contents())
196 web_contents_stack_.push_back(web_contents);
198 app_web_content_ = web_contents;
200 if (is_platform_app()) {
201 EXPECT_EQ(GetFirstAppWindowWebContents(), active_web_contents());
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());
211 EXPECT_EQ(Chromoting_Main_URL(), GetCurrentURL());
214 void RemoteDesktopBrowserTest::Authorize() {
215 // The chromoting extension should be installed.
216 ASSERT_TRUE(extension_);
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());
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());
232 ClickOnControl("auth-button");
236 content::NavigationController* controller =
237 content::Source<content::NavigationController>(observer.source()).ptr();
239 web_contents_stack_.push_back(controller->GetWebContents());
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"));
247 void RemoteDesktopBrowserTest::Authenticate() {
248 // The chromoting extension should be installed.
249 ASSERT_TRUE(extension_);
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"));
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();");
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"));
272 void RemoteDesktopBrowserTest::Approve() {
273 // The chromoting extension should be installed.
274 ASSERT_TRUE(extension_);
276 if (is_platform_app()) {
277 // Popping the login window off the stack to return to the chromoting
279 web_contents_stack_.pop_back();
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),
289 &RemoteDesktopBrowserTest::IsAuthenticatedInWindow,
290 active_web_contents()));
292 ASSERT_TRUE(waiter.Wait());
294 ASSERT_EQ("accounts.google.com", GetCurrentURL().host());
296 // Is there a better way to verify we are on the "Request for Permission"
298 ASSERT_TRUE(HtmlElementExists("submit_approve_access"));
300 const GURL chromoting_main = Chromoting_Main_URL();
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
306 content::WindowedNotificationObserver observer(
307 content::NOTIFICATION_LOAD_STOP,
309 &RemoteDesktopBrowserTest::IsAuthenticatedInWindow,
310 browser()->tab_strip_model()->GetActiveWebContents()));
312 // Click to Approve the web-app.
313 ClickOnControl("submit_approve_access");
317 // Popping the login window off the stack to return to the chromoting
319 web_contents_stack_.pop_back();
322 ASSERT_TRUE(GetCurrentURL() == Chromoting_Main_URL());
324 EXPECT_TRUE(IsAuthenticated());
327 void RemoteDesktopBrowserTest::ExpandMe2Me() {
328 // The chromoting extension should be installed.
329 ASSERT_TRUE(extension_);
331 // The active tab should have the chromoting app loaded.
332 ASSERT_EQ(Chromoting_Main_URL(), GetCurrentURL());
333 EXPECT_TRUE(IsAuthenticated());
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"));
341 ExecuteScript("remoting.showMe2MeUiAndSave();");
343 EXPECT_TRUE(HtmlElementVisible("me2me-content"));
344 EXPECT_FALSE(HtmlElementVisible("me2me-first-run"));
347 void RemoteDesktopBrowserTest::DisconnectMe2Me() {
348 // The chromoting extension should be installed.
349 ASSERT_TRUE(extension_);
351 ASSERT_TRUE(RemoteDesktopBrowserTest::IsSessionConnected());
353 ClickOnControl("toolbar-stub");
355 EXPECT_TRUE(HtmlElementVisible("session-toolbar"));
357 ClickOnControl("toolbar-disconnect");
359 EXPECT_TRUE(HtmlElementVisible("client-dialog"));
360 EXPECT_TRUE(HtmlElementVisible("client-reconnect-button"));
361 EXPECT_TRUE(HtmlElementVisible("client-finished-me2me-button"));
363 ClickOnControl("client-finished-me2me-button");
365 EXPECT_FALSE(HtmlElementVisible("client-dialog"));
368 void RemoteDesktopBrowserTest::SimulateKeyPressWithCode(
369 ui::KeyboardCode keyCode,
371 SimulateKeyPressWithCode(keyCode, code, false, false, false, false);
374 void RemoteDesktopBrowserTest::SimulateKeyPressWithCode(
375 ui::KeyboardCode keyCode,
381 content::SimulateKeyPressWithCode(
382 active_web_contents(),
391 void RemoteDesktopBrowserTest::SimulateCharInput(char c) {
393 ui::KeyboardCode keyboard_code;
395 GetKeyValuesFromChar(c, &code, &keyboard_code, &shift);
396 ASSERT_TRUE(code != NULL);
397 SimulateKeyPressWithCode(keyboard_code, code, false, shift, false, false);
400 void RemoteDesktopBrowserTest::SimulateStringInput(const std::string& input) {
401 for (size_t i = 0; i < input.length(); ++i)
402 SimulateCharInput(input[i]);
405 void RemoteDesktopBrowserTest::SimulateMouseLeftClickAt(int x, int y) {
406 SimulateMouseClickAt(0, blink::WebMouseEvent::ButtonLeft, x, y);
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
414 "var clientPluginElement = "
415 "document.getElementById('session-client-plugin');"
416 "var clientPluginRect = clientPluginElement.getBoundingClientRect();");
418 int top = ExecuteScriptAndExtractInt("clientPluginRect.top");
419 int left = ExecuteScriptAndExtractInt("clientPluginRect.left");
420 int width = ExecuteScriptAndExtractInt("clientPluginRect.width");
421 int height = ExecuteScriptAndExtractInt("clientPluginRect.height");
426 ASSERT_LT(y, height);
428 content::SimulateMouseClickAt(
429 browser()->tab_strip_model()->GetActiveWebContents(),
432 gfx::Point(left + x, top + y));
435 void RemoteDesktopBrowserTest::Install() {
437 VerifyChromotingLoaded(false);
439 InstallChromotingAppUnpacked();
441 InstallChromotingAppCrx();
444 VerifyChromotingLoaded(true);
447 void RemoteDesktopBrowserTest::Cleanup() {
448 // TODO(weitaosu): Remove this hack by blocking on the appropriate
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());
455 UninstallChromotingApp();
456 VerifyChromotingLoaded(false);
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());
466 void RemoteDesktopBrowserTest::SetUpTestForMe2Me() {
467 VerifyInternetAccess();
469 LaunchChromotingApp();
471 LoadScript(app_web_content(), FILE_PATH_LITERAL("browser_test.js"));
473 EnsureRemoteConnectionEnabled();
476 void RemoteDesktopBrowserTest::Auth() {
477 // For this test, we must be given the user-name and password.
478 ASSERT_TRUE(!username_.empty() && !password_.empty());
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).
492 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
494 "browserTest.ensureRemoteConnectionEnabled(" + me2me_pin() + ")",
496 EXPECT_TRUE(result) << "Cannot start the host with Pin:" << me2me_pin();
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'"));
508 ClickOnControl("this-host-connect");
510 // Enter the pin # passed in from the command line.
511 EnterPin(me2me_pin(), remember_pin);
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 + "')");
521 EXPECT_FALSE(host_id.empty());
522 std::string element_id = "host_" + host_id;
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"));
529 ClickOnControl(element_id);
531 // Enter the pin # passed in from the command line.
532 EnterPin(me2me_pin(), remember_pin);
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()));
554 void RemoteDesktopBrowserTest::DisableDNSLookupForThisTest() {
555 mock_host_resolver_override_.reset();
558 void RemoteDesktopBrowserTest::ParseCommandLine() {
559 CommandLine* command_line = CommandLine::ForCurrentProcess();
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
568 if (command_line->HasSwitch(kOverrideUserDataDir)) {
569 const base::FilePath& override_user_data_dir =
570 command_line->GetSwitchValuePath(kOverrideUserDataDir);
572 ASSERT_FALSE(override_user_data_dir.empty());
574 command_line->AppendSwitchPath(switches::kUserDataDir,
575 override_user_data_dir);
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);
591 // No file for accounts specified. Read user-name and password from command
593 username_ = command_line->GetSwitchValueASCII(kUserName);
594 password_ = command_line->GetSwitchValueASCII(kUserPassword);
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);
602 no_cleanup_ = command_line->HasSwitch(kNoCleanup);
603 no_install_ = command_line->HasSwitch(kNoInstall);
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());
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);
617 // Enable experimental extensions; this is to allow adding the LG extensions
618 command_line->AppendSwitch(
619 extensions::switches::kEnableExperimentalExtensionApis);
622 void RemoteDesktopBrowserTest::ExecuteScript(const std::string& script) {
623 ASSERT_TRUE(content::ExecuteScript(active_web_contents(), script));
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()->
634 ExecuteScript(script);
640 bool RemoteDesktopBrowserTest::ExecuteScriptAndExtractBool(
641 content::WebContents* web_contents, const std::string& script) {
643 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
645 "window.domAutomationController.send(" + script + ");",
652 int RemoteDesktopBrowserTest::ExecuteScriptAndExtractInt(
653 content::WebContents* web_contents, const std::string& script) {
655 _ASSERT_TRUE(content::ExecuteScriptAndExtractInt(
657 "window.domAutomationController.send(" + script + ");",
664 std::string RemoteDesktopBrowserTest::ExecuteScriptAndExtractString(
665 content::WebContents* web_contents, const std::string& script) {
667 _ASSERT_TRUE(content::ExecuteScriptAndExtractString(
669 "window.domAutomationController.send(" + script + ");",
676 bool RemoteDesktopBrowserTest::LoadScript(
677 content::WebContents* web_contents,
678 const base::FilePath::StringType& path) {
680 base::FilePath src_dir;
681 _ASSERT_TRUE(PathService::Get(base::DIR_EXE, &src_dir));
682 base::FilePath script_path = src_dir.Append(path);
684 if (!base::ReadFileToString(script_path, &script)) {
685 LOG(ERROR) << "Failed to load script " << script_path.value();
689 return content::ExecuteScript(web_contents, script);
693 void RemoteDesktopBrowserTest::RunJavaScriptTest(
694 content::WebContents* web_contents,
695 const std::string& testName,
696 const std::string& testData) {
698 std::string script = "browserTest.runTest(browserTest." + testName + ", " +
701 LOG(INFO) << "Executing " << script;
704 content::ExecuteScriptAndExtractString(web_contents, script, &result));
707 base::JSONReader reader;
708 scoped_ptr<base::Value> value;
709 value.reset(reader.Read(result, base::JSON_ALLOW_TRAILING_COMMAS));
711 // Convert to dictionary
712 base::DictionaryValue* dict_value = NULL;
713 ASSERT_TRUE(value->GetAsDictionary(&dict_value));
716 std::string error_message;
717 std::string stack_trace;
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));
724 EXPECT_TRUE(succeeded) << error_message << "\n" << stack_trace;
727 void RemoteDesktopBrowserTest::ClickOnControl(const std::string& name) {
728 ASSERT_TRUE(HtmlElementVisible(name));
730 std::string has_disabled_attribute =
731 "document.getElementById('" + name + "').hasAttribute('disabled')";
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());
744 ExecuteScript("document.getElementById(\"" + name + "\").click();");
747 void RemoteDesktopBrowserTest::EnterPin(const std::string& 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());
763 "document.getElementById(\"pin-entry\").value = \"" + 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"));
774 ClickOnControl("pin-connect-button");
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());
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();
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");
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();
805 return ExecuteScriptAndExtractBool(
806 "remoting.clientSession != null && "
807 "remoting.clientSession.getState() == "
808 "remoting.ClientSession.State.CONNECTED");
811 bool RemoteDesktopBrowserTest::IsPinFormVisible() {
812 DismissHostVersionWarningIfVisible();
813 return HtmlElementVisible("pin-form");
816 void RemoteDesktopBrowserTest::DismissHostVersionWarningIfVisible() {
817 if (HtmlElementVisible("host-needs-update-connect-button"))
818 ClickOnControl("host-needs-update-connect-button");
821 void RemoteDesktopBrowserTest::SetUserNameAndPassword(
822 const base::FilePath &accounts_file_path, const std::string& account_type) {
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));
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));
833 const base::DictionaryValue* root_dict = NULL;
834 ASSERT_TRUE(root.get() && root->GetAsDictionary(&root_dict));
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_));
844 bool RemoteDesktopBrowserTest::IsAuthenticatedInWindow(
845 content::WebContents* web_contents) {
846 return ExecuteScriptAndExtractBool(
847 web_contents, "remoting.identity.isAuthenticated()");
851 bool RemoteDesktopBrowserTest::IsHostActionComplete(
852 content::WebContents* client_web_content,
853 std::string host_action_var) {
854 return ExecuteScriptAndExtractBool(
860 bool RemoteDesktopBrowserTest::IsEnabled(
861 content::WebContents* client_web_content,
862 const std::string& element_name) {
863 return !ExecuteScriptAndExtractBool(
865 "document.getElementById(\"" + element_name + "\").disabled");
868 } // namespace remoting