class Student(models.Model): name = models.CharField(max_length=255, help_text="学生姓名") create_time = models.DateTimeField(auto_now_add=True, help_text="创建时间") def __str__(self): return self.name
class Teacher(models.Model): name = models.CharField(max_length=255, help_text="老师姓名") create_time = models.DateTimeField(auto_now_add=True, help_text="创建时间") def __str__(self): return self.name
class Classe(models.Model): name = models.CharField(max_length=255, help_text="班级名称") teacher = models.ForeignKey(Teacher, help_text="老师") create_time = models.DateTimeField(auto_now_add=True, help_text="创建时间") def __str__(self): return self.name
class ClasseStudent(models.Model): student = models.ForeignKey(Student) classe = models.ForeignKey(Classe) create_time = models.DateTimeField(auto_now_add=True, help_text="创建时间") 测试数据
使用factory-boy来辅助构造测试数据,代码如下
class TeacherFactory(factory.DjangoModelFactory): class Meta: model = Teacher
name = factory.Sequence(lambda n: "Teacher #%s" % n)
class StudentFactory(factory.DjangoModelFactory): class Meta: model = Student
name = factory.Sequence(lambda n: "Student #%s" % n)
class ClasseFactory(factory.DjangoModelFactory): class Meta: model = Classe
name = factory.Sequence(lambda n: "Class #%s" % n)
class ClasseStudentFactory(factory.DjangoModelFactory): class Meta: model = ClasseStudent
student = factory.SubFactory(StudentFactory) classe = factory.SubFactory(ClasseFactory) 现在来伪造测试数据
在tests.py添加测试用例
class ModelTestCase(TestCase): def setUp(self): self.teacher_one = TeacherFactory() self.class_one = ClasseFactory(teacher=self.teacher_one) self.class_two = ClasseFactory(teacher=self.teacher_one) for i in range(40): ClasseStudentFactory(student=StudentFactory(), classe=self.class_one) for i in range(40): ClasseStudentFactory(student=StudentFactory(), classe=self.class_two) 可以看到,添加了一个老师,两个班,每个班加入了40个学生