简介
pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高。并且pytest兼容unittest的用例,支持的插件也更多
安装
pip install pytest
简单上手,创建个test_sample.py文件
deffunc(x):return x + 1
deftest_answer():assert func(3) == 5
运行测试,直接在当前文件夹运行pytest
collected 1item
test_sample.py F [100%]================================= FAILURES =================================
_______________________________ test_answer ________________________________
deftest_answer():> assert func(3) == 5Eassert 4 == 5E+ where 4 = func(3)
test_sample.py:6: AssertionError============================ 1 failed in 0.12s =============================
pytest运行规则:查找当前目录及其子目录下以test_*.py或*_test.py文件,找到文件后,在文件中找到以test开头函数并执行。
以类来封装用例
#content of test_class.py
classTestClass:deftest_one(self):
x= "this"
assert "h" inxdeftest_two(self):
x= "hello"
assert hasattr(x, "check")
运行可以使用pytest [file_path]指定文件,-q是静默模式,不会打印用例输出
$ pytest -q test_class.py
.F [100%]================================= FAILURES =================================
____________________________ TestClass.test_two ____________________________self=
deftest_two(self):
x= "hello"
> assert hasattr(x, "check")
E AssertionErro