用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()
这是一个测试代码:
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
不仅auth失败,而且request.authorization没有任何值(None)。 为什么会这样?有什么解决方案吗?
谢谢。
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
我找到了这个解决方案也许它可以帮助某人:
from requests.auth import _basic_auth_str
headers = {
'Authorization': _basic_auth_str(username, password),
}
你只需要使用库'请求'
from requests.auth import _basic_auth_str
headers = {
'Authorization': _basic_auth_str(username, password)
}
这对我来说都适用于python 3.6和2.7,而以下仅适用于2.7:
res = test_client.get("/", headers={"Authorization": "Basic {user}".format(user=b64encode(b"test_user:test_password"))})
如果您使用的是新版本的python(在我的情况下为3.7),您应该解码base64字符串。它返回字节,在stringify之后,它看起来像b'basestring',这是不正确的。
>>> base64.b64encode(b"user:password")
b'dXNlcjpwYXNzd29yZA=='
>>> base64.b64encode(b"user:password").decode()
'dXNlcjpwYXNzd29yZA=='
所以,现在我的测试看起来像
class TestServer(unittest.TestCase):
def setUp(self) -> None:
self.client = app.test_client()
user_credentials = base64.b64encode(b"user:password").decode()
self.headers = {"Authorization": "Basic {}".format(user_credentials)}