3

我正在使用 FlaskClient 测试我的 Flask 应用程序,以避免在测试我的应用程序时总是运行 Flask 服务器。

我创建了一个“sign_in”视图,当用户在我的前端成功登录时,它会返回一个带有加密令牌的“Authorization”标头。

此视图在正常环境中正常工作,它正确返回“授权”标头,但是当我在测试环境中测试此视图时,它不返回“授权”标头。视图None在“授权”标头中返回。

我已经在网上尝试了一些解决方案,例如添加self.app.config['TESTING'] = True到我的测试用例中,但是终端出现错误'FlaskClient' object has no attribute 'config',我已经尝试寻找解决方案,但没有成功。

我想知道可能会发生什么。

有谁知道这个问题的任何解决方案?

我将我的代码发送到下面进行分析。

先感谢您。

视图.py

@app.route("/sign_in", methods = ["POST"])
def sign_in():
    ...

    username, password = ...

    try:
        encoded_jwt_token = auth_login(username, password)
    except UserDoesNotExistException as error:
        return str(error), error.status_code

    resp = Response("Returned Token")
    resp.headers['Authorization'] = encoded_jwt_token

    return resp

测试.py

class TestAPIAuthLogin(TestCase):

    def setUp(self):
        self.app = catalog_app.test_client()
        # self.app.config['TESTING'] = True  # config does not exist

    def test_get_api_auth_login_user_test(self):
        username = "test"
        password = get_string_in_hash_sha512("test")
        authorization = 'Basic ' + get_string_in_base64(username + ":" + password)

        headers = {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
            'Authorization': authorization
        }

        response = self.app.get('/sign_in', headers=headers)
        # it returns None 
        authorization = response.headers.get("Authorization")

        self.assertIsNotNone(authorization)
        self.assertNotEqual(authorization, "")
4

3 回答 3

1

我相信这可能与 HTTP 请求处理标头的方式有关,它们将标头大写并添加HTTP_为前缀。尝试将您的标头更改为,HTTP_AUTHORIZATION而不仅仅是Authorization,因为测试客户端将无法正确设置它。

于 2019-04-15T14:12:06.850 回答
0

对于这个愚蠢的问题,我很抱歉。现在我已经想出答案了。问题是我试图GET在使用POST方法的视图中执行请求。

我刚刚替换了来自的请求

response = self.app.get('/sign_in', headers=headers)

response = self.app.post('/sign_in', headers=headers)

现在它开始起作用了。

如果有人遇到同样愚蠢的错误,我会在这里提出这个问题。

太感谢了。

于 2019-04-15T16:53:01.393 回答
0

如果 DRF 客户端存在类似问题,您可以使用,

client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token {token}'.format(token=token))

参考:https ://www.django-rest-framework.org/api-guide/testing/#credentialskwargs

于 2021-08-18T09:45:51.497 回答