简体   繁体   English

如何在pytest中为特定方法或功能定义设置和拆卸功能?

[英]How can I define a setup and teardown function for a specific method or function in pytest?

Pytest supports classical xunit style setup and teardown on the module/class/method/function level (in addition to pytests dependency injection mechanism ). Pytest在模块/类/方法/功能级别上支持经典的 xunit 样式设置和拆卸 (除了pytests依赖项注入机制外 )。 The function level setup and teardown functions are invoked for every test function in the module. 将为模块中的每个测试功能调用功能级别设置和拆卸功能 How can I define setup and teardown functions for specific test functions? 如何为特定的测试功能定义设置和拆卸功能?

import pytest

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

   yield resource

   resource.cleanup()

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

Using fixtures for setup and cleanup is a better approach that the try...finally suggested in the question comments, even when there is no code reuse goal: your single test is focused on asserting the appropriate conditions, and not on resource cleanup. 即使没有代码重用目标,使用fixture进行设置和清除也是try...finally在问题注释中建议的一种更好的方法:您的单个测试专注于声明适当的条件,而不是资源清除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM