I'm trying to use py.test
's fixtures with my unit tests, in conjunction with unittest
. I've put several fixtures in a conftest.py
file at the top level of the project (as described here), decorated them with @pytest.fixture
, and put their names as arguments to the test functions that require them.
The fixtures are registering correctly, as shown by py.test --fixtures test_stuff.py
, but when I run py.test
, I get NameError: global name 'my_fixture' is not defined
. This appears to only occur when I use subclasses of unittest.TestCase
—but the py.test
docs seem to say that it plays well with unittest
.
Why can't the tests see the fixtures when I use unittest.TestCase
?
@pytest.fixture
def my_fixture():
return 'This is some fixture data'
import unittest
import pytest
class TestWithFixtures(unittest.TestCase):
def test_with_a_fixture(self, my_fixture):
print(my_fixture)
@pytest.fixture()
def my_fixture():
return 'This is some fixture data'
import pytest
class TestWithFixtures:
def test_with_a_fixture(self, my_fixture):
print(my_fixture)
I'm asking this question more out of curiosity; for now I'm just ditching unittest
altogether.
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.TestCase
es. See that page for more information.