django单独测试model方法

python 复制代码
# myapp/models.py

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)
    published_date = models.DateField()
    isbn = models.CharField(max_length=13)

    def __str__(self):
        return self.title

    def is_published(self):
        return self.published_date <= timezone.now().date()

我们有一个Book 模型,并且你希望分别测试每个方法。

python 复制代码
# myapp/tests.py

from django.test import TestCase
from django.utils import timezone
from .models import Book
from datetime import timedelta

class BookModelTest(TestCase):
    def setUp(self):
        # 创建一个用于测试的样例书籍实例
        self.book = Book.objects.create(
            title="测试书籍",
            author="作者名字",
            published_date=timezone.now() - timedelta(days=1),
            isbn="1234567890123"
        )

    def test_is_published_true(self):
        # 测试 is_published 方法,当书籍已出版时
        self.assertTrue(self.book.is_published())

    def test_is_published_false(self):
        # 创建一本具有未来出版日期的书籍
        future_book = Book.objects.create(
            title="未来书籍",
            author="作者名字",
            published_date=timezone.now() + timedelta(days=1),
            isbn="9876543210987"
        )
        # 测试 is_published 方法,当书籍尚未出版时
        self.assertFalse(future_book.is_published())

    def test_string_representation(self):
        # 测试 Book 模型的 __str__ 方法
        self.assertEqual(str(self.book), "测试书籍")

各个测试的解释

  1. test_is_published_true 方法:

    • 测试当书籍的出版日期在过去时,is_published 方法返回 True
  2. test_is_published_false 方法:

    • 为一本未来出版日期的书籍测试 is_published 方法,确保它返回 False
  3. test_string_representation 方法:

    • 测试 __str__ 方法,确认它返回书籍的正确字符串表示形式。

单独运行这些测试

如果你想运行特定的测试,可以在运行 manage.py test 时指定测试方法。例如:

python 复制代码
python manage.py test myapp.tests.BookModelTest.test_is_published_true

这个命令将只运行 test_is_published_true 方法,使你能够隔离并验证模型中单个方法的行为。

如果测试所有方法,运行下面的命令:

python manage.py test myapp

相关推荐
清水白石00813 小时前
从“类型体操”到工程设计:用 Python 解释协变、逆变与不变
网络·windows·python
hrhcode13 小时前
【LangGraph】四.持久化:保存和恢复执行状态
python·ai·langchain·agent·langgraph
xxyy88813 小时前
关于labelimg安装后在标注过程中闪退和死机的问题处理
开发语言·python
北风toto13 小时前
Spring Boot / Spring Cloud 配置文件加密详解:使用 jasypt-spring-boot 实现 ENC() 加密
spring boot·后端·spring cloud
代码羊羊13 小时前
Rust 格式化输出完全攻略:从入门到精通
开发语言·后端·rust
Rust研习社13 小时前
Rust + PostgreSQL 极简技术栈应用开发
开发语言·数据库·后端·http·postgresql·rust
geovindu14 小时前
go:Template Method Pattern
开发语言·后端·设计模式·golang·模板方法模式
卷Java14 小时前
上下文压缩
开发语言·windows·python
AI技术增长14 小时前
Pytorch图像去噪实战(十二):DDPM图像去噪完整训练流程,构建可复现扩散模型工程
pytorch·python·深度学习
白晨并不是很能熬夜14 小时前
【RPC】第 4 篇:服务发现 — Zookeeper + 缓存容错
java·后端·程序人生·缓存·zookeeper·rpc·服务发现