Jon*_*use 6 unit-testing werkzeug pytest flask python-2.7
用pytest测试我的烧瓶应用程序时遇到问题.
App是基本的auth,它是request.authorization
烧瓶中的参数.
但是使用pytest,flask.test_client()没有request.authorization
.
这是一个夹具代码:
@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()
Run Code Online (Sandbox Code Playgroud)
这是一个测试代码:
def test_index(test_client):
res = test_client.get("/", headers={"Authorization": "Basic {user}".format(user=b64encode(b"test_user"))})
assert res.status_code == 200
Run Code Online (Sandbox Code Playgroud)
当我运行此测试时,我收到此错误:
E assert 401 == 200
E + where 401 = <Response streamed [401 UNAUTHORIZED]>.status_code
Run Code Online (Sandbox Code Playgroud)
不仅auth失败,而且request.authorization没有任何值(None).
为什么会这样?有什么解决方案吗?
谢谢.
Mig*_*uel 12
HTTP基本身份验证的凭据必须具有用冒号分隔的用户名和密码.试试这个:
def test_index(test_client):
res = test_client.get("/", headers={"Authorization": "Basic {user}".format(user=b64encode(b"test_user:test_password"))})
assert res.status_code == 200
Run Code Online (Sandbox Code Playgroud)
我找到了解决方案。也许可以帮助某人:
from requests.auth import _basic_auth_str
headers = {
'Authorization': _basic_auth_str(username, password),
}
Run Code Online (Sandbox Code Playgroud)
您只需要使用库“请求”