This example shows a simple contact form with three fields. The tests check if the form accepts valid data, rejects an invalid email, and rejects a missing name.
from django import forms
from django.test import TestCase
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
class ContactFormTest(TestCase):
def test_valid_form(self):
form_data = {
'name': 'John Doe',
'email': 'john@example.com',
'message': 'Hello, this is a test message.'
}
form = ContactForm(data=form_data)
self.assertTrue(form.is_valid())
def test_invalid_email(self):
form_data = {
'name': 'John Doe',
'email': 'not-an-email',
'message': 'Hello, this is a test message.'
}
form = ContactForm(data=form_data)
self.assertFalse(form.is_valid())
self.assertIn('email', form.errors)
def test_missing_name(self):
form_data = {
'name': '',
'email': 'john@example.com',
'message': 'Hello, this is a test message.'
}
form = ContactForm(data=form_data)
self.assertFalse(form.is_valid())
self.assertIn('name', form.errors)