蓝色天空.知识 · 实践 · 创造
我的收藏
Flask 教程目录 32章
Flask / LEARN BY DOING

Flask 测试客户端与 pytest

用独立数据库夹具实际验证请求、会话、重定向、命令及异常传播。

学完这一章,你能够

  • 用独立数据库夹具实际验证请求、会话、重定向、命令及异常传播。

测试客户端能观察什么

app.test_client() 直接通过 WSGI 驱动应用,不需启动网络服务。用 get、post、put、delete 创建请求。json= 会构造 JSON 正文和媒体类型,data= 可送表单或原始数据。响应提供状态、正文原字节和 JSON 解析结果。

本站断言首页的标题、未知路径的 404,以及创建、列表、更新和删除后的数据变化。另用真实 curl 和浏览器检查本机 HTTP,这两类观察与测试客户端分开记录。

将临时数据库放进夹具

在隔离环境安装 pytest。conftest.py 提供 app、client 和 runner 夹具。pytest 的 tmp_path 每个测试独立;工厂设置 TESTING 与数据库路径,随后 CLI 初始化所需的表。数据库连接由应用上下文结束时关闭。

TESTING 在未显式设置 PROPAGATE_EXCEPTIONS 时会让普通异常传播。本站用受控 RuntimeError 验证,并检查失败请求仍关闭连接。按场景写清测试名和实际预期,便于区分失败分支。

分开测试登录与注入会话

登录测试先取表单令牌,再分别发错误口令、错误令牌及正确输入。follow_redirects=True 可查看最终响应,用 history 检查中间的跳转,本站观察 303 后使用 GET。

session_transaction 适用于直接安排测试会话,再观察后续视图。此路径绕过凭据验证,应与实际登录测试分别断言。

调用 CLI 和运行测试组

app.test_cli_runner() 默认运行应用注册的命令,检查 exit_code 和 output 后仍可单独打开数据库核实效果。routes 属于 Flask 的顶层 CLI,本站显式把 Flask CLI 传给 runner 才运行它。

在工程根目录运行 python -m pytest tests -v 可看到具体测试。也可以按单个文件或名字运行。已运行的工程含 12 个命名测试,另有实际进程 CLI、curl 和浏览器观察。

测试实践

实践用途本机验证
临时数据库每个测试用自己的文件。验证 g、异常清理和另一个应用路径。
TESTING可观察未处理异常,仍受 PROPAGATE_EXCEPTIONS 控制。受控异常传播,连接关闭。
清晰职责每组断言围绕同一行为或流程。测试集拆分连接、会话、CLI 和请求轨迹。
命名名称标明场景与观察目标。pytest 实际发现并执行命名函数。
跟随跳转分别检查中间重定向和最终视图。登录后观察 303 和最终 GET。

运行真实 pytest 并核对会话与 CLI

含完整源码 · 193 行
展开查看收起
python
from contextlib import closing
import json
import re
import sqlite3

import pytest
from flask import abort,current_app,g,has_app_context,has_request_context,request,session

from flask.cli import cli as flask_cli

from fieldnotes import create_app
from flow import capture,create_flow
from ledger import get_db,standalone
from orm_check import run as orm


def test_home_and_absence(client,record):
    home=client.get("/")
    unknown=client.get("/absent")
    record("home and unmatched URL","GET /, /absent","Read real Flask status, text and body bytes",
           [200,True,True,404],[home.status_code,"潮汐便笺" in home.text,b"<!doctype html>" in home.data,unknown.status_code])


def test_creating_listing_updating_and_deleting(client,record):
    row={"title":"  浪高  ","body":"first","operator_id":1}
    new=client.post("/api/notes",json=row)
    post=f"/api/notes/{new.json['id']}"
    index=client.get("/api/notes")
    found=client.get(post)
    update=client.put(post,json={"title":"涨潮","body":"revision"})
    delete=client.delete(post)
    record("JSON API full CRUD and joined row",row,"Create, list, read, replace, delete and recheck missing record",
           [201,"浪高",200,"north","first",200,"涨潮",200,404,404],
           [new.status_code,new.json["title"],index.status_code,index.json[0]["operator"],found.json["body"],
            update.status_code,update.json["title"],delete.status_code,client.get(post).status_code,
            client.delete(post).status_code])


