python-2.7 - python - Flask test_client() 没有使用 pytest 的 request.authorization

标签 python-2.7 unit-testing flask pytest werkzeug

使用 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/

相关文章:

python-2.7 - 当我更改主窗口大小时如何隐藏或剪切 Qwidget() 文本

unit-testing - 如何对数据结构的内部(组织)进行单元测试?

java - 如何对使用 Google Guice 的类进行单元测试?

python - 有什么方法可以让一个进程拥有写锁而其他进程只能并行读取?

python - 如何在 Python 中按每个元组的某个索引的整数值对元组列表进行排序?

python - Flask、Jinja2、 "$"字符上的 Babel 错误

python - 如何在按下按钮后在 Flask 中显示图像

html - 如何在 Jinja2 中动态设置背景图片?

python-2.7 - 使用 sklearn 加载文件以执行 Kmeans

python - 无返回值的单元测试函数