欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 手游 > 33、单元测试实战练习题

33、单元测试实战练习题

2025/4/19 17:13:50 来源:https://blog.csdn.net/ldz_wolf/article/details/147292820  浏览:    关键词: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
    

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词