Why cant unittest.TestCases see my py.test fixtures?

You can use the pytest fixtures in unittest.TestCase with the pytest option autouse. However, if you use the test_ for the unit method using the fixture the following error will appear:

Fixtures are not meant to be called directly,...

### conftest.py
@pytest.fixture
def my_fixture():
    return 'This is some fixture data'

One solution is to use a prepare_fixture method to set fixtures as an attribute of the TestWithFixtures class, so that fixtures are available to all unit test methods.

### test_stuff.py
       
import unittest
import pytest
    
class TestWithFixtures(unittest.TestCase):
    

    @pytest.fixture(autouse=True)
    def prepare_fixture(self, my_fixture):
        self.myfixture = my_fixture

    def test_with_a_fixture(self):
        print(self.myfixture)

While pytest supports receiving fixtures via test function arguments for non-unittest test methods, unittest.TestCase methods cannot directly receive fixture function arguments as implementing that is likely to inflict on the ability to run general unittest.TestCase test suites.

From the note section at the bottom of: https://pytest.org/en/latest/unittest.html

It's possible to use fixtures with unittest.TestCasees. See that page for more information.


  1. define the fixture as an accessible variable, (like input in the following example). To define it, use request.cls.VARIABLE_NAME_YOU_DEFINE = RETURN_VALUE

  2. use @pytest.mark.usefixtures("YOUR_FIXTURE") to use fixture outside of the unittest class, inside the unittest class, access the fixture by self.VARIABLE_NAME_YOU_DEFINE.

e.g.

import unittest
import pytest


@pytest.fixture(scope="class")
def test_input(request):
    request.cls.input = {"key": "value"}


@pytest.mark.usefixtures("test_input")
class MyTestCase(unittest.TestCase):

    def test_something(self):
        self.assertEqual(self.input["key"], "value")