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 testHomepagePrefs(self): 89 """Verify homepage prefs.""" 90 # "Use the New Tab page" 91 self.SetPrefs(pyauto.kHomePageIsNewTabPage, True) 92 logging.debug('Setting %s to 1' % pyauto.kHomePageIsNewTabPage) 93 self.RestartBrowser(clear_profile=False) 94 self.assertEqual(self.GetPrefsInfo().Prefs(pyauto.kHomePageIsNewTabPage), 95 True) 96 # "Open this page" 97 url = self.GetFileURLForPath(os.path.join(self.DataDir(), 'title1.html')) 98 self.SetPrefs(pyauto.kHomePage, url) 99 self.SetPrefs(pyauto.kHomePageIsNewTabPage, False) 100 self.RestartBrowser(clear_profile=False) 101 self.assertEqual(self.GetPrefsInfo().Prefs(pyauto.kHomePage), url) 102 self.assertFalse(self.GetPrefsInfo().Prefs(pyauto.kHomePageIsNewTabPage)) 103 # TODO(nirnimesh): Actually verify that homepage loads. 104 # This requires telling pyauto *not* to set about:blank as homepage. 105 106 def testGeolocationPref(self): 107 """Verify geolocation pref. 108 109 Checks for the geolocation infobar. 110 """ 111 # GetBrowserInfo() call seems to fail later on in this test. Call it early. 112 # crbug.com/89000 113 branding = self.GetBrowserInfo()['properties']['branding'] 114 url = self.GetFileURLForPath(os.path.join( # triggers geolocation 115 self.DataDir(), 'geolocation', 'geolocation_on_load.html')) 116 self.assertEqual(3, # default state 117 self.GetPrefsInfo().Prefs(pyauto.kGeolocationDefaultContentSetting)) 118 self.NavigateToURL(url) 119 self.assertTrue(self.WaitForInfobarCount(1)) 120 self.assertTrue(self.GetBrowserInfo()['windows'][0]['tabs'][0]['infobars']) 121 # Disable geolocation 122 self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 2) 123 self.assertEqual(2, 124 self.GetPrefsInfo().Prefs(pyauto.kGeolocationDefaultContentSetting)) 125 self.ReloadTab() 126 # Fails on Win7/Vista Chromium bots. crbug.com/89000 127 if (self.IsWin7() or self.IsWinVista()) and branding == 'Chromium': 128 return 129 behavior = self._driver.execute_async_script( 130 'triggerGeoWithCallback(arguments[arguments.length - 1]);') 131 self.assertEqual( 132 behavior, Behaviors.BLOCK, 133 msg='Behavior is "%s" when it should be BLOCKED.' % behavior) 134 135 def testUnderTheHoodPref(self): 136 """Verify the security preferences for Under the Hood. 137 The setting is enabled by default.""" 138 pref_list = [pyauto.kNetworkPredictionEnabled, pyauto.kSafeBrowsingEnabled, 139 pyauto.kAlternateErrorPagesEnabled, 140 pyauto.kSearchSuggestEnabled] 141 for pref in pref_list: 142 # Verify the default value 143 self.assertEqual(self.GetPrefsInfo().Prefs(pref), True) 144 self.SetPrefs(pref, False) 145 self.RestartBrowser(clear_profile=False) 146 for pref in pref_list: 147 self.assertEqual(self.GetPrefsInfo().Prefs(pref), False) 148 149 def testHaveLocalStatePrefs(self): 150 """Verify that we have some Local State prefs.""" 151 self.assertTrue(self.GetLocalStatePrefsInfo()) 152 153 def testAllowSelectedGeoTracking(self): 154 """Verify hostname pattern and behavior for allowed tracking.""" 155 # Default location tracking option "Ask me". 156 self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 3) 157 self.NavigateToURL( 158 self.GetHttpURLForDataPath('geolocation', 'geolocation_on_load.html')) 159 self.assertTrue(self.WaitForInfobarCount(1)) 160 self.PerformActionOnInfobar('accept', infobar_index=0) # Allow tracking. 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 # Allow the hostname. 166 {hostname_pattern+','+hostname_pattern: {'geolocation': 1}}, 167 self.GetPrefsInfo().Prefs(pyauto.kContentSettingsPatternPairs)) 168 169 def testDismissedInfobarSavesNoEntry(self): 170 """Verify dismissing infobar does not save an exception entry.""" 171 # Default location tracking option "Ask me". 172 self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 3) 173 self.NavigateToURL( 174 self.GetFileURLForDataPath('geolocation', 'geolocation_on_load.html')) 175 self.assertTrue(self.WaitForInfobarCount(1)) 176 self.PerformActionOnInfobar('dismiss', infobar_index=0) 177 self.assertEqual( 178 {}, self.GetPrefsInfo().Prefs(pyauto.kContentSettingsPatternPairs)) 179 180 def testGeolocationBlockedWhenTrackingDenied(self): 181 """Verify geolocations is blocked when tracking is denied. 182 183 The test verifies the blocked hostname pattern entry on the Geolocations 184 exceptions page. 185 """ 186 # Ask for permission when site wants to track. 187 self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 3) 188 self.NavigateToURL( 189 self.GetHttpURLForDataPath('geolocation', 'geolocation_on_load.html')) 190 self.assertTrue(self.WaitForInfobarCount(1)) 191 self.PerformActionOnInfobar('cancel', infobar_index=0) # Deny tracking. 192 behavior = self._driver.execute_async_script( 193 'triggerGeoWithCallback(arguments[arguments.length - 1]);') 194 self.assertEqual( 195 behavior, Behaviors.BLOCK, 196 msg='Behavior is "%s" when it should be BLOCKED.' % behavior) 197 # Get the hostname pattern (e.g. http://127.0.0.1:57622). 198 hostname_pattern = ( 199 '/'.join(self.GetHttpURLForDataPath('').split('/')[0:3])) 200 self.assertEqual( 201 # Block the hostname. 202 {hostname_pattern+','+hostname_pattern: {'geolocation': 2}}, 203 self.GetPrefsInfo().Prefs(pyauto.kContentSettingsPatternPairs)) 204 205 def _CheckForVisibleImage(self, tab_index=0, windex=0): 206 """Checks whether or not an image is visible on the webpage. 207 208 Args: 209 tab_index: Tab index. Defaults to 0 (first tab). 210 windex: Window index. Defaults to 0 (first window). 211 212 Returns: 213 True if image is loaded, otherwise returns False if image is not loaded. 214 """ 215 # Checks whether an image is loaded by checking the area (width 216 # and height) of the image. If the area is non zero then the image is 217 # visible. If the area is zero then the image is not loaded. 218 # Chrome zeros the |naturalWidth| and |naturalHeight|. 219 script = """ 220 for (i=0; i < document.images.length; i++) { 221 if ((document.images[i].naturalWidth != 0) && 222 (document.images[i].naturalHeight != 0)) { 223 window.domAutomationController.send(true); 224 } 225 } 226 window.domAutomationController.send(false); 227 """ 228 return self.ExecuteJavascript(script, windex=windex, tab_index=tab_index) 229 230 def testImagesNotBlockedInIncognito(self): 231 """Verify images are not blocked in Incognito mode.""" 232 url = self.GetHttpURLForDataPath('settings', 'image_page.html') 233 self.RunCommand(pyauto.IDC_NEW_INCOGNITO_WINDOW) 234 self.NavigateToURL(url, 1, 0) 235 self.assertTrue(self._CheckForVisibleImage(windex=1), 236 msg='No visible images found in Incognito mode.') 237 238 def testBlockImagesForHostname(self): 239 """Verify images blocked for defined hostname pattern.""" 240 url = 'http://www.google.com' 241 page = settings.ManageExceptionsPage.FromNavigation( 242 self._driver, ContentTypes.IMAGES) 243 pattern, behavior = (url, Behaviors.BLOCK) 244 # Add an exception BLOCK for hostname pattern 'www.google.com'. 245 page.AddNewException(pattern, behavior) 246 self.NavigateToURL(url) 247 self.assertFalse(self._CheckForVisibleImage(), 248 msg='At least one visible image found.') 249 250 def testAllowImagesForHostname(self): 251 """Verify images allowed for defined hostname pattern.""" 252 url = 'http://www.google.com' 253 page = settings.ManageExceptionsPage.FromNavigation( 254 self._driver, ContentTypes.IMAGES) 255 pattern, behavior = (url, Behaviors.ALLOW) 256 # Add an exception ALLOW for hostname pattern 'www.google.com'. 257 page.AddNewException(pattern, behavior) 258 self.NavigateToURL(url) 259 self.assertTrue(self._CheckForVisibleImage(), 260 msg='No visible images found.') 261 262 def testProtocolHandlerRegisteredCorrectly(self): 263 """Verify sites that ask to be default handlers registers correctly.""" 264 url = self.GetHttpURLForDataPath('settings', 'protocol_handler.html') 265 self.NavigateToURL(url) 266 # Returns a dictionary with the custom handler. 267 asked_handler_dict = self._driver.execute_script( 268 'return registerCustomHandler()') 269 self.PerformActionOnInfobar( 270 'accept', infobar_index=test_utils.WaitForInfobarTypeAndGetIndex( 271 self, self.INFOBAR_TYPE)) 272 self._driver.find_element_by_id('test_protocol').click() 273 self.assertTrue( 274 self._driver.execute_script( 275 'return doesQueryConformsToProtocol("%s", "%s")' 276 % (asked_handler_dict['query_key'], 277 asked_handler_dict['query_value'])), 278 msg='Protocol did not register correctly.') 279 280 281 if __name__ == '__main__': 282 pyauto_functional.Main() 283