1#!/usr/bin/env python3
2#
3#   Copyright 2016 - Google
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16#
17#
18# Defines utilities that can be used to create android user account
19
20import re
21import time
22import logging as log
23
24
25
26def get_all_users(android_device):
27    all_users = {}
28    out = android_device.adb.shell("pm list users")
29
30    for user in re.findall("UserInfo{(.*\d*\w):", out):
31        all = user.split(":")
32        all_users[all[1]] = all_users.get(all[1], all[0])
33    return all_users
34
35
36def create_new_user(android_device, user_name):
37    out = android_device.adb.shell("pm create-user {}".format(user_name))
38    return re.search("Success(.* (.*\d))", out).group(2)
39
40
41def switch_user(android_device, user_id):
42    prev_user = get_current_user(android_device)
43    android_device.adb.shell("am switch-user {}".format(user_id))
44    if not _wait_for_user_to_take_place(android_device, prev_user):
45        log.error("Failed to successfully switch user {}".format(user_id))
46        return False
47    return True
48
49
50def remove_user(android_device, user_id):
51    return "Success" in android_device.adb.shell("pm remove-user {}".format(user_id))
52
53
54def get_current_user(android_device):
55    out = android_device.adb.shell("dumpsys activity")
56    result = re.search("mCurrentUserId:(\d+)", out)
57    return result.group(1)
58
59
60def _wait_for_user_to_take_place(android_device, user_id, timeout=10):
61    start_time = time.time()
62    while (start_time + timeout) > time.time():
63        time.sleep(1)
64        if user_id != get_current_user(android_device):
65            return True
66    return False
67