0

Let's explain my question with an example:

import pytest

@pytest.fixture(scope="session", autouse=True)
def print_session():
    print("session fixture")
    yield        

def setup_function(funtion):
    print("function setup")

def test_printer1():
    print("test test_printer1")
    
def test_printer2():
    print("test test_printer2")

Currently, I am getting this:

example3.py::test_printer1    
session fixture
function setup
test test_printer1

example3.py::test_printer2 
function setup
test test_printer2

But, I want to get this:

example3.py::test_printer1    
function setup
session fixture
test test_printer1

example3.py::test_printer2 
function setup
test test_printer2

Notice that setup_function must be executed prior to every single test case.

¿Is there any way to achieve such an aim? I mean to have a setup_function that gets executed prior to any fixture disregarding its scope on Pytest.

fraverta
  • 75
  • 1
  • 13
  • You can implement [pytest_sessionstart](https://docs.pytest.org/en/latest/reference/reference.html?highlight=pytest_sessionstart#std-hook-pytest_sessionstart) in `conftest.py`. – MrBean Bremen Mar 23 '22 at 20:04
  • Does this answer your question? [How to run a method before all tests in all classes?](https://stackoverflow.com/questions/17801300/how-to-run-a-method-before-all-tests-in-all-classes) – MrBean Bremen Mar 23 '22 at 20:07
  • @MrBeanBremen thanks for your suggestion. Actually, that post doesn't solve my problem bc I need the setup_function gets executed prior to every test case. I have improved the example to clarify my requirements. – fraverta Mar 23 '22 at 20:22
  • `pytest_sessionstart` gets executed before all test cases, so I'm not sure what you mean. – MrBean Bremen Mar 23 '22 at 20:25
  • @MrBeanBremen yes but `pytest_sessionstart` gets executed before all test cases but only once. I need to execute `setup_function` before every single test case. I mean given that I have 2 test cases, I need `setup_function` to be executed 2 times instead of once. – fraverta Mar 23 '22 at 20:40
  • You cannot execute it before each test case _and_ before session-scoped fixtures, because there is simply no time where this may happen (without ugly workarounds where you call it from 2 places). You may want to think about what you really need. – MrBean Bremen Mar 23 '22 at 20:43

1 Answers1

0

If Pytest is not a requirement you can use unittest to do that, i personally do exactly this in one of my projects.

import unittest
class TestExample(unittest.TestCase):
    def setUp(self):
        self.foo = 'bar'
    def tearDown(self):
        self.foo = None

Then you can create all your test cases as methods inside that class and every single one will have the setup function running before it and the teardown after it. Like so:

def test_foo(self):
    self.assertTrue(self.foo == 'bar')