[chromeos] Simplify chromeos device policy tests

- Remove the hacks that were there to accommodate /root/.forget_usernames
- Make setUp() re-entrant. This is so that errors in a test's setup does
  not affect the next test. (DNS server and auth server start at a fixed
  port, so failure to clean them up would affect the next test)
- Work around crbug.com/139166

BUG=139166
TEST=chromeos_device_policy.py

R=bartfab@chromium.org

Review URL: https://chromiumcodereview.appspot.com/10830053

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@149012 0039d316-1c4b-4281-b951-d872f2087c98
parent 8d3080ac
......@@ -2,8 +2,6 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import pyauto_functional # Must come before pyauto (and thus, policy_base).
import policy_base
......@@ -11,6 +9,14 @@ import policy_base
class ChromeosDevicePolicy(policy_base.PolicyTestBase):
"""Tests various ChromeOS device policies."""
# Cache user credentials for easy lookup.
private_info = policy_base.PolicyTestBase.GetPrivateInfo()
credentials = (private_info['prod_enterprise_test_user'],
private_info['prod_enterprise_executive_user'],
private_info['prod_enterprise_sales_user'])
_usernames = [credential['username'] for credential in credentials]
_passwords = [credential['password'] for credential in credentials]
def LoginAsGuest(self):
self.assertFalse(self.GetLoginInfo()['is_logged_in'],
msg='Expected to be logged out.')
......@@ -31,50 +37,6 @@ class ChromeosDevicePolicy(policy_base.PolicyTestBase):
self.assertFalse(self.GetLoginInfo()['is_logged_in'],
msg='Expected to not be logged in.')
# TODO(bartfab): Remove this after crosbug.com/20709 is fixed.
def TryToDisableLocalStateAutoClearing(self):
# Try to disable automatic clearing of the local state.
self.TryToDisableLocalStateAutoClearingOnChromeOS()
self._local_state_auto_clearing = \
self.IsLocalStateAutoClearingEnabledOnChromeOS()
if not self._local_state_auto_clearing:
# Prevent the inherited Logout() method from cleaning up /home/chronos
# as this also clears the local state.
self.set_clear_profile(False)
def ExtraChromeFlags(self):
"""Sets up Chrome to skip OOBE.
TODO(bartfab): Ensure OOBE is still skipped when crosbug.com/20709 is fixed.
Disabling automatic clearing of the local state has the curious side effect
of removing a flag that disables OOBE. This method adds back the flag.
"""
flags = policy_base.PolicyTestBase.ExtraChromeFlags(self)
flags.append('--login-screen=login')
return flags
def setUp(self):
policy_base.PolicyTestBase.setUp(self)
# TODO(bartfab): Remove this after crosbug.com/20709 is fixed.
self._local_state_auto_clearing = \
self.IsLocalStateAutoClearingEnabledOnChromeOS()
# Cache user credentials for easy lookup. The first user will become the
# owner.
credentials = (self.GetPrivateInfo()['prod_enterprise_test_user'],
self.GetPrivateInfo()['prod_enterprise_executive_user'],
self.GetPrivateInfo()['prod_enterprise_sales_user'])
self._usernames = [credential['username'] for credential in credentials]
self._passwords = [credential['password'] for credential in credentials]
def tearDown(self):
# TODO(bartfab): Remove this after crosbug.com/20709 is fixed.
# Try to re-enable automatic clearing of the local state and /home/chronos.
if not self._local_state_auto_clearing:
self.TryToEnableLocalStateAutoClearingOnChromeOS()
self.set_clear_profile(True)
policy_base.PolicyTestBase.tearDown(self)
def _CheckGuestModeAvailableInLoginWindow(self):
return self.ExecuteJavascriptInOOBEWebUI(
"""window.domAutomationController.send(
......@@ -113,13 +75,6 @@ class ChromeosDevicePolicy(policy_base.PolicyTestBase):
self.assertFalse(self._CheckGuestModeAvailableInLoginWindow(),
msg='Expected guest mode to not be available.')
# TODO(bartfab): Remove this after crosbug.com/20709 is fixed.
self.TryToDisableLocalStateAutoClearing()
if self._local_state_auto_clearing:
logging.warn("""Unable to disable local state clearing. Skipping remainder
of test.""")
return
# Log in as a regular so that the pod row contains at least one pod and the
# account picker is shown.
self.Login(user_index=0, expect_success=True)
......@@ -137,12 +92,6 @@ class ChromeosDevicePolicy(policy_base.PolicyTestBase):
def testShowUserNamesOnSignin(self):
"""Checks that the account picker can be enabled/disabled."""
# TODO(bartfab): Remove this after crosbug.com/20709 is fixed.
self.TryToDisableLocalStateAutoClearing()
if self._local_state_auto_clearing:
logging.warn('Unable to disable local state clearing. Skipping test.')
return
# Log in as a regular user so that the pod row contains at least one pod and
# the account picker can be shown.
self.Login(user_index=0, expect_success=True)
......@@ -163,8 +112,13 @@ class ChromeosDevicePolicy(policy_base.PolicyTestBase):
ommitted since the broken behavior should be fixed rather than protected by
tests.
"""
# TODO(nirnimesh): Remove show_user_names policy below when
# Login() automation can reliably handle relogin scenario.
# crbug.com/139166
# No whitelist
self.SetDevicePolicy({'allow_new_users': True})
self.SetDevicePolicy({'allow_new_users': True,
'show_user_names': False})
self.Login(user_index=0, expect_success=True)
self.Logout()
......@@ -174,18 +128,21 @@ class ChromeosDevicePolicy(policy_base.PolicyTestBase):
self.Logout()
self.SetDevicePolicy({'allow_new_users': True,
'user_whitelist': []})
'user_whitelist': [],
'show_user_names': False})
self.Login(user_index=0, expect_success=True)
self.Logout()
# Populated whitelist
self.SetDevicePolicy({'user_whitelist': [self._usernames[0]]})
self.SetDevicePolicy({'user_whitelist': [self._usernames[0]],
'show_user_names': False})
self.Login(user_index=0, expect_success=True)
self.Logout()
self.Login(user_index=1, expect_success=False)
self.SetDevicePolicy({'allow_new_users': True,
'user_whitelist': [self._usernames[0]]})
'user_whitelist': [self._usernames[0]],
'show_user_names': False})
self.Login(user_index=0, expect_success=True)
self.Logout()
self.Login(user_index=1, expect_success=True)
......@@ -193,19 +150,14 @@ class ChromeosDevicePolicy(policy_base.PolicyTestBase):
# New users not allowed, populated whitelist
self.SetDevicePolicy({'allow_new_users': False,
'user_whitelist': [self._usernames[0]]})
'user_whitelist': [self._usernames[0]],
'show_user_names': False})
self.Login(user_index=0, expect_success=True)
self.Logout()
self.Login(user_index=1, expect_success=False)
def testUserWhitelistInAccountPicker(self):
"""Checks that setting a whitelist removes non-whitelisted user pods."""
# TODO(bartfab): Remove this after crosbug.com/20709 is fixed.
self.TryToDisableLocalStateAutoClearing()
if self._local_state_auto_clearing:
logging.warn('Unable to disable local state clearing. Skipping test.')
return
# Disable the account picker so that the login form is shown and the Login()
# automation call can be used.
self.PrepareToWaitForLoginFormReload()
......
......@@ -12,7 +12,6 @@ Usage:
sudo python suid_actions.py --action=CleanFlimflamDirs
"""
import logging
import optparse
import os
import shutil
......@@ -24,12 +23,9 @@ sys.path.append('/usr/local') # to import autotest libs.
from autotest.cros import constants
from autotest.cros import cryptohome
# TODO(bartfab): Remove when crosbug.com/20709 is fixed.
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
from pyauto import AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE
TEMP_BACKCHANNEL_FILE = '/tmp/pyauto_network_backchannel_file'
class SuidAction(object):
"""Helper to perform some super-user actions on ChromeOS."""
......@@ -89,38 +85,6 @@ class SuidAction(object):
"""Remove any existing cryptohome vaults."""
cryptohome.remove_all_vaults()
def TryToDisableLocalStateAutoClearing(self):
"""Try to disable clearing of the local state on session manager startup.
This will fail if rootfs verification is on.
TODO(bartfab): Remove this method when crosbug.com/20709 is fixed.
"""
os.system('mount -o remount,rw /')
os.remove(AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE)
os.system('mount -o remount,ro /')
if os.path.exists(AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE):
logging.debug('Failed to remove %s. Session manager will clear local '
'state on startup.' % AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE)
else:
logging.debug('Removed %s. Session manager will not clear local state on '
'startup.' % AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE)
def TryToEnableLocalStateAutoClearing(self):
"""Try to enable clearing of the local state on session manager startup.
This will fail if rootfs verification is on.
TODO(bartfab): Remove this method when crosbug.com/20709 is fixed.
"""
os.system('mount -o remount,rw /')
open(AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE, 'w').close()
os.system('mount -o remount,ro /')
if os.path.exists(AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE):
logging.debug('Created %s. Session manager will clear local state on '
'startup.' % AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE)
else:
logging.debug('Failed to create %s. Session manager will not clear local '
'state on startup.' % AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE)
def _GetEthInterfaces(self):
"""Returns a list of the eth* interfaces detected by the device."""
# Assumes ethernet interfaces all have "eth" in the name.
......
......@@ -102,6 +102,9 @@ class PolicyTestBase(pyauto.PyUITest):
device_id = string.upper(str(uuid.uuid4()))
machine_id = 'CROSTEST'
_auth_server = None
_dns_server = None
@staticmethod
def _Call(command, check=False):
"""Invokes a subprocess and optionally asserts the return value is zero."""
......@@ -321,7 +324,8 @@ class PolicyTestBase(pyauto.PyUITest):
cros_ui.stop(allow_fail=True)
# Stop mock GAIA server.
self._auth_server.stop()
if self._auth_server:
self._auth_server.stop()
# Reenable TPM if present.
if os.path.exists(TPM_SYSFS_PATH):
......@@ -331,7 +335,8 @@ class PolicyTestBase(pyauto.PyUITest):
self._ClearInstallAttributesOnChromeOS()
# Stop mock DNS server.
self._dns_server.stop()
if self._dns_server:
self._dns_server.stop()
# Stop mock DMServer.
self.StopHTTPServer(self._http_server)
......@@ -357,8 +362,16 @@ class PolicyTestBase(pyauto.PyUITest):
"""
if self.IsChromeOS():
# Perform the remainder of the setup with the device manager stopped.
self.WaitForSessionManagerRestart(
self._SetUpWithSessionManagerStopped)
try:
self.WaitForSessionManagerRestart(
self._SetUpWithSessionManagerStopped)
except:
# Destroy the non re-entrant services.
if self._auth_server:
self._auth_server.stop()
if self._dns_server:
self._dns_server.stop()
raise
pyauto.PyUITest.setUp(self)
self._branding = self.GetBrowserInfo()['properties']['branding']
......
......@@ -95,9 +95,6 @@ _REMOTE_PROXY = None
_OPTIONS = None
_BROWSER_PID = None
# TODO(bartfab): Remove when crosbug.com/20709 is fixed.
AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE = '/root/.forget_usernames'
class PyUITest(pyautolib.PyUITestBase, unittest.TestCase):
"""Base class for UI Test Cases in Python.
......@@ -483,30 +480,6 @@ class PyUITest(pyautolib.PyUITestBase, unittest.TestCase):
"""Remove any existing cryptohome vaults."""
PyUITest.RunSuperuserActionOnChromeOS('RemoveAllCryptohomeVaults')
@staticmethod
def TryToDisableLocalStateAutoClearingOnChromeOS():
"""Disable clearing of the local state on session manager startup.
TODO(bartfab): Remove this method when crosbug.com/20709 is fixed.
"""
PyUITest.RunSuperuserActionOnChromeOS('TryToDisableLocalStateAutoClearing')
@staticmethod
def TryToEnableLocalStateAutoClearingOnChromeOS():
"""Enable clearing of the local state on session manager startup.
TODO(bartfab): Remove this method when crosbug.com/20709 is fixed.
"""
PyUITest.RunSuperuserActionOnChromeOS('TryToEnableLocalStateAutoClearing')
@staticmethod
def IsLocalStateAutoClearingEnabledOnChromeOS():
"""Check if the session manager is set to clear the local state on startup.
TODO(bartfab): Remove this method when crosbug.com/20709 is fixed.
"""
return os.path.exists(AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE)
@staticmethod
def _IsInodeNew(path, old_inode):
"""Determine whether an inode has changed. POSIX only.
......@@ -772,16 +745,17 @@ class PyUITest(pyautolib.PyUITestBase, unittest.TestCase):
'--sync-notification-method=p2p',
]
def GetPrivateInfo(self):
@staticmethod
def GetPrivateInfo():
"""Fetch info from private_tests_info.txt in private dir.
Returns:
a dictionary of items from private_tests_info.txt
"""
private_file = os.path.join(
self.DataDir(), 'pyauto_private', 'private_tests_info.txt')
PyUITest.DataDir(), 'pyauto_private', 'private_tests_info.txt')
assert os.path.exists(private_file), '%s missing' % private_file
return self.EvalDataFrom(private_file)
return PyUITest.EvalDataFrom(private_file)
def WaitUntil(self, function, timeout=-1, retry_sleep=0.25, args=[],
expect_retval=None, debug=True):
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment