gpt4 book ai didi

python - 模拟 Python 属性的函数

转载 作者:行者123 更新时间:2023-12-01 03:32:20 27 4
gpt4 key购买 nike

我这里有:

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?

最佳答案

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

关于python - 模拟 Python 属性的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40752211/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com