def test_validation_and_foreign_keys(client,record):
    wrong=client.post("/api/notes",json={"title":" ","body":"notes"})
    missing=client.post("/api/notes",json={"title":"wave","body":"note","operator_id":999})
    invalid=client.post("/api/notes",json=[])
    bad_type=client.post("/api/notes",data="note")
    valid=client.post("/api/notes",json={"title":"safe","body":"note"})
    record("request shape title and actual foreign key",["empty title","missing operator","list","text","valid"],
           "Submit independent JSON and media-type branches and inspect table after rejected writes",
           [400,400,400,415,201,1],
           [wrong.status_code,missing.status_code,invalid.status_code,bad_type.status_code,valid.status_code,
            len(client.get("/api/notes").json)])


def test_standalone_parameter_binding_and_orm(client,record,tmp_path):
    label="O'Reef; DROP TABLE note;"
    client.post("/api/notes",json={"title":label,"body":"text"})
    path=tmp_path/"notes.sqlite"
    with closing(sqlite3.connect(path)) as connection:
        actual=connection.execute("SELECT title FROM note WHERE title=?",(label,)).fetchone()[0]
        remaining=connection.execute("SELECT COUNT(*) FROM note").fetchone()[0]
    record("standalone Row bound SQL and ORM insert",label,"Reopen file, retrieve the exact value and run actual SQLite ORM example",
           [{"id":1,"label":"first tide"},label,1,"High tide"],
           [standalone(tmp_path/"standalone.sqlite"),actual,remaining,orm()])


def test_login_and_session_transaction(client,record):
    token=re.search(r'name="token" value="([^"]+)"',client.get("/auth/login").text).group(1)
    form={"operator":"north","password":"fixture-password","token":token}
    wrong=client.post("/auth/login",data={**form,"password":"bad"})
    bad=client.post("/auth/login",data={**form,"token":"bad"})
    result=client.post("/auth/login",data=form,follow_redirects=True)
    isolated=client.application.test_client()
    initial=isolated.get("/")
    with isolated.session_transaction() as state:
        state["operator"]="fixture-operator"
    record("login redirect versus direct session setup",["wrong password","wrong token","valid","test shortcut"],
           "Use real form and redirects, then seed independent cookie through session_transaction",
           [401,400,200,["/"],"GET",True,False,True],
           [wrong.status_code,bad.status_code,result.status_code,[r.headers["Location"] for r in result.history],
            result.request.method,"观测员 north" in result.text,"观测员 north" in initial.text,
            "观测员 fixture-operator" in isolated.get("/").text])


