|
1 | 1 | from __future__ import unicode_literals
|
2 | 2 | from django.core.validators import MaxValueValidator
|
| 3 | +from django.core.exceptions import ValidationError |
3 | 4 | from django.db import models
|
4 | 5 | from django.test import TestCase
|
5 | 6 | from rest_framework import generics, serializers, status
|
@@ -146,3 +147,42 @@ def test_max_value_validation_fail(self):
|
146 | 147 | response = view(request, pk=obj.pk).render()
|
147 | 148 | self.assertEqual(response.content, b'{"number_value": ["Ensure this value is less than or equal to 100."]}')
|
148 | 149 | self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
| 150 | + |
| 151 | + |
| 152 | +class TestChoiceFieldChoicesValidate(TestCase): |
| 153 | + CHOICES = [ |
| 154 | + (0, 'Small'), |
| 155 | + (1, 'Medium'), |
| 156 | + (2, 'Large'), |
| 157 | + ] |
| 158 | + |
| 159 | + CHOICES_NESTED = [ |
| 160 | + ('Category', ( |
| 161 | + (1, 'First'), |
| 162 | + (2, 'Second'), |
| 163 | + (3, 'Third'), |
| 164 | + )), |
| 165 | + (4, 'Fourth'), |
| 166 | + ] |
| 167 | + |
| 168 | + def test_choices(self): |
| 169 | + """ |
| 170 | + Make sure a value for choices works as expected. |
| 171 | + """ |
| 172 | + f = serializers.ChoiceField(choices=self.CHOICES) |
| 173 | + value = self.CHOICES[0][0] |
| 174 | + try: |
| 175 | + f.validate(value) |
| 176 | + except ValidationError: |
| 177 | + self.fail("Value %s does not validate" % str(value)) |
| 178 | + |
| 179 | + def test_nested_choices(self): |
| 180 | + """ |
| 181 | + Make sure a nested value for choices works as expected. |
| 182 | + """ |
| 183 | + f = serializers.ChoiceField(choices=self.CHOICES_NESTED) |
| 184 | + value = self.CHOICES_NESTED[0][1][0][0] |
| 185 | + try: |
| 186 | + f.validate(value) |
| 187 | + except ValidationError: |
| 188 | + self.fail("Value %s does not validate" % str(value)) |
0 commit comments