蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

创建、更新、删除和依赖覆盖的测试

PYTHONCPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0test_lab.py
test_lab.py203 行
from datetime import datetime,timedelta,timezone
import json
import os
from pathlib import Path
from secrets import token_bytes
import sqlite3

import jwt
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.exc import IntegrityError

from database import SessionLocal,database_path,engine
from db_models import Account,Note
from main import app
from security_lab import (audience,fixture_password,hasher,issue,issuer,members,
                          signing_key,verify_password)
from catalog_lab import get_label,make_catalog


def check(name,inputs,expected,actual,operation="Run the named assertion on the local application."):
    assert actual==expected,(name,inputs,expected,actual)
    if output:=os.environ.get("MBSKY_CASE_OUTPUT"):
        with Path(output).open("a",encoding="utf8") as stream:
            stream.write(json.dumps(dict(name=name,input=inputs,expected=expected,actual=actual,operation=operation),
                                    ensure_ascii=False)+"\n")


def pair(response):
    return [response.status_code,response.json()]


def token_headers(value):
    return {"Authorization":"Bearer "+value}


def test_security_password_and_docs():
    with TestClient(app) as c:
        base={"grant_type":"password","username":"reader","password":fixture_password}
        result=c.post("/token",data=base)
        token=result.json()["access_token"]
        outcome=jwt.decode(token,signing_key,algorithms=["HS256"],issuer=issuer,audience=audience)
        check("password form issues JWT","local synthetic login",[200,"bearer","reader",300,True],
              [result.status_code,result.json()["token_type"],outcome["sub"],outcome["exp"]-outcome["iat"],
               outcome["nbf"]==outcome["iat"]])
        for name,data in (("wrong password",{**base,"password":"wrong"}),
                          ("unknown account",{**base,"username":"absent"}),
                          ("inactive account at login",{**base,"username":"inactive"})):
            r=c.post("/token",data=data)
            check(name,name,[401,"Bearer",{"detail":"credentials invalid"}],
                  [r.status_code,r.headers["www-authenticate"],r.json()])
        missing=c.post("/token",data={k:v for k,v in base.items() if k!="grant_type"})
        check("strict password form needs grant_type","missing grant_type",422,missing.status_code)
        headers=token_headers(token)
        check("current public member","valid bearer",[200,{"handle":"reader","disabled":False}],
              pair(c.get("/members/me",headers=headers)))
        check("protected notes derive owner","valid bearer",[200,[{"title":"北岸","owner":"reader"}]],
              pair(c.get("/members/me/notes",headers=headers)))
        check("inactive bearer rejected","valid token for inactive account",[403,{"detail":"account inactive"}],
              pair(c.get("/members/me",headers=token_headers(issue("inactive")))))
        doc=c.get("/openapi.json").json()
        scheme=doc["components"]["securitySchemes"]["OAuth2PasswordBearer"]
        check("OAuth schema tokenUrl","OpenAPI",[{"OAuth2PasswordBearer":[]}, "token"],
              [doc["paths"]["/members/me"]["get"]["security"][0],scheme["flows"]["password"]["tokenUrl"]])
    first=members["reader"].password_hash
    second=hasher.hash(fixture_password)
    check("Argon2id hash and verify","one synthetic password",[True,True,True,False],
          [first.startswith("$argon2id$"),first!=second,verify_password(fixture_password,second),
           verify_password("wrong",second)],"Hash the same fixture twice and verify correct and wrong input.")


