使用pytest进行设置和拆卸

时间:2019-04-10 19:35:52

标签: python pytest fixtures

我的测试模块中有少量测试,需要一些通用的设置和拆卸才能在测试之前和之后运行。我不需要安装和拆卸即可运行每个功能,只需其中的几个即可。我发现我可以使用fixtures

@pytest.fixture
def reset_env():
    env = copy.deepcopy(os.environ)
    yield None
    os.environ = env


def test_that_does_some_env_manipulation(reset_env):
    # do some tests

我实际上不需要从固定装置返回任何东西来在测试功能中使用,所以我真的不需要参数。我只是用它来触发设置和拆卸。

有没有一种方法可以指定测试功能使用安装/拆卸夹具而不需要夹具参数?也许装饰者会说测试功能使用了某种固定装置?

2 个答案:

答案 0 :(得分:1)

感谢上面hoefling的评论

@pytest.mark.usefixtures('reset_env')
def test_that_does_some_env_manipulation():
    # do some tests

答案 1 :(得分:0)

您可以在灯具中使用autouse=True。自动使用会在灯具范围开始时自动执行灯具。 在您的代码中:

@pytest.fixture(autouse=True)
def reset_env():
    env = copy.deepcopy(os.environ)
    yield None
    os.environ = env


def test_that_does_some_env_manipulation():
    # do some tests

但是您需要注意灯具的范围,因为每个范围都会触发灯具。如果所有这些测试都在一个目录下,则可以将其放在目录的conftest文件中。否则,您可以在测试文件中声明灯具。

Relevant pytest help doc

相关问题