Python3单元测试uuid



我有一个函数,它为api调用构建有效负载。在有效载荷我使用uuid生成头的唯一号码。但是当我试图比较预期结果时,它永远不会匹配,因为每次调用函数generate_payload返回新的uuid。如何处理这个通过单元测试?

my.py

import uuid

def generate_payload():
payload = {
"method": "POST",
"headers": {"X-Transaction-Id":"" +str(uuid.uuid4())+""},
"body": {
"message": {
"messageVersion": 1
},
}
}
return payload

test_my.py

import my
def test_generate_payload():
expected_payload = {'method': 'POST', 'headers': {'X-Transaction-Id': '5396cbce-4d6c-4b5a-b15f-a442f719f640'}, 'body': {'message': {'messageVersion': 1}}}
assert my.generate_payload == expected_payload 

运行test -python -m pytest -vs test_my.py误差

...Full output truncated (36 lines hidden), use '-vv' to show

我试着使用下面的,但没有运气

assert my.generate_payload == expected_payload , '{0} != {1}'.format(my.generate_payload , expected_payload)

尝试使用mock:

def example():
return str(uuid.uuid4())
# in tests...
from unittest import mock
def test_example():
# static result
with mock.patch('uuid.uuid4', return_value='test_value'):
print(example())  # test_value
# dynamic results
with mock.patch('uuid.uuid4', side_effect=('one', 'two')):
print(example())  # one
print(example())  # two

您可以通过模拟uuid.uuid4()调用从测试中删除随机性:

@mock.patch('my.uuid') # mock the uuid module in your IUT
def test_generate_payload(mock_uuid):
mock_uuid.uuid4.return_value = 'mocked-uuid'  # make the mocked module return a constant string
expected_payload = {'method': 'POST', 'headers': {'X-Transaction-Id': 'mocked-uuid'}, 'body': {'message': {'messageVersion': 1}}}
assert my.generate_payload == expected_payload

mock.patch的文档

最新更新