Skip to content

pytest 快速入门

使用 pip 进行安装 Pytest:

shell
pip install pytest

第一个测试函数

Pytest 使用 Python 的 assert 进行条件判断,最简单的测试函数如:

python
# filename: test01.py
def test_passing():
    assert (1, 2, 3) == (1, 2, 3)

使用命令 pytest 运行测试函数:

shell
$ pytest test01.py
=========================== test session starts ============================
platform win32 -- Python 3.12.9, pytest-8.4.0, pluggy-1.6.0
rootdir: Z:\zhengxin\py_test
plugins: anyio-4.9.0, langsmith-0.3.34
collected 1 item

test01.py .                                                           [100%]

============================ 1 passed in 0.03s =============================

pytest 使用 . 标识测试成功(PASSED)。

测试失败

下面是一个失败的测试函数:

python
# filename: test02.py
def test_failing():
    assert (1, 2, 3) == (3, 2, 1)

运行结果为:

shell
$ pytest test02.py
=========================== test session starts ============================
platform win32 -- Python 3.12.9, pytest-8.4.0, pluggy-1.6.0
rootdir: Z:\zhengxin\py_test
plugins: anyio-4.9.0, langsmith-0.3.34
collected 1 item

test02.py F                                                           [100%]

================================= FAILURES =================================
_______________________________ test_failing _______________________________

    def test_failing():
>       assert (1, 2, 3) == (3, 2, 1)
E       assert (1, 2, 3) == (3, 2, 1)
E
E         At index 0 diff: 1 != 3
E         Use -v to get more diff

test02.py:3: AssertionError
========================= short test summary info ==========================
FAILED test02.py::test_failing - assert (1, 2, 3) == (3, 2, 1)
============================ 1 failed in 0.14s =============================

pytest 使用 F 标识测试失败(FAILED)。

pytest 对失败的测试给出了非常人性化的提示。


可以使用 -v 选项,显示测试的详细信息。

使用 pytest -h 查看 pytest 的所有选项。