flask:进行单元测试时,request.authorization始终为None

时间:2018-06-26 17:25:24

标签: python flask python-unittest

我希望有人能帮助我。

我必须在flask api中编写一个带有Python的unittest的单元测试。我有一个登录路由,当使用React前端通过应用程序访问它时,它的运行情况非常好,但是每当我尝试从测试中发布时,request.authorization为None ...这会让我发疯

我在Internet上四处张望,尝试了许多不同的方法,但是无论我做什么,request.authorization在进行测试时始终为None

测试:

import unittest
import base64

from backend.peace_api import app


class TestLogin(unittest.TestCase):

    # Assert login() with correct authentication
    def test_login(self):
        with app.app_context():
            tester = app.test_client(self)

            auth = 'seo@hotmail.com:password'

            authheader = base64.b64encode(bytes(auth, 'UTF-8'))
            headers = {"HTTP_AUTHORIZATION": "Bearer " + str(authheader), "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"}

            response = tester.post('/api/login/', headers=dict(headers))
            print(response.json)

            self.assertEqual(response.status_code, 200)


if __name__ == '__main__':
    unittest.main()

路线:

import jwt
import datetime
from flask import Blueprint, request, jsonify
from backend.peace_api import database, secret_key
from backend.peace_api.flat.models.flat import Flat


login_blueprint = Blueprint("login", __name__)


@login_blueprint.route("/", methods=["POST"])
def login():
    auth = request.authorization # This here is always None
    print("Hello World")
    print(request)
    print(request.authorization)
    if auth is None:
        return jsonify({"success": False}, 401)

    email = auth.username
    password = auth.password

    if email is None or email is None or password is None:
        return jsonify({"success": False}, 500)

    mongo_flat = database.flats.find_one({"email": email})
    if mongo_flat is not None:
        flat = Flat(
            mongo_flat["_id"],
            mongo_flat["name"],
            mongo_flat["email"],
            mongo_flat["password"],
            mongo_flat["tasks"],
            mongo_flat["members"],
        )

        if password == flat.password and email == flat.email:
            token = jwt.encode(
                {
                    "id": str(flat.id),
                    "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30),
                },
                secret_key,
            )
            return jsonify({"token": token.decode("UTF-8")})

        else:
            return jsonify({"success": False}, 401)
    else:
        return jsonify({"success": False}, 401)

打印的消息:

Testing started at 19:15 ...
Launching unittests with arguments python -m unittest test_login.TestLogin in [...]\tests
Hello World
<Request 'http://localhost/api/login/' [POST]>
None


Ran 1 test in 0.017s

OK
[{'success': False}, 401]

老实说,我不知道该怎么办...谢谢您的帮助

1 个答案:

答案 0 :(得分:3)

因此您的设置存在一些问题,这些问题导致标头未发送或发送但格式不正确。

  1. 标题的名称是“授权”,而不是“ HTTP_AUTHORIZATION”。
  2. 授权标头的凭据值必须按照the spec进行base64编码。
  3. Werkzeug的默认authorization middleware仅支持Basic auth,因此您的Bearer令牌将不起作用,除非您使用的扩展为Werkzeug添加了Bearer支持(不包括)了解更多有关您的设置的信息,很难知道那里发生了什么。

这是一个非常简化的Flask应用,它演示了具有正常运行的Authorization标头的测试客户端:

import flask
import base64

app = flask.Flask("app")

@app.route("/")
def test():
    print(flask.request.authorization)
    return "Worked"

with app.test_client() as c:
    c.get("/", headers={"Authorization": "Basic {}".format(base64.b64encode(b"useo@hotmail.com:pass").decode("utf8"))})

哪些印刷品:

{'password': 'pass', 'username': 'seo@hotmail.com'}
<Response streamed [200 OK]>

在这里问了类似的问题:

Flask werkzeug request.authorization is none but Authorization headers present