[pytest-dev] How to add delay before processing captured output

Nikolaus Rath Nikolaus at rath.org
Wed Feb 17 16:06:49 EST 2016


Hello,

I have a test that starts a background process, and then checks its
response to various queries. Now, I would like to test for particular
bug where some query causes the server to crash. However, there's an
interesting problem with this:


I when running with capturing disabled, I can see the final words of the
server on the screen. When running with capturing (fd capturing, to be
exact), these last messages are lost.

I eventually figured out that the problem is that the test fails before
the server crashes (because the server returns an invalid response
before crashing), and capfd then shows the captured output before the
server had a chance to print its last words.

If I explicitly ignore the test failure, I am able to see the full
captured output. In other words, if

def my_test():
    check_server_response()

becomes

def my_test():
    try:
       check_server_response()
    except:
       time.sleep(1)
       wait

then the server gets enough time to die before the test fails.


Now, I realize that adding a delay is rather hacky, but I do not see a
better way to implement this (after all, I have to take into account
that the server could also hang). However, I really do not want to
insert sleep calls into every single test.

Therefore, I tried to define a custom "wait a little" autouse fixture
that just does this:

@pytest.fixture(autouse=True)
def wait_for_server(request, capfd):
    def wait_a_moment():
        time.sleep(1)
    request.addfinalizer(wait_a_moment)


...but this did not actually have the desired effect. It seems the
fixture is only run *after* capfd has read the the output.


Is there a way to add a delay that is (1) only incurred when a test
fails and (2) executed right after the test fails (ie., before the capfd
finalizer runs)?


Thanks,
-Nikolaus


-- 
GPG encrypted emails preferred. Key id: 0xD113FCAC3C4E599F
Fingerprint: ED31 791B 2C5C 1613 AF38 8B8A D113 FCAC 3C4E 599F

             »Time flies like an arrow, fruit flies like a Banana.«


More information about the pytest-dev mailing list