1# Copyright (c) 2013 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
5from dbus.mainloop.glib import DBusGMainLoop
6
7from autotest_lib.client.bin import test
8from autotest_lib.client.common_lib import error
9from autotest_lib.client.common_lib.cros import session_manager
10from autotest_lib.client.cros import cros_ui, cryptohome
11
12
13class login_RetrieveActiveSessions(test.test):
14    """Ensure that the session_manager correctly tracks active sessions.
15    """
16    version = 1
17
18
19    def initialize(self):
20        super(login_RetrieveActiveSessions, self).initialize()
21        cros_ui.restart()
22
23
24    def run_once(self):
25        bus_loop = DBusGMainLoop(set_as_default=True)
26        sm = session_manager.connect(bus_loop)
27
28        cryptohome_proxy = cryptohome.CryptohomeProxy(bus_loop)
29        users = ['first_user@nowhere.com', 'second_user@nowhere.com']
30        for user in users:
31            cryptohome_proxy.ensure_clean_cryptohome_for(user)
32
33        sm.StartSession(users[0], '')
34        self.__check_for_users_in_actives(users[:1],
35                                          sm.RetrieveActiveSessions())
36
37        sm.StartSession(users[1], '')
38        self.__check_for_users_in_actives(users, sm.RetrieveActiveSessions())
39
40
41    def __check_for_users_in_actives(self, users, actives):
42        """Checks that only members of users are in actives.
43
44        If there are too many (or too few) entries in actives, this method
45        raises.  Also, if each member of users is not present in the keys of
46        actives, then the method also raises.
47
48        @param users: iterable of user names to be checked for.
49        @param actives: a dictionary of {user: userhash}, the keys of which
50                        are expected to match users.
51
52        @raises error.TestFail: if one of the above criteria is not met.
53        """
54        expected_sessions = len(users)
55        if len(actives) != expected_sessions:
56            raise error.TestFail("%d session(s) should be active, not: %s" %
57                                 (expected_sessions, str(actives)))
58
59        if set(users) != set(actives.keys()):
60            raise error.TestFail("Expected sessions for %s, got %s" %
61                                 (users, actives))
62
63
64    def cleanup(self):
65        # Bounce UI, without waiting for the browser to come back. Best effort.
66        cros_ui.stop(allow_fail=True)
67        cros_ui.start(allow_fail=True, wait_for_login_prompt=False)
68