我有一个实现REST api的flask应用程序。出于某些原因,我使用HTTP摘要身份验证。我已经使用Flask-HTTPAuth库实现了摘要式身份验证,它可以工作;但是,我无法在单元测试中进行身份验证。
对于单元测试,在设置身份验证之前,我会这样做:
class FooTestCase(unittest.TestCase):
def setUp(self):
self.app = foo.app.test_client()
def test_root(self):
response = self.app.get('/')
# self.assert.... blah blah blah在实现身份验证之前,这是很好的。现在我得到一个401,它应该是摘要身份验证请求的初始响应。我已经搜索并遵循了一些关于http basic auth (使用参数,data ={#各种东西}和follow_redirects=True)的建议,但是没有成功。
有没有人知道如何在这种情况下实现单元测试?
发布于 2016-08-13 07:40:17
不幸的是,在Flask-HTTPAuth中很难测试或绕过摘要身份验证。
一种选择是实际计算正确的散列,并在测试期间执行完整的身份验证。您可以在Flask-HTTPAuth unit tests中看到一些这样的示例。这里有一个:
def test_digest_auth_login_valid(self):
response = self.client.get('/digest')
self.assertTrue(response.status_code == 401)
header = response.headers.get('WWW-Authenticate')
auth_type, auth_info = header.split(None, 1)
d = parse_dict_header(auth_info)
a1 = 'john:' + d['realm'] + ':bye'
ha1 = md5(a1).hexdigest()
a2 = 'GET:/digest'
ha2 = md5(a2).hexdigest()
a3 = ha1 + ':' + d['nonce'] + ':' + ha2
auth_response = md5(a3).hexdigest()
response = self.client.get(
'/digest', headers={
'Authorization': 'Digest username="john",realm="{0}",'
'nonce="{1}",uri="/digest",response="{2}",'
'opaque="{3}"'.format(d['realm'],
d['nonce'],
auth_response,
d['opaque'])})
self.assertEqual(response.data, b'digest_auth:john')在本例中,用户名为john,密码为bye。假设您为某个用户提供了一些可在单元测试中使用的预先确定的凭据,因此可以将这些凭据插入到上面的a1变量中。这种身份验证舞蹈可以包含在一个辅助函数中,该函数在测试期间包装请求的发送,这样您就不必在每次测试中重复此操作。
发布于 2016-08-13 03:21:38
在测试中没有必要使用真实的身份验证。运行测试时禁用身份验证,或者创建测试用户并在测试中使用此测试用户。
例如:
@digest_auth.get_password
def get_pw(username):
if running_from_tests():
if username == 'test':
return 'testpw'
else:
return None
else:
# ... normal auth that you have当然,此测试用户在生产环境中一定不能处于活动状态:)有关running_from_tests()的实现,请参阅Test if code is executed from within a py.test session (如果您使用的是py.test)。
https://stackoverflow.com/questions/38925016
复制相似问题