使用 pytest 测试我的 flask 应用程序时遇到问题。
应用程序需要基本身份验证,这是 request.authorization
的参数在 flask 中。
但是对于 pytest,flask.test_client() 没有 request.authorization
.
这是 fixture 的代码:
@pytest.yield_fixture(scope='session')
def app()
app = create_app()
# some setup code
ctx = app.app_context()
ctx.push()
yield app
ctx.pop()
# some teadown code
@pytest.fixture
def test_client(app)
return app.test_client()
这是一个测试代码:
def test_index(test_client):
res = test_client.get("/", headers={"Authorization": "Basic {user}".format(user=b64encode(b"test_user"))})
assert res.status_code == 200
当我运行此测试时,出现此错误:
E assert 401 == 200
E + where 401 = <Response streamed [401 UNAUTHORIZED]>.status_code
不仅认证失败,而且 request.authorization 没有任何值(value)(无)。
为什么会发生这种情况?有什么解决办法吗?
谢谢。
最佳答案
HTTP 基本身份验证的凭据必须包含用户名和密码,以冒号分隔。如果你还在使用 python 2,试试这个:
def test_index(test_client):
credentials = b64encode(b"test_user:test_password")
res = test_client.get("/", headers={"Authorization": "Basic {}".format(credentials)})
assert res.status_code == 200
Python 3 对数据完整性有一点严格,因此您必须确保在将字节发送到服务器之前正确解码字节:
def test_index(test_client):
credentials = b64encode(b"test_user:test_password").decode('utf-8')
res = test_client.get("/", headers={"Authorization": f"Basic {credentials}"})
assert res.status_code == 200
关于python-2.7 - python - Flask test_client() 没有使用 pytest 的 request.authorization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30249082/