assertRaises不会引发ValidationError

时间:2019-10-18 02:40:34

标签: python django

在对ImageField传递无效文件进行测试时,Django断言没有引发 ValidationError 。这是在具有self.assertRaises 上下文的中完成的。但是,当我访问 form.errors.as_data()时,它表明ValidationError在技术上被提出。我不清楚发生了什么。

#tests.py
from django.core.exceptions import ValidationError

class SubmitProfileForm(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.data = {
            'email': 'test@email.com',
            'birth':'2019-01-01',
            'coding_level': 'Hobbyist',
            'bio': 'About me...',
            'github': 'http://www.github.com',
        }
        cls.image = open(join(dirname(__file__), 'images/test_file.txt'), 'rb')
        cls.file = {
            'avatar': SimpleUploadedFile(
                name=cls.image.name,
                content=cls.image.read()
            )
        }

    def test_invalid_file_uploaded(self):
        with self.assertRaises(ValidationError):
            form = ProfileForm(self.data, self.file)
            form.errors
            print(form.errors.as_data())

# forms.py

class ProfileForm(ModelForm):

    class Meta:
        model = Profile
        fields = (
            'email', 'birth', 'coding_level', 'bio', 'github', 'avatar'
        )
# models.py

class Profile(models.Model):

    hobby = "Hobbyist"
    develop = "Developer"
    coding_level = (
        (hobby, hobby),
        (develop, develop)
    )

    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    email = models.EmailField()
    birth = models.DateField(verbose_name="Date Of Birth")
    coding_level = models.CharField(
        verbose_name="Experience",
        max_length=20,
        choices=coding_level, default=hobby, blank=False
    )
    bio = models.TextField(
        verbose_name="User Bio",
        validators=[MinLengthValidator(10, message="Add more to your bio!")]
    )
    github = models.URLField(
        verbose_name="GitHub link",
        validators=[check_submitted_link],
        unique=True
    )
    avatar = models.ImageField(upload_to="images/%Y/%m/%d/")

实际结果:

print(form.errors.as_data())

'''{'avatar': [ValidationError(['Upload a valid image. 
The file you uploaded was either not an image or a corrupted image.'])]}
'''

AssertionError: ValidationError not raised

预期结果:捕获到ValidationError

1 个答案:

答案 0 :(得分:1)

该错误在内部引发,但被Django捕获。 assertRaises仅在引发未捕获的错误时才会触发。类似于执行以下操作:

def index_out_of_bounds():
    array = ["too", "short"]
    try:
        x = array[100]
    except IndexError:
        print("Error!")

index_out_of_bounds()

这将在方法内部引发IndexError,但是由于被捕获,因此也不会触发assertRaises(IndexError)条件。