Interval between tests in pytest
Asked Answered
F

3

5

Is there a common practice to add interval between tests in pytest? Currently integration tests fail but work fine if running the tests individually.

Forcible answered 12/12, 2017 at 10:13 Comment(0)
A
19

You can use autouse fixtures in pytest to automatically sleep in between test cases:

@pytest.fixture(autouse=True)
def slow_down_tests():
    yield
    time.sleep(1)

This fixture will automatically be used for all test cases and will yield execution to a test case so it can run normally, but when the test finishes, the execution will come back to this fixture and the sleep will be run.

Academicism answered 6/4, 2021 at 18:22 Comment(0)
G
4

If you want a teardown in a module for every function of the module:

import time
def teardown_function(function):   # the function parameter is optional
    time.sleep(3)

If you want a teardown in a class for every method of the class, you've two options.

  1. In this you can't access the invoked method:
class TestClass:
    def teardown(self):
        time.sleep(1)
  1. If you need to access it:
class TestClass:
    def teardown_method(self, method):
        print(method)
        time.sleep(1)

If you want a teardown that will be invoked once after a class:

@classmethod
def teardown_class(cls):
    print(cls)
    time.sleep(2)

All of this methods works in the same way for setups. You can see the documentation. Use fixtures for more complex implementations.

Gonsalve answered 4/2, 2018 at 12:11 Comment(0)
S
0

You can insert time.sleep(1) in the teardown method of each test, i.e:

class TestClass:
    def setup(self):
        pass

    def teardown(self):
        time.sleep(1) # sleep for 1 second
Schwa answered 2/1, 2018 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.