当前位置:网站首页>Monkey/ auto traverse test, integrate screen recording requirements
Monkey/ auto traverse test, integrate screen recording requirements
2022-07-03 21:02:00 【Little brother said test】
1、 demand
Recent development response :Monkey/ Occurs when automatically traversing the test FC、ANR Other questions , adopt log Unable to accurately locate the cause of the problem and the recurrence path , I hope the screen recording can be added during the test , Easy to locate the path and cause of problem recurrence .( For automatic traversal test, please refer to :https://github.com/bytedance/Fastbot_Android)
The recording screen of the mobile phone is defective :
- The duration cannot be controlled during the test
- It is easy to be interrupted in the test
- Long time screen recording consumes too much mobile phone memory
2、 Solutions
Monkey/ When traversing the test automatically , adopt adb Command intermittent screen recording , Then parse the test log, If no error message appears , Just delete the previous recording , conversely , Save and export the recording .
3、 flow chart

flow chart .jpg
4、 Testing process
4.1、Python Third party libraries required for environment and source code
4.2、 Modify as required monkey_through.yaml Configuration information ( Notice the space between the fields )
4.3、 Turn on the device log, keep usb Connecting device , Do not interrupt during the test
4.4、 perform main() Method ( An exception will automatically terminate the test , And export the screen recording to the script directory )
5、Yaml Sample configuration file
# Test type :Monkey/Through
testType: Through
# 【Monkey】
Monkey:
# Package name
packageName: com.google.android.dialer
# Number of runs
runTimes: 500
# Seed value
runSeed: 999
# Event flow interval ( Company : millisecond )
runThrottle: 500
pctTouch: 50
pctMotion: 20
pctTrackball: 5
pctSyskeys: 5
pctAppSwitch: 5
pctRotation: 5
# 【 Automatic traversal 】
Through:
# Package name
packageName: com.example.anrfcapp
# Test the clock ( Company : minute )
runMinutes: 10
# Time flow interval
runThrottle: 500
# Screen recording configuration
screenRecord:
# Recording time ( Company : second )
recordTime: 60
5、 Source code
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2021/11/15 16:31
# @Author : CuiShuangqi
# @Email : [email protected]
# @File : monkeyScreenRecord.py
"""
demand : Integrate Monkey、 Auto traverse test , And add screen recording function ( Intermittent screen recording , If no error is reported, the previous recording screen will be deleted )
notes : Please modify before testing monkey_through.yaml The configuration file
"""
import os
import time
import yaml
# Get mobile information
def get_device_info():
# Wait for the phone to connect
print(" Wait for the device to connect ...")
os.system("adb wait-for-device")
print(" Device connected successfully , The parameters are as follows :")
# Mobile phone model
phoneModel = os.popen("adb shell getprop ro.product.model").read().strip('\n')
# mobile phone SOC
socModel = os.popen("adb shell getprop ro.board.platform").read().strip('\n').upper()
# Software version
softwareVersion = os.popen("adb shell getprop ro.build.display.id").read().strip('\n')
# Android version
androidVersion = os.popen("adb shell getprop ro.build.version.release").read().strip('\n')
print(f"【 Mobile phone model 】:{phoneModel}",
f"\n【 Mobile platform 】:{socModel}",
f"\n【 Software version 】:{softwareVersion}",
f"\n【 Android version 】:{androidVersion}")
# Read configuration information
def read_yaml(test_type: str):
yamlPath = os.path.join(os.getcwd(), "monkey_through.yaml")
with open(yamlPath, "r", encoding="GBK") as f:
return yaml.load(f.read(), Loader=yaml.FullLoader)[test_type]
# Judge the mobile phone test environment
def is_test_environment(test_type: str) -> bool:
# The current directory of the script
curPath = os.getcwd()
flag = False
# Monkey test
if test_type == "Monkey":
print("Monkey There is no need to configure the test environment for testing !")
flag = True
# Auto traverse test
elif test_type == "Through":
jarFiles = os.popen("adb shell find /sdcard/ -name '*.jar'").read()
if "/sdcard/framework.jar" in jarFiles and "/sdcard/monkeyq.jar" in jarFiles:
print(" Already exists in the device framework.jar、monkeyq.jar!")
flag = True
else:
cur_files = []
for root, dirs, files in os.walk(os.getcwd()):
for f in files:
cur_files.append(os.path.join(root, f))
frameworkJarPath = os.path.join(curPath, "framework.jar")
monkeyqJarPath = os.path.join(curPath, "monkeyq.jar")
# Determine whether the script directory has jar package
if frameworkJarPath in cur_files and monkeyqJarPath in cur_files:
# The current directory exists jar package , push jar Package to /sdcard/
if os.system(f"adb push {frameworkJarPath} /sdcard/") == 0 and \
os.system(f"adb push {monkeyqJarPath} /sdcard/") == 0:
print(" push framework.jar、monkeyq.jar to /sdcard/ Catalog success !")
flag = True
else:
print(" push framework.jar、monkeyq.jar to /sdcard/ Directory failed !")
flag = False
else:
print(" The current directory of the script does not exist framework.jar、monkeyq.jar!")
flag = False
else:
print(" Test type parameter error !")
flag = False
return flag
def test_monkey_or_through(test_type: str):
# Background operation
if test_type == "Monkey":
monkeyCommand = f'adb shell "monkey ' \
f'-p {read_yaml("Monkey")["packageName"]} ' \
f'--throttle {read_yaml("Monkey")["runThrottle"]} ' \
f'--randomize-throttle ' \
f'--ignore-crashes ' \
f'--ignore-timeouts ' \
f'--ignore-security-exceptions ' \
f'--ignore-native-crashes ' \
f'--pct-touch {read_yaml("Monkey")["pctTouch"]} ' \
f'--pct-motion {read_yaml("Monkey")["pctMotion"]} ' \
f'--pct-trackball {read_yaml("Monkey")["pctTrackball"]} ' \
f'--pct-syskeys {read_yaml("Monkey")["pctSyskeys"]} ' \
f'--pct-appswitch {read_yaml("Monkey")["pctAppSwitch"]} ' \
f'--pct-rotation {read_yaml("Monkey")["pctRotation"]} ' \
f'-v -v -v {read_yaml("Monkey")["runTimes"]} ' \
f'1>/sdcard/monkeyInfo.txt 2>/sdcard/monkeyError.txt &"'
os.system(monkeyCommand)
elif test_type == "Through":
throughCommand = f'adb shell ' \
f'"CLASSPATH=/sdcard/monkeyq.jar:/sdcard/framework.jar ' \
f'exec app_process /system/bin com.android.commands.monkey.Monkey ' \
f'-p {read_yaml("Through")["packageName"]} ' \
f'--agent robot ' \
f'--running-minutes {read_yaml("Through")["runMinutes"]} ' \
f'--throttle {read_yaml("Through")["runThrottle"]} -v -v -v ' \
f'1>/sdcard/throughInfo.txt 2>/sdcard/throughError.txt &"'
os.system(throughCommand)
# Screen Recording
def screen_record(test_type: str) -> str:
# Recording seconds
recordTime = read_yaml("screenRecord")["recordTime"]
# Recording file name
timeFlag = time.strftime('%Y-%m-%d_%H%M%S', time.localtime(time.time()))
recordName = f"/sdcard/{test_type}_{timeFlag}.mp4"
print(" Recording screen ... Do not disconnect !")
recordCommand = f'adb shell screenrecord --time-limit {recordTime} {recordName}'
os.system(recordCommand)
print(" The recording screen has ended !")
# Return to recording mp4 The name of the file , It is convenient to delete the file when there is no exception
return recordName
# Judge whether the mobile phone is abnormal
def is_Exception(testType: str) -> bool:
flag = False
if testType == "Monkey":
# analysis /sdcard/monkeyError.txt
throughErrorInfo = os.popen('adb shell cat /sdcard/monkeyError.txt').read()
if "ANR" in throughErrorInfo or "NOT RESPONDING" in throughErrorInfo or "CRASH" in throughErrorInfo:
flag = True
print("Monkey There are exceptions in the test !!!")
elif testType == "Through":
# analysis /sdcard/throughError.txt
throughErrorInfo = os.popen('adb shell cat /sdcard/throughError.txt').read()
if "ANR" in throughErrorInfo or "NOT RESPONDING" in throughErrorInfo or "CRASH" in throughErrorInfo:
flag = True
print(" There is an exception in automatic traversal !!!")
# Export video
else:
print(" No abnormality was found in this test !")
return flag
# main
def main():
get_device_info()
testType = read_yaml("testType")
if is_test_environment(testType):
# Start testing
test_monkey_or_through(testType)
while True:
# Recording screen
recordName = screen_record(testType)
findMonkeyPsCommand = 'adb shell ps | findstr -i "monkey"'
commandList = os.popen(findMonkeyPsCommand).read().strip("\n").split(" ")
if commandList[0] != "":
# Determine whether an exception occurs
if is_Exception(testType):
# Export the screen recording to the current directory
if os.system(f"adb pull {recordName} {os.getcwd()}") == 0:
print(f" The video has been exported to :【{os.getcwd()}】")
else:
print(f" Failed to export video , Stored :{recordName}")
# Inquire about monkey process id result , And go empty
myList = [i for i in commandList if i != '']
# Take the second value of the list , That is to say monkey process id
monkeyId = myList[1]
# kill Drop the traversal process
if os.system(f"adb shell kill {monkeyId}") == 0:
print(" The process ended successfully !")
else:
print(" Process end failed , Please try to end the process manually !")
break
else:
# Delete the previous screen recording , And record the screen again
if os.system(f"adb shell rm {recordName}") == 0:
print(" The screen recording was deleted successfully !")
else:
print(" Failed to delete screen recording !")
break
else:
# The test is over
print(" The test is over , No abnormality found , The last screen recording of the test has been saved !")
break
else:
print(" Failed to initialize the test environment !")
if __name__ == '__main__':
main()
The following is the supporting information , For doing 【 software test 】 For our friends, it should be the most comprehensive and complete war preparation warehouse , This warehouse also accompanied me through the most difficult journey , I hope it can help you !
Last : It can be in the official account : Programmer Xiaohao ! Get a free copy of 216 Page software testing engineer interview guide document information . And the corresponding video learning tutorial is free to share !, It includes basic knowledge 、Linux necessary 、Shell、 The principles of the Internet 、Mysql database 、 Special topic of bag capturing tools 、 Interface testing tool 、 Test advanced -Python Programming 、Web automated testing 、APP automated testing 、 Interface automation testing 、 Testing advanced continuous integration 、 Test architecture development test framework 、 Performance testing 、 Safety test, etc. .
If my blog helps you 、 If you like my blog content , please “ give the thumbs-up ” “ Comment on ” “ Collection ” One button, three links ! Friends who like software testing , You can join our testing technology exchange group :779450660 There are various software testing resources and technical discussions )
边栏推荐
- Leetcode daily question 540 A single element in an ordered array Valentine's Day special article looking for a single dog in a pile of lovers ~ the clown is myself
- 18、 MySQL -- index
- Discussion Net legacy application transformation
- @Transactional注解失效的场景
- Sort out several network request methods of JS -- get rid of callback hell
- 【愚公系列】2022年7月 Go教学课程 002-Go语言环境安装
- Strange way of expressing integers (expanding Chinese remainder theorem)
- Pengcheng cup Web_ WP
- How to handle wechat circle of friends marketing activities and share production and release skills
- Node MySQL serialize cannot rollback transactions
猜你喜欢
![Measurement fitting based on Halcon learning -- Practice [1]](/img/71/9f6c27aa89035b2550bdb0ac902045.jpg)
Measurement fitting based on Halcon learning -- Practice [1]

