pytest how to invoke pytest

选择运行哪个测试

命令行形式

  • 运行测试在module
pytest test_mod.py
  • 运行测试在一个目录
pytest testing/
  • 运行测试通过关键字表达
pytest -k "MyClass and not method"

这将运行包含与给定字符串表达式(不区分大小写)匹配的名称的测试,这些名称可以包括使用文件名、类名和函数名作为变量的 Python 运算符。上面的示例将运行 TestMyClass.test _ something,但不运行 TestMyClass.test _ method _ simple。

  • 运行测试通过节点模式
pytest test_mod.py::TestClass::test_method
  • 运行测试 marker 表达式
pytest -m slow

这个命令会运行 被 @pytest.mark.slow 装饰器装饰的用例

  • 从包中运行测试
pytest --pyargs pkg.testing

这将导入 pkg.test 并使用其文件系统位置来查找和运行测试。

help

pytest --version   # shows where pytest was imported from
pytest --fixtures  # show available builtin function arguments
pytest -h | --help # show help on command line and config file options

分析测试执行时间

pytest --durations=10 --durations-min=1.0

获得1.0 s 长度内最慢的10个测试持续时间列表 默认情况下,pytest 不会显示太小的测试持续时间(< 0.005 s) ,除非在命令行上传递-vv

管理插件的加载

提前加载插件 通过-p 命令提前加载插件

pytest -p mypluginmodule

不加载插件

pytest -p no:mypluginmodule

其他调用pytest的方式

  • python解释器
python -m pytest [...]
  • 通过main函数
retcode = pytest.main()

添加插件

import sys

import pytest

class MyPlugin:
    def pytest_sessionfinish(self):
        print("*** test run reporting finishing")

if __name__ == "__main__":
    sys.exit(pytest.main(["-qq"], plugins=[MyPlugin()]))
posted @ 2025-02-02 22:39  且任荣枯  阅读(2)  评论(0编辑  收藏  举报