def test_cli_tables_routes_and_idempotence(runner,app,record):
    init=runner.invoke(args=["init-db"])
    routes=runner.invoke(cli=flask_cli,args=["routes"])
    with closing(sqlite3.connect(app.config["DATABASE"])) as conn:
        tables=[r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")]
        accounts=conn.execute("SELECT COUNT(*) FROM operator").fetchone()[0]
    record("Flask CLI runner initializes and lists routes",["init-db","routes"],"Invoke CLI and inspect separate SQLite connection",
           [0,True,0,True,["note","operator"],1],
           [init.exit_code,"tables ready" in init.output,routes.exit_code,"/api/notes" in routes.output,tables,accounts])


def test_connection_context_lifetime_and_testing_mode(tmp_path,record):
    path=tmp_path/"isolated.sqlite"
    connections=[]
    app=create_app({"TESTING":True,"DATABASE":str(path),"CONNECTION_OBSERVER":connections.append})
    @app.get("/same")
    def same():
        return {"same":get_db() is get_db()}
    @app.get("/broken")
    def broken():
        get_db()
        raise RuntimeError("fixture")
    c=app.test_client()
    same=c.get("/same").json["same"]
    with pytest.raises(RuntimeError,match="fixture"):
        c.get("/broken")
    with app.app_context():
        explicit=get_db()
        alive=explicit.execute("SELECT 1").fetchone()[0]
    closed=[]
    for db in connections:
        try:
            db.execute("SELECT 1")
        except sqlite3.ProgrammingError:
            closed.append(True)
    other=create_app({"DATABASE":str(tmp_path/"other.sqlite")})
    record("g connection reuse teardown and fixture isolation","successful and failing requests plus manual context",
           "Verify reuse, distinct connections, teardown on propagated error and separate app path",
           [True,True,1,3,[True]*3,True,False],
           [same,connections[0] is not connections[1],alive,len(connections),closed,
            other.config["DATABASE"]!=str(path),has_app_context()])


def test_app_and_request_proxy_scope(record):
    app=create_flow()
    with app.app_context():
        g.label="temp"
        app_only=(current_app._get_current_object() is app,g.label,has_request_context())
        with pytest.raises(RuntimeError):
            _=request.method
    with app.test_request_context("/record/7?tag=ice"):
        both=(current_app._get_current_object() is app,request.path,request.args["tag"],
              request.view_args["number"],len(session),hasattr(g,"label"))
        hooks_ran=any(e.startswith("before") for e in app.extensions["events"])
    record("app and request proxies have distinct scopes","application context and manually built request",
           "Compare supported proxies, matched typed rule, absence of dispatch and cleanup",
           [[True,"temp",False],[True,"/record/7","ice",7,0,False],False,False,False],
           [list(app_only),list(both),hooks_ran,has_app_context(),has_request_context()])


def test_wsgi_order_and_short_circuit(record):
    normal=capture(create_flow(),"/record/7")
    halt=capture(create_flow(),"/halt")
    expected=["wsgi_entry","appcontext_pushed","request_started","before:record:7","before_second","view:7",
              "after_second","after_first","request_finished:201","start_response:201","teardown_request:NoneType",
              "request_tearing_down:NoneType","teardown_appcontext:True","appcontext_tearing_down","appcontext_popped"]
    record("WSGI matching hooks and short circuit",["/record/7","/halt"],"Capture WSGI status, hook order, and true skipped view",
           [201,{"number":7},expected,202,True,False,False],
           [normal["status"],json.loads(normal["body"]),normal["events"],halt["status"],
            "after_first" in halt["events"],"before_second" in halt["events"],"unexpected_view" in halt["events"]])


def test_return_variants_and_stream_lifetime(record):
    keys=["text","bytes","dict","list","tuple","response","stream","kept"]
    data=[capture(create_flow(),"/return/"+kind) for kind in keys]
    statuses=[x["status"] for x in data]
    types=[x["headers"]["Content-Type"].split(";")[0] for x in data]
    plain,kept=data[-2:]
    record("return conversion and stream context",keys,"Consume actual WSGI body and compare context timing",
           [[200,200,200,200,203,202,200,200],["text/html","text/html","application/json","application/json",
            "text/html","text/plain","text/html","text/html"],"fixture",{"north":1},[1,2],"wave\n","wave\n",True,True,2],
           [statuses,types,data[4]["headers"]["X-Lab"],json.loads(data[2]["body"]),json.loads(data[3]["body"]),
            plain["body"],kept["body"],
            plain["events"].index("iteration_context:False")>plain["events"].index("appcontext_popped"),
            kept["events"].index("appcontext_popped")<kept["events"].index("iteration_context:True")
              <len(kept["events"])-1,kept["events"].count("appcontext_popped")])


def test_signals_and_handled_vs_unhandled(record):
    paths=["/notice","/known","/abort","/fault","/missing"]
    data=[capture(create_flow(),p) for p in paths]
    event_names=("message_flashed:info","template_rendered","handle_lookup","handle_http:404",
                 "got_request_exception:RuntimeError","request_finished:500","teardown_request:RuntimeError")
    record("lifecycle signals and exception paths",paths,"Run template, flash, class handler, abort and unhandled failure",
           [[200,422,404,500,404],[True]*7,False],
           [[x["status"] for x in data],[e in data[i]["events"] for i,e in zip((0,0,1,2,3,3,3),event_names)],
            any(e.startswith("got_request_exception") for e in data[1]["events"])])


def test_security_and_cors_headers(record):
    app=create_flow()
    expected="https://reader.example.test"
    allowed=capture(app,"/cors",method="OPTIONS",headers={"Origin":expected,"Access-Control-Request-Method":"GET"})
    refused=capture(app,"/cors",headers={"Origin":"https://other.example.test"})
    keys=("X-Content-Type-Options","X-Frame-Options","Content-Security-Policy","X-XSS-Protection")
    record("response security and CORS headers","allowlisted Origin and another Origin",
           "Read actual security headers and OPTIONS response without claiming browser enforcement",
           [200,expected,"GET, OPTIONS","Origin",None,["nosniff","DENY","default-src 'self'; frame-ancestors 'none'",None]],
           [allowed["status"],allowed["headers"].get("Access-Control-Allow-Origin"),
            allowed["headers"].get("Access-Control-Allow-Methods"),allowed["headers"].get("Vary"),
            refused["headers"].get("Access-Control-Allow-Origin"),[refused["headers"].get(k) for k in keys]])
12 个测试通过。CLI 真正初始化临时表,实际登录与测试会话分别得到预期结果。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

完整开发工程

解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。

下载本章实验包 (mbskycom202611a488.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Flask

课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202611a488.zip

下载课程关联工程包:Flask

课程关联工程包(登记关联32章) · 含当前章节或实例 · mbskycom202611a482.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

筛选登录和会话相关测试,可分别看到失败与成功分支。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习