2016-03-05 49 views
3

我一直在为我的ModelForm编写单元测试,它有一个ModelChoiceField。我使用模拟数据创建Form实例。UnitTest ModelForm具有模型数据的ModelChoiceField

这里是我的模型:

# models.py 
class Menu(models.Model): 
    dish = models.ForeignKey(Dish, default=None) 
    price = models.DecimalField(max_digits=7, decimal_places=2) 

# forms.py 
class MenuForm(forms.ModelForm): 
    class Meta: 
     model = Menu 
     fields = ('dish', 'price',) 

    def clean(self): 
     cleaned_data = super(MenuForm, self).clean() 
     price = cleaned_data.get('price', None) 
     dish = cleaned_data.get('dish', None) 

     # Some validation below 
     if price < 70: 
      self.add_error('price', 'Min price threshold') 
      return cleaned_data 

这里是我的测试案例:

class MenuFormTest(TestCase): 
    def test_price_threshold(self): 
     mock_dish = mock.Mock(spec=Dish) 
     form_data = { 
      'dish': mock_dish, 
      'price': 80, 
     } 
     form = forms.MenuForm(data=form_data) 
     self.assertTrue(form.is_valid()) 

这失败,出现以下错误:

<ul class="errorlist"><li>dish<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul> 

如何使避免抛出错误。那里的form.is_valid()应该是True。有没有办法补丁ModelChoiceField'squeryset?我试图修补形式的dish场像下面clean()方法:

form = forms.MenuForm(data=form_data) 
dish_clean_patcher = mock.patch.object(form.fields['dish'], 'clean') 
dish_clean_patch = dish_clean_patcher.start() 
dish_clean_patch.return_value = mock_dish 

self.assertTrue(form.is_valid()) 

那么它看起来像,同时节省了表格数据实例中_post_clean()方法模式失败。这是回溯:

Traceback (most recent call last): 
    File "/home/vagrant/venv/local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched 
    return func(*args, **keywargs) 
    File "/vagrant/myapp/tests/test_forms.py", line 51, in test_price_threshold 
    self.assertFalse(form.is_valid()) 
    File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/forms.py", line 185, in is_valid 
    return self.is_bound and not self.errors 
    File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/forms.py", line 177, in errors 
    self.full_clean() 
    File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/forms.py", line 396, in full_clean 
    self._post_clean() 
    File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/models.py", line 427, in _post_clean 
    self.instance = construct_instance(self, self.instance, opts.fields, construct_instance_exclude) 
    File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/models.py", line 62, in construct_instance 
    f.save_form_data(instance, cleaned_data[f.name]) 
    File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 874, in save_form_data 
    setattr(instance, self.name, data) 
    File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 632, in __set__ 
    instance._state.db = router.db_for_write(instance.__class__, instance=value) 
    File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/utils.py", line 300, in _route_db 
    if instance is not None and instance._state.db: 
    File "/home/vagrant/venv/local/lib/python2.7/site-packages/mock/mock.py", line 716, in __getattr__ 
    raise AttributeError("Mock object has no attribute %r" % name) 
AttributeError: Mock object has no attribute '_state' 

我该如何避免该部分?我不想让它根本看着instance._state.db

我正在测试表单吗?或者我应该不要致电form.is_valid(),只需拨打form.clean()方法,完全修补super(MenuForm, self).clean()方法,然后检查form.errors

回答

7

我会说打电话form.is_valid()是测试表单的好方法。虽然我不确定是否嘲笑模型。

Internally the form is calling get_limit_choices_to on your dish field(哪个Django当前正在为您创建)。

You would need to mock the dish field's .queryset or get_limit_choices_to here(或调用堆栈中的其他地方,使这里的值无意义)以某种方式实现你想要的。

另外,在测试中创建一个Dish并让Django的内部继续做他们正在做的事情会更简单。

class MenuFormTest(TestCase): 
    def test_price_threshold(self): 
     dish = Dish.objects.create(
      # my values here 
     ) 
     form_data = { 
      'dish': dish.id, 
      'price': 80, 
     } 
     form = MenuForm(data=form_data) 
     self.assertTrue(form.is_valid()) 

如果你真的对不使用Django的测试数据库设置,一个策略可能是嘲笑MenuForm.cleanMenuForm._post_clean

class MenuFormTest(TestCase): 
    def test_price_threshold(self): 
     mock_dish = mock.Mock(spec=Dish) 
     form_data = { 
      'dish': 1, 
      'price': 80, 
     } 
     form = MenuForm(data=form_data) 
     form.fields['dish'].clean = lambda _: mock_dish 
     form._post_clean = lambda : None 
     self.assertTrue(form.is_valid()) 

你需要问自己你的目标是与该考什么如果你打算这样做。

+0

使用'Model.objects.create'似乎是比使用'mock.Mock'更好的选择。我的意思是,为什么要使用图书馆,如果没有它,事情就可以轻松完成。 – xyres

0

如果认为你的测试不是“单位”就够了。你似乎想要测试价格门槛吗?也许你可以做这样的事情:

# forms.py 
class MenuForm(forms.ModelForm): 
    class Meta: 
     model = Menu 
     fields = ('dish', 'price',) 

    def clean(self): 
     cleaned_data = super(MenuForm, self).clean() 
     price = cleaned_data.get('price', None) 
     dish = cleaned_data.get('dish', None) 

     # Some validation below 
     if not self._is_price_valid(price): 
      self.add_error('price', 'Min price threshold') 
      return cleaned_data 

    def _is_price_valid(self, price): 
     return price >= 70 

而且测试:

class MenuFormTest(TestCase): 
    def test_price_threshold(self): 
     form = forms.MenuForm() 
     self.assertTrue(form._is_price_valid(80)) 

我同意,在这个例子中这是一个有点“大材小用”只需添加一个方法TA返回一个简单的比较,但如果你只是想测试价格门槛而不打扰Django内部的表单验证过程,它不是很差的隔离它