我在这里:
class Authentication(MethodView):
@staticmethod
def make_payload(identity):
iat = datetime.utcnow()
exp = iat + timedelta(seconds=300)
nbf = iat + timedelta(seconds=0)
identity = identity.key.urlsafe()
return {'exp': exp, 'iat': iat, 'nbf': nbf, 'identity': identity}
基于JWT。我想模仿identity.key.urlsafe()
以返回1
这是一个用户ID:
def test_make_payload(self):
def get_urlsafe():
return self.user_id
now = datetime.utcnow()
mock_identity = MagicMock()
mock_identity.key.return_value = MagicMock(urlsafe=get_urlsafe)
payload = Authentication.make_payload(mock_identity)
现在,一切都有效,除了我的模拟。目标是让它返回1
:
ipdb> payload
{'identity': <MagicMock name='mock.key.urlsafe()' id='4392456656'>, 'iat': datetime.datetime(2016, 11, 22, 21, 34, 41, 605698), 'nbf': datetime.datetime(2016, 11, 22, 21, 34, 41, 605698), 'exp': datetime.datetime(2016, 11, 22, 21, 39, 41, 605698)}
ipdb> payload['identity']
<MagicMock name='mock.key.urlsafe()' id='4392456656'>
如何模拟此嵌套调用以使urlsafe
在我的模拟中返回1?谢谢
答案 0 :(得分:2)
我认为您希望将模拟的side_effect
设置为get_urlsafe
:
def test_make_payload(self):
def get_urlsafe():
return self.user_id
now = datetime.utcnow()
mock_identity = MagicMock()
mock_identity.key.urlsafe.side_effect = get_urlsafe
payload = Authentication.make_payload(mock_identity)
side_effect:调用Mock时要调用的函数。请参阅side_effect属性。用于引发异常或动态更改返回值。使用与mock相同的参数调用该函数,并且除非它返回DEFAULT,否则此函数的返回值将用作返回值。