Unified management of Android device WiFi and device automatic test practice (sorting and summarizing scattered knowledge)

As we all know, the UI automation test of Android single device has been relatively perfect, and there are countless automation frameworks or tools. However, there is not much content to introduce multi device management. When there are many mobile phones in your hand, you have to touch this thing to make an automatic test platform. Get rid of USB restrictions and access WiFi in order to be more free

Framework introduction

1.ATX

ATX(AutomatorX) is an open source automated testing tool that supports testing native applications, games and Web applications on iOS and Android platforms. Use Python to write test cases, and use image recognition and control positioning technology to complete the automation of the game. Attach a special IDE to complete the rapid writing of scripts.   Test interview dictionary 

ATX agent runs inside the mobile phone and adds remote control and automation functions to the mobile phone. The most important function of ATX server is to summarize the ATX agent on a web page and provide an API to obtain the list of all devices

2.uiautomator

UIAutomator is one of the few automation frameworks officially supported by Android. UIAutomator is updated with the release of Android version. As a control based automation framework, UIAutoamtor's overall framework and API are simple and clear, which is very easy to start. After being released, it has been highly praised by many developers, but some developers still feel that it is a pity that they do not support resourceId retrieval controls. The official made up for this shortcoming in the subsequent Level 18. So far, UIAutomator has occupied a place in the field of automated testing and met the needs of most developers.
What are the characteristics of UI autoamtor compared with other automation frameworks? I think it can be described as rough but flexible, simple and reliable. It has many advantages in detail,
To sum up, there are the following points

Official support update: Android native support, less test dependent environment, easy to create·

Clear hierarchical interface: the framework is hierarchical, the results are clear, the API is clear, and the starting cost is very low.

Control based interaction: supports Android native control resolution, which is more compatible than coordinate interaction.

Independent of source code: the testing process is based on black box and can be tested for all distribution versions.

Excellent event waiting: rich interfaces, flexible and accurate control and excellent performance in event waiting.

Support cross process testing: in the automation framework, there are few with this feature, and the test scope is ROM.

In terms of technology selection, in addition to the testing involving the Web, UIAutomator can basically help users implement it. If the user wants to do ROM level test or App room test
Collaboration requires cross process testing, so UIAutomator will be a very good choice; Users are eager to write simple and powerful code, so they might as well choose one
Try, UI Automator can let users see its elegant side in event waiting; It doesn't matter if you don't have code. You can also compare competing products. Unit test and performance test
Test, pressure test and UIAutomator can be the user's choice; Simple but not simple, leaving developers more free space to play, lightweight, flexible, powerful and reliable,
This is UIAutomator

3.python-uiautomator2

python-uiautomator2 encapsulates Google's own uiautomator2 testing framework and provides a convenient Python interface. He allows testers to write Python test code directly on PC, operate mobile applications and complete automation, which greatly improves the efficiency of automatic code writing.

As shown in the figure, python-ui automator2 is mainly divided into two parts: Python client and mobile device

  • python side: run scripts and send HTTP requests to mobile devices

  • Mobile device: the HTTP service encapsulated with uiautomator2 runs on the mobile device, parses the received request and converts it into uiautomator2 code.

The whole process

  1. Install the ATX agent (daemon) on the mobile device, and then the ATX agent starts the uiautomator2 service (port 7912 by default) to listen

  2. Write and execute the test script on the PC (equivalent to sending an HTTP request to the server of the mobile device)

  3. The mobile device receives the HTTP request from the PC through WIFI or USB and performs the specified operation

API introduction

github:https://github.com/openatx/uiautomator2

Chinese translation: https://blog.csdn.net/qq_38071435/article/details/80003212

1. Installation:

pip install --pre uiautomator2
#Or you can go directly from github Upper source code installation
git clone https://github.com/openatx/uiautomator2
pip install -e uiautomator2
pip install pillow  #Screenshot Captor 

2. To initialize the phone, you need an environment SDK

python -m uiautomator2 init
 This can only be used after initialization
pip install --pre --upgrade weditor#Install automated UI positioning
python -m weditor#start-up

The device side programs required for automatic installation of this library: uiautomator server, ATX agent, openstf / minicap, openstf / minitouch , can be downloaded and installed separately

Configuration completed

3. Open mobile port: adb forward tcp: 7912 tcp: 7912

Connect mobile phone: device_ip = 127.0.0.1 

I don't know why. I forgot. It seems to be used when installing ATX agent by myself

4. Common commands:

1,install apk: python -m uiautomator2 install $ device_ip https://example.org/some.apk
2,Clear cache: python -m uiautomator2
3,Stop all applications: python -m uiautomator2 app-stop-all $ device_ip
4,Screenshot: python -m uiautomator2 screenshot $ device_ip screenshot.jpg
5,Check daemon threads: d.healthcheck()
6,Open debug: d.debug = true
7,Get connection information: d.info
8,shell Command: d.adb_shell('pwd')
9,resolving power: d.window_size()
10,View current application information: d.current_app()
11,View serial number: d.serial

