python - uuid 的 Python3 单元测试
问题描述
我有为 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
推荐阅读
- swift - PromiseKit 在 Promises 中包装外部闭包
- postgresql - 有一个没有间隙的序数列
- python - Pathlib Path.rename() 创建中间目录的方式?
- javascript - 在 javascript ES6 中寻找更高效的排序算法
- python-3.x - Python为类的字典理解定义迭代器
- html - html固定导航栏
- assembly - 多字指令的影响
- java - 测试结果中未考虑 JMeter 作为代码断言
- python-3.x - PuLP: TypeError: Can only add LpConstraintVar, LpConstraint, LpAffineExpression or True objects
- visual-studio-code - VSCode gotoLine 快捷方式也充当“输入”键