断言在python中用json字符串调用的模拟函数 [英] Assert mocked function called with json string in python
问题描述
在python中编写一些单元测试,并使用MagicMock模拟出接受JSON字符串作为输入的方法.在我的单元测试中,我想断言它是使用给定的参数调用的,但是我遇到了assert语句的问题,因为除字符串的assert语句外,dict中对象的顺序无关紧要.下面是我要实现的目标的简化示例.
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))
以上内容可能会通过,也可能由于字典中的键在转储到json时的键的任意顺序而失败,即'{"a":"a", "b":"b"}'
和'{"b":"b", "a":"a"}'
都是有效的转储,但是其中一个会失败,而一个会通过,但是我想编写测试,以便其中任何一个都可以通过.
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.
推荐答案
不幸的是,您需要在此处进行自己的检查.您可以通过其call_args_list
属性(或简单地
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)
我仍然使用assert_called_once_with
来确保仅使用单个位置参数调用该函数一次,然后使用
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.
这篇关于断言在python中用json字符串调用的模拟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!