模拟一个属性的函数 python

mock a function of an attribute python

我这里有:

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}

基于智威汤逊。我想模拟 identity.key.urlsafe() 到 return 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)

现在,一切正常,除了我的模拟。目标是 return 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 return 1 ?谢谢

在我看来,您想将模拟的 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)

来自documentation

side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT, the return value of this function is used as the return value.