First time working with MagicMock, and I think I've confused myself.
Testing a django project, so in a file called services.py
I have these important elements (extremely simplified and with many bits cut out, of course)::
from django.template.loader import get_template
class Email:
def send_success_attempt_email(self):
template = get_template('emails/foo.html')
I want to test that when send_success_attempt_email
gets called, get_template
gets called with the correct arguments. So I wrote a test with a patch:
@patch('django.template.loader.get_template')
def test_email_template_should_be_used(self, get_template):
email = Email()
email.send_success_attempt_email()
print(get_template.call_count)
get_template.assert_called_with('emails/foo.html')
Which prints 0
for the call_count
, and spits out the
AssertionError nose.proxy.AssertionError:
Expected call: get_template('emails/foo.html')
Not called
I've seen that a common pitfall is to patch the wrong instance, but I have tried many variations on the patch (for instance, @patch('services.get_template')
) but while that changes the error (nose.proxy.EncodeError: Can't pickle <class 'unittest.mock.MagicMock'>: it's not the same object as unittest.mock.MagicMock
), it does not alleviate it.
I know I must have a fundamental misunderstanding. What is it?