Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest: full cleanup between tests [closed]

In a module, I have two tests:

@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

case 1

When these two tests are executed individually, all is ok, i.e. both

pytest ./test_module.py:test_1

and immediately after:

pytest ./test_module.py:test_2

run until completion and pass with success.

case 2

But:

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

reports:

collected 2 items
test_module.py .

and hangs forever (after investigation: test_1 completed successfully, but the second call to prepare_stuff hangs).

question

In my specific setup prepare_stuff, clean_stuff and somecode are quite evolved, i.e. they create and delete some shared memory segments, which when done wrong can results in some hanging. So some issue here is possible.

But my question is: are there things occurring between two calls of pytest (case 1) that do not occur between the call of test_1 and test_2 from the same "pytest process" (case 2), which could explain why "case 1" works ok while "case 2" hangs between test_1 and test_2 ? If so, is there a way to "force" the same "cleanup" to occur between test_1 and test_2 for "case 2" ?

Note: I already tried to specify the scope of "myfixture" to "function", and also double checked that "clean_stuff" is called after "test_1", even in "case 2".

like image 1000
Vince Avatar asked Nov 15 '22 18:11

Vince


1 Answers

The current structure of myfixture guarantee cleanup() is called between test_1 and test_2, unless prepare_stuff() is raising an unhandled exception. You will probably notice this, so the most likely issue is that cleanup() dosn't "clean" everything prepare_stuff() did, so prepare_stuff() can't setup something again.

As for your question, there is nothing pytest related that can cause the hang between the tests. You can force cleanup() to be called (even if an exception is being raised) by adding finalizer, it will be called after the teardown part

@pytest.fixture
def myfixture(request):
    request.addfinalizer(cleanup)
    prepare_stuff()
    yield 1
like image 186
Guy Avatar answered Dec 21 '22 01:12

Guy