Ticket #13184: test_form.py

File test_form.py, 2.8 KB (added by Mark, 14 years ago)
Line 
1from django.conf import settings
2settings.configure(
3 DATABASE_ENGINE = 'sqlite3',
4 DATABASE_NAME = ':memory:',
5 installed_apps = ('test_form',),
6 DEBUG = True
7)
8
9from django.db import models
10from django.core import exceptions
11from django import forms
12
13import unittest
14
15class CoreValidationError(Exception):
16 """
17
18 The "inner" python type doesn't need to know about django at all, so we pretend,
19 that a different exception is raised
20 """
21 pass
22
23class TestType(object):
24
25 def __init__(self, text):
26 if text != 'foo':
27 raise CoreValidationError('The value must be "foo", received "%s"' % text)
28 self.data = text
29
30class TestFieldSubfieldBase(models.Field):
31 __metaclass__ = models.SubfieldBase
32
33 def __init__(self, *args, **kwargs):
34 super(TestFieldSubfieldBase, self).__init__(*args, **kwargs)
35
36 def to_python(self, value):
37 if isinstance(value, TestType):
38 return value
39 if value is None or value == '':
40 return None
41 try:
42 return TestType(value)
43 except CoreValidationError, e:
44 raise exceptions.ValidationError(str(e))
45
46class TestField(models.Field):
47
48 def __init__(self, *args, **kwargs):
49 super(TestField, self).__init__(*args, **kwargs)
50
51 def to_python(self, value):
52 if isinstance(value, TestType):
53 return value
54 if value is None or value == '':
55 return None
56 try:
57 return TestType(value)
58 except CoreValidationError, e:
59 raise exceptions.ValidationError(str(e))
60
61class MyModel(models.Model):
62
63 class Meta:
64 app_label = 'test_form'
65
66 field_with_subfieldbase = TestFieldSubfieldBase(blank=True)
67 field_without_subfieldbase = TestField(blank=True)
68
69
70class MyForm(forms.ModelForm):
71
72 class Meta:
73 model = MyModel
74
75
76class TestValidation(unittest.TestCase):
77
78 def test_valid_value_with_subfieldbase(self):
79 form = MyForm(data={u'field_with_subfieldbase':u'foo'})
80 print form.errors
81 self.assertTrue(form.is_valid())
82
83 def test_invalid_value_with_subfieldbase(self):
84 form = MyForm(data={u'field_with_subfieldbase':u'bar'})
85 self.assertFalse(form.is_valid())
86
87 def test_valid_value_without_subfieldbase(self):
88 form = MyForm(data={u'field_without_subfieldbase':u'foo'})
89 self.assertTrue(form.is_valid())
90
91 def test_invalid_value_without_subfieldbase(self):
92 form = MyForm(data={u'field_without_subfieldbase':u'bar'})
93 self.assertFalse(form.is_valid())
94
95if __name__ == '__main__':
96 suite = unittest.TestLoader().loadTestsFromTestCase(TestValidation)
97 unittest.TextTestRunner(verbosity=2).run(suite)
Back to Top