给定一个视图,使用以下代码从两个字段具有'unique_together'
的模型创建对象:
def form_valid(self, form):
field1 = form.cleaned_data['field1']
field2 = form.cleaned_data['field2']
try:
TheModel.objects.create(org=self.request.org, field1=field1, field2=field2)
except IntegrityError as e:
if 'UNIQUE constraint' in e.message:
messages.error(self.request, _('field1 already exists.'))
return super(ModelFormMixin, self).form_valid(form)
messages.success(self.request, _('Fields have been successfully updated.'))
return super(ModelFormMixin, self).form_valid(form)
当'unique_together'
抛出错误时,我如何进行单元测试以显示错误消息?
我当前的测试会抛出TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
这是目前的测试:
@patch.object(messages, 'error')
def test_error_handling(self, error_mock):
TheModel.objects.create(org=self.org, field1='somepath', field2='anotherpath2')
with transaction.atomic():
response = self.client.post(reverse('configurations.create_amodel', args=(self.org.slug,)),
{'field1': 'somepath', 'field2': 'anotherpath'}, follow=True)
self.assertTrue(error_mock.called)
我无法弄清楚如何使测试工作(测试捕获异常时运行的代码)
这是我的表单类:
class RedirectForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(RedirectForm, self).__init__(*args, **kwargs)
field1 = forms.CharField(label='field1', required=True)
field2 = forms.CharField(label='field2', required=True)
class Meta:
model = TheModel
fields = ('field1', 'field2')
答案 0 :(得分:0)
您可以从响应上下文中获取消息,然后检查您的错误。
messages = list(response.context['messages'])
self.assertEqual(len(messages), 1)
self.assertEqual(str(messages[0]), 'field1 already exists.')
您可以在此处阅读更多内容:How can I unit test django messages?
答案 1 :(得分:0)
我发现使用" TransactionTestCase"可以避免在模型中调用异常的整个问题。而不是" TestCase"在测试类中:
即。
class CreateRedirectViewTests(TransactionTestCase):
调用unique_together
异常时发布错误消息的测试可以通过以下方式完成:
@patch.object(messages, 'error')
def test_error_message(self, error_mock):
self.client.post(reverse('configurations.create_amodel', args=(self.org.slug,)),
{'field1': 'somepath', 'field2': 'anotherpath'}, follow=True)
self.client.post(reverse('configurations.create_amodel', args=(self.org.slug,)),
{'field1': 'somepath', 'field2': 'anotherpath'}, follow=True)
self.assertTrue(error_mock.called)