Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock - testing if a method is called without specifying arguments

I'm mocking out Django's send_mail function using the Mock library:

from django.core.mail import send_mail
send_mail = Mock()

My problem arises when I want to assert that send_mail was called. I can't use assert_called_with or related methods because they expect arguments, which I won't fully know/don't want to type out (it involves templates) in the testing environment. I just want to know the method has been called. Print statements clearly indicate that it is called, yet if I try this:

self.assertEqual(send_mail.called, True) 

I get an error, as the called attribute is still False. How can I test if a method has been called without having to specify attributes.

like image 589
user1427661 Avatar asked Jan 21 '14 17:01

user1427661


1 Answers

You haven't mocked the send_mail method correctly. You only rebound the name in your own module, not anywhere else.

This would be a correct rebinding:

from django.core import mail
mail.send_mail = Mock()

but it's easier to use the patch() context manager / decorator:

with patch('django.core.mail.send_mail') as mocked_send_mail:
    # run your tests
    self.assertTrue(mocked_send_mail.called)
like image 165
Martijn Pieters Avatar answered Oct 02 '22 00:10

Martijn Pieters