0

I have some functionality that makes a request to a third party. Within that request are some values that are dynamically created—for example, a date.

# example.py

...

payload = json.dumps({
    'id': uuid.uuid4(),
    'name': 'example',
    'date': datetime.now(),
    'foo': 'bar'
})

...

response = self.make_request(url, params=None, data=payload, method='post')

The functionality works great. Now I am attempting to write a unit test.

# test_example.py

@mock.patch('path.to.module.make_request')
test_successfully_does_stuff(self, make_request_mock):
    make_request_mock.return_value = {
        'status': 'OK'
        'success': True,
    }

    self.make_request()

    ...    

    make_request_mock.assert_called_with('https://example.com', params=None, data=json.dumps({
        'id': uuid.uuid4(),
        'name': 'example',
        'date': datetime.now(),
        'foo': 'bar'
    })

Asserting called_once works great:

make_request_mock.assert_called_once()

What I would like to assert, is that the make_requet call has all of the necessary attributes. Meaning I'd like to assert that id, name, date are included in the request. If I add a new attribute—or accidentally remove an attribute in the code, I'd like my test to pick that up.

When I run this test, I get an error that my expected and actual data doesn't match. This makes sense as datetime.now() and uuid4() will render different values when they are called.

For example, here is the result from date:

Expected: "date": "2023-07-05T20:00:28.130604"
Actual:   "date": "2023-07-05T20:40:51.575151",

I realize that the mock data is completely arbitrary and it could be anything I want. However I feel it may be important to test this. Is there a way to assert that my call has the necessary attributes?

EDIT

For clarification, it's the object attributes I want to assert are there, the actual values aren't as important.

Damon
  • 4,151
  • 13
  • 52
  • 108

1 Answers1

0

This is from a slightly older thread, but it seems this SO thread has potential solutions.

Since the values aren't of much concern, you could test that an attribute exists on the requesting instance:

self.assertTrue(hasattr(make_request_mock, 'date'))

If there are a large number of attributes, this approach may seem a bit much.

Damon
  • 4,151
  • 13
  • 52
  • 108