You need to enable JavaScript to run this app. Django models.py测试编写方法、测试要点及VS Code运行指导
优惠活动
大模型
产品
解决方案
定价
更多

Django models.py测试编写方法、测试要点及VS Code运行指导

Django 模型测试基础指引(适配你提供的models.py代码)

测试文件规范存放位置

  • Django 内置的测试框架默认会自动识别每个app下的tests.py文件,也可以新建名为tests的Python包,把测试拆成test_models.py、test_views.py等单独模块,不需要额外安装测试依赖包,直接使用Django自带的django.test.TestCase即可完成所有模型测试。

你当前代码需要覆盖的测试范围

按照模型测试的最小必要覆盖原则,针对你定义的三个模型,需要验证的内容包括:

  • 通用基础项
    • 模型实例正常创建、字段值可正确读写
    • 类中定义的__str__方法返回字符串和预期一致
    • 数据库字段约束生效(外键级联规则、唯一值限制、可选空字段的配置符合预期)
  • 各模型专属验证项
    1. Profile模型
      • 和User表的一对一关联绑定正常
      • 删除关联用户时,对应的Profile记录会随用户级联删除
      • institute、department字段允许传空值的特性正常
    2. Access模型
      • 多对多关联用户的绑定、解绑操作正常
      • endpoint字段的unique=True约束生效,重复添加相同endpoint的记录会触发数据库错误
    3. Request模型
      • 自定义的start()方法执行后,created_time字段会被更新为当前时间,且值会同步保存到数据库
      • user字段允许传空值的特性正常

可直接复用的测试代码

把下面的代码放到app下的tests/test_models.py文件中即可运行(如果是新建tests目录,记得在目录下加一个空的__init__.py文件):

from django.test import TestCase
from django.contrib.auth.models import User
from django.utils import timezone
from django.db.utils import IntegrityError
import datetime

# 导入对应模型
from .models import Profile, Access, Request


class ProfileModelTest(TestCase):
    def setUp(self):
        # 每个测试用例执行前自动创建测试用户,无需重复写创建用户的代码
        self.test_user = User.objects.create_user(
            username="test_student",
            email="test@example.com",
            password="testpass123"
        )

    def test_profile_instance_create(self):
        profile = Profile.objects.create(
            user=self.test_user,
            institute="测试大学",
            department="计算机学院"
        )
        self.assertEqual(profile.user, self.test_user)
        self.assertEqual(profile.institute, "测试大学")
        self.assertEqual(profile.department, "计算机学院")

    def test_profile_str_output(self):
        profile = Profile.objects.create(
            user=self.test_user,
            institute="测试大学",
            department="计算机学院"
        )
        expected_output = f"Email:{self.test_user.email} Department:{profile.department} Institute:{profile.institute}"
        self.assertEqual(str(profile), expected_output)

    def test_null_field_allowed(self):
        # 验证两个可选字段为空时可正常创建实例
        profile = Profile.objects.create(user=self.test_user)
        self.assertIsNone(profile.institute)
        self.assertIsNone(profile.department)

    def test_cascade_delete_with_user(self):
        profile = Profile.objects.create(user=self.test_user)
        self.test_user.delete()
        self.assertEqual(Profile.objects.count(), 0)


class AccessModelTest(TestCase):
    def setUp(self):
        self.test_user = User.objects.create_user(
            username="test_researcher",
            email="research@example.com",
            password="testpass123"
        )

    def test_access_instance_create(self):
        access = Access.objects.create(endpoint="pubmed")
        access.user.add(self.test_user)
        self.assertIn(self.test_user, access.user.all())
        self.assertEqual(access.endpoint, "pubmed")

    def test_access_str_output(self):
        access = Access.objects.create(endpoint="foster")
        self.assertEqual(str(access), "foster")

    def test_endpoint_unique_constraint(self):
        Access.objects.create(endpoint="all")
        # 验证重复创建同endpoint的记录会抛出唯一约束错误
        with self.assertRaises(IntegrityError):
            Access.objects.create(endpoint="all")


class RequestModelTest(TestCase):
    def setUp(self):
        self.test_user = User.objects.create_user(
            username="test_api_user",
            email="api@example.com",
            password="testpass123"
        )

    def test_request_instance_create(self):
        req = Request.objects.create(
            url="https://test-api.com/sample",
            user=None
        )
        self.assertEqual(req.url, "https://test-api.com/sample")
        self.assertIsNone(req.user)
        # 验证默认创建时间和当前时间的差值在1秒内
        self.assertAlmostEqual(
            req.created_time,
            timezone.now(),
            delta=datetime.timedelta(seconds=1)
        )

    def test_start_method_functionality(self):
        # 先手动把创建时间设为1小时前
        old_time = timezone.now() - datetime.timedelta(hours=1)
        req = Request.objects.create(
            url="https://test-api.com/sample",
            user=self.test_user,
            created_time=old_time
        )
        # 执行自定义的start方法
        req.start()
        # 验证内存中的实例时间已更新
        self.assertAlmostEqual(
            req.created_time,
            timezone.now(),
            delta=datetime.timedelta(seconds=1)
        )
        # 验证数据库中的记录时间也已同步更新
        db_req = Request.objects.get(id=req.id)
        self.assertAlmostEqual(
            db_req.created_time,
            timezone.now(),
            delta=datetime.timedelta(seconds=1)
        )

在VS Code中运行测试的操作步骤

  • 前置准备:确认VS Code当前选中的Python解释器是你的Django项目对应的虚拟环境
  • 两种运行方式可二选一:
    1. 终端命令运行
      打开VS Code内置终端,执行命令:
      • 仅运行模型测试:python manage.py test 你的app名称.tests.test_models
      • 运行整个app下的所有测试:python manage.py test 你的app名称
    2. 测试面板图形化运行
      打开VS Code侧边栏的烧杯形状测试图标,首次配置时选择unittest作为测试框架,指定测试路径为你app下的tests目录,配置完成后即可在面板中直接点击运行按钮执行测试,同时可以查看测试通过率、失败堆栈信息。

注意:Django执行测试时会自动创建临时测试数据库,测试运行完成后会自动销毁,不会对你本地的正式开发数据库产生任何修改,可放心编写执行测试。

内容的提问来源于stack exchange,提问作者Yashvi Srivastava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.25 13:24:03