原文档链接:Get Started - pytest documentation
1.pytest安装与基本使用
要求:Python 3.8+
1.安装pip install pytest
2.创建一个python文件命名test_sample.py或者sample_test.py(test_开头的文件或者_test结尾的文件pytest默认都会执行)
# content of test_sample.py def func(x): return x + 1 def test_answer(): assert func(3) == 5
执行结果:
============================= test session starts =============================
collecting ... collected 1 item
test_sample.py::test_answer FAILED [100%]
test_sample.py:5 (test_answer)
4 != 5
预期:5
实际:4
<点击以查看差异>
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:7: AssertionError
============================== 1 failed in 0.15s ==============================
3.方法以test_开头或者_test结尾的也能自动执行(但是如果是项目执行的话会跳过不是test_开头或者_test结尾的文件,这个要注意,同样,在类中也会跳过不是test_开头和_test结尾的方法)
def test_one(): x = "this" assert "h" in x def test_two(): x = "hello" assert hasattr(x, "check")
执行结果:
============================= test session starts =============================
collecting ... collected 2 items
ptest.py::test_one PASSED [ 50%]
ptest.py::test_two FAILED [100%]
ptest.py:16 (test_two)
def test_two():
x = "hello"
> assert hasattr(x, "check")
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
ptest.py:19: AssertionError
========================= 1 failed, 1 passed in 0.16s =========================