以下是三個練習題的具體實現方案,包含完整代碼示例和詳細說明:
練習題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 }}
關鍵配置說明:
-
定時觸發器:使用cron表達式控制執行頻率
-
多Python版本支持:修改
python-version
矩陣 -
依賴緩存優化:
- name: Cache dependenciesuses: actions/cache@v3with:path: ~/.cache/pipkey: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}
-
郵件通知:添加失敗通知配置
- 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>
以上實現方案具有以下生產級特性:
-
錯誤追蹤:在測試報告中直接顯示失敗代碼上下文
-
環境隔離:使用虛擬環境保證測試純凈性
-
敏感信息保護:通過GitHub Secrets管理憑證
-
執行效率優化:并行測試執行配置
strategy:matrix:python-version: ["3.8", "3.9", "3.10"]fail-fast: false
建議將代碼分階段實施,每個功能點完成后運行完整測試套件,確保系統穩定性。