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.
pytest supports running Python unittest -based tests out of the box. It's meant for leveraging existing unittest -based test suites to use pytest as a test runner and also allow to incrementally adapt the test suite to take full advantage of pytest's features.
Fixtures and their visibility are a bit odd in pytest. They don't require importing, but if you defined them in a test_*. py file, they'll only be available in that file. You can however put them in a (project- or subfolder-wide) conftest.py to use them in multiple files.
To access the fixture function, the tests have to mention the fixture name as input parameter. Pytest while the test is getting executed, will see the fixture name as input parameter. It then executes the fixture function and the returned value is stored to the input parameter, which can be used by the test.
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.
You can use pytest fixtures in unittest.TestCase
with pytest autouse
:
@pytest.fixture
def my_fixture():
return 'This is some fixture data'
import unittest
import pytest
class TestWithFixtures(unittest.TestCase):
@pytest.fixture(autouse=True)
def test_with_a_fixture(self, my_fixture):
print(my_fixture)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With