Как PrivateFileField обрабатывает валидаторы в django?

class AbstractFirmwareImage(TimeStampedEditableModel):
    build = models.ForeignKey(get_model_name('Build'), on_delete=models.CASCADE)
    file = PrivateFileField(
        'File',
        upload_to=get_build_directory,
        max_file_size=app_settings.MAX_FILE_SIZE,
        storage=app_settings.PRIVATE_STORAGE_INSTANCE,
        max_length=255,
        validators=[MaxLengthValidator(255)],
    )
    type = models.CharField(
        blank=True,
        max_length=128,
        choices=FIRMWARE_IMAGE_TYPE_CHOICES,
        help_text=_(
            'firmware image type: model or '
            'architecture. Leave blank to attempt '
            'determining automatically'
        ),
    )

Я хочу увеличить ограничение на длину имени файла до 255, и это реализовано правильно, что я знаю, так как я проверил это несколько раз на моем локальном сервере. Но когда я проверяю его для большего имени файла, тесты проходят без ошибок? Почему так происходит?

def test_filename_within_limit(self, **kwargs):
        org = kwargs.pop('organization', self._get_org())
        category = kwargs.pop('category', self._get_category(organization=org))
        build1 = self._create_build(category=category, version='0.1')
        file = SimpleUploadedFile('a' * 74763, b'')
        image = self._create_firmware_image(
            build=build1, type=self.TPLINK_4300_IMAGE, file=file
        )
        image.full_clean()

    def test_filename_exceeds_limit(self):
        file = SimpleUploadedFile('a' * 300, b'')
        image = FirmwareImage(file=file)
        with self.assertRaises(ValidationError):
            image.full_clean()
def _create_build(self, **kwargs):
        opts = dict(version='0.1')
        opts.update(kwargs)
        category_opts = {}
        if 'organization' in opts:
            category_opts = {'organization': opts.pop('organization')}
        if 'category' not in opts:
            opts['category'] = self._get_category(**category_opts)
        b = Build(**opts)
        b.full_clean()
        b.save()
        return b

    def _create_firmware_image(self, **kwargs):
        opts = dict(type=self.TPLINK_4300_IMAGE)
        opts.update(kwargs)
        build_opts = {}
        if 'organization' in opts:
            build_opts['organization'] = opts.pop('organization')
        if 'build' not in opts:
            opts['build'] = self._get_build(**build_opts)
        if 'file' not in opts:
            opts['file'] = self._get_simpleuploadedfile()
        fw = FirmwareImage(**opts)
        fw.full_clean()
        fw.save()
        return fw
def full_clean(self, exclude=None, validate_unique=True, validate_constraints=True):
        """
        Call clean_fields(), clean(), validate_unique(), and
        validate_constraints() on the model. Raise a ValidationError for any
        errors that occur.
        """
        errors = {}
        if exclude is None:
            exclude = set()
        else:
            exclude = set(exclude)

        try:
            self.clean_fields(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)

        # Form.clean() is run even if other validation fails, so do the
        # same with Model.clean() for consistency.
        try:
            self.clean()
        except ValidationError as e:
            errors = e.update_error_dict(errors)

        # Run unique checks, but only for fields that passed validation.
        if validate_unique:
            for name in errors:
                if name != NON_FIELD_ERRORS and name not in exclude:
                    exclude.add(name)
            try:
                self.validate_unique(exclude=exclude)
            except ValidationError as e:
                errors = e.update_error_dict(errors)

        # Run constraints checks, but only for fields that passed validation.
        if validate_constraints:
            for name in errors:
                if name != NON_FIELD_ERRORS and name not in exclude:
                    exclude.add(name)
            try:
                self.validate_constraints(exclude=exclude)
            except ValidationError as e:
                errors = e.update_error_dict(errors)

        if errors:
            raise ValidationError(errors)

Интересно, может быть, тесты написаны неправильно или есть проблема с файловым полем.

Вернуться на верх