def test_token_rejection_and_alternatives():
    with TestClient(app) as c:
        now=datetime.now(timezone.utc)
        claims={"sub":"reader","iss":issuer,"aud":audience,"iat":now,"nbf":now,"exp":now+timedelta(minutes=5)}
        encode=lambda value,key=signing_key,algorithm="HS256": jwt.encode(value,key,algorithm=algorithm)
        invalid=[
            ("no bearer",{}),("malformed JWT",token_headers("not-a-token")),
            ("invalid signature",token_headers(encode(claims,key=token_bytes(32)))),
            ("algorithm outside allowlist",token_headers(encode(claims,key=token_bytes(48),algorithm="HS384"))),
            ("expired JWT",token_headers(issue("reader",timedelta(seconds=-10)))),
            ("future not-before",token_headers(encode({**claims,"nbf":now+timedelta(minutes=1)}))),
            ("wrong audience",token_headers(encode({**claims,"aud":"other"}))),
            ("wrong issuer",token_headers(encode({**claims,"iss":"other"}))),
            ("missing subject",token_headers(encode({k:v for k,v in claims.items() if k!="sub"}))),
            ("unknown subject",token_headers(issue("absent"))),
        ]
        for name,headers in invalid:
            r=c.get("/members/me",headers=headers)
            check(name,name,[401,"Bearer"],[r.status_code,r.headers["www-authenticate"]])
        accepted=c.get("/legacy-basic",auth=("reader",fixture_password))
        denied=c.get("/legacy-basic",auth=("reader","wrong"))
        check("Basic success and challenge","synthetic credentials",
              [[200,{"channel":"basic"}],401,"Basic"],[pair(accepted),denied.status_code,denied.headers["www-authenticate"]])
        answers=[c.get("/key/header",headers={"X-Lab-Key":"fixture-key"}),
            c.get("/key/query",params={"lab_key":"fixture-key"}),
            c.get("/key/cookie",headers={"Cookie":"lab_key=fixture-key"})]
        check("API keys in three locations","synthetic header, query and cookie",
              [[200,{"channel":v}] for v in ("header","query","cookie")],[pair(r) for r in answers])
        check("API key missing or wrong","none and invalid",[401,401],
              [c.get("/key/header").status_code,c.get("/key/header",headers={"X-Lab-Key":"wrong"}).status_code])


def test_catalog_methods_and_errors():
    lab=make_catalog()
    with TestClient(lab) as c:
        check("TestClient startup and root","GET /",[200,{"ready":True}],pair(c.get("/")))
        original={"name":"北岸","price":4.5}
        check("TestClient POST body",original,[201,{"id":1,**original}],pair(c.post("/samples",json=original)))
        check("TestClient GET record",1,[200,original],pair(c.get("/samples/1")))
        altered={"name":"南岸","price":7.5}
        check("TestClient PUT then GET",altered,[[200,altered],[200,altered]],
              [pair(c.put("/samples/1",json=altered)),pair(c.get("/samples/1"))])
        removed=c.delete("/samples/1")
        check("TestClient DELETE then 404",1,[204,"",[404,{"detail":"sample missing"}]],
              [removed.status_code,removed.content.hex(),pair(c.get("/samples/1"))])
        invalid=c.get("/samples/wrong")
        check("TestClient path error", "wrong",[422,["path","key"]],
              [invalid.status_code,invalid.json()["detail"][0]["loc"]])
        invalid=c.post("/samples",json={"name":"north"})
        check("TestClient body error","price omitted",[422,["body","price"]],
              [invalid.status_code,invalid.json()["detail"][0]["loc"]])
    check("TestClient lifespan shutdown","leave TestClient context",False,lab.state.started)


def test_catalog_request_context_and_override():
    lab=make_catalog()
    with TestClient(lab) as c:
        r=c.get("/context",params={"offset":5,"limit":20},headers={"X-Lab-Tag":"fixture"})
        check("TestClient query and headers","offset=5 limit=20 X-Lab-Tag",
              [200,{"offset":5,"limit":20,"x_lab_tag":"fixture"}],pair(r))
        before=c.get("/label").json()["label"]
        try:
            lab.dependency_overrides[get_label]=lambda:"overridden"
            during=c.get("/label").json()["label"]
        finally:
            del lab.dependency_overrides[get_label]
        after=c.get("/label").json()["label"]
        check("dependency override restored","before, during, after",["live label","overridden","live label"],
              [before,during,after])
    isolated=make_catalog()
    with TestClient(isolated) as c:
        check("factory creates isolated test state","fresh app GET record",404,c.get("/samples/1").status_code)


