当前位置:网站首页>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 )
边栏推荐
- Refer to some books for the distinction between blocking, non blocking and synchronous asynchronous
- Do you really know how old you are?
- MySQL 8.0 data backup and recovery
- TLS environment construction and plaintext analysis
- Instructions for common methods of regular expressions
- What is the maximum number of concurrent TCP connections for a server? 65535?
- 强化學習-學習筆記1 | 基礎概念
- Rhcsa third day operation
- Kubernetes 通信异常网络故障 解决思路
- Compilation Principle -- syntax analysis
猜你喜欢
C 10 new feature [caller parameter expression] solves my confusion seven years ago
@Transactional注解失效的场景
2022 safety officer-c certificate examination and safety officer-c certificate registration examination
Summary of common operation and maintenance commands
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of rotary tablet presses in the global market in 2022
如临现场的视觉感染力,NBA决赛直播还能这样看?
Experience summary of database storage selection
How to choose cache read / write strategies in different business scenarios?
thrift go
Custom view incomplete to be continued
随机推荐
MySQL——索引
Basic preprocessing and data enhancement of image data
Interval product of zhinai sauce (prefix product + inverse element)
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of rotary tablet presses in the global market in 2022
Kubernetes 通信异常网络故障 解决思路
Get log4net log file in C - get log4net log file in C
CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
Shortest path problem of graph theory (acwing template)
Analysis of gas fee setting under eip1559
Analyse de REF nerf
Link aggregation based on team mechanism
Wireless network (preprocessing + concurrent search)
@Transactional注解失效的场景
(5) Web security | penetration testing | network security operating system database third-party security, with basic use of nmap and masscan
[secretly kill little buddy pytorch20 days -day02- example of image data modeling process]
"Designer universe" argument: Data Optimization in the design field ultimately falls on cost, safety and health | chinabrand.com org
What is the maximum number of concurrent TCP connections for a server? 65535?
Capture de paquets et tri du contenu externe - - autoresponder, composer, statistiques [3]
Sightseeing - statistics of the number of shortest paths + state transfer + secondary small paths
强化学习-学习笔记1 | 基础概念