1# Copyright (c) 2013 The Chromium OS 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
5import logging
6
7import common
8from autotest_lib.client.bin import test
9from autotest_lib.client.common_lib import error
10from autotest_lib.client.common_lib.cros import chromedriver
11from autotest_lib.client.cros import httpd
12
13
14class desktopui_UrlFetchWithChromeDriver(test.test):
15    """Test fetching url and cookie using Chrome Driver."""
16    version = 1
17
18    def initialize(self, live=True):
19        """Initialize the test.
20
21        @param live: Set to True to access external websites. Otherwise, test
22                     with localhost http server. Default value is set to True.
23        """
24        self._live = live
25        super(desktopui_UrlFetchWithChromeDriver, self).initialize()
26
27        if self._live:
28            self._test_url = 'http://www.msn.com/'
29            self._expected_title = 'MSN.com'
30            self._domain = '.msn.com'
31        else:
32            self._test_url = 'http://localhost:8000/hello.html'
33            self._expected_title = 'Hello World'
34            self._domain = 'localhost'
35            self._testServer = httpd.HTTPListener(8000, docroot=self.bindir)
36            self._testServer.run()
37
38
39    def cleanup(self):
40        """Clean up the test environment, e.g., stop local http server."""
41        if not self._live and hasattr(self, '_testServer'):
42            self._testServer.stop()
43        super(desktopui_UrlFetchWithChromeDriver, self).cleanup()
44
45
46    def run_once(self):
47        """Run the test code."""
48        with chromedriver.chromedriver() as chromedriver_instance:
49            driver = chromedriver_instance.driver
50            driver.delete_all_cookies()
51            driver.get(self._test_url)
52
53            logging.info('Expected tab title: %s. Got: %s',
54                         self._expected_title, driver.title)
55            if driver.title != self._expected_title:
56                raise error.TestError('Getting title failed, got title: %s'
57                                      % driver.title)
58
59            cookie_found = any([cookie for cookie in
60                                driver.get_cookies()
61                                if cookie['domain'] == self._domain])
62            if not cookie_found:
63                raise error.TestError('Expected cookie for %s' % self._test_url)
64
65