python unit test pytest

pytest

创建测试文件:在项目目录下创建一个名为 test_*.py 的测试文件,其中 * 可以是任何字符串。

编写测试函数:在测试文件中编写测试函数,函数名称必须以 test_ 开头。

运行测试:在项目目录下运行 pytest 命令来运行测试。pytest 将自动发现并执行所有以 test_ 开头的测试函数,并输出测试结果。
例如,在项目目录下创建一个名为 test_math.py 的测试文件,其中包含以下测试函数:

def test_addition():
    assert 1 + 2 == 3

def test_subtraction():
    assert 4 - 2 == 2

pytest:运行所有测试用例。

pytest <test_file>:运行指定测试文件中的所有测试用例。

pytest -k :运行包含表达式 的测试用例,例如 pytest -k “add” 将运行所有名称中包含 add 的测试用例。

pytest -m < mark >:运行带有标记 < mark > 的测试用例,例如 pytest -m smoke 将只运行标记为 smoke 的测试用例。

pytest --fixtures:列出所有可用的 fixture 函数。

pytest --capture=:指定输出方式,例如 pytest --capture=sys 将使用标准输出,pytest --capture=tee-sys 则同时将输出保存到文件和标准输出。

pytest --verbose 或 -v:显示详细输出信息,包括每个测试用例的执行结果、fixture 的调用情况等。

pytest --failed-first:首先运行上次失败的测试用例,然后再运行全部测试用例。

pytest --maxfail=:指定最大失败数,例如 pytest --maxfail=2 将在第二个失败后停止测试。

pytest --pdb:在测试失败时进入调试模式,允许用户查看和调试代码。

pytest --cov=

:生成代码覆盖率报告,例如 pytest --cov=mymodule 将生成 mymodule 模块的覆盖率报告。

这些命令只是 pytest 命令中的一部分,它还有许多其他功能和选项。你可以在终端中输入 pytest --help 来查看所有可用的命令和选项。
注意:pytest 将默认捕获所有的输出,通过 “-s” 参数来开启输出

猜你喜欢

转载自blog.csdn.net/greatcoder/article/details/129846142