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

心已入冬 提交于 2020-01-02 02:21:27

问题


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?


Doesn't work:

conftest.py

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

test_stuff.py

import unittest
import pytest

class TestWithFixtures(unittest.TestCase):

    def test_with_a_fixture(self, my_fixture):
         print(my_fixture)

Works:

conftest.py

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

test_stuff.py

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.


回答1:


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.



来源:https://stackoverflow.com/questions/22677654/why-cant-unittest-testcases-see-my-py-test-fixtures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!