pytest
是一个能够简化成测试系统构建、方便测试规模扩展的框架,它让测试变得更具表现力和可读性–模版代码不再是必需的。只需要几分钟的时间,就可以对你的应用开始一个简单的单元测试或者复杂的功能测试。
1. 安装pytest
pip install -U pytest
检查版本
> pytest --version
pytest 7.0.1
2. 创建第一个测试
# test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
然后在该py文件的目录下执行pytest
================================================= test session starts =================================================
platform win32 -- Python 3.9.9, pytest-7.0.1, pluggy-1.0.0
rootdir: D:\Code\Pytest
collected 1 item
test_sample.py F [100%]
====================================================== FAILURES =======================================================
_____________________________________________________ test_answer _____________________________________________________
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:5: AssertionError
=============================================== short test summary info ===============================================
FAILED test_sample.py::test_answer - assert 4 == 5
================================================== 1 failed in 0.12s ==================================================
PS D:\Code\Pytest>
[100%]
指的是运行所有测试用例的总体进度。完成后,pytest会显示一个报告,如上述测试,是一个失败报告,因为func(3)
不返回5。
3. 运行多个测试
pytest _*.py
或者pytest *_
可以使pytest运行目录下的多个符合条件的文件。
4. 以安静报告模式执行测试用例
pytest -q test_sysexit.py
注:-q与--quiet
的效果一样。
5. 将一个类的多个测试分组
一旦开发了多个测试,你可能需要将它们分组到一个类中。pytest使创建包含多个测试的类变得容易:
# chapter-1\test_class.py
class TestClass:
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = "hello"
assert hasattr(x,"check")
执行测试:
> pytest -q .\chapter-1\test_class.py
.F [100%]
=============================== FAILURES ===============================
__________________________ TestClass.test_two __________________________
self = <test_class.TestClass object at 0x000001BBDAB0A9D0>
def test_two(self):
x = "hello"
> assert hasattr(x,"check")
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
chapter-1\test_class.py:11: AssertionError
======================= short test summary info ========================
FAILED chapter-1\test_class.py::TestClass::test_two - AssertionError: ...
1 failed, 1 passed in 0.07s
从输出的报告中可以看到:
test_one
测试通过,用.
表示,test_two
测试失败,用F
表示;- 清楚的看到,
test_two
失败的原因是:False = hasattr('hello', 'check')
注意:
测试类要符合特定规则,
pytest
才能发现它:
- 测试类的命令要符合
Test*
规则;- 测试类中不能有
__init__()
方法;