Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert call to method using Mock python

Tags:

python

mocking

I am trying to do some unit testing using the mock library in Python. I have the following code:

def a():
    print 'a'

def b():
    print 'b'
    if some condition
        a()

How do I assert that a call for b has been made when a mock call to b has been made? I have tried the following code, but it failed:

mymock=Mock()
mymock.b()
assertTrue(a.__call__ in mymock.mock_calls)

For some reason, I think that the mymock.b() has nothing to do with the method b(). What can be done for this?

like image 741
Gaurav Sood Avatar asked Apr 09 '12 19:04

Gaurav Sood


1 Answers

If you patch a, you can ensure it was called like so:

with mock.patch('__main__.a') as fake_a:
    b()
    fake_a.assert_called_with()

If your method is in a different module:

import mymodule

with mock.patch('mymodule.a') as fake_a:
    mymodule.b()
    fake_a.assert_called_with()
like image 65
Sionide21 Avatar answered Sep 26 '22 17:09

Sionide21