Register Login

Pytest Fixtures Example

Updated May 18, 2018

How to perform Pytest Fixtures- Python Unit Testing?

Please follow the steps below:

1.First take a look at the sample database class. It has the database object, connection and the cursor.

2.The cursor will return the database queries.

3.Next we will create two unit tests.

  • To verify Ram's employee id
  • To verify Tim's employee id

4.Create a function to test Ram's id. You have to create a server. Once the server is created, you have to then create a cursor object.

5.Next, add a cur.execute and paste the query.

6.Next copy the code and paste it below to create a function for Tim's id.

7.Next run the test using pytest –v command.

8.There are following issues with this code.

  • Code repetition
  • And creating expensive DB connection in every test case

9.You can, however, resolve these issues using the following concepts.

  • Setup and Teardown methods
  • Fixtures (recommended method)

The tear down concept will initialize everything you need right at the beginning.

10.You need to create a connection and a cursor object global.

11.Next setup a module method. Next, initialize the connection and the cursor.

12.Get rid of the lines highlighted in blue as they are not needed.

13.Next, create a ‘teardown’ module. To clean up after initialization, add two close lines.

14.All the things that the test modules need are being initialized in the setup module. After the process is complete, the teardown module will close the connection and the cursor.

15.Now run the program.

16.Now the issue of repeating same lines of code has been solved. Now we look at Pytest fixtures. First, import the ‘pytest’ module and add a ‘pytest’ fixture.

17.Next define a cursor.

18.Now run the program to view the output. Fixtures leverage concept of dependency injection method is better as global variables are not needed.

19.Now add a print function to see the program is performing as expected.

20.Run the program to view the output. Use the code pytest -v –capture=no.

21.To restrict the repetitive code you have to create a scope.

22.Next run the program to view the output. You will notice that the setting up only happens once.

23.Next, initialize ‘teardown’.

24.Next, run the program and view the output.