标记测试在独立过程中运行

时间:2017-08-02 13:33:20

标签: python pytest

我正在使用pytest。我有一个测试,涉及检查导入是什么时发生。这很容易实现,但是当测试在pytest中运行时,它会在与许多其他测试相同的过程中运行,这可能会事先导入该事物。

有没有办法将测试标记为在自己的进程中运行?理想情况下,有某种类似的装饰者,如

If TLD = Listtld Then
    If Product = "auto renewal" Then
        If Period = "1 year" Then
            Cells(3 + startnumber, 3).Value = Sheets("pricelist").Cells(2 + startnumber, 2)
        ElseIf Period = "2 years" Then
            Cells(3 + startnumber, 3).Value = Sheets("pricelist").Cells(3 + startnumber, 2)
        ElseIf Period = "3 years" Then
            Cells(3 + startnumber, 3).Value = Sheets("pricelist").Cells(4 + startnumber, 2)
        ElseIf Period = "4 years" Then
            Cells(3 + startnumber, 3).Value = Sheets("pricelist").Cells(5 + startnumber, 2)
        ElseIf Period = "5 years" Then
            Cells(3 + startnumber, 3).Value = Sheets("pricelist").Cells(6 + startnumber, 2)
        End If
    End If
End If

但我还没有找到类似的东西。

1 个答案:

答案 0 :(得分:3)

我不知道pytest插件允许标记测试在自己的进程中运行。我检查的两个是pytest-xdistptyest-xprocess(此处为a list of pytest plugins),但他们看起来并不像你做的那样想。

我选择不同的解决方案。我假设您检查模块是否已导入的方式是它是否在sys.modules中。因此,我确保sys.modules在测试运行之前不包含您感兴趣的模块。

这样的事情将确保sys.modules在测试运行之前处于干净状态。

import sys

@pytest.fixture
def clean_sys_modules():
    try:
        del sys.modules['yourmodule']
    except KeyError:
        pass
    assert 'yourmodule' not in sys.modules # Sanity check.

@pytest.mark.usefixtures('clean_sys_modules')
def test_foo():
    # Do the thing you want NOT to do the import.
    assert 'yourmodule' not in sys.modules