Search code examples
pytest

How to handle data creation and testing the data in pytest


Pytest says in it's documentation that each test has unique class instance of the class and you can't share the same class between tests.

"Having each test share the same class instance would be very detrimental to test isolation and would promote poor test practices."

How should I handle a case where I need to create data in the beginning of the test, perform several manipulations on the data, and then check the data, if I can't pass the data to another function?

It's possible to do this in a single function but it would be too long, unreadable and hard to debug.


Solution

  • the thing is in pytest , each test function runs in a new instance of its test class ,to prevent the side effect in implementing date between tests pytest provide some mechanisms to handle this kinds of situations where you need to set up data once and use it across multiple test functions .

    Using Fixtures

    Fixtures in pytest are functions that can provide data, setup the resources and perform initialization required by tests. it can be used also to creatre data at the beginning of tests and share it across multiple test functions , you can use it in class or module , function .

    There is an example :

    import pytest
    #Fixtures are defined using the @pytest.fixture decorator
    @pytest.fixture 
    def initial_data():
        # Create initial data
        data = {'key': 'value'}
        return data
    def test_manipulate_data(initial_data):
        # Test function that uses initial_data fixture
        data = initial_data
        # Perform manipulations on data
        data['key'] = 'new_value'
        # Assertion or checks
        assert data['key'] == 'new_value'
    
    def test_another_function(initial_data):
        # Another test function that uses initial_data fixture
        data = initial_data
        # Perform different manipulations
        data['new_key'] = 'new_value'
        # Assertion or checks
        assert 'new_key' in data
    

    in this example : the initial_data fixture creates the initial date ({'key':'value'}) and provides it to both test_manipulate_data and test_another_function

    Each test function receives initial_data as an argument, ensuring they operate on the same data.