金天牛

导航

pytest学习笔记-第一篇

一、单元测试框架

主流:

Pythonunittest pytest(主流)

Javatestng(主流)、junit

pytest做什么:发现测试用例、执行测试用例、判断测试结果、生成测试报告

二、简介

1、pytest可以结合seleniumUI)、requests(接口)、appiumAPP)完成自动化

2、可以生成自定义的allure报告,可以和jenkins持续集成

3、pytest常用插件:

 Pytest-html 生成html报告的插件

Pytest-xdist  多线程运行插件

Pytest-ordering   改变用例执行顺序

Pytest-rerunfailres   失败用例重跑

Allure-pytest  生成美观自定义的allure报告

4、通过在项目的根目录下新建 requirements.txt 报错插件和对应的版本信息

例如:

allure-pytest==2.9.45
allure-python-commons==2.9.45

terminal通过以下命令安装 pip install -r requirements.txt  

 Venv表示虚拟环境

 Alt+Enter自动导包

三、Pytest用例规则和基础应用

1、模块名必须以test_开头或者_test结尾

2、测试类必须以Test开头,且不带init方法

3、测试用例必须以test_开头

执行方式:

1、命令行方式执行:直接命令:pytest     会直接执行所有用例

 执行参数:-v 输出详细信息   -s输出调试信息(例如print

-n表示多线程运行(前提已经安装Pytest-xdist),例如 -n=2

--reruns num  失败重跑(前提已安装Pytest-rerunfailres

raise Exception()抛出异常

 try except  解决异常

 -x 出现一个用例失败即停止测试。如:pytest -vs -x

 --maxfail  出现几个失败才终止。如:pytest -vs --maxfail=2

 --html

 运行测试用例名称中包含某个字符串的测试用例

 -k “login  or   user” 运行用例名称中包含”login ”或”user”的用例

2、通过主函数main方式执行

 pytest.main([“-vs”])

3、通过全局配置文件pytest.ini文件执行

注意:

①一般放在项目的根目录下,名称必须是pytest.ini

②编码格式为ANSI,

pytest.ini可以改变默认的测试用例规则

④不管是命令行运行也好还是说主函数运行也好,都会加载这个主配置文件

 pytest.ini 文件举例

[pytest]        #文件头要有的

addopts = -vs        # 默认执行参数

testpaths = ./test_case        #制定测试用例的位置

python_files = ms_*.py         # python文件的规则,此处表示以ms_开头的文件

python_classes = Test*         #改变测试类的,如果=WW 表示执行以WW开头的类

Python_functions= test_*      #改变函数的开头

#测试用例分组执行

markers=

smoke:   smoke case

product_manager:    prduct modules test case

user_manager:       user manager modules case

 

使用markers时,测试用例函数上面需要加上装饰器:

@pytest.mark.smoke       #表示smoke的用例

@pytest.mark.user_manager      #表示user_manager模块的用例

运行时pytest -m “smoke” 表示只执行带有smoke的冒烟用例

posted on 2022-04-16 22:00  金天牛  阅读(61)  评论(0编辑  收藏  举报