Home > other >  Python3 unit test for uuid
Python3 unit test for uuid

Time:10-16

I have function which build the payload for api call. in payload i am using uuid to generate the unique number for header. but when i am trying to compare the expected result it never match as every time call function generate_payload return new uuid. How to handle this to pass unit test?

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 

run test - python -m pytest -vs test_my.py error

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

I tried using below also but no luck

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

CodePudding user response:

Try to use 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

CodePudding user response:

You can remove the randomness from the test by mocking the uuid.uuid4() call:

@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

Docs for mock.patch

  • Related