summaryrefslogtreecommitdiff
path: root/tests/regressiontests
diff options
context:
space:
mode:
authorJacob Kaplan-Moss <jacob@jacobian.org>2008-08-31 20:10:50 +0000
committerJacob Kaplan-Moss <jacob@jacobian.org>2008-08-31 20:10:50 +0000
commit4ae746b574a84e30a8be4f207c9f386fa09c03f9 (patch)
tree5b77386f6a88c6d4bfcea16829b418f259e66b55 /tests/regressiontests
parent3e71a684b35066285034f05efed5bb83dc1cf644 (diff)
Added a `TypedChoiceField` which acts just like `ChoiceField`, except that it
returns a value coerced by some provided function. Refs #6967. git-svn-id: http://code.djangoproject.com/svn/django/trunk@8771 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'tests/regressiontests')
-rw-r--r--tests/regressiontests/forms/fields.py47
1 files changed, 47 insertions, 0 deletions
diff --git a/tests/regressiontests/forms/fields.py b/tests/regressiontests/forms/fields.py
index cbd59a4089..7f55ec4ead 100644
--- a/tests/regressiontests/forms/fields.py
+++ b/tests/regressiontests/forms/fields.py
@@ -1077,6 +1077,53 @@ Traceback (most recent call last):
...
ValidationError: [u'Select a valid choice. 6 is not one of the available choices.']
+# TypedChoiceField ############################################################
+
+# TypedChoiceField is just like ChoiceField, except that coerced types will
+# be returned:
+>>> f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
+>>> f.clean('1')
+1
+>>> f.clean('2')
+Traceback (most recent call last):
+...
+ValidationError: [u'Select a valid choice. 2 is not one of the available choices.']
+
+# Different coercion, same validation.
+>>> f.coerce = float
+>>> f.clean('1')
+1.0
+
+
+# This can also cause weirdness: be careful (bool(-1) == True, remember)
+>>> f.coerce = bool
+>>> f.clean('-1')
+True
+
+# Even more weirdness: if you have a valid choice but your coercion function
+# can't coerce, you'll still get a validation error. Don't do this!
+>>> f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
+>>> f.clean('B')
+Traceback (most recent call last):
+...
+ValidationError: [u'Select a valid choice. B is not one of the available choices.']
+
+# Required fields require values
+>>> f.clean('')
+Traceback (most recent call last):
+...
+ValidationError: [u'This field is required.']
+
+# Non-required fields aren't required
+>>> f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False)
+>>> f.clean('')
+''
+
+# If you want cleaning an empty value to return a different type, tell the field
+>>> f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None)
+>>> print f.clean('')
+None
+
# NullBooleanField ############################################################
>>> f = NullBooleanField()