萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Flask 單元測試與錯誤處理:pytest、自定義錯誤頁、郵件報警實戰

為什麼需要測試?

手動測試不具備可重複性、回歸防禦。自動化測試能在重構、升級依賴、新增功能時,**瞬間驗證既有功能未破壞**。

測試環境建置

pip install pytest pytest-cov factory-boy

# conftest.py
import pytest
from app import create_app, db

@pytest.fixture
def app():
    app = create_app('testing')
    with app.app_context():
        db.create_all()
        yield app
        db.drop_all()

@pytest.fixture
def client(app):
    return app.test_client()

測試配置 config.py

class TestingConfig(Config):
    TESTING = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
    WTF_CSRF_ENABLED = False
    MAIL_SUPPRESS_SEND = True

模型測試範例 tests/test_models.py

def test_user_avatar(app):
    from models import User
    u = User(nickname='john', email='john@example.com')
    assert u.avatar(128) == 'https://www.gravatar.com/avatar/...'

def test_follow_unfollow(app):
    from models import User
    u1 = User(nickname='john', email='john@example.com')
    u2 = User(nickname='susan', email='susan@example.com')
    db.session.add_all([u1, u2])
    db.session.commit()
    
    assert u1.is_following(u2) is False
    u1.follow(u2)
    db.session.commit()
    assert u1.is_following(u2) is True
    assert u1.followed.count() == 1
    u1.unfollow(u2)
    db.session.commit()
    assert u1.is_following(u2) is False

視圖測試範例 tests/test_views.py

def test_login_logout(client):
    # 登入頁面
    rv = client.get('/login')
    assert rv.status_code == 200
    
    # 提交登入 (模擬 OpenID 回調略)
    # ...
    
    # 登出
    rv = client.get('/logout', follow_redirects=True)
    assert b'Sign In' in rv.data

自定義錯誤頁面

# views.py
@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_error(error):
    db.session.rollback()
    return render_template('500.html'), 500

# templates/404.html
{% extends "base.html" %}
{% block content %}
<h1>頁面不存在 (404)</h1>
<p><a href="{{ url_for('index') }}">回首頁</a></p>
{% endblock %}

# templates/500.html
{% extends "base.html" %}
{% block content %}
<h1>伺服器內部錯誤 (500)</h1>
<p>管理員已收到通知,請稍後再試。</p>
<p><a href="{{ url_for('index') }}">回首頁</a></p>
{% endblock %}

錯誤郵件通知

# config.py
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USE_SSL = True
MAIL_USERNAME = 'alerts@example.com'
MAIL_PASSWORD = 'app-password'
ADMINS = ['admin@example.com']

# app/__init__.py (僅非 DEBUG 時啟用)
if not app.debug:
    import logging
    from logging.handlers import SMTPHandler
    mail_handler = SMTPHandler(
        mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
        fromaddr=app.config['MAIL_USERNAME'],
        toaddrs=app.config['ADMINS'],
        subject='Microblog 伺服器錯誤',
        credentials=(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']),
        secure=()
    )
    mail_handler.setLevel(logging.ERROR)
    app.logger.addHandler(mail_handler)

執行測試

# 執行所有測試並顯示覆蓋率
pytest --cov=app --cov-report=term-missing

# 僅執行特定模組
pytest tests/test_models.py -v

結語

**測試金字塔**:大量單元測試(模型/工具函式)+ 適量整合測試(視圖/API)+ 少量 E2E 測試。配合 **CI/CD 管線強制跑測試**,讓 Bug 無處遁形。錯誤頁面友善化 + 郵件報警,讓生產環境異常可見、可控、可追蹤。

copyright © 萬盛學電腦網 all rights reserved