PayrollManagementSystem/frontend/e2e/login_flow.py
liuwenxin 273ebf4657 chore: 初始化项目结构与登录鉴权模块
后端 FastAPI 六层结构(api/services/repositories/models/schemas/core),
统一响应信封、全局异常、日志脱敏;6 张表经 Alembic 迁移建库,SQL 留存
db/migration;登录鉴权含图形验证码(Redis GETDEL 防重放)、JWT、登录限流、
登出黑名单(TTL=令牌剩余有效期)、登录日志。

前端 Vue3 + TS + Element Plus 骨架,含登录页、路由守卫、请求封装与 Vite 代理。

工程配置:uv 锁定 Python 3.12、ruff 检查与格式化、editorconfig、gitattributes。

测试 184 项(单元 155 / 集成 29)全绿,浏览器端到端 8 项通过。

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-09 18:46:36 +08:00

191 lines
7.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""浏览器端端到端验证:登录 + 图形验证码。
验证的是**只有真实浏览器才能暴露**的问题:
- 路由守卫是否真的拦住了未登录访问
- 验证码图片能否经 Vite 代理正常渲染(跨前后端的完整链路)
- 登录失败后验证码是否自动刷新 —— 后端用 GETDEL 消费了验证码,
前端不刷新的话第二次提交必然失败,而这个问题在人工测试时极易被忽略
- 刷新页面能否用 /me 恢复会话
- 登出后令牌是否立即失效
**运行前置**(缺一不可)::
docker compose -f docker/docker-compose.dev.yml up -d # MySQL + Redis
cd backend && uv run uvicorn app.main:app --port 8000 # 后端
cd frontend && pnpm dev # 前端
运行::
cd frontend && python e2e/login_flow.py
依赖:Python `playwright` 包与 chromium(`python -m playwright install chromium`)。
"""
import os
import subprocess
import sys
from playwright.sync_api import Page, sync_playwright
BASE_URL = "http://127.0.0.1:5173"
USERNAME = "admin"
PASSWORD = "Admin@2026"
REDIS_CONTAINER = "ys-redis-dev"
def _redis_password() -> str:
"""从 docker/.env 读取 Redis 密码。
测试脚本无法用应用配置(那需要后端 venv),故直接读环境文件。
"""
if value := os.environ.get("REDIS_PASSWORD"):
return value
env_file = os.path.join(os.path.dirname(__file__), "..", "..", "docker", ".env")
with open(env_file, encoding="utf-8") as handle:
for line in handle:
if line.startswith("REDIS_PASSWORD="):
return line.split("=", 1)[1].strip()
raise RuntimeError("未能从 docker/.env 读取 REDIS_PASSWORD")
def redis_get(key: str) -> str | None:
"""读取 Redis 键值。仅用于自动化测试 —— 生产当然不能这样取验证码答案。"""
result = subprocess.run(
["docker", "exec", REDIS_CONTAINER, "redis-cli", "-a", _redis_password(),
"--no-auth-warning", "get", key],
capture_output=True, text=True, encoding="utf-8", check=False,
)
return result.stdout.strip() or None
def _fail(step: str, detail: str) -> None:
print(f" ✗ {step}:{detail}")
sys.exit(1)
def run(page: Page) -> None:
captured_captcha_ids: list[str] = []
console_errors: list[str] = []
def on_response(response) -> None:
if "/api/v1/auth/captcha" not in response.url or response.status != 200:
return
try:
captured_captcha_ids.append(response.json()["data"]["captcha_id"])
except Exception:
# 页面导航后响应体已不可读(Playwright 会抛协议错误)。
# 事件回调里未捕获的异常会成为不稳定的噪声来源,故静默跳过。
pass
page.on("response", on_response)
page.on("console", lambda msg: console_errors.append(msg.text) if msg.type == "error" else None)
page.on("pageerror", lambda exc: console_errors.append(str(exc)))
def at_dashboard() -> bool:
"""判断是否真的在首页。
不能用 `**/dashboard` 这类 glob —— 它会把
`/login?redirect=/dashboard` 也匹配上,导致"登录失败"被误判为成功。
"""
from urllib.parse import urlparse
return urlparse(page.url).path == "/dashboard"
def toast_text() -> str:
locator = page.locator(".el-message")
return locator.first.text_content().strip() if locator.count() else ""
# ---- 1. 路由守卫:未登录访问首页应被拦回登录页 ----
page.goto(BASE_URL, wait_until="networkidle")
if "/login" not in page.url:
_fail("路由守卫", f"未登录访问首页未被拦截,当前 URL={page.url}")
print(f"✓ 1. 路由守卫 未登录访问 / → 重定向到 {page.url}")
# ---- 2. 验证码渲染(证明 浏览器→Vite代理→uvicorn→Redis 全链路通)----
image = page.locator(".captcha__image img")
image.wait_for(state="visible", timeout=10_000)
src = image.get_attribute("src") or ""
if not src.startswith("data:image/png;base64,"):
_fail("验证码渲染", f"图片 src 前缀异常:{src[:40]}")
if len(src) < 1000:
_fail("验证码渲染", f"图片数据过小({len(src)}),可能未真正渲染")
print(f"✓ 2. 验证码渲染 PNG base64 长度 {len(src)}(代理链路已通)")
# ---- 3. 输错验证码 → 应提示且验证码自动刷新 ----
first_id = captured_captcha_ids[-1]
page.fill('input[autocomplete="username"]', USERNAME)
page.fill('input[autocomplete="current-password"]', PASSWORD)
page.fill('input[autocomplete="off"]', "XXXX")
page.click("button:has-text('登 录')")
page.wait_for_timeout(1500)
if "/login" not in page.url:
_fail("失败处理", f"登录失败后不应离开登录页,当前 URL={page.url}")
second_id = captured_captcha_ids[-1]
if second_id == first_id:
_fail("验证码刷新", "登录失败后验证码未刷新 —— 第二次提交必然报「验证码错误」")
print("✓ 3. 失败自动刷新 验证码已换新(GETDEL 消费后的必要处理)")
# ---- 4. 正确登录 ----
answer = redis_get(f"ys:captcha:{second_id}")
if not answer:
_fail("取验证码", f"Redis 中未找到 ys:captcha:{second_id}")
page.fill('input[autocomplete="off"]', answer)
page.click("button:has-text('登 录')")
page.wait_for_timeout(2000)
if not at_dashboard():
detail = f"仍停留在 {page.url}"
if message := toast_text():
detail += f",提示:{message}"
if console_errors:
detail += f",控制台错误:{console_errors[:3]}"
_fail("登录", detail)
page.wait_for_load_state("networkidle")
print(f"✓ 4. 登录成功 跳转到 {page.url}")
if USERNAME not in page.content():
_fail("用户信息", "首页未显示当前用户名")
print("✓ 5. 用户信息 首页已展示当前账号")
# ---- 6. 刷新页面 → 守卫应调用 /me 恢复会话 ----
page.reload(wait_until="networkidle")
if "/dashboard" not in page.url:
_fail("会话恢复", f"刷新后被踢回登录页,当前 URL={page.url}")
print("✓ 6. 会话恢复 刷新页面后仍保持登录(/me 恢复成功)")
# ---- 7. 登出 → 令牌立即失效 ----
page.click("text=退出登录")
page.wait_for_url("**/login**", timeout=10_000)
print(f"✓ 7. 登出 回到 {page.url}")
page.goto(f"{BASE_URL}/dashboard", wait_until="networkidle")
page.wait_for_timeout(1000)
if at_dashboard():
_fail("登出失效", "登出后仍能访问受保护页面")
print("✓ 8. 令牌失效 登出后直接访问 /dashboard 被拦回登录页")
def main() -> int:
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=True)
page = browser.new_page()
page.set_default_timeout(10_000)
try:
run(page)
except Exception as exc: # noqa: BLE001 — 测试脚本需要打印完整失败原因
page.screenshot(path="e2e/failure.png", full_page=True)
print(f"\n✗ 执行中断:{type(exc).__name__}: {exc}")
print(" 已保存截图 e2e/failure.png")
return 1
finally:
browser.close()
print("\n全部通过。")
return 0
if __name__ == "__main__":
raise SystemExit(main())