5. Quick start:

import uiautomator2 as u2
#adopt WIFI
d = u2.connect('10 .0.0.1')#u2.connect_wifi('10 .0.0.1')of#alias 
#adopt usb Get device
d = u2.connect('123456f')#u2.connect_usb('123456f')of#alias

6. System operation:

1,Installation, only indicate url: d.app_install('http://some-domain.com/some.apk')
2,Start: d.app_start("com.example.hello_world")#Start with package name
3,Stop application: d.app_stop("com.example.hello_world")
            d.app_clear('com.example.hello_world')
        Stop all apps: d.app_stop_all()
5,Push a file to your phone: d.push("foo.txt "Yes"“/ SD card/")
6,Push and rename: d.push("foo.txt "Yes"“/sdcard/bar.txt")
7,Push and change file mode: d.push("foo.sh","/ data / local / tmp /",mode = 0o755)
8,To pull a file from a device: d.pull("/ sdcard / tmp.txt","tmp.txt")#If the file is not found on the device, FileNotFoundError Will appear 
    d.pull("/ sdcard / some-file-not-exist.txt","tmp.txt")

7. Application connection session:

1,Start application: sess = d.session("com.netease.cloudmusic"
2,Session connection running program: sess = d.session("com.netease.cloudmusic"
3,Detect whether it should crash: SESS(written words= "Music ") Click ()
    Check whether the session is normal: sess.running()

8. Mobile phone hardware operation

1,d.screen_on()#Open screen d.screen_off()#Close screen
2,Get current screen status: d.info.get('screenOn')#android 4.4
3,Press soft/Hardware
d,press("home")#Press home Key, with key name 
d,press("back")#Press the back key with the main name 
d,press(0x07,0x02)#Press key code 0×07("0")And META ALT(0x02)
d,unlock()Unlock screen

Practice code

Design patterns used

PageObject design mode:

1. Encapsulate all "element (including control) attributes" and "element operations" of a page in one class~~~~

  1. Purpose: the test code is separated from the tested page object code. If any page element is changed in the later stage, only the code of the corresponding page object (i.e. the corresponding Class file) needs to be modified without modifying the test code

  2. Try to use xpath to find page elements instead of name,Link and other methods; xpath is based on the area where the page element is located. Generally, it will not change, and the test code is basically undisturbed

  3. The purpose of separating the page element attribute information from the code, that is, from the tested object code, is to further reduce the subsequent maintenance cost caused by page changes

def install(d):#Installation element selection
    lists = ["com.kingroot.kinguser:id/button_right", "vivo:id/vivo_adb_install_ok_button", "android:id/button1",
             "com.android.packageinstaller:id/decide_to_continue"]
    while True:
        for i in lists:
            anzhuang(i,d)
def anzhuang(string,d):#Element trigger
    try:
        s = d(resourceId=string)
        if s.exists:
            s.click()
    except:
        pass

Get the list of currently available devices from ATX server

1. On the device management page of ATX server, the list of currently available devices is listed. So I tried to get the device list from the network request on this page. Sure enough, I got something:

From the list request, get the list of currently available devices through the present attribute, and then you can call them one by one for testing.

def getDevices():#Get online ip
    url=r'http://192.168.1.110:8000/list'.encode()
    r=requests.get(url)
    deviceList=[]
    content=json.loads(r.text)
    for device in content:
        if device['present']:
            deviceList.append(device['ip'])
            print(device['ip'])

python starts and shuts down services

Open service

obj1=subprocess.Popen(['rethinkdb','--http-port','8090'],cwd=r'C:\rethinkdb-2.3.6',shell=True, stdout=subprocess.PIPE)
obj2=subprocess.Popen(['atx-server','--port','8000'],cwd=r'C:\Users\Extranet\go\src\github.com\openatx\atx-server',shell=True,stdout=subprocess.PIPE)
obj3=subprocess.Popen(['python','-m','http.server','8888'],cwd=r'C:\Users\Extranet\Desktop',shell=True,stdout=subprocess.PIPE)

Shut down service

subprocess.Popen('TASKKILL /F /IM rethinkdb.exe', shell=True, stdout=subprocess.PIPE)
subprocess.Popen('TASKKILL /F /IM atx-server.exe', shell=True, stdout=subprocess.PIPE)
subprocess.Popen('TASKKILL /F /IM python.exe',shell=True, stdout=subprocess.PIPE)

Framework API usage

iplist=getDevices()
for ip in iplist:#
    d = u2.connect('%s'%ip.strip())
    d.unlock()
    d.healthcheck()
    d.app_uninstall_all()
    az=threading.Thread(target=install,args=(d,))
    az.start()
    package=d.app_install('http://192.168.1.110:8888/T11.apk')
    #d.disable_popups()
    print(package)
    d.app_start(package)

Test interview dictionary 

Keywords: software testing

Added by Angry Lettuce on Fri, 21 Jan 2022 07:44:28 +0200