我正在尝试模拟uuid4().hex
@freeze_time("2022-01-01")
@patch.object(uuid, 'uuid4', side_effect=[0])
def test_get_token(d):
assert g("username", "supersecret") == "f"
但是我得到了错误
headers = {"iat": now.int_timestamp, "jti": uuid.uuid4().hex}
E AttributeError:"int"对象没有属性"hex">
如何使用pytest模拟.hex
每次都返回相同的值?
您可以使用return_value
分配模拟值,例如,您可以执行以下操作:
import uuid
def function():
return uuid.uuid4().hex
@patch.object(uuid, 'uuid4')
def test_get_token(d_uuid4):
d_uuid4.return_value.hex = '10'
assert function() == '10'
我需要能够有多个十六进制的返回值,所以我就是这样做的。
@patch("uuid.uuid4")
def test(mock_uuid)
def create_hex_mock(i: int):
"""Creates the mock for calling uuid4.hex"""
mock_hex = MagicMock()
mock_hex.hex = str(i)
return mock_hex
mock_uuid.side_effect = [create_hex_mock(i+1) for i in range(12)]
print(mock_uuid().hex) # 1
print(mock_uuid().hex) # 2