pytest的基础(命名、运行、标签和断言)

1. pytest命名规则

模块的命名要以test”开头或者“_test.py”结尾

类的命名要以Test”开头

测试用例的命名要以test”开头

2. 使用pytest执行测试用例

cmd命令行参数运行:

1)最多允许失败的用例

pytest -x  # 遇到第一个失败时,退出执行
pytest --maxfail=2  # 遇到第二个失败时,退出执行

2)运行指定的测试用例

指定模块

pytest test_mod.py # test_mod.py为模块名

指定文件

pytest test_01/ # test_01/ 为路径

3)使用自定义标签运行指定用例,如何自定义标签请看第1.3节

pytest -m demo

pytest -m demo # demo为标签名

4)输出一个简单的总结报告

pytest -rA

-r是输出总结报告,后面跟着的参数是筛选,可以叠加筛选条件

f:失败的

E:出错的

s:跳过执行的

x:跳过执行,并标记为xfailed

X:跳过执行,并标记为xpassed

p:测试通过的

P:测试通过,并且有输出信息的;即用例中有print

a:除了测试通过的,其他所有的;即除了pP

A:所有的

 

5)在代码中调用pytest

使用pytest.main()函数,参数必须放在元组或列表中,参数使用和命令行一致

if __name__ == '__main__':
    pytest.main(["-k","make and not two"])

6)输出报告

纯文本格式报告

pytest --resultlog=path

junitxml格式报告

pytest --junitxml=path

html报告(需先安装插件pip install pytest-html

pytest --html=path

 

 

3. 自定义标签

首先要在main函数(执行pytest命令的入口函数,和测试用例文件夹同级)的同级目录下新增一个叫pytest.ini的文件(文件名不能改),然后定义标签

[pytest] # 区域名,固定不能动
markers = # mark标记,固定不能动
    skome: describe must be English # 标签名,冒号后面为标签描述,必须为英文
    test1:describe must be English
    demo:a test for pytest

定义好后在测试类或测试用例前打上标记

@pytest.mark.demo # demo为标签名

可打多个标签

 

4. 断言

  1. 使用assert断言,后面可跟表达式,具有普适性,最常用

assert 200==100

  1. 使用pytest.raise()断言,针对某类具体异常进行断言

def test_match(self):
    with pytest.raises(ValueError):
        myfunc()

如果myfunc()这个函数体(被测试的内容)没有抛出ValueError异常,则断言失败

猜你喜欢

转载自www.cnblogs.com/handsomesuancaiyu/p/12115343.html