Python3 uuid 的单元测试

Python3 unit test for uuid

我有为 api 调用构建负载的函数。在有效负载中,我使用 uuid 为 header 生成唯一编号。但是当我试图比较预期结果时,它永远不会匹配,因为每次调用函数 generate_payload return new 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 

运行 测试 - 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)

您可以通过模拟 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

的文档

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