Upstream version 7.35.144.0
[platform/framework/web/crosswalk.git] / src / chrome / test / functional / prefs.py
1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 import logging
7 import os
8 import shutil
9
10 import pyauto_functional  # Must be imported before pyauto
11 import pyauto
12 import test_utils
13
14 from webdriver_pages import settings
15 from webdriver_pages.settings import Behaviors, ContentTypes
16
17
18 class PrefsTest(pyauto.PyUITest):
19   """TestCase for Preferences."""
20
21   INFOBAR_TYPE = 'rph_infobar'
22
23   def setUp(self):
24     pyauto.PyUITest.setUp(self)
25     self._driver = self.NewWebDriver()
26
27   def Debug(self):
28     """Test method for experimentation.
29
30     This method will not run automatically.
31     """
32     while True:
33       raw_input('Interact with the browser and hit <enter> to dump prefs... ')
34       self.pprint(self.GetPrefsInfo().Prefs())
35
36   def testSessionRestore(self):
37     """Test session restore preference."""
38     url1 = 'http://www.google.com/'
39     url2 = 'http://news.google.com/'
40     self.NavigateToURL(url1)
41     self.AppendTab(pyauto.GURL(url2))
42     num_tabs = self.GetTabCount()
43     # Set pref to restore session on startup.
44     self.SetPrefs(pyauto.kRestoreOnStartup, 1)
45     logging.debug('Setting %s to 1' % pyauto.kRestoreOnStartup)
46     self.RestartBrowser(clear_profile=False)
47     self.assertEqual(self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup), 1)
48     self.assertEqual(num_tabs, self.GetTabCount())
49     self.ActivateTab(0)
50     self.assertEqual(url1, self.GetActiveTabURL().spec())
51     self.ActivateTab(1)
52     self.assertEqual(url2, self.GetActiveTabURL().spec())
53
54   def testNavigationStateOnSessionRestore(self):
55     """Verify navigation state is preserved on session restore."""
56     urls = ('http://www.google.com/',
57             'http://news.google.com/',
58             'http://dev.chromium.org/',)
59     for url in urls:
60       self.NavigateToURL(url)
61     self.TabGoBack()
62     self.assertEqual(self.GetActiveTabURL().spec(), urls[-2])
63     self.SetPrefs(pyauto.kRestoreOnStartup, 1)  # set pref to restore session
64     self.RestartBrowser(clear_profile=False)
65     # Verify that navigation state (forward/back state) is restored.
66     self.TabGoBack()
67     self.assertEqual(self.GetActiveTabURL().spec(), urls[0])
68     for i in (-2, -1):
69       tab.GoForward()
70       self.assertEqual(self.GetActiveTabURL().spec(), urls[i])
71
72   def testSessionRestoreURLs(self):
73     """Verify restore URLs preference."""
74     url1 = self.GetFileURLForPath(os.path.join(self.DataDir(), 'title1.html'))
75     url2 = self.GetFileURLForPath(os.path.join(self.DataDir(), 'title2.html'))
76     # Set pref to restore given URLs on startup
77     self.SetPrefs(pyauto.kRestoreOnStartup, 4)  # 4 is for restoring URLs
78     self.SetPrefs(pyauto.kURLsToRestoreOnStartup, [url1, url2])
79     self.RestartBrowser(clear_profile=False)
80     # Verify
81     self.assertEqual(self.GetPrefsInfo().Prefs(pyauto.kRestoreOnStartup), 4)
82     self.assertEqual(2, self.GetTabCount())
83     self.ActivateTab(0)
84     self.assertEqual(url1, self.GetActiveTabURL().spec())
85     self.ActivateTab(1)
86     self.assertEqual(url2, self.GetActiveTabURL().spec())
87
88   def testGeolocationPref(self):
89     """Verify geolocation pref.
90
91     Checks for the geolocation infobar.
92     """
93     # GetBrowserInfo() call seems to fail later on in this test. Call it early.
94     # crbug.com/89000
95     branding = self.GetBrowserInfo()['properties']['branding']
96     url = self.GetFileURLForPath(os.path.join(  # triggers geolocation
97         self.DataDir(), 'geolocation', 'geolocation_on_load.html'))
98     self.assertEqual(3,  # default state
99         self.GetPrefsInfo().Prefs(pyauto.kGeolocationDefaultContentSetting))
100     self.NavigateToURL(url)
101     self.assertTrue(self.WaitForInfobarCount(1))
102     self.assertTrue(self.GetBrowserInfo()['windows'][0]['tabs'][0]['infobars'])
103     # Disable geolocation
104     self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 2)
105     self.assertEqual(2,
106         self.GetPrefsInfo().Prefs(pyauto.kGeolocationDefaultContentSetting))
107     self.ReloadTab()
108     # Fails on Win7/Vista Chromium bots.  crbug.com/89000
109     if (self.IsWin7() or self.IsWinVista()) and branding == 'Chromium':
110       return
111     behavior = self._driver.execute_async_script(
112         'triggerGeoWithCallback(arguments[arguments.length - 1]);')
113     self.assertEqual(
114         behavior, Behaviors.BLOCK,
115         msg='Behavior is "%s" when it should be BLOCKED.'  % behavior)
116
117   def testAllowSelectedGeoTracking(self):
118     """Verify hostname pattern and behavior for allowed tracking."""
119     # Default location tracking option "Ask me".
120     self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 3)
121     self.NavigateToURL(
122         self.GetHttpURLForDataPath('geolocation', 'geolocation_on_load.html'))
123     self.assertTrue(self.WaitForInfobarCount(1))
124     self.PerformActionOnInfobar('accept', infobar_index=0)  # Allow tracking.
125     # Get the hostname pattern (e.g. http://127.0.0.1:57622).
126     hostname_pattern = (
127         '/'.join(self.GetHttpURLForDataPath('').split('/')[0:3]))
128     self.assertEqual(
129         # Allow the hostname.
130         {hostname_pattern+','+hostname_pattern: {'geolocation': 1}},
131         self.GetPrefsInfo().Prefs(pyauto.kContentSettingsPatternPairs))
132
133   def testDismissedInfobarSavesNoEntry(self):
134     """Verify dismissing infobar does not save an exception entry."""
135     # Default location tracking option "Ask me".
136     self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 3)
137     self.NavigateToURL(
138         self.GetFileURLForDataPath('geolocation', 'geolocation_on_load.html'))
139     self.assertTrue(self.WaitForInfobarCount(1))
140     self.PerformActionOnInfobar('dismiss', infobar_index=0)
141     self.assertEqual(
142         {}, self.GetPrefsInfo().Prefs(pyauto.kContentSettingsPatternPairs))
143
144   def testGeolocationBlockedWhenTrackingDenied(self):
145     """Verify geolocations is blocked when tracking is denied.
146
147     The test verifies the blocked hostname pattern entry on the Geolocations
148     exceptions page.
149     """
150     # Ask for permission when site wants to track.
151     self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 3)
152     self.NavigateToURL(
153         self.GetHttpURLForDataPath('geolocation', 'geolocation_on_load.html'))
154     self.assertTrue(self.WaitForInfobarCount(1))
155     self.PerformActionOnInfobar('cancel', infobar_index=0)  # Deny tracking.
156     behavior = self._driver.execute_async_script(
157         'triggerGeoWithCallback(arguments[arguments.length - 1]);')
158     self.assertEqual(
159         behavior, Behaviors.BLOCK,
160         msg='Behavior is "%s" when it should be BLOCKED.'  % behavior)
161     # Get the hostname pattern (e.g. http://127.0.0.1:57622).
162     hostname_pattern = (
163         '/'.join(self.GetHttpURLForDataPath('').split('/')[0:3]))
164     self.assertEqual(
165         # Block the hostname.
166         {hostname_pattern+','+hostname_pattern: {'geolocation': 2}},
167         self.GetPrefsInfo().Prefs(pyauto.kContentSettingsPatternPairs))
168
169   def _CheckForVisibleImage(self, tab_index=0, windex=0):
170     """Checks whether or not an image is visible on the webpage.
171
172     Args:
173       tab_index: Tab index. Defaults to 0 (first tab).
174       windex: Window index. Defaults to 0 (first window).
175
176     Returns:
177       True if image is loaded, otherwise returns False if image is not loaded.
178     """
179     # Checks whether an image is loaded by checking the area (width
180     # and height) of the image. If the area is non zero then the image is
181     # visible. If the area is zero then the image is not loaded.
182     # Chrome zeros the |naturalWidth| and |naturalHeight|.
183     script = """
184       for (i=0; i < document.images.length; i++) {
185         if ((document.images[i].naturalWidth != 0) &&
186             (document.images[i].naturalHeight != 0)) {
187           window.domAutomationController.send(true);
188         }
189       }
190       window.domAutomationController.send(false);
191     """
192     return self.ExecuteJavascript(script, windex=windex, tab_index=tab_index)
193
194   def testBlockImagesForHostname(self):
195     """Verify images blocked for defined hostname pattern."""
196     url = 'http://www.google.com'
197     page = settings.ManageExceptionsPage.FromNavigation(
198         self._driver, ContentTypes.IMAGES)
199     pattern, behavior = (url, Behaviors.BLOCK)
200     # Add an exception BLOCK for hostname pattern 'www.google.com'.
201     page.AddNewException(pattern, behavior)
202     self.NavigateToURL(url)
203     self.assertFalse(self._CheckForVisibleImage(),
204                      msg='At least one visible image found.')
205
206   def testAllowImagesForHostname(self):
207     """Verify images allowed for defined hostname pattern."""
208     url = 'http://www.google.com'
209     page = settings.ManageExceptionsPage.FromNavigation(
210         self._driver, ContentTypes.IMAGES)
211     pattern, behavior = (url, Behaviors.ALLOW)
212     # Add an exception ALLOW for hostname pattern 'www.google.com'.
213     page.AddNewException(pattern, behavior)
214     self.NavigateToURL(url)
215     self.assertTrue(self._CheckForVisibleImage(),
216                     msg='No visible images found.')
217
218   def testProtocolHandlerRegisteredCorrectly(self):
219     """Verify sites that ask to be default handlers registers correctly."""
220     url = self.GetHttpURLForDataPath('settings', 'protocol_handler.html')
221     self.NavigateToURL(url)
222     # Returns a dictionary with the custom handler.
223     asked_handler_dict = self._driver.execute_script(
224         'return registerCustomHandler()')
225     self.PerformActionOnInfobar(
226         'accept', infobar_index=test_utils.WaitForInfobarTypeAndGetIndex(
227             self, self.INFOBAR_TYPE))
228     self._driver.find_element_by_id('test_protocol').click()
229     self.assertTrue(
230         self._driver.execute_script(
231             'return doesQueryConformsToProtocol("%s", "%s")'
232             % (asked_handler_dict['query_key'],
233                asked_handler_dict['query_value'])),
234         msg='Protocol did not register correctly.')
235
236
237 if __name__ == '__main__':
238   pyauto_functional.Main()