Pytest: How to run a piece of code only one time before all tests run ?

Created on 23 Jul 2018  路  5Comments  路  Source: pytest-dev/pytest

Hi,

I use pytest as my testing framework.

I would like some piece of code to run only one time before the tests start to run, I would like this also to work even if I run only some of the tests (For example using the -k parameter on the command line)

Where is the recommendation to write that code ? Use fixtures or traditional JUnit style ? Can someone explain more about this topic ?

Thanks a lot !!!

David

question

Most helpful comment

hi @david-fliguer-ws ,

due to lack of a use-case I'm going to presume that an autouse session scoped fixture is sufficient
@pytest.fixture(scope="session", autouse=True)

there is more than just that to run code before tests, but in order to give more to the point advise we need to know what you are setting out to do instead of how you think it should be done

-- Ronny

All 5 comments

GitMate.io thinks possibly related issues are https://github.com/pytest-dev/pytest/issues/1484 (running py.test), https://github.com/pytest-dev/pytest/issues/3053 (How to set the staged of tests running?), https://github.com/pytest-dev/pytest/issues/2544 (Run tests truly programmatically), https://github.com/pytest-dev/pytest/issues/2713 (Database errors BEFORE running tests), and https://github.com/pytest-dev/pytest/issues/471 (pytest keeps running deleted tests).

hi @david-fliguer-ws ,

due to lack of a use-case I'm going to presume that an autouse session scoped fixture is sufficient
@pytest.fixture(scope="session", autouse=True)

there is more than just that to run code before tests, but in order to give more to the point advise we need to know what you are setting out to do instead of how you think it should be done

-- Ronny

@david-fliguer-ws hope the above comment helped you resolve this! If not please comment here and we can reopen / provide more direction :)

As a walk-around, code inside __init__.py file in your tests folder will execute before all tests.

It will also execute if no test runs, which may be a problem

Was this page helpful?
0 / 5 - 0 ratings