class ExampleSerializer(serializers.Serializer): choice_field = serializers.ChoiceField(['red', 'green', 'blue']) integer_field = serializers.IntegerField(min_value=1, max_value=1000) char_field = serializers.CharField(required=False, min_length=3, max_length=40)
class TestChoiceField(FieldValues): """ Valid and invalid values for `ChoiceField`. """ valid_inputs = { 'poor': 'poor', 'medium': 'medium', 'good': 'good', } invalid_inputs = {'amazing': ['"amazing" is not a valid choice.']} outputs = {'good': 'good', '': ''} field = serializers.ChoiceField(choices=[ ('poor', 'Poor quality'), ('medium', 'Medium quality'), ('good', 'Good quality'), ]) def test_allow_blank(self): """ If `allow_blank=True` then '' is a valid input. """ field = serializers.ChoiceField(allow_blank=True, choices=[ ('poor', 'Poor quality'), ('medium', 'Medium quality'), ('good', 'Good quality'), ]) output = field.run_validation('') assert output == ''
def test_choices(self): """ Make sure a value for choices works as expected. """ f = serializers.ChoiceField(choices=self.CHOICES) value = self.CHOICES[0][0] try: f.to_internal_value(value) except serializers.ValidationError: self.fail("Value %s does not validate" % str(value))
def test_allow_blank(self): """ If `allow_blank=True` then '' is a valid input. """ field = serializers.ChoiceField(allow_blank=True, choices=[ ('poor', 'Poor quality'), ('medium', 'Medium quality'), ('good', 'Good quality'), ]) output = field.run_validation('') assert output == ''
class TestChoiceFieldWithListChoices(FieldValues): """ Valid and invalid values for a `Choice` field that uses a flat list for the choices, rather than a list of pairs of (`value`, `description`). """ valid_inputs = { 'poor': 'poor', 'medium': 'medium', 'good': 'good', } invalid_inputs = {'awful': ['"awful" is not a valid choice.']} outputs = {'good': 'good'} field = serializers.ChoiceField(choices=('poor', 'medium', 'good'))
class TestChoiceFieldWithType(FieldValues): """ Valid and invalid values for a `Choice` field that uses an integer type, instead of a char type. """ valid_inputs = { '1': 1, 3: 3, } invalid_inputs = { 5: ['"5" is not a valid choice.'], 'abc': ['"abc" is not a valid choice.'] } outputs = {'1': 1, 1: 1} field = serializers.ChoiceField(choices=[ (1, 'Poor quality'), (2, 'Medium quality'), (3, 'Good quality'), ])
class ExampleSerializer(serializers.Serializer): choice_field = serializers.ChoiceField(['red', 'green', 'blue']) integer_field = serializers.IntegerField(max_value=10) char_field = serializers.CharField(required=False)