我在我的模块中使用 keystoneclient 在传递用户凭据时检索 auth_token。然后,将令牌放入 req.headers['X-Auth-Token'] 中,如下代码所示。我想为这个类写一个单元测试。我假设我需要模拟 Keystone 身份验证部分。我是单元测试和模拟的新手,所以请帮助我了解我应该如何处理这个问题。
from keystoneclient.v3 import client
from keystoneclient import exceptions as keystone_exceptions
class TokenChecker(wsgi.Middleware):
def myrequest(self,req):
try:
token = self.check_credential(userid,password)
except HTTPUnauthorized as e:
return e
req.headers['X-Auth-Token'] = token
def check_credential(self, userid, password):
keystone = client.Client(
username = foo
password = foo2
user_domain_name = foo3
domain_name = foo4
auth_url = foo5
endpoint = foo6
)
try:
keystone.authenticate()
return keystone.auth_token
except (keystone_exceptions.AuthorizationFailure,
keystone_exceptions.Unauthorized) as e:
raise HTTPUnauthorized(e)
我根据提供的答案创建的单元测试,
@mock.patch.object(TokenChecker, 'check_password', return_value= 'testtoken')
def test_with_valid_auth_header(self,check_password_mock):
req = webob.Request.blank('/')
checker = TokenChecker(req)
checker.process_request(req)
self.assertNotEqual(req.headers['X-Auth-Token'], 1)
我认为这有点写错了..但我不能确切地说出来。它在 X-Auth-Token 上向我抛出 KeyError。您能否建议一种将提供的答案合并到我的代码中的方法?