[英]Python3 unit test for uuid
我有為 api 調用構建有效負載的函數。 在有效載荷中,我使用uuid
生成標頭的唯一編號。 但是當我試圖比較預期的結果時,它永遠不會匹配,因為每次調用函數generate_payload
返回新的uuid
。 如何處理這個以通過單元測試?
我的.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
運行測試 - 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.