繁体   English   中英

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

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

Pytest在模块/类/方法/功能级别上支持经典的 xunit 样式设置和拆卸 (除了pytests依赖项注入机制外 )。 将为模块中的每个测试功能调用功能级别设置和拆卸功能 如何为特定的测试功能定义设置和拆卸功能?

import pytest

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

   yield resource

   resource.cleanup()

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

即使没有代码重用目标,使用fixture进行设置和清除也是try...finally在问题注释中建议的一种更好的方法:您的单个测试专注于声明适当的条件,而不是资源清除。

暂无
暂无

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

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