def test_sqlalchemy_round_trip():
    with TestClient(app) as c:
        app.state.db_events=[]
        data={"email":"local-fixture@example.test","password":"long-local-fixture"}
        create=c.post("/db/accounts",json=data)
        record=create.json()
        key=record["id"]
        check("ORM account output","create independent account",[201,{"id":key,"email":data["email"],"active":True}],
              pair(create))
        check("ORM duplicate and missing account","repeat email and read absent id",[409,404],
              [c.post("/db/accounts",json=data).status_code,c.get("/db/accounts/90000").status_code])
        check("ORM filters and paginates","read with offset 0, limit 1",[[record],[]],
              [c.get("/db/accounts?offset=0&limit=1").json(),c.get("/db/accounts?offset=10000&limit=1").json()])
        new=c.post(f"/db/accounts/{key}/notes",json={"title":"水位记录"})
        note=new.json()["id"]
        check("ORM note owner and missing owner","existing and missing foreign key",
              [[201,{"id":note,"owner_id":key,"title":"水位记录"}],404],
              [pair(new),c.post("/db/accounts/90000/notes",json={"title":"missing"}).status_code])
        with SessionLocal() as session:
            account=session.get(Account,key)
            check("ORM relationship traversal","follow both sides of account-note mapping",
                  [["水位记录"],key],[[row.title for row in account.notes],session.get(Note,note).owner.id])
        replacement=c.put(f"/db/notes/{note}",json={"title":"风向记录"})
        check("ORM update read delete","replace note, list, delete",[200,"风向记录",204,[]],
              [replacement.status_code,c.get("/db/notes").json()[0]["title"],
               c.delete(f"/db/notes/{note}").status_code,c.get("/db/notes").json()])
        events=app.state.db_events
        check("session lifecycle and checkin","successful and failing requests",[True,True,0],
              [all(events[i][0]==events[i+1][0] and events[i][1:]==("open",)
                   and events[i+1][1:]==("close",) for i in range(0,len(events),2)),
               len(events)==len(set(events)),engine.pool.checkedout()])
        connection=sqlite3.connect(database_path)
        try:
            encoded=connection.execute("SELECT password_hash FROM accounts WHERE id=?",(key,)).fetchone()[0]
        finally:
            connection.close()
        check("SQLite stores Argon2id","query disk independently",[True,True,False],
              [encoded.startswith("$argon2id$"),verify_password(data["password"],encoded),encoded==data["password"]])
        with SessionLocal() as session:
            assert session.get(Account,key).email==data["email"]
            session.add(Note(owner_id=90000,title="invalid"))
            with pytest.raises(IntegrityError):
                session.commit()
            session.rollback()
            check("SQLite FK and rollback recovery","direct invalid foreign key then SELECT",data["email"],
                  session.get(Account,key).email)


def test_blog_api_and_contract():
    with TestClient(app) as c:
        check("blog root JSON","GET /",[200,{"message":"欢迎来到蓝色天空网观测日记"}],pair(c.get("/")))
        check("blog dynamic path","GET /hello/蓝湾",[200,{"greeting":"你好,蓝湾"}],pair(c.get("/hello/蓝湾")))
        schema=c.get("/openapi.json").json()
        op=schema["paths"]["/hello/{name}"]["get"]
        check("blog schema metadata","/openapi.json",["蓝色天空网观测日记","1.0.0",True,"string"],
              [schema["info"]["title"],schema["info"]["version"],op["parameters"][0]["required"],
               op["parameters"][0]["schema"]["type"]])
本例需在 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0

入口文件:projects/fastapi-security-database-lab/tests/test_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 test_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:FastAPI

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

下载课程关联工程包:FastAPI

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a182.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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