前言
官网介绍,特点如下:
安装:
pip install -U pytest
查看版本
pytest --version
用例的识别与运行
用例编写规范
创建文件名为 test_add.py 文件,代码如下:
1 import pytest 2 3 def add(x,y): 4 return x + y 5 6 @pytest.mark.add 7 def test_add(): 8 assert add(1,2) == 3 9 assert add(2,3) == 5 10 assert add(10,2) == 12 11 12 class TestDemo: 13 14 def test_demo(self): 15 x = "hello world" 16 print(f"{x} python") 17 assert ‘h‘ in x 18 19 def test_demo2(self): 20 x = ‘hello‘ 21 assert hasattr(x,"check")
可以直接使用pytest命令运行,pytest会找当前目录以及递归查找子目录下的所有的 test_*.py 或 *_test.py 的文件,把其当做测试文件。在这些文件里,pytest 会收集符合编写规范的函数、类以及方法,当作测试用例并执行。
执行如下:
$ pytest test_add.py .... test_add.py ..F [100%] .... self = <test_add.TestDemo object at 0x7f885351b280> def test_demo2(self): x = ‘hello‘ > assert hasattr(x,"check") E AssertionError: assert False E + where False = hasattr(‘hello‘, ‘check‘) test_add.py:28: AssertionError ======================================================= 1 failed, 2 passed in 0.05s ========================================================
结果分析:
执行结果中, F 代表用例未通过(断言错误), . 代表用例通过。如果报错会有详细的错误信息, pytest 也支持运行unittest 模式的用例。
写在最后的话:小白同学愿意和大家一起成长~
原文:https://www.cnblogs.com/murcy/p/14928855.html