简体   繁体   中英

Mocking, assert_called with, in python

I need to make sure a function is being called with a specific argument in python. I have mocked this function out using magic mock.

self.function = MagicMock()
self.function(subject= "Hello World")

Does something exist along the lines of

self.function.assert_called_with("Hello World")

or

self.function.assert_called_with(subject= "Hello World")

Sorry if this has been asked before, but I've been poking around the mock docs and it doesn't seem like any of the assert statements will work for me.

EDIT: I added some debug output

When I attempt to debug, I see

AssertionError: 
Expected call: mock('Hello World')
Actual call: mock('thing i dont care about', 'Hello World', 'thing i dont care about')

So apparently, the function is being called, but the assert is acting weird. It doesn't recognize "Hello World" in the list of arguments or something.

EDIT2:

I changed up my code a little bit, and it still isn't matching properly

self.function = MagicMock(field1 = None, field2 = None, subject = None, field4 = None)

#later on...
self.function(1,2,"Hello World",4)  #these params will not always be 1,2,4 .. I made them so to
                                     #show an example

#even further down the road
self.function.assert_called_with(ANY, ANY, "Hello World", ANY)

Something like this isn't working for me either. Still getting the error

AssertionError: 
Expected call: mock(<ANY>, <ANY>, "Hello World", <ANY>)
Actual call: mock(1,2,"Hello World", 4)

Again, I couldn't just do something like

How does "ANY" correspond to pattern matching an argument?

What you have written works perfectly as you had intended. Taking out the self, here is a simplified version-

func = mock.MagicMock()
func(subject="Hello World")
# assert that func was indeed called with subject="Hello World"
# this goes well since it was indeed called with "Hello World"
func.assert_called_with(subject="Hello World") 
# this fails since func was not called with "Bye World"
AssertionError: Expected call: mock(subject='Bye World')
Actual call: mock(subject='Hello World') 
# The mock also distinguishes between calls with positional and keyword arguments
# so func(subject="Hello World") is not same as func("Hello World") w.r.t.
# the assert statements

Thats what is expected. So if you want to ensure that the mock function was indeed called with expected arguments, simply use-

func(key=<args>)
func.assert_called_with(key=<args>)

or

func(<args>)
func.assert_called_with(<args>)

Just remember to match the function signature in call and assert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM