HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

06-测试和Celery(Testing & Celery)

第 3 / 45 段:Testing(测试)

Django 风格指南 (HackSoft) · 发布 2026-02-05 · 更新 2026-11-11 · 标签:Django、测试、Celery、异步任务

Testing(测试)(续)

project_name/app_name/tests/services/test_a_very_neat_service.py

2. 测试类名

格式:

class TheNameOfTheThingThatIsTestedTests(TestCase):
    pass

示例:

# tests/services/test_a_very_neat_service.py

from django.test import TestCase

class AVeryNeatServiceTests(TestCase):
    """
    测试 a_very_neat_service 服务
    """

    def test_service_does_something_correctly(self):
        # 测试实现
        pass

    def test_service_handles_edge_case(self):
        # 测试实现
        pass

工具函数的测试

对于工具函数的测试,我们遵循类似的模式。

示例 1:单个工具模块

如果我们有:

project_name/common/utils.py

那么测试文件是:

project_name/common/tests/test_utils.py

在该文件中放置不同的测试用例。


示例 2:拆分的工具模块

如果我们将 utils.py 模块拆分为子模块:

源代码:

project_name/common/utils/
├── __init__.py
├── files.py
├── strings.py
└── dates.py

测试代码:

project_name/common/tests/utils/
├── __init__.py
├── test_files.py
├── test_strings.py
└── test_dates.py