Я пишу pytests для тестирования вызовов API. Сначала я использую API POST для входа в систему. Затем мне нужно протестировать API PUT, который позволяет зарегистрированному пользователю редактировать информацию профиля. PUT api сначала проверяет, является ли g.current_user.id = id профиля для редактирования. Но в то время как в pytest запрос put вызывает следующую ошибку: AttributeError: у объекта '_AppCtxGlobals' нет атрибута 'current_user'
Я пытался использовать один и тот же app_context в обоих, POST и PUT API. Я пытался использовать current_app, но возникла та же ошибка.
Это тестовые утверждения. Первый проходит, второй не проходит:
with test_client as client:
login = {'username':'washington', 'password':'FlaskIsAwesome'}
l = client.post('/auth/login', data=login, follow_redirects=True)
assert l.status_code == 200
u = json.loads(client.put('api/users/1', data=updateuser, headers=headers).data)
assert u == json.loads(client.get('api/users/1').data)
Это test_client в conftest.py:
@pytest.fixture(scope='session')
def test_client():
flask_app = create_app('test')
flask_app.config['TESTING'] = True
# Flask provides a way to test your application by exposing
# the Werkzeug test Client and handling the context locals
# for you.
testing_client = flask_app.test_client()
# Establish an application context before running the tests.
ctx = flask_app.app_context()
ctx.push()
yield testing_client # this is where the testing happens!
ctx.pop()
Вот как определяется API PUT:
def put(self, id):
"""
Updates the profile information of a user
"""
if g.current_user.id != id:
abort(403)
user = User.query.get_or_404(id)
data = request.get_json() or {}
if 'username' in data and data['username'] != user.username and \
User.query.filter_by(username=data['username']).first():
return bad_request('please use a different username')
if 'email' in data and data['email'] != user.email and \
User.query.filter_by(email=data['email']).first():
return bad_request('please use a different email address')
user.from_dict(data, new_user=False)
db.session.commit()
return user.to_dict()
Я ожидаю, что запрос PUT успешно обновит информацию профиля пользователя, который вошел в систему через запрос POST ранее. Он возвращает обновленную информацию о пользователе в форме словаря Python.
Но я столкнулся с этой единственной ошибкой: AttributeError: '_AppCtxGlobals' объект не имеет атрибута 'current_user'