当前位置: 首页 > news >正文

33、单元测试实战练习题

以下是三个练习题的具体实现方案,包含完整代码示例和详细说明:


练习题1:TDD实现博客评论功能

步骤1:编写失败测试

# tests/test_blog.py
import unittest
from blog import BlogPost, Comment, InvalidCommentErrorclass TestBlogSystem(unittest.TestCase):def test_create_comment(self):post = BlogPost(title="Python测试教程", content="...")comment = post.add_comment(user="开发者", text="非常实用!")self.assertIsInstance(comment, Comment)self.assertEqual(len(post.comments), 1)def test_comment_validation(self):post = BlogPost(title="TDD实践", content="...")with self.assertRaises(InvalidCommentError):post.add_comment(user="", text="空用户测试")def test_comment_display(self):post = BlogPost(title="测试驱动开发", content="...")post.add_comment(user="Alice", text="清晰易懂")self.assertIn("Alice: 清晰易懂", post.display_comments())

步骤2:实现最小功能

# blog.py
class InvalidCommentError(Exception):passclass Comment:def __init__(self, user, text):self.user = userself.text = textclass BlogPost:def __init__(self, title, content):self.title = titleself.content = contentself.comments = []def add_comment(self, user, text):if not user or not text:raise InvalidCommentError("用户和内容不能为空")comment = Comment(user, text)self.comments.append(comment)return commentdef display_comments(self):return "\n".join([f"{c.user}: {c.text}" for c in self.comments])

步骤3:运行测试

python -m unittest tests/test_blog.py -v

步骤4:重构优化

  • 添加评论时间戳功能
  • 实现评论分级嵌套
  • 添加敏感词过滤机制

练习题2:生成HTML测试报告

安装依赖

pip install pytest-html

配置测试命令

# 生成基础报告
pytest --html=report.html# 带附加信息的报告
pytest --html=detailed_report.html --self-contained-html \--metadata Project "博客系统" \--metadata Environment "测试环境"

示例报告配置类

# conftest.py
def pytest_configure(config):config._metadata["测试类型"] = "单元测试"config._metadata["Python版本"] = "3.9"def pytest_html_report_title(report):report.title = "博客系统测试报告"

高级配置(截取失败用例截图)

# conftest.py
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):outcome = yieldreport = outcome.get_result()if report.when == "call" and report.failed:html = "<div><img src='data:image/png;base64,...'/></div>"report.extra = [pytest_html.extras.html(html)]

练习题3:GitHub Actions每日构建

配置文件路径

.github/workflows/daily-build.yml

name: Daily Buildon:schedule:- cron: '0 0 * * *'  # 每天UTC时间0点运行workflow_dispatch:     # 允许手动触发jobs:build:runs-on: ubuntu-lateststeps:- name: Checkout codeuses: actions/checkout@v3- name: Set up Pythonuses: actions/setup-python@v4with:python-version: '3.10'- name: Install dependenciesrun: |python -m pip install --upgrade pippip install -r requirements.txtpip install pytest pytest-html- name: Run testsrun: pytest --html=report.html --cov=src- name: Upload reportuses: actions/upload-artifact@v3with:name: test-reportpath: report.html- name: Codecov integrationuses: codecov/codecov-action@v3with:token: ${{ secrets.CODECOV_TOKEN }}

关键配置说明:

  1. 定时触发器:使用cron表达式控制执行频率

  2. 多Python版本支持:修改python-version矩阵

  3. 依赖缓存优化

    - name: Cache dependenciesuses: actions/cache@v3with:path: ~/.cache/pipkey: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}
    
  4. 邮件通知:添加失败通知配置

    - name: Send emailif: failure()uses: dawidd6/action-send-mail@v3with:server_address: smtp.example.comserver_port: 587username: ${{ secrets.MAIL_USERNAME }}password: ${{ secrets.MAIL_PASSWORD }}subject: 每日构建失败通知body: 测试用例执行失败,请及时处理!to: dev-team@example.com
    

验证实施效果

测试报告示例

<!-- report.html -->
<html><head><title>博客系统测试报告</title><style>/* 自动生成样式 */</style></head><body><h1>测试覆盖率 92%</h1><table><tr><th>模块</th><th>覆盖率</th></tr><tr><td>blog.py</td><td>100%</td></tr><tr><td>comment.py</td><td>85%</td></tr></table><h2>失败用例追踪</h2><div class="log">AssertionError: 预期8,实际得到9</div></body>
</html>

以上实现方案具有以下生产级特性:

  1. 错误追踪:在测试报告中直接显示失败代码上下文

  2. 环境隔离:使用虚拟环境保证测试纯净性

  3. 敏感信息保护:通过GitHub Secrets管理凭证

  4. 执行效率优化:并行测试执行配置

    strategy:matrix:python-version: ["3.8", "3.9", "3.10"]fail-fast: false
    

建议将代码分阶段实施,每个功能点完成后运行完整测试套件,确保系统稳定性。

相关文章:

  • 数理逻辑(Mathematical Logic)综论与跨学科应用
  • 算力云平台部署—AI数字人视频—未来之窗超算中心
  • 神经隐写术与量子加密:AI生成图像的隐蔽传输——突破数字水印新维度
  • 【算法】快速排序、归并排序(非递归版)
  • 【WPF】 自定义控件的自定义属性
  • git常用修改命令
  • DDD架构设计
  • 数据结构与算法学习导航
  • 【python】pysharm常用快捷键使用-(1)
  • Linux 常用命令总结
  • 个人博客系统后端 - 用户信息管理功能实现指南(上)
  • PTA:模拟EXCEL排序
  • XCZU7EG‑L1FFVC1156I 赛灵思XilinxFPGA ZynqUltraScale+ MPSoC EG
  • jdk node redis nginx mysql直接部署
  • 性能测试方案设计思路总结
  • ADVB发送器设计
  • api护照查验-GO国内护照查验接口-身份安全卫士
  • 操作教程|通过DataEase制作MaxKB系统数据大屏
  • 【前端】跟着maxkb学习流程图画法
  • 【含文档+PPT+源码】基于微信小程序的非遗文化黄梅戏宣传平台的设计与实现
  • 明查|哈佛大学批改美教育部长来信,红笔标出语法错误?
  • 2025年度上海市住房城乡建设管理委工程系列中级职称评审工作启动
  • 央行:当前我国债券市场定价效率、机构债券投资交易和风险管理能力仍有待提升
  • 明明睡够了,怎么还有黑眼圈?可能是身体在求救
  • 金融监管总局:近五年民企贷款投放年平均增速比各项贷款平均增速高出1.1个百分点
  • 调节负面情绪可以缓解慢性疼痛