python+uiautomator2+pytest automated testing framework (3)

python+uiautomator2+pytest automated testing framework (3)

Purpose Solve the operation of multiple devices, parallel multiple devices and multiple use cases at the same time

1. Modify conftest.py

The initialization device has been modified, judged according to the connected devices, and passed to the corresponding process

#初始化设备
@pytest.fixture(scope="session", autouse=True)
def driver(tmp_path_factory, worker_id):
    devices_list = drivers.android.devices()
    if not devices_list:
        raise

    global device

    if worker_id == "master":
        log.info('单台测试')
        device = drivers.android.device_android(devices_list[0])
        return device

    root_tmp_dir = tmp_path_factory.getbasetemp().parent

    fn = root_tmp_dir / "devices.json"
    log.info(type(fn))
    log.info(fn)
    log.info(fn.is_file())
    log.info('fn.is_file()')
    with FileLock(str(fn) + ".lock"):
        log.info(fn.is_file())
        if fn.is_file():
            devices_ls = fn.read_text()
            if not devices_ls:
                return Exception('No Device')
            device_serial, devices_l = _devices_list_pop(devices_ls)
            device = drivers.android.device_android(device_serial)
            fn.write_text(
                str(devices_l)
            )
        else:
            device = drivers.android.device_android(devices_list[0])
            devices_list.pop(0)
            fn.write_text(str(devices_list))
    log.info(device)
    return device


def _devices_list_pop(dl):
    d = dl[1:-1].replace("'", '').strip().split(', ')
    ds = d[0]
    d.pop(0)
    return ds, d

2. Rewrite the lib/func.py file

Check whether the device attribute exists, and lock the process

import _ctypes
import os
import re
import threading

from filelock import FileLock
from lib.loggers import log
import time


def think_time(func):
    def thinktime(*args, **kwargs):
        time.sleep(1)
        return func(*args, **kwargs)
        time.sleep(1)

    return thinktime

#进程加锁
class GetDevice(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        time.sleep(0.5)

    @classmethod
    #检查是否存在device属性
    def instance(cls, *args, **kwargs):
        if not hasattr(GetDevice, "_device"):
            GetDevice._device = str(*args)

        return _ctypes.PyObj_FromPtr(int(GetDevice._device))

    def _device_lock(self):
        fn = "./drivers/devices.json"
        lock = FileLock(fn + ".lock")
        with lock:
            if os.path.isfile(fn):
                open(fn, ).read_text()
            else:
                driver = [1, 2, 3]
                driver_s = str(id(driver[0]))
                open(fn, 'a').write(driver_s)

3. Change drivers/android.py

Modify the initialization, and obtain multi-device, check for exceptions


def device_android(d_id = 1) -> u2.Device:
    log.info(d_id)
    if isinstance(d_id, int):
        return u2.connect()
    else:
        return u2.connect(d_id)


def devices():
    a = os.popen('adb devices').readlines()
    if len(a) >= 2:
        dl = [i.split('\t')[0] for i in a if '\t' in i]
    else:
        dl = 'adb 异常,未获取到设备'
    return dl

4、pytest. ini

Add multi-process and multi-use case group execution statement

addopts = -v -s -n 3 --dist loadfile --html=./report/report.html --self-contained-html

Guess you like

Origin blog.csdn.net/qq_34004131/article/details/118530019