本文共 1053 字,大约阅读时间需要 3 分钟。
在pytest中,标记(@pytest.mark.*)是一种强大的测试控制工具,可以帮助开发者灵活管理测试用例的执行流程。通过合理运用标记,可以实现对特定测试函数的条件执行,例如只测试完成标记的函数、只测试未完成标记的函数,或者直接跳过不需要执行的测试。
@pytest.mark.done
默认情况下,pytest会自动测试所有函数。如果你只想测试带有@pytest.mark.done标记的函数,可以通过以下命令实现:pytest -m done test.py
这将只执行带有@pytest.mark.done标记的测试函数。
@pytest.mark.unfinished
如果你希望只测试未标记的函数,可以使用:pytest -m unfinished test.py
这将跳过所有带有@pytest.mark.unfinished标记的测试函数。
@pytest.mark.skip
如果某些测试函数暂时不适用或不需要执行,可以直接使用@pytest.mark.skip标记跳过它们。例如:import pytest@pytest.mark.skipdef test_api(): pass
或者通过命令跳过特定标记的测试:
pytest -m "not (skip)" test.py
如果需要根据特定条件跳过测试,可以使用@pytest.mark.skipif标记。例如,跳过运行环境不符合要求的测试:
import pytest@pytest.mark.skipif(conn.__version__ < '0.2.0', reason='不支持until v0.2.0')def test_api(): pass
代码示例
import pytest@pytest.mark.finisheddef test1_fun(): assert 1 == 1@pytest.mark.unfinisheddef test2_fun(): assert 1 == 1
只测试完成标记的函数:
pytest -m "done" test.py
只测试未完成标记的函数:
pytest -m "unfinished" test.py
跳过特定标记的函数:
pytest -m "not (skip)" test.py
通过合理运用pytest的标记功能,可以更高效地管理测试用例,提升测试效率和代码可维护性。
转载地址:http://qzrfk.baihongyu.com/