Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert_called_with the first call if the method has been called twice in another method?

eg in t.py

def a(obj):
  print obj

def b():
  a(1)
  a(2)

then:

from t import b

with patch('t.a') as m:
  b()
  m.assert_called_with(1)

I get:

AssertionError: Expected call: a(1)
Actual call: a(2)
like image 586
James Lin Avatar asked Jan 10 '23 15:01

James Lin


1 Answers

The most straightforward approach would be to get the first item from mock.call_args_list and check if it is called with 1:

call_args_list

This is a list of all the calls made to the mock object in sequence (so the length of the list is the number of times it has been called).

assert m.call_args_list[0] == call(1)

where call is imported from mock: from mock import call.

Also, mock_calls would work in place of call_args_list too.

Another option would be to use assert_any_call():

m.assert_any_call(1)
like image 59
alecxe Avatar answered Feb 01 '23 05:02

alecxe