Django为数据库的ORM写测试例(TestCase)

时间:2023-12-25 18:58:37

models.py里的数据库定义如下:

from django.db import models

# Create your models here.

class Teachers(models.Model):

    name = models.CharField(max_length=32)

class Classes(models.Model):

    title = models.CharField(max_length=32)
    a = models.ManyToManyField(Teachers)

class Students(models.Model):
    username = models.CharField(max_length=32)
    age = models.IntegerField()
    gender = models.BooleanField()
    cs = models.ForeignKey(Classes, on_delete=models.CASCADE)

tests.py里的内容如下,注意红色部分,是比较麻烦一点的,要构建好相关的orm语句及使用assertIn之类的来测试。

from django.test import TestCase
from .models import Students, Teachers, Classes

# Create your tests here.

class ModelTest(TestCase):

    def setUp(self):
        t1 = Teachers.objects.create(name="Mrs. Chane")
        t2 = Teachers.objects.create(name="Mss. Fang")
        Teachers.objects.create(name="ABC")
        c1 = Classes(title="123")
        c1.save()
        c1.a.add(t1)
        c1.a.add(t2)
        c1.save()
        Students.objects.create(username="bb",
                                age=23,
                                gender=True,
                                cs=c1)

    def test_teacher_models(self):
        result = Teachers.objects.get(name="Mrs. Chane")
        self.assertEqual(result.name, "Mrs. Chane")

    def test_class_models(self):
        t1 = Teachers.objects.get(name="Mrs. Chane")
        t2 = Teachers.objects.get(name="Mss. Fang")
        t3 = Teachers.objects.get(name="ABC")
        result = Classes.objects.get(title=")
        self.assertEqual(result.title, "123")
        self.assertIn(t1, result.a.all())
        self.assertIn(t2, result.a.all())
        self.assertNotIn(t3, result.a.all())

    def test_student_models(self):
        result = Students.objects.get(username="bb")
        self.assertEqual(result.age, 23)
        c1 = Classes.objects.get(title=")
        self.assertEqual(result.cs, c1)
        self.assertEqual(result.gender, True)