1

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?

fildred13
  • 2,280
  • 8
  • 28
  • 52
  • 1
    Possible duplicate of [Python Mocking a method from an imported module](http://stackoverflow.com/questions/16134281/python-mocking-a-method-from-an-imported-module) – Dan Getz Apr 14 '16 at 03:28
  • I agree, it could be a duplicate, but looking at the answers of that question, I would expect `@patch('services.get_template')` to work, but it throws the strange error which I have edited into my questions to highlight the oddness. – fildred13 Apr 14 '16 at 03:34
  • Nope, that second error isn't actually related to the patch being incorrect, it is something else. The error message threw me because I thought I was just still constructing the patch wrong. – fildred13 Apr 14 '16 at 03:52
  • Try patching `...services.get_template` instead as services might be loaded before you patch and has kept the original `get_template` reference before you patch it – Marco A. Apr 14 '16 at 07:15

0 Answers0