Assert mocked function called with json string in python

Writing some unit tests in python and using MagicMock to retrieve a method that takes a JSON string as input. In my unit test, I want to assert that it is called with the given arguments, however, I encounter problems with the statement, since the ordering of the objects inside the dict does not matter, moreover, in the assert statement for the string. A simplified example of what I'm trying to achieve below.

mock_funct = MagicMock()
# mocked function called elsewhere
expected = {"a":"a", "b":"b"}
mock_funct.assert_called_once_with(json.dumps(expected))

The above may pass or may fail due to arbitrary ordering of keys inside the dict when it is reset to json, i.e. how '{"a":"a", "b":"b"}'and '{"b":"b", "a":"a"}'are valid dumps, but one of them fails, and one will take place, but I would like to write a test to pass either.

+4
source share
1 answer

, . call_args_list ( call_args , , ), , unittest , ...

mock_funct.assert_called_once_with(mock.ANY)
call = mock_funct.call_args
call_args, call_kwargs = call  # calls are 2-tuples of (positional_args, keyword_args)
self.assertEqual(json.loads(call_args[0]), expected)

assert_called_once_with, , , , , , .

+9

All Articles