首页 > 解决方案 > 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)

标签: pythonpython-3.xpytest

解决方案


尝试使用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

推荐阅读