用于某些测试用例的 pytest fixture
pytest fixture for certain test cases
有一个测试class和如下测试用例:
class TestSomething():
...
@pytest.fixture(autouse=True)
def before_and_after_testcases(self):
setup()
yield
cleanup()
def test_abc_1():
...
def test_abc_2():
...
def test_def_1():
...
def test_def_2():
...
问题是,对于测试 class 中的每个测试用例,before_and_after_testcases()
会 运行。是否可以让 fixture 仅应用于函数名称中带有 abc
模式的测试用例?夹具不应该在 test_def_xxx
上 运行,但我不知道如何排除那些测试用例。
autouse=True
fixture 自动应用于所有测试,要删除该自动应用程序,您将删除 autouse=True
但现在该夹具未应用于任何!
要将该夹具手动应用于需要它的测试,您可以:
- 添加该灯具的名称作为参数(如果您需要该灯具具有的值)
- 用
@pytest.mark.usefixtures('fixture_name_here')
装饰需要该夹具的测试
另一种方法是将您的一个测试 class 分成多个测试 classes,将需要特定自动使用的 fixtures 的测试分组
免责声明:我是一名 pytest
开发人员,但我不认为这与此答案完全相关所以只需要披露从属关系
有一个测试class和如下测试用例:
class TestSomething():
...
@pytest.fixture(autouse=True)
def before_and_after_testcases(self):
setup()
yield
cleanup()
def test_abc_1():
...
def test_abc_2():
...
def test_def_1():
...
def test_def_2():
...
问题是,对于测试 class 中的每个测试用例,before_and_after_testcases()
会 运行。是否可以让 fixture 仅应用于函数名称中带有 abc
模式的测试用例?夹具不应该在 test_def_xxx
上 运行,但我不知道如何排除那些测试用例。
autouse=True
fixture 自动应用于所有测试,要删除该自动应用程序,您将删除 autouse=True
但现在该夹具未应用于任何!
要将该夹具手动应用于需要它的测试,您可以:
- 添加该灯具的名称作为参数(如果您需要该灯具具有的值)
- 用
@pytest.mark.usefixtures('fixture_name_here')
装饰需要该夹具的测试
另一种方法是将您的一个测试 class 分成多个测试 classes,将需要特定自动使用的 fixtures 的测试分组
免责声明:我是一名 pytest
开发人员,但我不认为这与此答案完全相关所以只需要披露从属关系