How to use Fixtures in Python Pytest

What are fixtures?

In the PyTest framework fixtures are the functions that provide scalable and comprehensible content for tests. Fixtures are considered to be the most powerful technique for designing tests.

These are usable and can be used for both simple and complex test situations. the function can use fixture by putting the fixture name in the place of the input parameter. It also includes environment or datasets and also improves over the x-unit style of setups.

A function is said to be a fixture by:

@pytest.fixture

Below are the prerequisites required to use the PyTest fixture 

python 3.6+ or  pypy3

PyTest End to end Automation test using fixtures

  1. Open IDE (Vs code or Pycharm).
  2. Execute the following command and it will install pytest in our IDE.
    $pip install pytest
  3. Next, import module pytest by using following command.
    import pytest
  4. Create a test file named test_1.py
  5. Your testing files should follow this manner given below:
  6. Now add the below code to test_1.py.
    import pytest
    @pytest.fixture
    def variable_():
        return 40
    @pytest.fixture
    def variable_2():
        return 30
    @pytest.fixture
    def add_(variable_,variable_2):
        return [variable_ , variable_2]
    def test(add_):
        add_.append(35)
        assert add_ == [40,30,35]

    we have defined a fixture function named variable_, which provides input to the other test functions. while pytest functions are getting executed, first the fixture name as variable_ get executed and returned the stored value as input parameter,

    That can be used by tests.function variable_2 return value 30 and add_ return list including variable_ and variable_2 .

    now the test function takes add_ as a parameter and by using built function append() it appends 35 to the list. Assert function test both the list values and generate a test case.

  7. Execute the test_1.py file by using the following command:
    $pytest test_1.py
  8. The above command will result as:Hence, the test case passed successfully showing the comparison of two list add_ == [40,30,35] without any error.

Thus, In this tutorial, we have learned about PyTest fixtures, how to implement tests using fixtures in Python PyTest for example.