Make hitting "Enter" submit the add/change profile dialog.
[chromium-blink-merge.git] / chrome / test / functional / prefs.py
blob8fca68c24bcb97056b462e52e1beeb2d950c9f78
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.
6 import logging
7 import os
8 import shutil
10 import pyauto_functional # Must be imported before pyauto
11 import pyauto
12 import test_utils
14 from webdriver_pages import settings
15 from webdriver_pages.settings import Behaviors, ContentTypes
18 class PrefsTest(pyauto.PyUITest):
19 """TestCase for Preferences."""
21 INFOBAR_TYPE = 'rph_infobar'
23 def setUp(self):
24 pyauto.PyUITest.setUp(self)
25 self._driver = self.NewWebDriver()
27 def Debug(self):
28 """Test method for experimentation.
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())
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())
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])
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())
88 def testSessionRestoreShowBookmarkBar(self):
89 """Verify restore for bookmark bar visibility."""
90 assert not self.GetPrefsInfo().Prefs(pyauto.kShowBookmarkBar)
91 self.SetPrefs(pyauto.kShowBookmarkBar, True)
92 self.assertEqual(True, self.GetPrefsInfo().Prefs(pyauto.kShowBookmarkBar))
93 self.RestartBrowser(clear_profile=False)
94 self.assertEqual(True, self.GetPrefsInfo().Prefs(pyauto.kShowBookmarkBar))
95 self.assertTrue(self.GetBookmarkBarVisibility())
97 def testDownloadDirPref(self):
98 """Verify download dir pref."""
99 test_dir = os.path.join(self.DataDir(), 'downloads')
100 file_url = self.GetFileURLForPath(os.path.join(test_dir, 'a_zip_file.zip'))
101 download_dir = self.GetDownloadDirectory().value()
102 new_dl_dir = os.path.join(download_dir, 'My+Downloads Folder')
103 downloaded_pkg = os.path.join(new_dl_dir, 'a_zip_file.zip')
104 os.path.exists(new_dl_dir) and shutil.rmtree(new_dl_dir)
105 os.makedirs(new_dl_dir)
106 # Set pref to download in new_dl_dir
107 self.SetPrefs(pyauto.kDownloadDefaultDirectory, new_dl_dir)
108 self.DownloadAndWaitForStart(file_url)
109 self.WaitForAllDownloadsToComplete()
110 self.assertTrue(os.path.exists(downloaded_pkg))
111 shutil.rmtree(new_dl_dir, ignore_errors=True) # cleanup
113 def testToolbarButtonsPref(self):
114 """Verify toolbar buttons prefs."""
115 # Assert defaults first
116 self.assertFalse(self.GetPrefsInfo().Prefs(pyauto.kShowHomeButton))
117 self.SetPrefs(pyauto.kShowHomeButton, True)
118 self.RestartBrowser(clear_profile=False)
119 self.assertTrue(self.GetPrefsInfo().Prefs(pyauto.kShowHomeButton))
121 def testNetworkPredictionEnabledPref(self):
122 """Verify DNS prefetching pref."""
123 # Assert default
124 self.assertTrue(self.GetPrefsInfo().Prefs(pyauto.kNetworkPredictionEnabled))
125 self.SetPrefs(pyauto.kNetworkPredictionEnabled, False)
126 self.RestartBrowser(clear_profile=False)
127 self.assertFalse(self.GetPrefsInfo().Prefs(
128 pyauto.kNetworkPredictionEnabled))
130 def testHomepagePrefs(self):
131 """Verify homepage prefs."""
132 # "Use the New Tab page"
133 self.SetPrefs(pyauto.kHomePageIsNewTabPage, True)
134 logging.debug('Setting %s to 1' % pyauto.kHomePageIsNewTabPage)
135 self.RestartBrowser(clear_profile=False)
136 self.assertEqual(self.GetPrefsInfo().Prefs(pyauto.kHomePageIsNewTabPage),
137 True)
138 # "Open this page"
139 url = self.GetFileURLForPath(os.path.join(self.DataDir(), 'title1.html'))
140 self.SetPrefs(pyauto.kHomePage, url)
141 self.SetPrefs(pyauto.kHomePageIsNewTabPage, False)
142 self.RestartBrowser(clear_profile=False)
143 self.assertEqual(self.GetPrefsInfo().Prefs(pyauto.kHomePage), url)
144 self.assertFalse(self.GetPrefsInfo().Prefs(pyauto.kHomePageIsNewTabPage))
145 # TODO(nirnimesh): Actually verify that homepage loads.
146 # This requires telling pyauto *not* to set about:blank as homepage.
148 def testGeolocationPref(self):
149 """Verify geolocation pref.
151 Checks for the geolocation infobar.
153 # GetBrowserInfo() call seems to fail later on in this test. Call it early.
154 # crbug.com/89000
155 branding = self.GetBrowserInfo()['properties']['branding']
156 url = self.GetFileURLForPath(os.path.join( # triggers geolocation
157 self.DataDir(), 'geolocation', 'geolocation_on_load.html'))
158 self.assertEqual(3, # default state
159 self.GetPrefsInfo().Prefs(pyauto.kGeolocationDefaultContentSetting))
160 self.NavigateToURL(url)
161 self.assertTrue(self.WaitForInfobarCount(1))
162 self.assertTrue(self.GetBrowserInfo()['windows'][0]['tabs'][0]['infobars'])
163 # Disable geolocation
164 self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 2)
165 self.assertEqual(2,
166 self.GetPrefsInfo().Prefs(pyauto.kGeolocationDefaultContentSetting))
167 self.ReloadTab()
168 # Fails on Win7/Vista Chromium bots. crbug.com/89000
169 if (self.IsWin7() or self.IsWinVista()) and branding == 'Chromium':
170 return
171 behavior = self._driver.execute_async_script(
172 'triggerGeoWithCallback(arguments[arguments.length - 1]);')
173 self.assertEqual(
174 behavior, Behaviors.BLOCK,
175 msg='Behavior is "%s" when it should be BLOCKED.' % behavior)
177 def testUnderTheHoodPref(self):
178 """Verify the security preferences for Under the Hood.
179 The setting is enabled by default."""
180 pref_list = [pyauto.kNetworkPredictionEnabled, pyauto.kSafeBrowsingEnabled,
181 pyauto.kAlternateErrorPagesEnabled,
182 pyauto.kSearchSuggestEnabled, pyauto.kShowOmniboxSearchHint]
183 for pref in pref_list:
184 # Verify the default value
185 self.assertEqual(self.GetPrefsInfo().Prefs(pref), True)
186 self.SetPrefs(pref, False)
187 self.RestartBrowser(clear_profile=False)
188 for pref in pref_list:
189 self.assertEqual(self.GetPrefsInfo().Prefs(pref), False)
191 def testJavaScriptEnableDisable(self):
192 """Verify enabling disabling javascript prefs work """
193 self.assertTrue(
194 self.GetPrefsInfo().Prefs(pyauto.kWebKitJavascriptEnabled))
195 url = self.GetFileURLForDataPath(
196 os.path.join('javaScriptTitle.html'))
197 title1 = 'Title from script javascript enabled'
198 self.NavigateToURL(url)
199 self.assertEqual(title1, self.GetActiveTabTitle())
200 self.SetPrefs(pyauto.kWebKitJavascriptEnabled, False)
201 title = 'This is html title'
202 self.NavigateToURL(url)
203 self.assertEqual(title, self.GetActiveTabTitle())
205 def testHaveLocalStatePrefs(self):
206 """Verify that we have some Local State prefs."""
207 self.assertTrue(self.GetLocalStatePrefsInfo())
209 def testAllowSelectedGeoTracking(self):
210 """Verify hostname pattern and behavior for allowed tracking."""
211 # Default location tracking option "Ask me".
212 self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 3)
213 self.NavigateToURL(
214 self.GetHttpURLForDataPath('geolocation', 'geolocation_on_load.html'))
215 self.assertTrue(self.WaitForInfobarCount(1))
216 self.PerformActionOnInfobar('accept', infobar_index=0) # Allow tracking.
217 # Get the hostname pattern (e.g. http://127.0.0.1:57622).
218 hostname_pattern = (
219 '/'.join(self.GetHttpURLForDataPath('').split('/')[0:3]))
220 self.assertEqual(
221 # Allow the hostname.
222 {hostname_pattern+','+hostname_pattern: {'geolocation': 1}},
223 self.GetPrefsInfo().Prefs(pyauto.kContentSettingsPatternPairs))
225 def testDismissedInfobarSavesNoEntry(self):
226 """Verify dismissing infobar does not save an exception entry."""
227 # Default location tracking option "Ask me".
228 self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 3)
229 self.NavigateToURL(
230 self.GetFileURLForDataPath('geolocation', 'geolocation_on_load.html'))
231 self.assertTrue(self.WaitForInfobarCount(1))
232 self.PerformActionOnInfobar('dismiss', infobar_index=0)
233 self.assertEqual(
234 {}, self.GetPrefsInfo().Prefs(pyauto.kContentSettingsPatternPairs))
236 def testGeolocationBlockedWhenTrackingDenied(self):
237 """Verify geolocations is blocked when tracking is denied.
239 The test verifies the blocked hostname pattern entry on the Geolocations
240 exceptions page.
242 # Ask for permission when site wants to track.
243 self.SetPrefs(pyauto.kGeolocationDefaultContentSetting, 3)
244 self.NavigateToURL(
245 self.GetHttpURLForDataPath('geolocation', 'geolocation_on_load.html'))
246 self.assertTrue(self.WaitForInfobarCount(1))
247 self.PerformActionOnInfobar('cancel', infobar_index=0) # Deny tracking.
248 behavior = self._driver.execute_async_script(
249 'triggerGeoWithCallback(arguments[arguments.length - 1]);')
250 self.assertEqual(
251 behavior, Behaviors.BLOCK,
252 msg='Behavior is "%s" when it should be BLOCKED.' % behavior)
253 # Get the hostname pattern (e.g. http://127.0.0.1:57622).
254 hostname_pattern = (
255 '/'.join(self.GetHttpURLForDataPath('').split('/')[0:3]))
256 self.assertEqual(
257 # Block the hostname.
258 {hostname_pattern+','+hostname_pattern: {'geolocation': 2}},
259 self.GetPrefsInfo().Prefs(pyauto.kContentSettingsPatternPairs))
261 def _CheckForVisibleImage(self, tab_index=0, windex=0):
262 """Checks whether or not an image is visible on the webpage.
264 Args:
265 tab_index: Tab index. Defaults to 0 (first tab).
266 windex: Window index. Defaults to 0 (first window).
268 Returns:
269 True if image is loaded, otherwise returns False if image is not loaded.
271 # Checks whether an image is loaded by checking the area (width
272 # and height) of the image. If the area is non zero then the image is
273 # visible. If the area is zero then the image is not loaded.
274 # Chrome zeros the |naturalWidth| and |naturalHeight|.
275 script = """
276 for (i=0; i < document.images.length; i++) {
277 if ((document.images[i].naturalWidth != 0) &&
278 (document.images[i].naturalHeight != 0)) {
279 window.domAutomationController.send(true);
282 window.domAutomationController.send(false);
284 return self.ExecuteJavascript(script, windex=windex, tab_index=tab_index)
286 def testImageContentSettings(self):
287 """Verify image content settings show or hide images."""
288 url = self.GetHttpURLForDataPath('settings', 'image_page.html')
289 self.NavigateToURL(url)
290 self.assertTrue(self._CheckForVisibleImage(),
291 msg='No visible images found.')
292 # Set to block all images from loading.
293 self.SetPrefs(pyauto.kDefaultContentSettings, {'images': 2})
294 self.NavigateToURL(url)
295 self.assertFalse(self._CheckForVisibleImage(),
296 msg='At least one visible image found.')
298 def testImagesNotBlockedInIncognito(self):
299 """Verify images are not blocked in Incognito mode."""
300 url = self.GetHttpURLForDataPath('settings', 'image_page.html')
301 self.RunCommand(pyauto.IDC_NEW_INCOGNITO_WINDOW)
302 self.NavigateToURL(url, 1, 0)
303 self.assertTrue(self._CheckForVisibleImage(windex=1),
304 msg='No visible images found in Incognito mode.')
306 def testBlockImagesForHostname(self):
307 """Verify images blocked for defined hostname pattern."""
308 url = 'http://www.google.com'
309 page = settings.ManageExceptionsPage.FromNavigation(
310 self._driver, ContentTypes.IMAGES)
311 pattern, behavior = (url, Behaviors.BLOCK)
312 # Add an exception BLOCK for hostname pattern 'www.google.com'.
313 page.AddNewException(pattern, behavior)
314 self.NavigateToURL(url)
315 self.assertFalse(self._CheckForVisibleImage(),
316 msg='At least one visible image found.')
318 def testAllowImagesForHostname(self):
319 """Verify images allowed for defined hostname pattern."""
320 url = 'http://www.google.com'
321 page = settings.ManageExceptionsPage.FromNavigation(
322 self._driver, ContentTypes.IMAGES)
323 pattern, behavior = (url, Behaviors.ALLOW)
324 # Add an exception ALLOW for hostname pattern 'www.google.com'.
325 page.AddNewException(pattern, behavior)
326 self.NavigateToURL(url)
327 self.assertTrue(self._CheckForVisibleImage(),
328 msg='No visible images found.')
330 def testProtocolHandlerRegisteredCorrectly(self):
331 """Verify sites that ask to be default handlers registers correctly."""
332 url = self.GetHttpURLForDataPath('settings', 'protocol_handler.html')
333 self.NavigateToURL(url)
334 # Returns a dictionary with the custom handler.
335 asked_handler_dict = self._driver.execute_script(
336 'return registerCustomHandler()')
337 self.PerformActionOnInfobar(
338 'accept', infobar_index=test_utils.WaitForInfobarTypeAndGetIndex(
339 self, self.INFOBAR_TYPE))
340 self._driver.find_element_by_id('test_protocol').click()
341 self.assertTrue(
342 self._driver.execute_script(
343 'return doesQueryConformsToProtocol("%s", "%s")'
344 % (asked_handler_dict['query_key'],
345 asked_handler_dict['query_value'])),
346 msg='Protocol did not register correctly.')
349 if __name__ == '__main__':
350 pyauto_functional.Main()