当前位置:网站首页>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 :

  1. The duration cannot be controlled during the test
  2. It is easy to be interrupted in the test
  3. 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 )

原网站

版权声明
本文为[Little brother said test]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202142337128320.html