Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating form noses setup_package() to pytest

right now I'm trying to convert some API tests from Nose to Pytest. When I tried to do that I faced a little problem: Pytest doesnt support the "setup_package()" functionality. The "setup_package()" is in the __init__.py file of where the tests are.

This is the directory structure:

tests/__init__.py
      test_001.py
      test_002.py
      ...

A easy solution would be to give the setup_package() function a fixture, but the problem here is, that my setup_package() is accessing a global counter in the __init__.py. So that the __ini__.py file looks like that:

counter_id = 0

def setup_package():
    global counter
    counter = some_function()

def teardown_package():
    global counter
    clear_object(counter_id)

Im pretty sure, that there is very easy solution to migrate this but as I'm new to Pytest I want to know the "pytestian" way of migrating this particular example to Pytest! My first idea was to use a fixture with params functionality, but I'm not sure if it's a good way to migrate at all.

like image 954
Faram Avatar asked Feb 15 '26 00:02

Faram


1 Answers

As @hoefling already hinted in the comments:

I just created a new conftest.py (relate to In pytest, what is the use of conftest.py files?) file in the tests directory (see initial question for the folder structure).

tests/__init__.py
      conftest.py
      test_001.py
      test_002.py
      ... 

In that conftest.py file, I just copied the setup_package function in it, with the following fixture:

@pytest.fixture(scope='session', autouse=True)
def setup_and_teardown_package():
(...) #setup
yield
(...) #teardown

Regarding the counter_id: We don't need flags anymore, as we have a single function for our setup and teardown, so that the variables wont be lost. The yield tells the function to stop, till all the tests are done, and then to continue with the the method. So basically: Everything BEFORE yield will behave like the setup and everything AFTER the yield will behave like the teardown -> There is no need for globals anymore :)

like image 99
Faram Avatar answered Feb 16 '26 12:02

Faram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!