Ostap Maliuvanchuk
Ostap Maliuvanchuk

Reputation: 1175

Pytest init setup for few modules

Say i have next tests structure:

test/
  module1/   
    test1.py
  module2/
    test2.py
  module3/
    test3.py

How can i setup some method to be called only once before all this tests?

Upvotes: 19

Views: 30578

Answers (3)

Allen Ellis
Allen Ellis

Reputation: 318

If you are using Django and trying to create database objects using hpk42's answer, it will fail with this error:

RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it

In this situation, pytest offers an example piece of code to work around this:

import pytest

from myapp.models import Widget

@pytest.fixture(scope='function')
def django_db_setup(django_db_setup, django_db_blocker):
    with django_db_blocker.unblock():
        Widget.objects.create(...)

Documentation is here: https://pytest-django.readthedocs.io/en/latest/database.html#populate-the-test-database-if-you-use-transactional-or-live-server

Upvotes: 0

Amit K.
Amit K.

Reputation: 609

If you mean only once in each run of the test suit, then setup and teardown are what you are looking for.

def setup_module(module):
    print ("This will at start of module")

def teardown_module(module):
    print ("This will run at end of module")

Similarly you can have setup_function and teardown_function which will run at start and end of each test function repetitively. You can also add setup and teardown member function in test classes to run at start and end of the test class run.

Upvotes: 2

hpk42
hpk42

Reputation: 23571

You can use autouse fixtures:

# content of test/conftest.py 

import pytest
@pytest.fixture(scope="session", autouse=True)
def execute_before_any_test():
    # your setup code goes here, executed ahead of first test

See pytest fixture docs for more info.

Upvotes: 37

Related Questions