33、单元测试实战练习题

发布于:2025-04-19 ⋅ 阅读:(26) ⋅ 点赞:(0)

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


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

步骤1:编写失败测试

# tests/test_blog.py
import unittest
from blog import BlogPost, Comment, InvalidCommentError

class 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):
    pass

class Comment:
    def __init__(self, user, text):
        self.user = user
        self.text = text

class BlogPost:
    def __init__(self, title, content):
        self.title = title
        self.content = content
        self.comments = []
    
    def add_comment(self, user, text):
        if not user or not text:
            raise InvalidCommentError("用户和内容不能为空")
        
        comment = Comment(user, text)
        self.comments.append(comment)
        return comment
    
    def 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 = yield
    report = 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 Build

on:
  schedule:
    - cron: '0 0 * * *'  # 每天UTC时间0点运行
  workflow_dispatch:     # 允许手动触发

jobs:
  build:
    runs-on: ubuntu-latest
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v3
    
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.10'
    
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt
        pip install pytest pytest-html
    
    - name: Run tests
      run: pytest --html=report.html --cov=src
    
    - name: Upload report
      uses: actions/upload-artifact@v3
      with:
        name: test-report
        path: report.html
    
    - name: Codecov integration
      uses: codecov/codecov-action@v3
      with:
        token: ${{ secrets.CODECOV_TOKEN }}

关键配置说明:

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

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

  3. 依赖缓存优化

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

    - name: Send email
      if: failure()
      uses: dawidd6/action-send-mail@v3
      with:
        server_address: smtp.example.com
        server_port: 587
        username: ${{ 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
    

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


网站公告

今日签到

点亮在社区的每一天
去签到