12

Pytest has setup and teardowns hooks for module, class, method.

I want to create my custom test environment in setup (before start of test session) and cleanup after all tests will be finished. In other words, how can I use hooks like setup_session and teardown_session?

orion_tvv
  • 1,681
  • 4
  • 17
  • 29
  • http://stackoverflow.com/questions/23667610/difference-between-setupclass-and-setup-in-python-unittest – Ari Gold Nov 17 '16 at 17:11
  • @AriGold. Actually I do not use any unittest class. I am writing test functions that using pytest fixtures. I see the example of setup_class/teardown_class usage in your link. But I am looking for something like setup_session/teardown_session. – orion_tvv Nov 17 '16 at 20:41

1 Answers1

31

These hooks work well for me:

def pytest_sessionstart(session):
    # setup_stuff

def pytest_sessionfinish(session, exitstatus):
    # teardown_stuff

But actually next fixture with session scope looks much prettier:

@fixture(autouse=True, scope='session')
def my_fixture():
    # setup_stuff
    yield
    # teardown_stuff
orion_tvv
  • 1,681
  • 4
  • 17
  • 29
  • That is the approach I was using (a session-scoped auto-use fixture). However, in pytest version `4.0` [they removed yield tests](https://docs.pytest.org/en/stable/deprecations.html#yield-tests) and this appears to no longer work. Any alternatives that you know of? – campellcl Sep 10 '20 at 00:22
  • @campellcl You missunderstood the difference between yield tests and yield fixtures as I can see. I just tested my code with pytest==4.0.0 and it worked like a charm). So you should use asserts inside tests instead of yeild-tests. – orion_tvv Sep 10 '20 at 19:07
  • Do we have an option to make this work when we run test in parrallel. i see the same code keep on running for all tests – Gaurav Khurana Jun 10 '21 at 12:53
  • @Gauravkhurana You can try to create some lock mechanism (e.g. file) in setup, remove while teardown and skip initialization if it already existing. – orion_tvv Jun 10 '21 at 22:21
  • Just a side note: using `pytest_sessionstart` will invoke the code **before** the collection, while the fixture version will be called after – Romuald Brunet Aug 17 '23 at 11:58