Skip to content

Commit ed562fc

Browse files
committed
first commit
0 parents  commit ed562fc

File tree

5 files changed

+200
-0
lines changed

5 files changed

+200
-0
lines changed

README.md

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# README
2+
3+
### 文件结构:
4+
5+
- **实验报告.pdf**
6+
- **code**
7+
- adbfunc.py
8+
- config.py
9+
- test.py
10+
- README.md
11+
12+
---
13+
14+
### 运行方法请参考实验报告内容:
15+
16+
代码运行环境请参考 **实验报告****2 实验环境条件**
17+
18+
连接设备方法、智能Monkey运行方法等操作请参考 **实验报告****3.2.3 运行智能测试方法**

code/adbfunc.py

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import os
2+
import platform
3+
import time
4+
5+
class AndroidDebugBridge(object):
6+
@staticmethod
7+
# 执行命令
8+
def call_adb(command):
9+
command_result = ''
10+
command_text = f'adb {command}'
11+
print("执行命令:" + command_text)
12+
results = os.popen(command_text, "r")
13+
while 1:
14+
line = results.readline()
15+
if not line:
16+
break
17+
command_result += line
18+
results.close()
19+
return command_result
20+
21+
# 连接设备检查
22+
def attached_devices(self):
23+
result = self.call_adb("devices")
24+
devices = result.partition('\n')[2].replace('\n', '').split('\tdevice')
25+
return [device for device in devices if len(device) > 2]
26+
27+
# 打开指定app
28+
def open_app(self, packageName, activity, devices):
29+
result = self.call_adb(
30+
f"-s {devices} shell am start -n {packageName}/{activity}")
31+
check = result.partition('\n')[2].replace('\n', '').split('\t ')
32+
if check[0].find("Error") >= 1:
33+
return False
34+
else:
35+
return True
36+
37+
# 判断测试app是否在某个界面
38+
def if_top(self, pkg_name, moduleKey):
39+
result = self.current_activity()
40+
if result == '':
41+
return "the process doesn't exist."
42+
print(result)
43+
if (pkg_name in result and moduleKey in result and "leakcanary" not in result) or "WkBrowserActivity" in result or "CordovaWebActivity" in result:
44+
return True
45+
else:
46+
return False
47+
48+
def current_activity(self):
49+
result = self.call_adb("shell dumpsys activity | findstr mResumedActivity")
50+
return result
51+
52+
# 判断是否测试中app在某个界面停留时间过久
53+
def if_dead_lock(self, start_time, current_activity, max_time):
54+
while current_activity == self.current_activity():
55+
end_time = time.time()
56+
print(f"同一页面停留时间: {(end_time - start_time)}")
57+
if end_time - start_time > max_time:
58+
print("超过限定时间:随机打开设定的activity")
59+
return True
60+
else:
61+
return False
62+
else:
63+
return False
64+

code/config.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class MonkeyConfig(object):
2+
# 测试的app包名
3+
package_name = "com.sina.weibo"
4+
# 测试app中模块的关键词
5+
module_key = "com.sina.weibo"
6+
# 设置当测试app卡死时,要自动跳回到随机一个下列界面
7+
activity = [".MainTabActivity",
8+
".page.SearchResultActivity",
9+
".feed.DetailWeiboActivity",
10+
".page.NewCardListActivity",
11+
".photoalbum.imageviewer.ImageViewer",
12+
]
13+
# monkey 命令
14+
monkeyCmd = f"monkey -p {package_name} --throttle 300 " \
15+
"--pct-appswitch 5 --pct-touch 30 --pct-motion 60 --pct-anyevent 5 " \
16+
"--ignore-timeouts --ignore-crashes --monitor-native-crashes -v -v -v 3000 > "

code/test.py

