python - 如何在 pytest 中为特定方法或函数定义设置和拆卸函数?

标签 python unit-testing pytest

Pytest 支持 classical xunit style setup and teardown在模块/类/方法/函数级别(除了 pytests dependency injection mechanism )。功能级别setup and teardown functions are invoked for every test function在模块中。如何为特定测试功能定义设置和拆卸功能?

最佳答案

import pytest

@pytest.fixture
def resource():
   resource = foo()

   yield resource

   resource.cleanup()

def test_feature(resource):
   assert bar(resource) == 27

使用 fixture 进行设置和清理是比 try...finally 更好的方法在问题评论中建议,即使没有代码重用目标:您的单个测试专注于断言适当的条件,而不是资源清理。

关于python - 如何在 pytest 中为特定方法或函数定义设置和拆卸函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46562835/

相关文章:

python - Sublime Text 2 和 PYTHONPATH

python - hasattr() 与 try-except block 处理不存在的属性

java - Maven 单元测试 FileNotFound 错误

java - 单元测试时支持H2数据库中的DB2功能

c# - 为什么 Assert.AreEqual(T obj1, Tobj2) 会因相同的字节数组而失败

python - 在 Python Selenium 中查找 innerHTML 文本的 div id

Python POST 表单登录网站

python - 如何让 py.test 识别子目录中的 conftest.py?

python - pytest-mocks 并声明类级别的固定装置

python - pytest 中的参数化测试对于不同的测试函数具有不同的标记