예제 #1
0
    def test_enumfield_init(self):
        # TEST: initialize EnumField with an instance of Enum
        EnumField(enum=self.Color)
        EnumField(self.Color)

        # TEST: initialize EnumField with non-Enum - throws an error
        expected_error = EnumField.default_error_messages['not_enum']
        for non_enum in [1, 'blah'] + list(EMPTY_VALUES):
            with self.assertRaisesMessage(RuntimeError, str(expected_error)):
                log_input(non_enum)
                EnumField(enum=non_enum)
예제 #2
0
    def test_enumfield_required(self):
        enum_field = EnumField(enum=self.Color)

        # TEST: valid enum value
        valid_val = self.Color.GREEN
        self.assertEqual(valid_val, enum_field.clean(valid_val))

        # TEST: invalid enum value
        invalid_val = 4
        expected_error = EnumField.default_error_messages['invalid']
        expected_error = str([expected_error.format(invalid_val, self.Color)])
        with self.assertRaisesMessage(ValidationError, expected_error):
            enum_field.clean(invalid_val)

        # TEST: required=True - non-None empty values throw an error
        for empty_val in ['', [], (), {}]:
            expected_error = EnumField.default_error_messages['invalid']
            expected_error = str(
                [expected_error.format(empty_val, self.Color)])
            with self.assertRaisesMessage(ValidationError, expected_error):
                log_input(empty_val)
                enum_field.clean(empty_val)

        # TEST: required=True - None throws error
        with self.assertRaisesMessage(ValidationError,
                                      "['This field is required.']"):
            self.assertEqual(valid_val, enum_field.clean(None))
예제 #3
0
    class Create(Form):
        email = fields.EmailField(required=True)
        password = fields.CharField(required=True)
        name = fields.CharField(required=True)
        surname = fields.CharField(required=True)
        phone = fields.CharField(required=False)

        is_active = BooleanField(required=False)
        is_vpn = BooleanField(required=False)

        source = EnumField(enum=User.Source, required=False)
        role = ModelChoiceField(to_field_name='name',
                                queryset=Group.objects.all(),
                                required=True)
        additional_data = AnyField(required=False)

        language_id = ModelChoiceField(queryset=Language.objects.all(),
                                       required=False)

        def clean_username(self):
            if User.objects.filter(
                    username=self.cleaned_data['username']).exists():
                raise ValidationError(
                    _('User with this username already exists!'))
            return self.cleaned_data['username']

        def clean_email(self):
            if User.objects.filter(email=self.cleaned_data['email']).exists():
                raise ValidationError(
                    _('User with this email already exists!'))
            return self.cleaned_data['email']
예제 #4
0
class AlbumForm(Form):
    title = fields.CharField(max_length=100)
    year = fields.IntegerField()
    artist = FormField(form=ArtistForm)
    songs = FormFieldList(form=SongForm)
    type = EnumField(enum=Album.AlbumType, required=True)
    metadata = DictionaryField(fields.DateTimeField())

    def clean_year(self):
        if self.cleaned_data['year'] == 1992:
            raise ValidationError("Year 1992 is forbidden!", 'forbidden-value')
        return self.cleaned_data['year']

    def clean(self):
        if (self.cleaned_data['year']
                == 1998) and (self.cleaned_data['artist']['name']
                              == "Nirvana"):
            raise ValidationError("Sounds like a bullshit",
                                  code='time-traveling')
        return self.cleaned_data

    def fill_artist(self, obj, value: dict):
        return Artist(name=value.get('name'),
                      genres=value.get('genres'),
                      members=value.get('members'))
예제 #5
0
    class Basic(Form):
        name = fields.CharField(max_length=100, required=True)
        type = EnumField(enum=Service.ServiceType, required=True)
        variables = AnyField(required=False)

        remote_id = ModelChoiceField(queryset=Remote.objects.all(),
                                     required=True)

        def clean_name(self):
            if ' ' in self.cleaned_data['name']:
                raise ValidationError(_('Service name cannot contain spaces.'))

            return self.cleaned_data['name']
예제 #6
0
    class Update(Form):
        email = fields.EmailField(required=True)
        name = fields.CharField(required=True)
        surname = fields.CharField(required=True)
        phone = fields.CharField(required=False)

        is_vpn = BooleanField(required=False)
        is_active = BooleanField(required=False)

        source = EnumField(enum=User.Source, required=False)
        role = ModelChoiceField(to_field_name='name',
                                queryset=Group.objects.all(),
                                required=False)
        additional_data = AnyField(required=False)
        assign_projects = FormFieldList(form=AssignProjectsForm,
                                        required=False)

        language_id = ModelChoiceField(queryset=Language.objects.all(),
                                       required=False)
예제 #7
0
    def test_enumfield_required_false(self):
        enum_field = EnumField(enum=self.Color, required=False)

        # TEST: valid enum value
        valid_val = self.Color.BLUE
        self.assertEqual(valid_val, enum_field.clean(valid_val))

        # TEST: required=False - non-None empty values throw an error
        for empty_val in ['', [], (), {}]:
            expected_error = EnumField.default_error_messages['invalid']
            expected_error = str(
                [expected_error.format(empty_val, self.Color)])
            with self.assertRaisesMessage(ValidationError, expected_error):
                log_input(empty_val)
                enum_field.clean(empty_val)

        # TEST: required=False - None allowed
        self.assertIsNone(enum_field.clean(None))
예제 #8
0
 class Basic(Form):
     name = fields.CharField(max_length=100, required=True)
     type = EnumField(enum=ApiKey.ApiKeyType, required=True)
     key = fields.CharField(max_length=100, required=True)
     secret = fields.CharField(max_length=100, required=True)
     is_active = fields.BooleanField(required=False)
 class MyAlbumForm(Form):
     title = fields.CharField(max_length=100)
     year = fields.IntegerField()
     artist_id = ModelChoiceField(queryset=Artist.objects.all())
     type = EnumField(enum=Album.AlbumType, required=True)
예제 #10
0
class UserCatalogForm(Form):
    user_id = forms.ModelChoiceField(queryset=User.objects.all())
    mode = EnumField(UserCatalog.Mode)