pytest:测试之间的完全清理

Vin*_*nce 6 python freeze fixtures pytest

在一个模块中,我有两个测试:

@pytest.fixture
def myfixture(request):
    prepare_stuff()
    yield 1
    clean_stuff()
    # time.sleep(10) # in doubt, I tried that, did not help

def test_1(myfixture):
    a = somecode()
    assert a==1

def test_2(myfixture):
    b = somecode()
    assert b==1
Run Code Online (Sandbox Code Playgroud)

情况1

当这两个测试单独执行时,一切都ok,即两者

pytest ./test_module.py:test_1
Run Code Online (Sandbox Code Playgroud)

紧接着:

pytest ./test_module.py:test_2
Run Code Online (Sandbox Code Playgroud)

运行直至完成并成功通过。

案例2

但:

pytest ./test_module.py -k "test_1 or test_2"
Run Code Online (Sandbox Code Playgroud)

报告:

collected 2 items
test_module.py .
Run Code Online (Sandbox Code Playgroud)

并永远挂起(经过调查:test_1成功完成,但第二次调用prepare_stuff挂起)。

问题

在我的具体设置中prepare_stuffclean_stuffsomecode已经相当进化,即它们创建和删除一些共享内存段,如果做得错误,可能会导致一些挂起。所以这里可能存在一些问题。

但我的问题是:在两次调用pytest(案例1)之间是否发生了在同一“pytest进程”(案例2)的调用test_1test_2来自同一“pytest进程”(案例2)的调用之间发生的事情,这可以解释为什么“案例1”工作正常,而“案例 2" 挂在test_1和之间test_2?如果是这样,是否有办法“强制”在“情况 2”之间test_1test_2“情况 2”之间进行相同的“清理”?

注意:我已经尝试将“myfixture”的范围指定为“function”,并且还仔细检查了“clean_stuff”在“test_1”之后调用,即使在“情况2”中也是如此。

Vad*_*der 0

prepare_stuff您和/或职能部门可能正在发生某些事情clean_stuff。当您运行测试时:

pytest ./test_module.py -k "test_1 or test_2"

它们在相同的执行上下文、相同的进程等中运行。因此,例如,如果clean_stuff没有进行适当的清理,那么下一个测试的执行可能会失败。当您运行测试时:

pytest ./test_module.py:test_1
pytest ./test_module.py:test_2
Run Code Online (Sandbox Code Playgroud)

它们在不同的执行上下文中运行,即它们在绝对干净的环境中启动,并且除非您正在修改某些外部资源,否则您可以clean_stuff在这种情况下轻松删除它们,并且它们无论如何都会通过。

要排除pytest问题,只需尝试运行:

    prepare_stuff()

    a = somecode()
    assert a==1

    clean_stuff()

    prepare_stuff()

    b = somecode()
    assert b==1

    clean_stuff()
Run Code Online (Sandbox Code Playgroud)

我很确定您也会遇到同样的问题,这将确认问题出在您的代码中,但不在pytest.