summaryrefslogtreecommitdiffstats
path: root/chrome/test/functional/policy_prefs_ui.py
blob: 82cc51d6fdbc6fd84c2444997aee4b9ab50ff286 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#!/usr/bin/python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# If this test is failing, please check these steps.
#
# - You introduced a new policy:
#   Cool! Edit |policies| below and add an entry for it. See the comment above
#   it for the format.
#
# - This test fails after your changes:
#   Did you change the chrome://settings WebUI and edited "pref" attributes?
#   Make sure any preferences that can be managed by policy have a "pref"
#   attribute. Ping joaodasilva@chromium.org or bauerb@chromium.org.
#
# - This test fails for other reasons, or is flaky:
#   Ping joaodasilva@chromium.org, pastarmovj@chromium.org or
#   mnissler@chromium.org.

import logging

import pyauto_functional  # must come before pyauto.
import pyauto


class PolicyPrefsUITest(pyauto.PyUITest):
  BROWSER         = 0
  PERSONAL        = 1
  ADVANCED        = 2
  SEARCH_ENGINES  = 3
  PASSWORDS       = 4
  AUTOFILL        = 5
  CONTENT         = 6
  LANGUAGES       = 7
  EXTENSIONS      = 8
  SYSTEM          = 9
  INTERNET        = 10
  ACCOUNTS        = 11

  settings_pages = [
      'chrome://settings/browser',
      'chrome://settings/personal',
      'chrome://settings/advanced',
      'chrome://settings/searchEngines',
      'chrome://settings/passwords',
      'chrome://settings/autofill',
      'chrome://settings/content',
      'chrome://settings/languages',
      'chrome://settings/extensions',
  ]
  if pyauto.PyUITest.IsChromeOS():
    settings_pages += [
        'chrome://settings/system',
        'chrome://settings/internet',
        'chrome://settings/accounts',
    ]

  # Each policy has an entry with a tuple (Value, Pages, OS)
  #
  # |Value| is the value the policy should have when it is enforced.
  #
  # |Pages| is a list with integer indices into |settings_pages|, and lists all
  #         the pages that should display the managed-banner.
  #         Leave empty if this policy doesn't display anything visible in
  #         the settings.
  #
  # |OS| is a list of platforms where this policy should be tested. When empty,
  #      all platforms are tested. Valid platforms are 'win', 'mac', 'linux'
  #      and 'chromeos'.
  policies = {
    'HomepageLocation': ('http://chromium.org', [ BROWSER ]),
    'HomepageIsNewTabPage': (True, [ BROWSER ]),
    # TODO(joaodasilva): Couldn't verify on linux.
    'DefaultBrowserSettingEnabled': (False, [], [ 'win', 'mac', 'linux' ]),
    # TODO(joaodasilva): Test this on windows.
    'ApplicationLocaleValue': ('', [], [ 'win' ]),
    'AlternateErrorPagesEnabled': (False, [ ADVANCED ]),
    'SearchSuggestEnabled': (False, [ ADVANCED ]),
    'DnsPrefetchingEnabled': (False, [ ADVANCED ]),
    'DisableSpdy': (True, []),
    'DisabledSchemes': ( ['file' ], []),
    'JavascriptEnabled': (False, [ CONTENT ]),
    'IncognitoEnabled': (False, []),
    'IncognitoModeAvailability': (1, []),
    'SavingBrowserHistoryDisabled': (True, []),
    'RemoteAccessClientFirewallTraversal': (True, []),
    'RemoteAccessHostFirewallTraversal': (True, []),
    'PrintingEnabled': (False, []),
    # Note: supported_on is empty for this policy.
    'CloudPrintProxyEnabled': (True, [], []),
    'SafeBrowsingEnabled': (False, [ ADVANCED ]),
    # TODO(joaodasilva): This is only in place on official builds, but the
    # SetUserCloudPolicy call is a nop on official builds. Should be ADVANCED.
    'MetricsReportingEnabled': (False, []),
    'PasswordManagerEnabled': (False, [ PERSONAL ]),
    # TODO(joaodasilva): Should be PASSWORDS too. http://crbug.com/97749
    'PasswordManagerAllowShowPasswords': (False, [ PERSONAL ]),
    'AutoFillEnabled': (False, [ PERSONAL ]),
    'DisabledPlugins': (['Flash'], []),
    'EnabledPlugins': (['Flash'], []),
    'DisabledPluginsExceptions': (['Flash'], []),
    'DisablePluginFinder': (True, []),
    # TODO(joaodasilva): Should be PERSONAL. http://crbug.com/97749
    'SyncDisabled': (True, []),
    'UserDataDir': ('${users}/${user_name}/chrome-test', [], [ 'win', 'mac' ]),
    'DiskCacheDir': ('${user_home}/test-cache', [], [ 'win', 'mac', 'linux' ]),
    'DownloadDirectory': ('${user_home}/test-downloads', [ ADVANCED ],
                          [ 'win', 'mac', 'linux' ]),
    'ClearSiteDataOnExit': (True, [ CONTENT ]),
    # TODO(joaodasilva): Should be ADVANCED. http://crbug.com/97749
    'ProxyMode': ('direct', [], [ 'win', 'mac', 'linux' ]),
    # TODO(joaodasilva): Should be ADVANCED. http://crbug.com/97749
    'ProxyServerMode': (0, [], [ 'win', 'mac', 'linux' ]),
    'ProxyServer': ('http://localhost:8080', [], [ 'win', 'mac', 'linux' ]),
    'ProxyPacUrl': ('http://localhost:8080/proxy.pac', [],
                    [ 'win', 'mac', 'linux' ]),
    'ProxyBypassList': ('localhost', [], [ 'win', 'mac', 'linux' ]),
    'AuthSchemes': ('AuthSchemes', []),
    'DisableAuthNegotiateCnameLookup': (True, []),
    'EnableAuthNegotiatePort': (False, []),
    'AuthServerWhitelist': ('localhost', []),
    'AuthNegotiateDelegateWhitelist': ('localhost', []),
    'GSSAPILibraryName': ('libwhatever.so', [], [ 'mac', 'linux' ]),
    'AllowCrossOriginAuthPrompt': (False, [], [ 'win', 'mac', 'linux' ]),
    'ExtensionInstallBlacklist': ( ['*'], []),
    'ExtensionInstallWhitelist': ( ['lcncmkcnkcdbbanbjakcencbaoegdjlp' ], []),
    'ExtensionInstallForcelist': (
        ['lcncmkcnkcdbbanbjakcencbaoegdjlp;' +
         'https://clients2.google.com/service/update2/crx' ], []),
    'ShowHomeButton': (True, [ BROWSER ]),
    'DeveloperToolsDisabled': (True, []),
    'RestoreOnStartup': (0, [ BROWSER ]),
    # TODO(joaodasilva): Should be BROWSER. http://crbug.com/97749
    'RestoreOnStartupURLs': ([ 'chromium.org' ], []),
    # TODO(joaodasilva): The banner is out of place. http://crbug.com/77791
    'BlockThirdPartyCookies': (True, [ CONTENT ]),
    # TODO(joaodasilva): Should be BROWSER. http://crbug.com/97749
    'DefaultSearchProviderEnabled': (False, []),
    'DefaultSearchProviderName': ('google.com', []),
    'DefaultSearchProviderKeyword': ('google', []),
    # TODO(joaodasilva): Should be BROWSER. http://crbug.com/97749
    'DefaultSearchProviderSearchURL': ('http://www.google.com/?q={searchTerms}',
                                       []),
    'DefaultSearchProviderSuggestURL':
        ('http://www.google.com/suggest?q={searchTerms}', []),
    'DefaultSearchProviderInstantURL':
        ('http://www.google.com/instant?q={searchTerms}', []),
    'DefaultSearchProviderIconURL': ('http://www.google.com/favicon.ico', []),
    'DefaultSearchProviderEncodings': ([ 'UTF-8' ], []),
    'DefaultCookiesSetting': (2, [ CONTENT ]),
    'DefaultImagesSetting': (2, [ CONTENT ]),
    'DefaultJavaScriptSetting': (2, [ CONTENT ]),
    'DefaultPluginsSetting': (2, [ CONTENT ]),
    'DefaultPopupsSetting': (2, [ CONTENT ]),
    'DefaultNotificationsSetting': (2, [ CONTENT ]),
    'DefaultGeolocationSetting': (2, [ CONTENT ]),
    'AutoSelectCertificateForUrls':
        ([ '{\'pattern\':\'https://example.com\',' +
           '\'filter\':{\'ISSUER\':{\'CN\': \'issuer-name\'}}}' ], []),
    'CookiesAllowedForUrls': ([ '[*.]google.com' ], []),
    'CookiesBlockedForUrls': ([ '[*.]google.com' ], []),
    'CookiesSessionOnlyForUrls': ([ '[*.]google.com' ], []),
    'ImagesAllowedForUrls': ([ '[*.]google.com' ], []),
    'ImagesBlockedForUrls': ([ '[*.]google.com' ], []),
    'JavaScriptAllowedForUrls': ([ '[*.]google.com' ], []),
    'JavaScriptBlockedForUrls': ([ '[*.]google.com' ], []),
    'PluginsAllowedForUrls': ([ '[*.]google.com' ], []),
    'PluginsBlockedForUrls': ([ '[*.]google.com' ], []),
    'PopupsAllowedForUrls': ([ '[*.]google.com' ], []),
    'PopupsBlockedForUrls': ([ '[*.]google.com' ], []),
    'NotificationsAllowedForUrls': ([ '[*.]google.com' ], []),
    'NotificationsBlockedForUrls': ([ '[*.]google.com' ], []),
    'Disable3DAPIs': (True, []),
    'PolicyRefreshRate': (300000, [], [ 'chromeos' ]),
    # Only valid on chrome_frame.
    'ChromeFrameRendererSettings': (0, [], []),
    # Only valid on chrome_frame.
    'RenderInChromeFrameList': ([ 'google.com' ], [], []),
    # Only valid on chrome_frame.
    'RenderInHostList': ([ 'google.com' ], [], []),
    # Only valid on chrome_frame.
    'ChromeFrameContentTypes': ([ 'text/xml' ], [], []),
    'ChromeOsLockOnIdleSuspend': (True, [ PERSONAL ], [ 'chromeos' ]),
    'InstantEnabled': (False, [ BROWSER ]),
    'TranslateEnabled': (False, [ ADVANCED ]),
    'AllowOutdatedPlugins': (False, []),
    'AlwaysAuthorizePlugins': (True, []),
    'BookmarkBarEnabled': (False, [ BROWSER ]),
    'EditBookmarksEnabled': (False, []),
    'AllowFileSelectionDialogs': (False, [ ADVANCED ],
                                  [ 'win', 'mac', 'linux' ]),
    # Only valid on chrome_frame.
    'GCFUserDataDir': ('${user_name}/test-frame', [], []),
    # device_only.
    'DevicePolicyRefreshRate': (300000, [], []),
    # device_only.
    'ChromeOsReleaseChannel': ('stable-channel', [], []),
    'ImportBookmarks': (False, [], [ 'win', 'mac', 'linux' ]),
    'ImportHistory': (False, [], [ 'win', 'mac', 'linux' ]),
    'ImportHomepage': (False, [], [ 'win', 'mac', 'linux' ]),
    'ImportSearchEngine': (False, [], [ 'win', 'mac', 'linux' ]),
    'ImportSavedPasswords': (False, [], [ 'win', 'mac', 'linux' ]),
    'MaxConnectionsPerProxy': (32, []),
    'HideWebStorePromo': (True, []),
    'URLBlacklist': ([ 'google.com' ], []),
    'URLWhitelist': ([ 'google.com' ], []),
  }

  def GetPlatform(self):
    if self.IsChromeOS():
      return 'chromeos'
    elif self.IsLinux():
      return 'linux'
    elif self.IsMac():
      return 'mac'
    elif self.IsWin():
      return 'win'
    else:
      self.fail(msg='Unknown platform')

  def IsBannerVisible(self):
    """Returns true if the managed-banner is visible in the current page."""
    ret = self.ExecuteJavascript("""
        var visible = false;
        var banner = document.getElementById('managed-prefs-banner');
        if (banner)
          visible = !banner.hidden;
        domAutomationController.send(visible.toString());
    """)
    return ret == 'true'

  def testNoPoliciesNoBanner(self):
    """Verifies that the banner isn't present when no policies are in place."""

    self.SetPolicies({})
    for page in PolicyPrefsUITest.settings_pages:
      self.NavigateToURL(page)
      self.assertFalse(self.IsBannerVisible(), msg=
          'Unexpected banner in %s.\n'
          'Please check that chrome/test/functional/policy_prefs_ui.py has an '
          'entry for any new policies introduced.' % page)

  def RunPoliciesShowBanner(self, include_expected, include_unexpected):
    """Tests all the policies on each settings page.
    If |include_expected|, pages where the banner is expected will be verified.
    If |include_unexpected|, pages where the banner should not appear will also
    be verified. This can take some time."""

    os = self.GetPlatform()

    for policy in PolicyPrefsUITest.policies:
      policy_test = PolicyPrefsUITest.policies[policy]
      if len(policy_test) >= 3 and not os in policy_test[2]:
        continue
      expected_pages = [ PolicyPrefsUITest.settings_pages[n]
                         for n in policy_test[1] ]
      did_test = False
      for page in PolicyPrefsUITest.settings_pages:
        expected = page in expected_pages
        if expected and not include_expected:
          continue
        if not expected and not include_unexpected:
          continue
        if not did_test:
          did_test = True
          policy_dict = {
            policy: policy_test[0]
          }
          self.SetPolicies(policy_dict)
        self.NavigateToURL(page)
        self.assertEqual(expected, self.IsBannerVisible(), msg=
            'Banner was%sexpected in %s, but it was%svisible.\n'
            'The policy tested was "%s".\n'
            'Please check that chrome/test/functional/policy_prefs_ui.py has '
            'an entry for any new policies introduced.' %
                (expected and ' ' or ' NOT ', page, expected and ' NOT ' or ' ',
                 policy))
      if did_test:
        logging.debug('Policy passed: %s' % policy)

  def testPoliciesShowBanner(self):
    """Verifies that the banner is shown when a pref is managed by policy."""
    self.RunPoliciesShowBanner(True, False)

  # This test is disabled by default because it takes a very long time,
  # for little benefit.
  def PoliciesDontShowBanner(self):
    """Verifies that the banner is NOT shown on unrelated pages."""
    self.RunPoliciesShowBanner(False, True)

  def testFailOnPoliciesNotTested(self):
    """Fails for all policies listed in GetPolicyDefinitionList() that aren't
    listed in |PolicyPrefsUITest.policies|, and thus are not tested by
    |testPoliciesShowBanner|."""

    all_policies = self.GetPolicyDefinitionList()
    for policy in all_policies:
      self.assertTrue(policy in PolicyPrefsUITest.policies, msg=
          'Policy "%s" does not have a test in '
          'chrome/test/functional/policy_prefs_ui.py.\n'
          'Please edit the file and add an entry for this policy.' % policy)
      test_type = type(PolicyPrefsUITest.policies[policy][0]).__name__
      expected_type = all_policies[policy]
      self.assertEqual(expected_type, test_type, msg=
          'Policy "%s" has type "%s" but the test value has type "%s".' %
              (policy, expected_type, test_type))

  def testTogglePolicyTogglesBanner(self):
    """Verifies that toggling a policy also toggles the banner's visitiblity."""
    # |policy| just has to be any policy that has at least a settings page that
    # displays the banner when the policy is set.
    policy = 'ShowHomeButton'

    policy_test = PolicyPrefsUITest.policies[policy]
    page = PolicyPrefsUITest.settings_pages[policy_test[1][0]]
    policy_dict = {
      policy: policy_test[0]
    }

    self.SetPolicies({})
    self.NavigateToURL(page)
    self.assertFalse(self.IsBannerVisible())

    self.SetPolicies(policy_dict)
    self.assertTrue(self.IsBannerVisible())

    self.SetPolicies({})
    self.assertFalse(self.IsBannerVisible())


if __name__ == '__main__':
  pyauto_functional.Main()