+102
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import datetime
2+
import os
3+
import random
4+
import time
5+
from multiprocessing import Pool
6+
from typing import Dict, Union
7+
import adbfunc
8+
import config
9+
from adbfunc import AndroidDebugBridge
10+
11+
adb = adbfunc.AndroidDebugBridge()
12+
monkeyConfig = config.MonkeyConfig()
13+
14+
# 检测设备
15+
def runnerPool():
16+
devices_Pool = []
17+
devices = adb.attached_devices()
18+
if devices:
19+
for item in range(0, len(devices)):
20+
_app: Dict[str, Union[str, int]] = {"devices": devices[item], "num": len(devices)}
21+
devices_Pool.append(_app)
22+
pool = Pool(len(devices))
23+
pool.map(start, devices_Pool)
24+
pool.close()
25+
pool.join()
26+
else:
27+
print("未检测到连接的设备")
28+
29+
30+
def start(devices):
31+
device = devices["devices"]
32+
deviceNum = devices["num"]
33+
print(f"start device {device};num {deviceNum}")
34+
35+
# 启动初始activity
36+
adb.open_app(monkeyConfig.package_name, monkeyConfig.activity[0], device)
37+
38+
# log文件夹,存放每次test的结果日志
39+
logDir = os.path.join("log", f"{datetime.datetime.now().strftime('%Y%m%d_%p_%H%M%S')}")
40+
os.makedirs(logDir)
41+
adbLogFileName = os.path.join(logDir, "logcat.log")
42+
monkeyLogFile = os.path.join(logDir, "monkey.log")
43+
monkeyConfig.monkeyCmd = f"adb -s {device} shell {monkeyConfig.monkeyCmd + monkeyLogFile}"
44+
45+
# 开始测试
46+
start_monkey(monkeyConfig.monkeyCmd, logDir)
47+
48+
start_activity_time = time.time()
49+
while True:
50+
# 判断测试的app的module是否在top
51+
if AndroidDebugBridge().if_top(monkeyConfig.package_name,
52+
monkeyConfig.module_key) is False:
53+
# 打开第一个设置好的activity(微博主界面)
54+
adb.open_app(monkeyConfig.package_name, monkeyConfig.activity[0], device)
55+
56+
current_activity = AndroidDebugBridge().current_activity()
57+
time.sleep(2)
58+
59+
# 判断测试时是否有在一个界面卡死的现象,设置时间范围为 10
60+
if AndroidDebugBridge().if_dead_lock(start_activity_time, current_activity, 10):
61+
adb.open_app(monkeyConfig.package_name, random.choice(monkeyConfig.activity), device)
62+
start_activity_time = time.time()
63+
64+
# 判断是否结束
65+
with open(monkeyLogFile, "r", encoding='utf-8') as monkeyLog:
66+
if monkeyLog.read().count('Monkey finished') > 0:
67+
print(f"{device}\n测试结束")
68+
break
69+
70+
# 给 crash 计数并输出
71+
with open(adbLogFileName, "r", encoding='utf-8') as logfile:
72+
print(
73+
f"{device}\n存在{logfile.read().count('FATAL EXCEPTION')}个crash!"
74+
f"请查看{adbLogFileName}文件")
75+
76+
77+
# 开始monkey测试
78+
def start_monkey(monkeyCmd, logDir):
79+
os.popen(monkeyCmd)
80+
print(f"start_monkey {monkeyCmd}")
81+
82+
# logcat文件中存入Monkey时的手机日志
83+
logFileName = os.path.join(logDir, "logcat.log")
84+
cmd2 = f"adb logcat -d >{logFileName}"
85+
os.popen(cmd2)
86+
87+
# 导出traces文件 用于分析ANR
88+
traceFilename = os.path.join(logDir, "anr_traces.log")
89+
cmd3 = f"adb shell cat /data/anr/traces.txt>{traceFilename}"
90+
os.popen(cmd3)
91+
92+
93+
def begin():
94+
os.popen("adb kill-server")
95+
os.popen("adb start-server")
96+
os.popen("adb root")
97+
98+
99+
if __name__ == '__main__':
100+
begin()
101+
time.sleep(1)
102+
runnerPool()

实验报告.pdf

1.24 MB
Binary file not shown.

0 commit comments

Comments
 (0)