[Answer]-Mocking a function called in django form


UPDATE: I guess I found out what the issue is. Although I have a hard time understanding why this happens it all depends on the imports. Apparently, I need to import the form class inside the patch and define the return value after I instantiate the form so:

class Test(TestCase):
  def test_form_a(self):
    with patch('b.get_resource') as mock_tool:
      from b import A
      form_data = {'arg1': '1', 'arg2': 'Music'}
      form = A(data=form_data)
      mock_tool.return_value = MagicMock(spec=MusicModel)

I guess its all due to module loading.


I’m not familiar with django form, so basically I modified your script in a proper testable way. It seems the tests are all passed, maybe you omit some cause-the-error codes in the question? However the following is a working example for your reference.

% nosetests test.py
test_no_patch_a (test.Test) … ok
test_patch_a (test.Test) … ok


def get_resource(arg1, arg2):
 return arg1


from a import get_resource
class A(object):
 arg1 = 'arg1'
 arg2 = 'arg2'
 res = None
 def __init__(self, data):
   self.res = get_resource(data['arg1'], data['arg2'])

 def bow(self):
   if self.res is None:
    return 'validationerror'
    return self.res


import unittest
from mock import patch
from b import A

class Test(unittest.TestCase):
  def test_patch_a(self):
    with patch('b.get_resource') as mock_tool:
      mock_tool.return_value = 'patched'
      data = {'arg1': '1', 'arg2': 'Music'}
      form = A(data=data)
      self.assertEqual('patched', form.bow())

  def test_no_patch_a(self):
    data = {'arg1': '1', 'arg2': 'Music'}
    form = A(data=data)
    self.assertEqual('1', form.bow())

Leave a comment