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

相关推荐
非优秀程序员7 小时前
第07章 孙德良的阳谋|《互联网产品恩仇录》
javascript·后端
非优秀程序员7 小时前
第06章 浙江帮的内战|《互联网产品恩仇录》
后端
非优秀程序员7 小时前
第08章 马云的反击|《互联网产品恩仇录》
后端
非优秀程序员7 小时前
题记|《互联网产品恩仇录》
后端·程序员·创业
Gopher_HBo11 小时前
Go CPU 剖析的"地基":信号、CAS、写屏障、无锁环形缓冲
后端
panbook11 小时前
从0到1实现一个分布式时序数据库(二):写入成功之后,如何用 WAL 找回数据
后端
Swot11 小时前
上传一张 4MB 图片,我先后撞上了三层请求体限制
后端
IT_陈寒11 小时前
Vite的HMR把我整不会了:一个生产环境的热更新坑
前端·人工智能·后端
OLRainM11 小时前
实习复盘:大模型网关渠道质量评分实战(二)—— 报错了到底算谁的锅?流式归因与 Token 补账踩过的 8 个真坑
后端
用户9562562542912 小时前
跟做:Firecrawl 单页转 Markdown 再丢进沙箱总结
python·api