py.test 和 django 中的上下文管理器

py.test and context manager in django

我正在尝试在测试中使用以下上下文管理器:

class APITest(TestCase):
    def create_scenario(self, user):
        # @pytest.yield_fixture
        @contextmanager
        def scenario():
            if user is not None:
                self.client.login(username=user.username, password='password')
            yield
            if user is not None:
                self.client.logout()
        return scenario

    def setUp(self):
        self.user = UserFactory.create()
        self.non_auth_scenario = self.create_scenario(None)
        self.auth_scenario = self.create_scenario(self.user)

    def test_foo_get(self):
        with self.non_auth_scenario:
            assert self.client.get('/api/foo/', format='json').status_code == 401
        with self.auth_scenario:
            assert self.client.get('/api/foo/', format='json').status_code == 200

我得到以下结果:

    def test_widget_get(self):
\>       with self.non_auth_scenario:
E       AttributeError: __exit__

我看过 pytest.yield_fixture 但我没有机会。有什么见解吗?

使用 context manager 时,您需要调用它:

self.non_auth_scenario():

一般情况:

>>> from contextlib import contextmanager
>>> @contextmanager
... def user(name):
...    print 'hello', name
...    yield
... 
>>> with user('world'):
...    pass
... 
hello world

这会引发与您相同的错误:

>>> with user:
...    print 'well'
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __exit__