我正在构建Flask Cookiecutter的测试,而我所有其他测试都运行良好。我在测试使用g
元素的函数时遇到问题,例如我的views.py文件中的g.user
。
我的conftest.py
与flask-cookiecutter完全相同,加上来自Flask-Testing的the faking resources and context trick的添加。
### conftest.py ###
...
from contextlib import contextmanager
from flask import appcontext_pushed, g
@contextmanager
def user_set(app, user):
def handler(sender, **kwargs):
g.user = user
with appcontext_pushed.connected_to(handler, app):
yield
...
这是我的测试文件:
### test_file.py ###
from .conftest import user_set
import pytest
from my_app.utils import presave_posted_settings # <-- fn I want to test
@pytest.fixture()
def form_data():
return {...bunch of data..}
@pytest.mark.usefixtures("form_data")
class TestPresaveSettings:
"""Test cases for checking attributes before saving"""
def test_presave_posted_settings(self, form_data, user, testapp):
"""User meals are selected in form"""
with user_set(testapp, user): #<-- testapp and user available from flask-cookiecutter conftest.py
assert presave_posted_settings(form_data)
当我在test_file.py
上运行测试时,我看到了:
user = <User 'user0'>, testapp = <webtest.app.TestApp object at 0x1101ee160>
def test_presave_posted_settings(self, form_data, user, testapp):
"""User meals are selected in form"""
with user_set(testapp, user):
> assert presave_posted_settings(form_data)
test_utils.py:20:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../my_app/utils.py:26: in presave_posted_settings
g.user.breakfast = g.user.lunch = g.user.dinner = g.user.snack = g.user.dessert = False
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <flask.g of 'my_app'>, name = 'user'
def __getattr__(self, name):
if name == '__members__':
return dir(self._get_current_object())
> return getattr(self._get_current_object(), name)
E AttributeError: '_AppCtxGlobals' object has no attribute 'user'
我用谷歌搜索过,大多数例子使用Unittest或在一个文件中进行所有pytest测试。我想坚持使用多个测试文件的模式,每个测试文件都利用conftest.py
,但我不能为我的生活找出如何设置它以便我可以测试使用的函数g
元素。谢谢!