简体   繁体   中英

Mocking a function called in django form

I have two modules.

a.py

def get_resource(arg1, arg2):
   return Modelobject based on arg1 and arg2 or None

b.py (form)

from a import get_resource
class A(forms.Form):
 arg1 = forms.CharField()
 arg2 = forms.CharField()
 def clean(self):
   res = get_resource(arg1, arg2)
   if res is None:
    validationerror
   else:
    cleaned_data.update(res_key=res)

Now I need to mock the get_resource part so that I donot need any database but I couldnot get it to work.

Here is what I tried but it doesnot work. What am I doing wrong ?

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

Also I tried side_effects with a function

def my_side_effect(*args, **kwargs):
  return value based on arg[0] and arg[1]

mock_tool.side_effect = my_side_effect

Since I am quite novice at mock and testing, Can anyone show me right direction ?

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

a.py

def get_resource(arg1, arg2):
 return arg1

b.py

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'
   else:
    return self.res

test.py

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())

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM