django test non-field validation errors

余生颓废 提交于 2020-01-23 00:34:12

问题


What is the django way to test non field specific validation errors?

For example, an email field will test is the text entered is a valid email address, but a non-field error will display above the form, with no relationship to any one field. It would, for instance, say that that email address is already registered.

When testing applications, how do you test these non-field validation errors?

Edit: To make the question more clear. I have a custom validation function, but I'd like to test that it's throwing the errors it's supposed to using the unittest framework provided by Django.

I could call the function directly and test it that way, but that doesn't ensure that it's being used properly in the view (ie: I want to do an integration test).

Thanks.

Edit: I have found the solution as how to test and not validate a field error.

It's done with assertFormError. Change the field name to None and change the error string to a list of error strings.

self.assertFormError(response, 'form', 'field name', 'error') # Test single field error
self.assertFormError(response, 'form', None, ['Error #1.', 'Error #2']) # Test general form errors

回答1:


Just for the sake of having an answer that is correct, even though it is already in the question itself I'll post the answer.

You can test a form for errors by using assertFormError().

Asserts that a field on a form raises the provided list of errors when rendered on the form.

Please note that the form name has to be the name of the form in the context not the actual form you are using for validation.

You can use it as follows for non_field_errors (general errors not related to any field):

self.assertFormError(response, 'form', None, 'Some error')

You can test for a specific field error as follows:

self.assertFormError(response, 'form', 'field_name', 'Some error')

You can also pass in a tuple of errors to test against.

errors = ['some error 1', 'some error 2']
self.assertFormError(response, 'form', 'field_name', errors)



回答2:


write a custom function that validates the fields and call it instead of form.is_valid().

Django docs provides a detialed description about this. check the below link.

https://docs.djangoproject.com/en/dev/ref/forms/validation/#form-field-default-cleaning

For Example: from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    email = forms.EmailField(required=False)
    message = forms.CharField(widget=forms.Textarea)

def clean_message(self):
    message = self.cleaned_data['message']
    num_words = len(message.split())
    if num_words < 4:
        raise forms.ValidationError("Not enough words!")
    return message

Herr clean_message will be my custom validation method



来源:https://stackoverflow.com/questions/10991239/django-test-non-field-validation-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!