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]])
本例需在 Windows、CPython 3.12、Flask 3.1.3、SQLite 3.53.1、pytest 9.2.0、隔离环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、CPython 3.12、Flask 3.1.3、SQLite 3.53.1、pytest 9.2.0、隔离环境
入口文件:projects/flask-fieldnotes/tests/test_fieldnotes.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
test_fieldnotes.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、CPython 3.12、Flask 3.1.3、SQLite 3.53.1、pytest 9.2.0、隔离环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202611a488.zip
课程关联工程包(登记关联32章) · 含当前章节或实例 · mbskycom202611a482.zip