初版:小白超人(从线上实例导出)

This commit is contained in:
deploy
2026-10-29 15:20:39 +08:00
commit b77a309873
100 changed files with 32168 additions and 0 deletions
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""重打 1.zip:最新代码;排除安装包/数据/凭据/缓存。
完成后解压冒烟:路由 + DOM 配平 + 聚类 NaN 防线 + 测试可收集。"""
import re
import shutil
import subprocess
import sys
import tempfile
import zipfile
from pathlib import Path
ROOT = Path(__file__).parent.parent
ZIP = ROOT / "1.zip"
EXCLUDE_DIR_PARTS = {"__pycache__", ".pytest_cache", ".reasonix", "backups",
"artifacts", ".git", "downloads"}
EXCLUDE_SUFFIX = (".pyc", ".pyo", ".log", ".tmp", ".bak", ".zip", ".db", ".db-wal",
".db-shm", ".pem", ".key", ".crt", ".exe", ".sqlite")
EXCLUDE_STEMS = ("token_config", "smtp_config", "admin_config", "secret_key")
def excluded(rel: Path) -> bool:
if set(rel.parts) & EXCLUDE_DIR_PARTS:
return True
if rel.suffix.lower() in EXCLUDE_SUFFIX:
return True
stem = rel.name.lower()
return stem == ".pack_baseline.json" or any(stem.startswith(p) for p in EXCLUDE_STEMS)
files = [(p, p.relative_to(ROOT).as_posix())
for p in sorted(ROOT.rglob("*"))
if p.is_file() and not excluded(p.relative_to(ROOT))]
if ZIP.exists():
ZIP.unlink()
with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
for p, arc in files:
zf.write(p, arc)
zf = zipfile.ZipFile(ZIP)
names = zf.namelist()
print(f"OK 1.zip: {len(names)} 文件, {ZIP.stat().st_size / 1048576:.2f} MB")
bad = [n for n in names
if n.lower().endswith((".exe", ".db", ".pem", ".key", ".crt", ".zip", ".log"))
or any(k in n.lower() for k in ("token_config", "smtp_config", "admin_config",
"secret_key", "users.db", "pack_baseline"))]
print("敏感审计:", ("!! " + str(bad)) if bad else "干净")
zf.close()
# ---------- 解压冒烟 ----------
stage = Path(tempfile.mkdtemp(prefix="xbniu_smoke_"))
zipfile.ZipFile(ZIP).extractall(stage)
ok = True
probe = (
"import sys, tempfile\n"
"from pathlib import Path\n"
f"sys.path.insert(0, r'{stage}')\n"
"import app as app_mod\n"
"import db\n"
"h = tempfile.NamedTemporaryFile(suffix='.db', delete=False); h.close()\n"
"db.DB_PATH = Path(h.name)\n"
"db.init_db()\n"
"rules = sorted(str(x) for x in app_mod.app.url_map.iter_rules())\n"
"need = ['/api/order/preview', '/api/order/add_round', '/api/map/freshness',\n"
" '/api/history/stats', '/api/campus/locations']\n"
"missing = [p for p in need if p not in rules]\n"
"print('routes:', 'OK' if not missing else missing)\n"
"sys.exit(1 if missing else 0)\n"
)
r = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True,
cwd=str(stage))
print(" ", (r.stdout or "").strip() or (r.stderr or "")[:200])
ok = ok and r.returncode == 0
html = (stage / "templates/map.html").read_text(encoding="utf-8")
o, c = (len(re.findall(r"<div\b", html)), len(re.findall(r"</div>", html)))
print(f" map.html div 配平: {o}/{c} {'OK' if o == c else '!!'}")
ok = ok and o == c
js = (stage / "static/js/map.js").read_text(encoding="utf-8")
c1 = "const CLUSTER_ZOOM = 18" in js
c2 = js.count("parseFloat(b.latitude) && parseFloat(b.longitude)") >= 2
c3 = "if (!isFinite(gx) || !isFinite(gy)) return;" in js
print(f" 聚类阈值18: {'OK' if c1 else '!!'};NaN防线: {'OK' if c2 and c3 else '!!'}")
ok = ok and c1 and c2 and c3
r2 = subprocess.run([sys.executable, "-m", "pytest", "--collect-only", "-q"],
capture_output=True, text=True, cwd=str(stage))
tail = (r2.stdout or "").strip().splitlines()
print(" pytest 收集:", tail[-1] if tail else "(无)")
ok = ok and bool(tail and "test" in tail[-1].lower())
shutil.rmtree(stage, ignore_errors=True)
print("冒烟结果:", "通过" if ok else "失败")
sys.exit(0 if ok else 1)
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""按本次口径重打 1.zip:最新代码,不含安装包(160MB 抓包工具)与任何数据/凭据。
范围与 pack_zip.ps1 一致(源码+模板+静态+测试+脚本),额外排除:
- downloads/*.exe 安装包(用户本次明确要求不带)
- *.db / *.db-* 数据库(含 WAL/SHM 旁文件)
- *.pem *.key *.crt 密钥与证书
- token/smtp/admin/secret 配置及其 .old-bak 备份
- __pycache__/.pytest_cache/.reasonix/backups/日志/临时产物
打包后逐条目审计 + 解压冒烟(init_db + pytest 采集)确保可运行。
"""
import zipfile
from pathlib import Path
ROOT = Path(__file__).parent.parent
ZIP = ROOT / "1.zip"
EXCLUDE_DIR_PARTS = {"__pycache__", ".pytest_cache", ".reasonix", "backups",
"artifacts", ".git", "downloads"}
EXCLUDE_SUFFIX = (".pyc", ".pyo", ".log", ".tmp", ".bak", ".zip", ".db", ".db-wal",
".db-shm", ".pem", ".key", ".crt", ".exe", ".sqlite")
EXCLUDE_NAMES = {"token_config.txt", "token_config.txt.old-bak", "smtp_config.txt",
"admin_config.txt", "secret_key.txt", "users.db", "bikes.db",
"server_config.json.keep", ".pack_baseline.json.keep"}
# scripts/.pack_baseline.json 是打包增量快照(运行时产物),一并排除
EXCLUDE_NAMES.add(".pack_baseline.json")
def excluded(rel: Path) -> bool:
parts = set(rel.parts)
if parts & EXCLUDE_DIR_PARTS:
return True
if rel.name in EXCLUDE_NAMES:
return True
if rel.suffix.lower() in EXCLUDE_SUFFIX:
return True
# token/smtp/admin/secret 任何变体
stem = rel.name.lower()
if any(stem.startswith(p) for p in
("token_config", "smtp_config", "admin_config", "secret_key")):
return True
return False
files = []
for p in sorted(ROOT.rglob("*")):
if not p.is_file():
continue
rel = p.relative_to(ROOT)
if excluded(rel):
continue
files.append((p, rel.as_posix()))
if ZIP.exists():
ZIP.unlink()
with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
for p, arc in files:
zf.write(p, arc)
# ---------- 审计 ----------
zf = zipfile.ZipFile(ZIP)
names = zf.namelist()
size_mb = ZIP.stat().st_size / 1048576
print(f"✓ 1.zip 重打包完成: {len(names)} 个文件, {size_mb:.1f} MB")
bad = [n for n in names
if n.lower().endswith((".exe", ".db", ".pem", ".key", ".crt", ".zip", ".log"))
or any(k in n.lower() for k in
("token_config", "smtp_config", "admin_config", "secret_key",
"users.db", "pack_baseline"))]
print(f"敏感/大文件审计: {'发现!! ' + str(bad) if bad else '干净(无 exe/db/密钥/token)'}")
required = ["app.py", "db.py", "campus.py", "alerts.py", "subscribe.py",
"wechat.py", "timer.py", "email_utils.py", "email_verify.py",
"routes/rental.py", "routes/admin.py", "routes/share.py",
"routes/auth.py", "routes/map_api.py", "routes/export.py",
"routes/subscribe.py", "routes/download.py",
"templates/map.html", "templates/admin.html", "templates/analysis.html",
"static/js/map.js", "static/css/map.css",
"scripts/pack_zip.ps1", "tests/test_history_30d.py",
"tests/test_rounds_and_preview.py", "tests/test_code_mail.py"]
missing = [r for r in required if r not in names]
print(f"关键文件校验: {'缺失!! ' + str(missing) if missing else '全部在位'}")
zf.close()
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""重打 1.zip:最新代码,不含安装包(160MB 抓包工具)与任何数据/凭据。
范围:源码+模板+静态+测试+脚本(与 git 最新提交一致)。
排除:exe/db(含wal,shm)/pem/key/crt/zip/token|smtp|admin|secret 配置及备份/
缓存/日志/artifacts/backups/打包基线快照。
打包后:逐条目审计 + 关键文件校验。
"""
import zipfile
from pathlib import Path
ROOT = Path(__file__).parent.parent
ZIP = ROOT / "1.zip"
EXCLUDE_DIR_PARTS = {"__pycache__", ".pytest_cache", ".reasonix", "backups",
"artifacts", ".git", "downloads"}
EXCLUDE_SUFFIX = (".pyc", ".pyo", ".log", ".tmp", ".bak", ".zip", ".db", ".db-wal",
".db-shm", ".pem", ".key", ".crt", ".exe", ".sqlite")
EXCLUDE_STEMS = ("token_config", "smtp_config", "admin_config", "secret_key")
def excluded(rel: Path) -> bool:
if set(rel.parts) & EXCLUDE_DIR_PARTS:
return True
if rel.suffix.lower() in EXCLUDE_SUFFIX:
return True
stem = rel.name.lower()
if stem == ".pack_baseline.json":
return True
if any(stem.startswith(p) for p in EXCLUDE_STEMS):
return True
return False
files = [(p, p.relative_to(ROOT).as_posix())
for p in sorted(ROOT.rglob("*"))
if p.is_file() and not excluded(p.relative_to(ROOT))]
if ZIP.exists():
ZIP.unlink()
with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
for p, arc in files:
zf.write(p, arc)
# ---------- 审计 ----------
zf = zipfile.ZipFile(ZIP)
names = zf.namelist()
size_mb = ZIP.stat().st_size / 1048576
print(f"OK 1.zip 打包完成: {len(names)} 个文件, {size_mb:.2f} MB")
bad = [n for n in names
if n.lower().endswith((".exe", ".db", ".pem", ".key", ".crt", ".zip", ".log"))
or any(k in n.lower() for k in
("token_config", "smtp_config", "admin_config", "secret_key",
"users.db", "pack_baseline"))]
print(f"敏感/大文件审计: {'发现!! ' + str(bad) if bad else '干净(无 exe/db/密钥/token)'}")
required = ["app.py", "db.py", "campus.py", "alerts.py", "subscribe.py",
"wechat.py", "timer.py", "email_utils.py", "email_verify.py",
"routes/rental.py", "routes/admin.py", "routes/share.py",
"routes/auth.py", "routes/map_api.py", "routes/export.py",
"routes/subscribe.py", "routes/download.py",
"templates/map.html", "templates/admin.html", "templates/analysis.html",
"static/js/map.js", "static/css/map.css",
"scripts/pack_zip.ps1",
"tests/test_history_30d.py", "tests/test_rounds_and_preview.py",
"tests/test_code_mail.py"]
missing = [r for r in required if r not in names]
print(f"关键文件校验: {'缺失!! ' + str(missing) if missing else f'全部在位({len(required)} 项)'}")
# 最新修复是否入包(登录门 DOM 修复在 map.html,聚类修复在 map.js)
newest = ["templates/map.html", "static/js/map.js"]
print(f"最新提交产物: {'在位' if all(n in names for n in newest) else '!! 缺失'}")
zf.close()
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""真实启动冒烟测试: 执行 app.py 的完整启动序列并验证 HTTP 服务可响应。
唯一差异: start_rental_timer 被置空, 避免测试期间触发真实提醒邮件/自动还车。"""
import sys
import threading
import time
import urllib.request
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # 项目根
import timer
timer.start_rental_timer = lambda *a, **k: None # 防止测试期间发出真实邮件
import app as app_module
app_module.init_db()
app_module.backup_database()
print("[smoke] init_db + backup 完成")
app_module.restore_active_timers()
app_module.start_all_order_checkers()
app_module.start_snapshot_scheduler()
PORT = 9987
t = threading.Thread(
target=lambda: app_module.app.run(host="127.0.0.1", port=PORT, debug=False),
daemon=True,
)
t.start()
# 等待服务就绪
ok = False
for _ in range(30):
time.sleep(0.3)
try:
with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/", timeout=3) as r:
body = r.read(200)
print(f"[smoke] GET / -> {r.status}, body[:60]={body[:60]!r}")
ok = r.status == 200
break
except Exception:
continue
# 再打两个关键接口
for path in ("/api/config", "/api/history/stats"):
try:
with urllib.request.urlopen(f"http://127.0.0.1:{PORT}{path}", timeout=5) as r:
print(f"[smoke] GET {path} -> {r.status}")
except Exception as e:
print(f"[smoke] GET {path} -> 异常 {e}")
ok = False
import os
os._exit(0 if ok else 1)
+96
View File
@@ -0,0 +1,96 @@
const path = require('path');
const fs = require('fs');
const { chromium } = require('playwright');
const root = path.resolve(__dirname, '..');
const outputDir = path.join(root, 'artifacts', 'screenshots');
const edgePath = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';
const pages = [
{ name: 'map', url: 'http://127.0.0.1:98/', settle: 1600, closeVersion: true },
{ name: 'map-authenticated', url: 'http://127.0.0.1:98/', settle: 1800, closeVersion: true, authenticatedUser: true },
{ name: 'analysis', url: 'http://127.0.0.1:98/analysis.html', settle: 1200 },
{ name: 'ring-progress', url: 'http://127.0.0.1:98/ring_progress.html?task_id=preview&total=24', settle: 700 },
{ name: 'admin-login', url: 'http://127.0.0.1:98/admin/login', settle: 700 },
{ name: 'admin-dashboard', url: 'http://127.0.0.1:98/admin', settle: 1200, authenticated: true },
];
function readAdminCredentials() {
const config = fs.readFileSync(path.join(root, 'admin_config.txt'), 'utf8');
const values = {};
for (const line of config.split(/\r?\n/)) {
const separator = line.indexOf('=');
if (separator > 0) values[line.slice(0, separator).trim()] = line.slice(separator + 1).trim();
}
if (!values.admin_username || !values.admin_password) {
throw new Error('admin_config.txt 中缺少管理员账号或密码');
}
return { username: values.admin_username, password: values.admin_password };
}
(async () => {
fs.mkdirSync(outputDir, { recursive: true });
const browser = await chromium.launch({ executablePath: edgePath, headless: true });
const context = await browser.newContext({
viewport: { width: 1440, height: 900 },
colorScheme: 'dark',
deviceScaleFactor: 1,
});
for (const item of pages) {
const page = await context.newPage();
page.on('dialog', dialog => dialog.dismiss());
if (item.authenticatedUser) {
const token = process.env.XBNIU_CAPTURE_TOKEN;
if (!token) throw new Error('缺少 XBNIU_CAPTURE_TOKEN');
await page.addInitScript(value => localStorage.setItem('auth_token', value), token);
}
if (item.authenticated) {
const credentials = readAdminCredentials();
await page.goto('http://127.0.0.1:98/admin/login', { waitUntil: 'domcontentloaded' });
await page.locator('#username').fill(credentials.username);
await page.locator('#password').fill(credentials.password);
await Promise.all([
page.waitForURL('**/admin'),
page.getByRole('button', { name: '登录', exact: true }).click(),
]);
}
await page.goto(item.url, { waitUntil: 'domcontentloaded' });
await page.waitForTimeout(item.settle);
if (item.authenticated) {
// 只修改截图页面中的 DOM,避免将真实邮箱与凭据编号写入图片。
await page.locator('.tab-content.active tbody tr').evaluateAll(rows => {
for (const row of rows) {
const cells = row.querySelectorAll('td');
if (cells[1]) cells[1].textContent = '••••••@•••';
if (cells[2]) cells[2].textContent = '••••••';
}
});
}
if (item.authenticatedUser) {
// 截图只展示登录后的主界面,忽略测试账号的过期凭据提示。
await page.addStyleTag({
content: '#token-expired-modal, .login-gate, .toast, #loading { display: none !important; }',
});
}
if (item.closeVersion) {
const close = page.locator('#version-modal .auth-close');
if (await close.isVisible()) {
await close.click();
await page.waitForTimeout(300);
}
// 本地截图环境不在百度地图 AK 的 Referer 白名单中,隐藏该环境提示。
await page.locator('.toast').evaluateAll(elements => {
for (const element of elements) {
if (element.textContent.includes('地图初始化失败')) element.classList.remove('show');
}
});
await page.addStyleTag({ content: '.toast { display: none !important; }' });
}
await page.screenshot({ path: path.join(outputDir, `${item.name}.png`) });
await page.close();
}
await browser.close();
console.log(outputDir);
})();
+96
View File
@@ -0,0 +1,96 @@
# -*- coding: utf-8 -*-
"""CDP driver v4: supports 'inject' step that pastes a value before eval."""
import json, sys, asyncio, io
import websockets
WS = None
console_msgs = []
page_errors = []
pending = {}
_id = [0]
async def connect(target_url_sub):
global WS
import urllib.request
data = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json").read().decode())
page = [t for t in data if t.get("type") == "page" and target_url_sub in t.get("url", "")]
if not page:
page = [t for t in data if t.get("type") == "page"]
WS = await websockets.connect(page[0]["webSocketDebuggerUrl"], max_size=50*1024*1024)
async def send(method, params=None):
_id[0] += 1
msg = {"id": _id[0], "method": method}
if params: msg["params"] = params
await WS.send(json.dumps(msg))
return _id[0]
async def recv_loop():
try:
while True:
raw = await WS.recv()
msg = json.loads(raw)
m = msg.get("method", "")
if m == "Runtime.consoleAPICalled":
args = [a.get("value", a.get("description", "")) for a in msg["params"].get("args", [])]
console_msgs.append((msg["params"].get("type", "log"), " ".join(str(a) for a in args)[:1000]))
elif m == "Runtime.exceptionThrown":
d = msg["params"]["exceptionDetails"]
txt = d.get("exception", {}).get("description") or d.get("text", "")
page_errors.append(txt[:1000])
elif "id" in msg and msg["id"] in pending:
fut = pending.pop(msg["id"])
if not fut.done():
fut.set_result(msg)
except Exception as e:
console_msgs.append(("driver-error", str(e)))
async def wait_for(rid, timeout=25):
loop = asyncio.get_event_loop()
fut = loop.create_future()
pending[rid] = fut
return await asyncio.wait_for(fut, timeout)
async def eval_js(expr, await_promise=False, timeout=25):
rid = await send("Runtime.evaluate", {"expression": expr, "returnByValue": True,
"awaitPromise": await_promise})
resp = await wait_for(rid, timeout)
r = resp.get("result", {})
if r.get("exceptionDetails"):
return {"__error__": (r["exceptionDetails"].get("exception", {}) or {}).get("description") or r["exceptionDetails"].get("text", "")}
return r.get("result", {}).get("value")
async def main(script, dbg_token):
await connect("127.0.0.1:98")
recv_task = asyncio.create_task(recv_loop())
rid = await send("Runtime.enable"); await wait_for(rid, 10)
rid = await send("Page.enable"); await wait_for(rid, 10)
for step in script:
kind = step.get("op", "eval")
if kind == "sleep":
await asyncio.sleep(step["ms"] / 1000)
continue
if kind == "nav":
rid = await send("Page.navigate", {"url": "http://127.0.0.1:98/"})
await wait_for(rid, 15)
continue
expr = step["expr"].replace("window.__DBG_TOKEN__", json.dumps(dbg_token))
try:
val = await eval_js(expr, await_promise=step.get("await", False))
except Exception as e:
val = {"__driver_error__": str(e)}
print("STEP", step.get("label", ""), "=>", json.dumps(val, ensure_ascii=False, default=str)[:2500])
await asyncio.sleep(1.2)
print("\n=== CONSOLE ===")
for t, m in console_msgs[-120:]:
print(f"[{t}] {m}")
print("\n=== PAGE ERRORS ===")
for e in page_errors[-40:]:
print(e)
recv_task.cancel()
if __name__ == "__main__":
with io.open(sys.argv[1], "r", encoding="utf-8") as f:
script = json.load(f)
token = io.open(sys.argv[2], "r", encoding="utf-8").read().strip()
asyncio.run(main(script, token))
+116
View File
@@ -0,0 +1,116 @@
param([switch]$Full)
# 增量更新包生成(update.zip)
# 用法: pwsh -File scripts/pack_update.ps1 → 增量 update.zip(不含 160MB 安装包)
# pwsh -File scripts/pack_update.ps1 -Full → 全量 1.zip(含安装包)
# 只打包「相对上次基准后有变化/新增」的文件 —— 用于覆盖式部署,避免重传 60MB 安装包等未变动内容。
#
# 基准机制:
# scripts/.pack_baseline.json 记录上次打包时每个文件的 (路径, 大小, 哈希)。
# 没有基准 = 首次全量(等价 1.zip,但不包含 downloads/*.exe 大文件——安装包基本不变,
# 如需全量含安装包用 -Full 开关)。
# 删除处理:基准里有、现在没有的文件会写入 update.zip 根的 _deleted.txt(部署时按行删)。
# 部署方式:解压覆盖到项目根即可(zip 内保留相对路径)。
$ErrorActionPreference = 'Stop'
$src = Split-Path -Parent $PSScriptRoot
$outZip = if ($Full) { Join-Path $src "1.zip" } else { Join-Path $src "update.zip" }
$baselinePath = Join-Path $PSScriptRoot ".pack_baseline.json"
$stage = Join-Path $env:TEMP "xbniu_update_stage"
$include = @(
'.gitignore','LICENSE','README.md','app.py','db.py','campus.py','alerts.py','subscribe.py',
'email_utils.py','email_verify.py','generate_icons.py','pytest.ini','rate_limit.py',
'rental_mail.py','requirements.txt','server_config.json','timer.py',
'update_creds_from_capture.py','wechat.py'
)
$dirs = @('routes','templates','static','scripts','tests')
$bigDirs = @('downloads') # 大文件(160MB 安装包),仅 -Full 时纳入
function Get-PackFiles {
param([switch]$WithBig)
$files = @()
foreach ($f in $include) {
$p = Join-Path $src $f
if (Test-Path $p) { $files += (Get-Item $p).FullName }
}
$allDirs = $dirs + $(if ($WithBig) { $bigDirs } else { @() })
foreach ($d in $allDirs) {
$s = Join-Path $src $d
if (-not (Test-Path $s)) { continue }
Get-ChildItem $s -Recurse -File | ForEach-Object {
$rel = $_.FullName.Substring($src.Length).TrimStart('\')
if ($rel -match '(^|[\\/])(__pycache__|\.pytest_cache|\.reasonix|backups)([\\/]|$)') { return }
if ($rel -match '\.(pyc|pyo|log|tmp|bak|zip)$') { return }
if ((Split-Path $rel -Leaf) -in @('.gitignore', '.pack_baseline.json')) { return }
$files += $_.FullName
}
}
return $files
}
function Get-FileKey($file) {
$item = Get-Item $file
$hash = (Get-FileHash $file -Algorithm SHA256).Hash
return @{ path = $file.Substring($src.Length + 1).Replace('\', '/'); size = $item.Length; hash = $hash }
}
$hasBaseline = (Test-Path $baselinePath) -and (-not $Full)
$baseline = @{}
if ($hasBaseline) {
try { $baseline = @(Get-Content $baselinePath -Raw -Encoding UTF8 | ConvertFrom-Json) } catch { $hasBaseline = $false }
}
# 当前全部打包文件(update 不含大文件;-Full 全量含大文件)
$current = Get-PackFiles -WithBig:$Full
$changed = @()
foreach ($f in $current) {
$key = Get-FileKey $f
$old = $baseline | Where-Object { $_.path -eq $key.path }
if (-not $hasBaseline -or -not $old -or $old.hash -ne $key.hash -or $old.size -ne $key.size) {
$changed += $f
}
}
# 被删除的文件(基准有、现在没有)
$deleted = @()
if ($hasBaseline) {
$currentRel = @($current | ForEach-Object { $_.Substring($src.Length + 1).Replace('\', '/') })
foreach ($old in $baseline) {
if ($currentRel -notcontains $old.path) { $deleted += $old.path }
}
}
if ($changed.Count -eq 0 -and $deleted.Count -eq 0) {
Write-Host "✓ 无任何变化,不需要生成更新包"
exit 0
}
# 建 stage(保持相对路径)
Remove-Item $stage -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Path $stage | Out-Null
foreach ($f in $changed) {
$rel = $f.Substring($src.Length + 1)
$target = Join-Path $stage $rel
$targetDir = Split-Path $target -Parent
if (-not (Test-Path $targetDir)) { New-Item -ItemType Directory -Path $targetDir -Force | Out-Null }
Copy-Item -LiteralPath $f -Destination $target -Force
}
if ($deleted.Count) {
Set-Content -Path (Join-Path $stage "_deleted.txt") -Value $deleted -Encoding UTF8
}
# 打包
Add-Type -AssemblyName System.IO.Compression.FileSystem
if (Test-Path $outZip) { Remove-Item $outZip -Force }
[System.IO.Compression.ZipFile]::CreateFromDirectory($stage, $outZip, [System.IO.Compression.CompressionLevel]::Optimal, $false)
# 更新基准
$allKeys = @()
foreach ($f in (Get-PackFiles -WithBig:$Full)) { $allKeys += Get-FileKey $f }
$allKeys | ConvertTo-Json -Depth 3 | Set-Content -Path $baselinePath -Encoding UTF8
$sizeKB = [math]::Round((Get-Item $outZip).Length/1KB, 0)
$mode = if ($Full) { '全量(1.zip)' } else { '增量(update.zip)' }
Write-Host "✓ $mode 打包完成: $($changed.Count) 个文件更新, $($deleted.Count) 个删除, $sizeKB KB"
Write-Host " 变更: $(($changed | ForEach-Object { $_.Substring($src.Length + 1) }) -join ', ')"
if ($deleted.Count) { Write-Host " 删除: $($deleted -join ', ')" }
Remove-Item $stage -Recurse -Force
+65
View File
@@ -0,0 +1,65 @@
# 源码分发包:只包含代码、模板、必要静态资源和项目说明。
# 用法: pwsh -File scripts/pack_zip.ps1
$ErrorActionPreference = 'Stop'
$src = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot))
$zip = Join-Path $src '1.zip'
$pendingZip = Join-Path $src '1.zip.tmp'
$include = @(
'.gitignore','LICENSE','README.md','app.py','db.py','campus.py','alerts.py','subscribe.py',
'email_utils.py','email_verify.py','generate_icons.py','map_cache.py','pytest.ini','rate_limit.py',
'rental_mail.py','requirements.txt','server_config.json','timer.py',
'update_creds_from_capture.py','wechat.py'
)
$dirs = @('routes','templates','static','scripts','tests')
$extensions = @('.py','.js','.cjs','.mjs','.css','.html','.ps1','.json',
'.svg','.png','.ico','.woff','.woff2','.ttf')
$files = [Collections.Generic.List[object]]::new()
foreach ($name in $include) {
$file = Join-Path $src $name
if (Test-Path -LiteralPath $file -PathType Leaf) { $files.Add((Get-Item -LiteralPath $file)) }
}
foreach ($dir in $dirs) {
$path = Join-Path $src $dir
if (-not (Test-Path -LiteralPath $path -PathType Container)) { continue }
Get-ChildItem -LiteralPath $path -Recurse -File | ForEach-Object {
$relative = [IO.Path]::GetRelativePath($src, $_.FullName).Replace('\','/')
if ($relative -match '(^|/)(__pycache__|\.pytest_cache|\.reasonix|backups|node_modules)(/|$)') { return }
if ($_.Name.StartsWith('.') -or $_.Name.StartsWith('_preview') -or $_.Name -eq '_layout_preview.html') { return }
if ($extensions -notcontains $_.Extension.ToLowerInvariant()) { return }
$files.Add($_)
}
}
Add-Type -AssemblyName System.IO.Compression.FileSystem
try {
$stream = [IO.File]::Open($pendingZip, [IO.FileMode]::Create)
$archive = [IO.Compression.ZipArchive]::new($stream, [IO.Compression.ZipArchiveMode]::Create)
try {
foreach ($file in $files) {
$relative = [IO.Path]::GetRelativePath($src, $file.FullName).Replace('\','/')
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile(
$archive, $file.FullName, $relative, [IO.Compression.CompressionLevel]::Optimal) | Out-Null
}
} finally { $archive.Dispose(); $stream.Dispose() }
$check = [IO.Compression.ZipFile]::OpenRead($pendingZip)
try {
$names = @($check.Entries | Select-Object -ExpandProperty FullName)
$required = @('app.py','db.py','map_cache.py','campus.py','alerts.py','subscribe.py',
'routes/export.py','routes/subscribe.py','routes/rental.py','routes/admin.py',
'templates/map.html','templates/admin.html','static/js/map.js',
'static/js/bike-clusters.js','static/js/settings-pages.js','static/css/bike-clusters.css','static/css/map-settings.css','requirements.txt')
$missing = @($required | Where-Object { $names -notcontains $_ })
if ($missing.Count) { throw "打包缺文件: $($missing -join ', ')" }
$unexpected = @($names | Where-Object {
$_ -match '(^|/)(downloads|artifacts|backups|logs|temp|sessions|__pycache__|\.git)/|\.(db|pem|key|crt|exe|zip|log|pyc)$|(^|/)(token_config|smtp_config|admin_config|secret_key)\.'
})
if ($unexpected.Count) { throw "压缩包包含非源码文件: $($unexpected -join ', ')" }
} finally { $check.Dispose() }
Move-Item -LiteralPath $pendingZip -Destination $zip -Force
$sizeKB = [math]::Round((Get-Item -LiteralPath $zip).Length / 1KB, 1)
Write-Host "1.zip 完成:$($names.Count) 个文件,$sizeKB KB(仅源码与必要资源)"
} finally {
if (Test-Path -LiteralPath $pendingZip) { Remove-Item -LiteralPath $pendingZip -Force }
}
+279
View File
@@ -0,0 +1,279 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""冒烟测试:验证应用可启动、路由无冲突、关键接口可响应。"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # 项目根
# 注意: app.py 导入时会重新包装 sys.stdout, 这里不能自己再包一层,
# 否则旧包装器被 GC 时会关闭底层 buffer。编码由 PYTHONIOENCODING 控制。
_ORIG_STDOUT = sys.stdout # 持有引用, 防止被 GC 后关闭底层流
from collections import defaultdict
PASS, FAIL = [], []
def check(name, fn):
try:
detail = fn()
PASS.append((name, detail))
print(f" [PASS] {name}" + (f" — {detail}" if detail else ""))
except Exception as e:
FAIL.append((name, f"{type(e).__name__}: {e}"))
print(f" [FAIL] {name} — {type(e).__name__}: {e}")
print("=" * 60)
print("1) 模块导入检查")
print("=" * 60)
def import_app():
import app as app_module
return f"app 模块导入成功, 蓝图 {len(app_module.app.blueprints)} 个: {', '.join(app_module.app.blueprints)}"
check("导入 app.py 及全部依赖 (db/wechat/timer/routes.*)", import_app)
def import_side_modules():
import rental_mail, email_utils, generate_icons # noqa: F401
return "rental_mail / email_utils / generate_icons 导入成功"
check("导入其余业务模块", import_side_modules)
app_obj = None
try:
import app as app_module
app_obj = app_module.app
except Exception:
pass
print()
print("=" * 60)
print("2) 路由冲突检查")
print("=" * 60)
def route_conflicts():
rules = defaultdict(list)
for r in app_obj.url_map.iter_rules():
if r.endpoint == "static":
continue
methods = sorted(m for m in r.methods if m not in ("HEAD", "OPTIONS"))
for m in methods:
rules[(m, r.rule)].append(r.endpoint)
dupes = {k: v for k, v in rules.items() if len(v) > 1}
if dupes:
raise AssertionError(f"发现 {len(dupes)} 处路由冲突: {dupes}")
return f"共 {len(rules)} 条 (method, path) 规则, 无重复注册"
check("检查重复路由 (Flask 静默覆盖, 需显式检测)", route_conflicts)
def route_summary():
rules = sorted(r.rule for r in app_obj.url_map.iter_rules() if r.endpoint != "static")
return f"{len(rules)} 条路由"
check("路由注册成功", route_summary)
print()
print("=" * 60)
print("3) 数据库连通性")
print("=" * 60)
def db_check():
import sqlite3
from pathlib import Path
p = Path("users.db")
if not p.exists():
raise AssertionError("users.db 不存在")
conn = sqlite3.connect(str(p))
conn.row_factory = sqlite3.Row
cur = conn.cursor()
tables = [r[0] for r in cur.execute(
"SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
counts = {}
for t in ("users", "rentals", "bike_history", "sessions"):
if t in tables:
counts[t] = cur.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
cur.execute("PRAGMA integrity_check")
integrity = cur.fetchone()[0]
conn.close()
if integrity != "ok":
raise AssertionError(f"数据库完整性异常: {integrity}")
return f"表 {len(tables)} 张, 行数: {counts}"
check("users.db 完整性与核心表", db_check)
def db_init_check():
"""init_db() 应可重复执行(幂等)而不报错 —— 用临时库验证。"""
import db, tempfile, os
from pathlib import Path
fd, tmp = tempfile.mkstemp(suffix=".db")
os.close(fd)
old = db.DB_PATH
db.DB_PATH = Path(tmp)
try:
db.init_db()
db.init_db() # 二次调用验证幂等
return "init_db 在临时库上执行两次均成功(幂等)"
finally:
db.DB_PATH = old
try:
os.remove(tmp)
except OSError:
pass
check("init_db 幂等性 (临时库)", db_init_check)
print()
print("=" * 60)
print("4) 模板与静态资源")
print("=" * 60)
def templates_check():
from pathlib import Path
tdir = Path("templates")
files = sorted(p.name for p in tdir.glob("*.html"))
if not files:
raise AssertionError("templates 目录为空")
return f"{len(files)} 个模板: {', '.join(files)}"
check("模板文件存在", templates_check)
def static_check():
from pathlib import Path
sdir = Path("static")
total = sum(1 for _ in sdir.rglob("*") if _.is_file())
if total == 0:
raise AssertionError("static 目录为空")
return f"{total} 个静态文件"
check("静态资源存在", static_check)
print()
print("=" * 60)
print("5) 关键接口冒烟 (Flask test client, 不真正监听端口)")
print("=" * 60)
def client():
app_obj.config["TESTING"] = True
return app_obj.test_client()
c = client()
EXPECTED = {
# (path): 说明。允许 200/3xx;404 属于页面/路由缺失
"/": "主页(地图)",
"/admin": "管理后台(未登录应跳转登录)",
"/admin/login": "管理员登录页",
"/analysis.html": "数据分析页",
"/rental/email-return": "邮件还车页",
"/ring_progress.html": "寻车进度页",
}
def page(path):
def fn():
r = c.get(path)
if r.status_code in (200, 301, 302, 304):
return f"{path} -> {r.status_code}"
if r.status_code == 404:
raise AssertionError(f"{path} -> 404 (页面/路由缺失)")
raise AssertionError(f"{path} -> {r.status_code}")
return fn
for path, name in EXPECTED.items():
check(f"页面 {name} {path}", page(path))
# API 类: 401/400 = 接口在且鉴权/校验正常; 404/500 = 有问题
API_ALLOW = {200, 400, 401, 302, 301}
APIS = [
("/api/bike_history", "无参数应返回400"),
("/api/analysis/overview", "分析总览"),
("/api/analysis/heatmap", "热力图"),
("/api/history/stats", "历史统计"),
("/api/history/bikes", "历史车辆列表"),
("/api/history/heatmap", "历史热力图"),
("/api/history/all_trajectory", "全量轨迹"),
]
def api(path):
def fn():
r = c.get(path)
if r.status_code in API_ALLOW:
return f"{path} -> {r.status_code}"
raise AssertionError(f"{path} -> {r.status_code}")
return fn
for path, desc in APIS:
check(f"API {desc} {path}", api(path))
def protected_api_check():
"""未登录访问受保护接口应返回 401(或明确拒绝) 而不是 500/404"""
paths = (
"/api/auth/rental_settings", "/api/rental/status",
"/api/share/active", "/api/auth/profile", "/api/order/status",
)
for path in paths:
r = c.get(path)
if r.status_code == 404:
raise AssertionError(f"{path} -> 404, 接口不存在")
if r.status_code >= 500:
raise AssertionError(f"{path} -> {r.status_code}, 服务端错误")
if r.status_code == 200:
body = r.get_json(silent=True) or {}
if body.get("rtn_code") not in (401, 403):
raise AssertionError(
f"{path} 未登录返回 200 且 rtn_code={body.get('rtn_code')}, 疑似未鉴权")
return "受保护接口未登录时均正确拒绝(无 500/404/越权)"
check("受保护接口鉴权兜底", protected_api_check)
def login_flow_check():
"""登录接口对错误凭据应返回明确失败而非 500"""
r = c.post("/api/auth/login",
json={"email": "smoke_nonexist@example.test", "password": "wrong"})
if r.status_code >= 500:
raise AssertionError(f"/api/auth/login -> {r.status_code}")
body = r.get_json(silent=True) or {}
if r.status_code == 200 and body.get("rtn_code") == 0:
raise AssertionError("错误凭据竟然登录成功!")
return f"/api/auth/login 错误凭据 -> {r.status_code} rtn_code={body.get('rtn_code')} (拒绝正常)"
check("登录接口错误凭据处理", login_flow_check)
print()
print("=" * 60)
print("冒烟测试结果汇总")
print("=" * 60)
print(f"通过: {len(PASS)} 失败: {len(FAIL)}")
if FAIL:
print("\n失败项:")
for name, err in FAIL:
print(f" - {name}: {err}")
sys.exit(1)
print("全部通过 ✅")
+49
View File
@@ -0,0 +1,49 @@
const { chromium } = require('playwright');
const edgePath = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';
const nativeUa = 'Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/153 Mobile Safari/537.36 xbniu-native/1.0';
(async () => {
const browser = await chromium.launch({ executablePath: edgePath, headless: true });
for (const colorScheme of ['light', 'dark']) {
const context = await browser.newContext({
colorScheme,
userAgent: nativeUa,
viewport: { width: 530, height: 942 },
deviceScaleFactor: 1,
});
const page = await context.newPage();
page.on('dialog', dialog => dialog.dismiss());
await page.goto(`http://127.0.0.1:98/?theme-check=${Date.now()}`, { waitUntil: 'domcontentloaded' });
await page.waitForSelector('#native-tools');
const result = await page.evaluate(() => {
const button = document.querySelector('#auth-btn');
const text = document.querySelector('#auth-btn-text');
const avatar = document.querySelector('#auth-avatar');
if (button) button.style.transition = 'none';
button?.classList.add('logged-in');
if (text) text.style.display = 'none';
if (avatar) { avatar.style.display = 'flex'; avatar.textContent = '3'; }
const inspect = selector => {
const style = getComputedStyle(document.querySelector(selector));
return {
background: style.backgroundColor,
color: style.color,
border: style.borderColor,
backdrop: style.backdropFilter || style.webkitBackdropFilter,
};
};
return {
htmlClass: document.documentElement.className,
avatarClass: button?.className,
avatarParent: button?.parentElement?.parentElement?.id,
avatar: inspect('#auth-btn'),
tools: inspect('#native-tools'),
legend: inspect('.legend'),
};
});
console.log(JSON.stringify({ colorScheme, ...result }));
await context.close();
}
await browser.close();
})();
+85
View File
@@ -0,0 +1,85 @@
const { chromium } = require('playwright');
const fs = require('fs');
const path = require('path');
const edgePath = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';
const outputDir = path.resolve(__dirname, '..', 'artifacts', 'screenshots');
const selectors = [
'.auth-btn',
'.locate-btn',
'.scan-btn',
'.bike-action-btn',
'.auth-submit',
'.profile-verify-btn',
'.radius-btn.active',
'.token-expired-btn.confirm',
'.code-send-btn',
'.return-confirm-btn.confirm',
'.unlock-confirm-btn.confirm',
'.lost-modal-btn.confirm',
'.share-req-row button',
'.share-mini-btn.primary',
];
function channel(value) {
const normalized = value / 255;
return normalized <= 0.04045
? normalized / 12.92
: ((normalized + 0.055) / 1.055) ** 2.4;
}
function luminance(rgb) {
const values = rgb.match(/[\d.]+/g).slice(0, 3).map(Number);
return 0.2126 * channel(values[0]) + 0.7152 * channel(values[1]) + 0.0722 * channel(values[2]);
}
function contrast(foreground, background) {
const light = Math.max(luminance(foreground), luminance(background));
const dark = Math.min(luminance(foreground), luminance(background));
return (light + 0.05) / (dark + 0.05);
}
(async () => {
const browser = await chromium.launch({ executablePath: edgePath, headless: true });
let failed = false;
for (const colorScheme of ['light', 'dark']) {
const context = await browser.newContext({ colorScheme, viewport: { width: 1280, height: 800 } });
const page = await context.newPage();
page.on('dialog', dialog => dialog.dismiss());
if (process.env.XBNIU_CAPTURE_TOKEN) {
await page.addInitScript(token => localStorage.setItem('auth_token', token), process.env.XBNIU_CAPTURE_TOKEN);
}
await page.goto('http://127.0.0.1:98/', { waitUntil: 'domcontentloaded' });
await page.waitForTimeout(500);
const results = await page.evaluate(items => items.map(selector => {
const element = document.querySelector(selector);
if (!element) return { selector, missing: true };
const style = getComputedStyle(element);
const themedBackground = getComputedStyle(document.body).getPropertyValue('--accent-color').trim();
const background = style.backgroundColor === 'rgba(0, 0, 0, 0)' && style.backgroundImage !== 'none'
? themedBackground
: style.backgroundColor;
return { selector, color: style.color, background };
}), selectors);
for (const result of results) {
if (result.missing) continue;
result.contrast = Number(contrast(result.color, result.background).toFixed(2));
if (result.contrast < 4.5) failed = true;
}
console.log(JSON.stringify({ colorScheme, results }, null, 2));
if (process.env.XBNIU_CAPTURE_TOKEN) {
fs.mkdirSync(outputDir, { recursive: true });
await page.addStyleTag({
content: '#token-expired-modal, .login-gate, .toast, #loading, #version-modal { display: none !important; }',
});
await page.screenshot({ path: path.join(outputDir, `map-authenticated-${colorScheme}.png`) });
}
await context.close();
}
await browser.close();
if (failed) process.exitCode = 1;
})();