Yyds dry goods inventory TCP & UDP

Apprentissage intensif - notes d'apprentissage 1 | concepts de base

Rhcsa third day operation

Haven't expressed the artifact yet? Valentine's Day is coming. Please send her a special gift~

thrift go

(5) Web security | penetration testing | network security operating system database third-party security, with basic use of nmap and masscan

MySQL——索引

Hcie security Day11: preliminarily learn the concepts of firewall dual machine hot standby and vgmp

Borui data and Sina Finance released the 2021 credit card industry development report
随机推荐
2022 low voltage electrician examination and low voltage electrician simulation examination question bank
[Yugong series] go teaching course 002 go language environment installation in July 2022
Qualcomm platform WiFi -- P2P issue
Last week's content review
电子科技大学|强化学习中有效利用的聚类经验回放
《ActBERT》百度&悉尼科技大学提出ActBERT,学习全局局部视频文本表示,在五个视频-文本任务中有效!...
设计电商秒杀系统
Study diary: February 14th, 2022
【c】 Digital bomb
Gauss elimination solves linear equations (floating-point Gauss elimination template)
In 2021, the global foam protection packaging revenue was about $5286.7 million, and it is expected to reach $6615 million in 2028
19、 MySQL -- SQL statements and queries
Get log4net log file in C - get log4net log file in C
Operate BOM objects (key)
浅议.NET遗留应用改造
【愚公系列】2022年7月 Go教学课程 002-Go语言环境安装
Discussion Net legacy application transformation
Shortest path problem of graph theory (acwing template)
APEC industry +: father of the king of the ox mill, industrial Internet "king of the ox mill anti-wear faction" Valentine's Day greetings | Asia Pacific Economic media | ChinaBrand
Wireless network (preprocessing + concurrent search)