0

Consider the following test method:

@patch("api.views.my_views.MyViewSet.send_customer_request")
def test_process_customers(self, send_customer_request_mock):

    process_customers(123, 456)
    # The above call eventually results in a call to send_customer_request
    # Note that my test does NOT call send_customer_request() directly.  It's a couple calls deep.

    expected_params = {
        "names": ["Rupert", "Steve"],
    }
    
    send_customer_request_mock.assert_called_with(expected_params)

This test passes some of the time, and fails other times. The problem is that the order of the names is nondeterministic. Sometimes it is called with ["Rupert", "Steve"], and sometimes it is called with ["Steve", "Rupert"].

I need to assert that exactly those two names are in the list, but without requiring the specific order that they're in.

Unfortunately, assert_called_with() expects a single exact value for the mocked method to be called with, but it's impossible to know exactly what it will be.

Ideally, I'd like to just retrieve the values that send_customer_request() gets called with, and then write my own assert statements/logic to test the values.

How can I achieve that?

JoeMjr2
  • 3,804
  • 4
  • 34
  • 62
  • Is [call_args_list](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_args_list) what you need? You can retrieve call arguments, make `set` from them and compare with expected set. – STerliakov May 25 '22 at 23:43
  • You could write something like: `for name in ['Steve', 'Rupert']: assert name in send_customer_request_mock.call_args[0]` – larsks May 26 '22 at 00:46
  • @larsks Thanks! Yes, call_args was what I needed. Worked great! – JoeMjr2 May 26 '22 at 15:10

0 Answers0