Django综合测试失败时应该通过

时间:2016-07-18 20:54:43

标签: python django django-unittest

我正在使用Django创建评估系统;但是,我有一个综合测试通过,我不知道为什么(它应该失败)。在测试中,我将bobenrollment对象的grade字段设置为“Excellent”。从下面的模型中可以看出,Enrollment模型没有成绩字段(没有一个模型可以)。我的印象是模型对象的点符号会访问模型字段(我可能对此不正确)。我不想写无效的测试,所以我想知道是什么让这个测试通过,我该怎么做才能让它破裂。谢谢!

class ClassAndSemesterModelTest(TestCase):

    def add_two_classes_to_semester_add_two_students_to_class(self):
        first_semester = Semester.objects.create(text='201530')
        edClass = EdClasses.objects.create(name='EG 5000') 
        edClass2 = EdClasses.objects.create(name='EG 6000')

        first_semester.classes.add(edClass)
        first_semester.classes.add(edClass2)

        bob = Student.objects.create(name="Bob DaBuilder")
        jane = Student.objects.create(name="Jane Doe")

        bobenrollment = Enrollment.objects.create(student=bob, edclass=edClass)
        janeenrollment = Enrollment.objects.create(student=jane,edclass=edClass)
        bobenrollment2 = Enrollment.objects.create(student=bob,edclass=edClass2)
        janeenrollment2 = Enrollment.objects.create(student=jane,edclass=edClass2)

    def test_students_link_to_enrollments(self):
        self.add_two_classes_to_semester_add_two_students_to_class()
        edclass1 = EdClasses.objects.get(name="EG 5000")
        bob = Student.objects.get(name="Bob DaBuilder")
        #The three lines below are the subject of my question
        bobenrollment = Enrollment.objects.get(edclass=edclass1, student=bob)
        bobenrollment.grade = "Excellent"
        self.assertEqual(bobenrollment.grade, "Excellent")

以下模型:

from django.db import models

class Student(models.Model):
    name = models.TextField(default="") 

    def __str__(self):
        return self.name
    #TODO add models

class EdClasses(models.Model):
    name = models.TextField(default='')
    students = models.ManyToManyField(Student, through="Enrollment")

    def __str__(self):
        return self.name

class Semester(models.Model):
    text = models.TextField(default='201530')
    classes = models.ManyToManyField(EdClasses) 
    def __str__(self):
        return self.text

class Enrollment(models.Model):
    student = models.ForeignKey(Student)
    edclass = models.ForeignKey(EdClasses)

Requirements.txt

beautifulsoup4==4.4.1
Django==1.5.4
ipython==3.1.0
LiveWires==2.0
nose==1.3.3
Pillow==2.7.0
projectname==0.1
pyperclip==1.5.11
pytz==2015.2
requests==2.10.0
selenium==2.53.6
six==1.9.0
South==1.0.2
swampy==2.1.7
virtualenv==1.11.5

1 个答案:

答案 0 :(得分:0)

  

我的印象是模型对象的点符号会访问模型字段(我可能对此不正确)

你对此有所了解。您没有考虑的是您可以动态地向python对象添加属性。例如:

In [1]: class MyClass():
   ...:     pass
   ...:
In [2]: a = MyClass()
In [3]: a.im_a_property = 'hello'
In [4]: print a.im_a_property
hello

如您所见,a实例将具有im_a_propery属性,即使该类未定义。这同样适用于代码中的以下行:

bobenrollment.grade = "Excellent"

Django模型会覆盖此行为,因此您可以无缝地将DB值作为模型实例的属性获取,但实例只是一个常规的python对象。

如果要测试grade属性是否正确保存,则应修改测试以在创建记录时添加grade的值并确保对assert的实例进行反对是你从数据库中读取的那个(即不事先修改它)。