Skip to content

Commit

Permalink
feat:添加“自动授权应用权限”方法,指定包名后自动赋予被测应用运行时所需权限,不再出现运行时权限弹窗,避免对用例执行的干扰 (#977)
Browse files Browse the repository at this point in the history
* add app_auto_grant_permissions methods

* fix some code specifications

* add target API version check when auto grant permission

* 修改判断是否执行动态权限的授予,改为使用手机系统版本
  • Loading branch information
caofengbin authored May 27, 2024
1 parent b3a97ab commit 5d20e56
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
4 changes: 4 additions & 0 deletions mobile_tests/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,7 @@ def test_session_app(dev: u2.Device, package_name):
def test_session_window_size(dev: u2.Device):
assert isinstance(dev.window_size(), tuple)


def test_auto_grant_permissions(dev: u2.Device):
dev.app_auto_grant_permissions('com.tencent.mm')

44 changes: 44 additions & 0 deletions uiautomator2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import logging
import os
import re
import string
import time
import warnings
from functools import cached_property
Expand Down Expand Up @@ -895,6 +896,49 @@ def app_info(self, package_name: str) -> Dict[str, Any]:
"versionCode": info.version_code,
}

def app_auto_grant_permissions(self, package_name: str) -> bool:
""" auto grant runtime permissions to target app,prevent dynamic permission pop-up window to pop up
Args:
package_name (str): package name
Returns:
bool of operate
"""
device_api_version = self.shell(['getprop', 'ro.build.version.sdk']).output
device_api_version = device_api_version.rstrip("\n")
output, _ = self.shell(['dumpsys', 'package', f'{package_name}'])

group_pattern = re.compile(r'^(\s*' + 'runtime' + r' permissions:[\s\S]+)', re.MULTILINE)
group_matcher = group_pattern.search(output)
if not group_pattern:
return False
group_match = group_matcher.group(1)
lines = group_match.split("\n")
if len(lines) < 2:
return False
title_indent = len(lines[0]) - len(lines[0].lstrip())
if device_api_version is None or int(device_api_version) < 23:
print('Skipping permissions grant option,only target api greater or equal to 23 support')
return True
for i in range(1, len(lines)):
line = lines[i]
current_indent = len(line) - len(line.lstrip())

if current_indent <= title_indent:
break

permission_name_pattern = re.compile(r'android\.\w*\.?permission\.\w+')
permission_name_matcher = permission_name_pattern.search(line)

if not permission_name_matcher:
continue
else:
permission_name = permission_name_matcher.group()
print(f'auto grant permission {permission_name}')
self.shell(['pm', 'grant', package_name, permission_name])
return True


class _DeprecatedMixIn:
@property
def wait_timeout(self): # wait element timeout
Expand Down

0 comments on commit 5d20e56

Please sign in to comment.