pytest钩子hook使用2

pytest是一种用于编写单元测试的Python库。它允许程序员编写测试用例来验证代码的正确性,并提供了一系列的勾子(hooks)来在测试的不同阶段执行一些额外的操作。

使用pytest的勾子,可以在测试运行过程中插入自定义代码。下面是一些常见的pytest勾子的使用方法:

  1. pytest_configure:在pytest运行时首次调用。可以在这里注册自定义的fixture、导入测试数据等。

```python

def pytest_configure(config):

注册自定义的fixture

config.addinivalue_line("pytest_plugins", "my_fixture")

```

  1. pytest_collection_modifyitems:在测试收集阶段调用,可以用来修改测试集合。

```python

def pytest_collection_modifyitems(config, items):

for item in items:

修改测试用例的名称

item.name = item.name.replace("test_", "check_")

```

  1. pytest_runtest_setup:在执行每个测试用例的设置阶段调用。

```python

def pytest_runtest_setup(item):

在每个测试用例执行之前执行的操作

pass

```

  1. pytest_runtest_teardown:在执行每个测试用例的清理阶段调用。

```python

def pytest_runtest_teardown(item, nextitem):

在每个测试用例执行之后执行的操作

pass

```

  1. pytest_runtest_logstart:在每个测试用例运行前的日志开始时调用。

```python

def pytest_runtest_logstart(nodeid, location):

在每个测试用例运行前记录日志

pass

```

以上只是一些常见的pytest勾子的使用方法,还有其他更多的勾子可以用来满足不同的需求。通过使用这些勾子,可以更好地控制和定制pytest的行为。

相关推荐
念越1 小时前
接口自动化测试从入门到实战:接口用例设计、Requests、Pytest、YAML、JSON Schema 与 Allure 报告
python·测试工具·自动化·json·pytest
霍格沃兹测试学院-小舟畅学4 天前
AI+Swagger:一键生成500条pytest接口用例
人工智能·pytest
把头塞进显示器13 天前
电商平台-测试报告
python·selenium·pytest
昔我往昔18 天前
pytest日志问题排查记录
python·pytest
黄昏恋慕黎明21 天前
博客论坛技术迭代
python·pytest
2601_9620782321 天前
Python接口自动化流程(pytest)
python·pytest·接口自动化·测试框架·断言
杨女士YRJ21 天前
python+pytest+01
python·pytest
2601_9620782322 天前
Python接口自动化框架:pytest
python·pytest·接口自动化·测试框架·restfulapi
2601_9620781922 天前
Appium+Python+pytest自动化测试框架详解
自动化测试·python·appium·pytest·移动应用
2601_9622845024 天前
安卓APP UI自动化测试:Python + UiAutomator2 + pytest + pytest-html
python·pytest·uiautomator2·ui自动化测试·安卓app