入门

安装 pytest

pytest 需要:Python 3.8+ 或 PyPy3。

  1. 在命令行中运行以下命令

pip install -U pytest
  1. 检查您是否安装了正确的版本

$ pytest --version
pytest 8.4.0

创建您的第一个测试

创建一个名为 test_sample.py 的新文件,包含一个函数和一个测试

# content of test_sample.py
def func(x):
    return x + 1


def test_answer():
    assert func(3) == 5

测试

$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
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:6: AssertionError
========================= short test summary info ==========================
FAILED test_sample.py::test_answer - assert 4 == 5
============================ 1 failed in 0.12s =============================

[100%] 指的是运行所有测试用例的总体进度。完成后,pytest 会显示失败报告,因为 func(3) 不返回 5

注意

您可以使用 assert 语句来验证测试预期。pytest 的高级断言内省将智能地报告断言表达式的中间值,这样您就可以避免许多 JUnit 遗留方法的名称。

运行多个测试

pytest 将运行当前目录及其子目录中所有形式为 test_*.py*_test.py 的文件。更普遍地,它遵循标准测试发现规则

断言抛出特定异常

使用 raises 辅助函数断言某些代码会抛出异常

# content of test_sysexit.py
import pytest


def f():
    raise SystemExit(1)


def test_mytest():
    with pytest.raises(SystemExit):
        f()

以“安静”报告模式执行测试函数

$ pytest -q test_sysexit.py
.                                                                    [100%]
1 passed in 0.12s

注意

-q/--quiet 标志使本例和后续示例的输出保持简洁。

有关指定预期异常的更多详细信息,请参见关于预期异常的断言

将多个测试分组到一个类中

一旦您开发了多个测试,您可能希望将它们分组到一个类中。pytest 使得创建一个包含多个测试的类变得容易

# content of 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 遵循其Python 测试发现约定发现所有测试,因此它会找到所有 test_ 前缀的函数。无需继承任何东西,但请确保您的类以 Test 为前缀,否则该类将被跳过。我们可以简单地通过传递文件名来运行模块

$ pytest -q test_class.py
.F                                                                   [100%]
================================= FAILURES =================================
____________________________ TestClass.test_two ____________________________

self = <test_class.TestClass object at 0xdeadbeef0001>

    def test_two(self):
        x = "hello"
>       assert hasattr(x, "check")
E       AssertionError: assert False
E        +  where False = hasattr('hello', 'check')

test_class.py:8: AssertionError
========================= short test summary info ==========================
FAILED test_class.py::TestClass::test_two - AssertionError: assert False
1 failed, 1 passed in 0.12s

第一个测试通过,第二个测试失败。您可以轻松地在断言中看到中间值,以帮助您理解失败的原因。

将测试分组到类中可能具有以下优点

  • 测试组织

  • 仅在该特定类中共享 fixture

  • 在类级别应用标记并使其隐式应用于所有测试

将测试分组到类中时需要注意的一点是,每个测试都有一个唯一的类实例。让每个测试共享同一个类实例将非常不利于测试隔离,并会促使不良测试实践。这在下面概述

# content of test_class_demo.py
class TestClassDemoInstance:
    value = 0

    def test_one(self):
        self.value = 1
        assert self.value == 1

    def test_two(self):
        assert self.value == 1
$ pytest -k TestClassDemoInstance -q
.F                                                                   [100%]
================================= FAILURES =================================
______________________ TestClassDemoInstance.test_two ______________________

self = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef0002>

    def test_two(self):
>       assert self.value == 1
E       assert 0 == 1
E        +  where 0 = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef0002>.value

test_class_demo.py:9: AssertionError
========================= short test summary info ==========================
FAILED test_class_demo.py::TestClassDemoInstance::test_two - assert 0 == 1
1 failed, 1 passed in 0.12s

请注意,在类级别添加的属性是类属性,因此它们将在测试之间共享。

为功能测试请求一个唯一的临时目录

pytest 提供了内置 fixture/函数参数来请求任意资源,例如唯一的临时目录

# content of test_tmp_path.py
def test_needsfiles(tmp_path):
    print(tmp_path)
    assert 0

在测试函数签名中列出名称 tmp_pathpytest 将查找并调用一个 fixture 工厂来在执行测试函数调用之前创建资源。在测试运行之前,pytest 会创建一个每个测试调用唯一的临时目录

$ pytest -q test_tmp_path.py
F                                                                    [100%]
================================= FAILURES =================================
_____________________________ test_needsfiles ______________________________

tmp_path = PosixPath('PYTEST_TMPDIR/test_needsfiles0')

    def test_needsfiles(tmp_path):
        print(tmp_path)
>       assert 0
E       assert 0

test_tmp_path.py:3: AssertionError
--------------------------- Captured stdout call ---------------------------
PYTEST_TMPDIR/test_needsfiles0
========================= short test summary info ==========================
FAILED test_tmp_path.py::test_needsfiles - assert 0
1 failed in 0.12s

有关临时目录处理的更多信息,请参见临时目录和文件

使用命令查找存在哪些内置 pytest fixture

pytest --fixtures   # shows builtin and custom fixtures

请注意,除非添加 -v 选项,否则此命令会省略带有前导 _ 的 fixture。

继续阅读

查看其他 pytest 资源,帮助您根据独特的工作流程自定义测试