我有一个实现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,它应作为摘要auth请求的初始响应。我进行了搜索,并遵循了一些与http基本身份验证相关的建议(使用参数data = {#various stuff}和follow_redirects = True),但是我没有成功。
在这种情况下,有谁知道如何实施单元测试?
python大神给出的解决方案
不幸的是,摘要身份验证在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
变量中。身份验证动作可以包含在辅助功能中,该辅助功能在测试期间包装了请求的发送,因此您不必在每个测试中都重复此步骤。
我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
Python:同时在for循环中添加到列表列表 - python我想用for循环外的0索引值创建一个新列表,然后使用for循环添加到相同的列表。我的玩具示例是:import random data = ['t1', 't2', 't3'] masterlist = [['col1', 'animal1', 'an…
在Python中迭代OrderedDict - python我有以下OrderedDict:OrderedDict([('r', 1), ('s', 1), ('a', 1), ('n', 1), ('y', 1)]) 实际上,这表示单词中字母的出现频率。第一步-我将使用最后两个元素来创建一个这样的联合元组; pair…
如何在Matplotlib条形图后面绘制网格线 - pythonx = ['01-02', '02-02', '03-02', '04-02', '05-02'] y = [2, 2, 3, 7, 2] fig, ax = plt.subplots(1, 1) ax.bar(range(len(y)), y, width=…
Celery任务不会通过记录器重要消息向管理员发送电子邮件 - python每次调用logger.critical,我的celery任务都不会向应用程序管理员发送电子邮件。我正在构建Django应用程序。我项目的当前配置允许应用程序的管理员在每次创建logger.critical消息时都收到一封电子邮件。设置起来非常简单,我只是遵循了两个项目(celery和Django)的文档。出于某种原因(我不确定),在celery任务中运行的代…