pytest - How to execute a function after specific tests
Asked Answered
B

3

7

I have some tests organized in several classes. I already have a test fixture with scope=class so that it would run before suite(class) of tests. However, I need to execute a function after some specific tests. Lets say I have 100 tests in a class, I already have a fixture that will execute a function before these tests, but I also want to run a function after 2-3 of these tests.

What is the best approach to achieve that? Can it be done with fixtures or anything else ?

Bannock answered 7/1, 2021 at 13:54 Comment(0)
W
15

First, write a fixture that will execute after a test finishes:

@pytest.fixture
def foo():
    yield
    print("do stuff after test")

Docs: Fixture finalization / executing teardown code

Now mark each test that should invoke this fixture with usefixtures("foo"):

@pytest.mark.usefixtures("foo")
def test_spam():
    ...

Docs: Use fixtures in classes and modules with usefixtures

Winch answered 8/1, 2021 at 9:35 Comment(2)
Thanks, exactly what I was looking for.Bannock
@Bannock if that answer is exactly what you were looking for, please accept it.Rupee
S
0

If you are using the python's built-in unittest module you can override the tearDown method to run something after each test in a class.

If you are using pytest's framework and using pytests fixtures, you can use the yield keyword in your fixtures.

It's documented in https://doc.pytest.org/en/latest/fixture.html#teardown-cleanup-aka-fixture-finalization.

Sinistrocular answered 7/1, 2021 at 14:3 Comment(1)
I'm using pytest, however this doesn't help me, because I don't want to have a teardown after each test or after all the tests, I want a teardown after specific tests. For example I run 100 tests and I want to run a function after test 30, 45 and 70Bannock
B
0

If you know the specific tests you want to run after you could set up the tests in a .csv with different values for each test for Example (index) (column) (column) Tests Test# Complete? test 1 1 T test 2 2 F

import pandas as pd 
#makes panda read your file and sets the variable as the data in the file
data = pd.read_csv("filename.csv") 
#Gets the value from the column 'test#' and 'complete' and sets as a variable
Var1 = DataFrame.get_value("the number test you want to take", 'Complete?')
If Var1 = T 
   #Run the rest of your program here
#Then you can just repeat this for the other tests you want to check for 

This isn't the prettiest solution but it works

Byway answered 7/1, 2021 at 14:21 Comment(1)
Thanks, I will keep this in mind. I was hoping for a more elegant solution to be honest. I imagined that decorators might be used to achieve something like thisBannock

© 2022 - 2024 — McMap. All rights reserved.