Assert mocked function called with json string in python

2024/10/2 6:25:18

Writing some unit tests in python and using MagicMock to mock out a method that accepts a JSON string as input. In my unit test, I want to assert that it is called with given arguments, however I run into issues with the assert statement, since the ordering of objects within the dict doesn't matter, besides in the assert statement for the string. Simplified example of what I am 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 the arbitrary ordering of the keys within the dict when it is dumped to json, ie both '{"a":"a", "b":"b"}' and '{"b":"b", "a":"a"}' are valid dumps but one would fail and one would pass, however I would like to write the test so that either would pass.

Answer

Unfortunately, you'll need to do your own checking here. You can get the calls from the mock via it's call_args_list attribute (or, simply call_args in this case since you have already asserted that it is called only once). I'll assume you're using unittest in my example code -- but it should be easy enough to adapt for any testing framework ...

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)

I've still used assert_called_once_with to make sure that the function was only called once with a single positional argument, but then I open up the call to look at that argument to check that it is correct.

https://en.xdnf.cn/q/70883.html

Related Q&A

read certificate(.crt) and key(.key) file in python

So im using the JIRA-Python module to connect to my companys instance on JIRA and it requires me to pass the certificate and key for this. However using the OpenSSL module,im unable to read my local ce…

Admin FileField current url incorrect

In the Django admin, wherever I have a FileField, there is a "currently" box on the edit page, with a hyperlink to the current file. However, this link is appended to the current page url, an…

Difference between generator expression and generator function

Is there any difference — performance or otherwise — between generator expressions and generator functions?In [1]: def f():...: yield from range(4)...:In [2]: def g():...: return (i for i in…

Django performance testing suite thatll report on metrics (db queries etc.)

I have a complex Django web application that has many person-years of work put into it. It might need optimisation sometime. There are several common operation/flows that I could script with (say) djan…

dev_appserver.py Opens a Text File, Does Not Deploy

It works fine on my other computer, but after setting up Google App Engine and creating the main.py and app.yaml files, I run dev_appserver.py app.yaml in Windows command prompt and instead of deployin…

How to pass a list from a view to template in django

I am trying pass to list from a view to template in Django.In my file wiew.py I define the view named hour # This Python file uses the following encoding: utf-8from django.shortcuts import render from …

Probing/sampling/interpolating VTK data using python TVTK or MayaVi

I would like to visualise a VTK data file (OpenFOAM output) using python. The plot I would like to make is a 1-d line plot of a quantity between two endpoints. To do so, the unstructured data should be…

Make Sphinx generate RST class documentation from pydoc

Im currently migrating all existing (incomplete) documentation to Sphinx.The problem is that the documentation uses Python docstrings (the module is written in C, but it probably does not matter) and t…

inspect.getfile () vs inspect.getsourcefile()

I was just going through the inspect module docs.What exactly is the difference between:inspect.getfile()andinspect.getsourcefile()I get exactly the same file path (of the module) for both.

Get a row of data in pandas as a dict

To get a row of data in pandas by index I can do:df.loc[100].tolist()Is there a way to get that row of data as a dict, other than doing:dict(zip(df.columns.tolist(),df.loc[100], tolist() ))