首页 > 解决方案 > 如何使用 test_client 登录并使用该登录的 app_context 发出 PUT 请求?

问题描述

我正在编写 pytests 来测试 API 调用。首先,我使用 POST api 让用户登录。然后我需要测试一个允许登录用户编辑配置文件信息的 PUT api。PUT api 首先检查 g.current_user.id = id 是否要编辑的配置文件。但是在 pytest 中,put 请求会引发以下错误:AttributeError: '_AppCtxGlobals' object has no attribute 'current_user'

我一直在尝试在 POST 和 PUT api 中使用相同的 app_context。我试图使用 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)

这是 conftest.py 中的 test_client:

@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()

这是 PUT api 的定义方式:

    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'

标签: pythonflaskflask-sqlalchemypytestflask-restful

解决方案


推荐阅读