簡體   English   中英

Django-如何編寫單元測試以檢查是否由ModelForm clean()針對ManyToMany關系引發ValidationError?

[英]Django - How to write unit test checking if ValidationError was raised by ModelForm clean() for ManyToMany relationship?

我的模型中有ManyToMany字段,我以僅為此目的創建的ModelForm形式為其編寫了自定義驗證。 驗證工作正常,但我不知道如何正確編寫單元測試。

#models.py

class Course(models.Model):
    # some code
    max_number_of_students = models.PositiveSmallIntegerField(
        default=30)

class ClassOccurrence(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE)    
    students = models.ManyToManyField(User, blank=True)
    # some code
# forms.py

class ClassOccurrenceForm(forms.ModelForm):
    # some code

    def clean(self):
        # Checks if number of students inscribed is not greater than allowed
        # for the course
        cleaned_data = super(ClassOccurrenceForm, self).clean()
        students = cleaned_data.get('students')
        course = cleaned_data.get('course')
        if students and course:
            if students.count() > course.max_number_of_students:
                raise ValidationError({
                    'students': "Too many students!})
        return cleaned_data

問題出在這部分:

# tests.py

    # some code
    def test_clean_number_of_students_smaller_than_max_students_number(self):        
        self.course_0.max_number_of_students = 5
        self.course_0.save()
        users = UserFactory.create_batch(10)
        self.assertRaises(ValidationError, self.class_occurrence_0.students.add(*users))      
        try:
            self.class_occurrence_0.students.add(*users)                
        except ValidationError as e:
            self.assertEqual(e.errors, {'students': ["Too many students!"]})

目前,它無法正常工作。 在測試方法中,似乎沒有在應該引發的地方引發ValidationError。 有人可以幫我解決嗎?

所以這似乎可行:

    #tests.py
    def test_clean_number_of_students_smaller_than_max_students_number(self):
        '''Check if number of students is not bigger than maximum number'''
        self.course_0.max_number_of_students = 5
        self.course_0.save()
        users = UserFactory.create_batch(10)
        form = ClassOccurrenceForm(
            {'students':[*users], 'course': self.course_0.pk}, 
            instance=self.class_occurrence_0
        )
        self.assertEqual(form.errors, 
            {'students': ["Too many students!"]})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM