I am using keystoneclient in my module to retrieve auth_token when user credential is passed. Then, put the token into req.headers['X-Auth-Token'] as below code. I want to write a unittest for this class. I am assuming that I need to mock Keystone authentication part. I am new to unittesting and mock so please help me understand how I should approach this.
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)
Unittest I created based on the answer I was provided,
@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)
I think this is somewhat written wrong.. but I can't exactly tell. It is throwing me KeyError on X-Auth-Token. Could you please suggest a way to incorporate the provided answer into my code?