嗨!在
我有一个使用HTTP基本身份验证(由flaskhttpauth实现)保护的路由。如果我使用curl,一切都可以正常工作(我可以访问路由),但是当进行单元测试时,即使我为它提供了正确的用户名和密码,也无法访问该路由。在
以下是我的测试模块中的相关代码片段:
class TestClient(object):
def __init__(self, app):
self.client = app.test_client()
def send(self, url, method, data=None, headers={}):
if data:
data = json.dumps(data)
rv = method(url, data=data, headers=headers)
return rv, json.loads(rv.data.decode('utf-8'))
def delete(self, url, headers={}):
return self.send(url, self.client.delete, headers)
class TestCase(unittest.TestCase):
def setUp(self):
app.config.from_object('test_config')
self.app = app
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
self.client = TestClient(self.app)
def test_delete_user(self):
# create new user
data = {'username': 'john', 'password': 'doe'}
self.client.post('/users', data=data)
# delete previously created user
headers = {}
headers['Authorization'] = 'Basic ' + b64encode((data['username'] + ':' + data['password'])
.encode('utf-8')).decode('utf-8')
headers['Content-Type'] = 'application/json'
headers['Accept'] = 'application/json'
rv, json = self.client.delete('/users', headers=headers)
self.assertTrue(rv.status_code == 200) # Returns 401 instead
以下是Flask HTTPAuth所需的回调方法:
^{pr2}$任何我的路线:
@app.route('/users', methods=['DELETE'])
@auth.login_required
def delete_user():
db.session.delete(g.user)
db.session.commit()
return jsonify({})
单元测试引发以下异常:
Traceback (most recent call last):
File "test_api.py", line 89, in test_delete_user
self.assertTrue(rv.status_code == 200) # Returns 401 instead
AssertionError: False is not true
我想再次强调的是,当我运行curl时,使用的参数与为我的测试客户机提供的参数完全相同时,一切正常,但是当我运行测试时,verify_password方法甚至没有被调用。在
非常感谢你的帮助!在
你会喜欢这个的。在
您的
send
方法:您的
^{pr2}$delete
方法:注意,您将
headers
作为第三个位置参数传递,因此它将作为data
传递到send()
。在下面是一个使用pytest和内置monkeypatch fixture如何实现这一点的示例。在
如果我在
some_flask_app
中有此API函数:我可以创建一个fixture,它返回一个flask测试客户机,并修补HTTPBasicAuth中的authenticate函数以始终返回
^{pr2}$True
:相关问题 更多 >
编程相关推荐