1# Copyright 2014 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import json
6import logging
7import os
8
9from autotest_lib.client.bin import test
10from autotest_lib.client.bin import utils
11from autotest_lib.client.common_lib import error
12from autotest_lib.client.common_lib.cros import chrome
13from autotest_lib.client.cros import cryptohome
14from autotest_lib.client.cros import power_status
15from autotest_lib.client.cros.enterprise import enterprise_fake_dmserver
16
17
18class enterprise_PowerManagement(test.test):
19    """Verify the power management policy setting."""
20    version = 1
21
22    def setup(self):
23        os.chdir(self.srcdir)
24        utils.make('OUT_DIR=.')
25
26    def initialize(self, percent_initial_charge_min=10):
27        """
28        Setup local variables and  init the fake DM server
29
30        @param percent_initial_charge_min: Minimum percentage of battery
31                                           required for the test to run.
32
33        """
34        # Username and password for the fake dm server can be anything
35        # they are not used to authenticate against GAIA.
36        self.username = 'fake-user@managedchrome.com'
37        self.password = 'fakepassword'
38
39        self._power_status = power_status.get_status()
40        if not self._power_status.on_ac():
41            # Ensure that the battery has some charge.
42            self._power_status.assert_battery_state(percent_initial_charge_min)
43        logging.info("Device power type is %s", self._power_type)
44
45        self.fake_dm_server = enterprise_fake_dmserver.FakeDMServer(
46                self.srcdir)
47        self.fake_dm_server.start(self.tmpdir, self.debugdir)
48
49    def cleanup(self):
50        self.fake_dm_server.stop()
51
52    @property
53    def _power_type(self):
54        """
55        Returns appropriate power type based on whether DUT is on AC or not.
56
57        @returns string of power type.
58
59        """
60        if self._power_status.on_ac():
61            return "AC"
62
63        return "Battery"
64
65    def _setup_lock_policy(self):
66        """Setup policy to lock screen in 10 seconds of idle time."""
67        self._screen_lock_delay = 10
68        screen_lock_policy = '{ "%s": %d }' % (
69                self._power_type, self._screen_lock_delay*1000)
70        policy_blob = """{
71            "google/chromeos/user": {
72                "mandatory": {
73                    "ScreenLockDelays": %s
74                }
75            },
76            "managed_users": [ "*" ],
77            "policy_user": "%s",
78            "current_key_index": 0,
79            "invalidation_source": 16,
80            "invalidation_name": "test_policy"
81        }""" % (json.dumps(screen_lock_policy), self.username)
82
83        self.fake_dm_server.setup_policy(policy_blob)
84
85    def _setup_logout_policy(self):
86        """Setup policy to logout in 10 seconds of idle time."""
87        self._screen_logout_delay = 10
88        idle_settings_policy = '''{
89            "%s": {
90                "Delays": {
91                    "ScreenDim": 2000,
92                    "ScreenOff": 3000,
93                    "IdleWarning": 4000,
94                    "Idle": %d
95                 },
96                 "IdleAction": "Logout"
97            }
98        }''' % (self._power_type, self._screen_logout_delay*1000)
99
100        policy_blob = """{
101            "google/chromeos/user": {
102                "mandatory": {
103                    "PowerManagementIdleSettings": %s
104                }
105            },
106            "managed_users": [ "*" ],
107            "policy_user": "%s",
108            "current_key_index": 0,
109            "invalidation_source": 16,
110            "invalidation_name": "test_policy"
111        }""" % (json.dumps(idle_settings_policy), self.username)
112
113        self.fake_dm_server.setup_policy(policy_blob)
114
115    def _create_chrome(self):
116        """
117        Create an instance of chrome.
118
119        @returns a telemetry browser instance.
120
121        """
122        extra_browser_args = '--device-management-url=%s ' %(
123                self.fake_dm_server.server_url)
124        return chrome.Chrome(
125                extra_browser_args=extra_browser_args,
126                autotest_ext=True,
127                disable_gaia_services=False,
128                gaia_login=False,
129                username=self.username,
130                password=self.password)
131
132    def run_once(self):
133        """Run the power management policy tests."""
134        self._setup_lock_policy()
135        with self._create_chrome() as cr:
136            utils.poll_for_condition(
137                    lambda: cr.login_status['isScreenLocked'],
138                            exception=error.TestFail('User is not locked'),
139                            timeout=self._screen_lock_delay*2,
140                            sleep_interval=1,
141                            desc='Expects to find Chrome locked.')
142
143        self._setup_logout_policy()
144        with self._create_chrome() as cr:
145            utils.poll_for_condition(
146                    lambda: not cryptohome.is_vault_mounted(user=self.username,
147                            allow_fail=True),
148                            exception=error.TestFail('User is not logged out'),
149                            timeout=self._screen_logout_delay*2,
150                            sleep_interval=1,
151                            desc='Expects to find user logged out.')
152