python+pytest+uiautomator2+allure移动端测试(二)

78 阅读2分钟

上一篇文章已经介绍了u2的基本操作,那么这篇就记录合入pytest框架。

由于python都是加载的第三方库,所以咱们先把第三方库版本固定一下

项目根目录新建requirements.text

pytest==7.2.0
pytest-html==3.2.0
pytest-xdist==3.1.0
pytest-ordering==0.6
pytest-rerunfailures==10.3
allure-pytest==2.12.0
pyyaml==6.0
uiautomator2==2.16.19

pip install -r requirements.txt 执行

相当于pip install 单独安装,只不过咱们可以直接运行文本,做到环境统一哈

pip install pytest -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn

pytest有三种使用方式

1、在测试类中使用main方法指定test方法或test类执行

if __name__ == '__main__':
    pytest.main()

咱们的测试目的是整个项目运行,不是单个方法或单个测试类运行,这个方法排除。

2、在pycharm命令窗口使用pytest指令运行

pytest -vs ./testcase/test_PyCall.py

个人感觉其实跟mian执行一样,运动的命令不一样而已,这个方法排除。

3、通过main方法读取pytest.ini文件运行(就是你了)

在项目根目录新建pytest.ini文件(文件名不要乱改)

格式为GBK,可以在pycharm打开该文件(在右下角第三个参数可以直接修改编码格式)

也可以选择pytest.ini》File》File Encoding》确定修改格式

[pytest]

addopts = -p no:warnings -vs --alluredir=./temps --clean-alluredir
# 指定运行文件路径
testpaths = ./testcase

# 自定义pytest文件名规则
python_files = test*.py
# 自定义pytest类名规则
python_classed = Test*
# 自定义pytest方法名规则
python_functions = test*
#标记分组执行
markers =
    smoke:冒烟
    pressure:压力

新建run.py文件,也位于项目根目录

(这个allure是加载报表库,暂时可忽略,可以先为空)

import os

import pytest

if __name__ == '__main__':
    pytest.main()
    os.system("allure generate ./temps -o ./reports --clean")

main方法里面是不带参数的,因为将参数已经写在pytest.ini文件中

addopts = -p no:warnings -vs --alluredir=./temps --clean-alluredir

检查是否配置成功

新建一个testcase包 testcase包新建个test类,规则如pytest.ini中所自定义规定

# 自定义pytest文件名规则
python_files = test*.py
# 自定义pytest类名规则
python_classed = Test*
# 自定义pytest方法名规则
python_functions = test*

再右键执行执行run.py,运行成功即可。

运行时提示PytestConfigWarning: Unknown config option: python_classed self._warn_or_fail_if_strict(f"Unknown config option: {key}\n")

忽略运行时提示:warnings

在pytest.ini 文件加上这个参数 [pytest] addopts = -p no:warnings

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 1天