This repository has been archived on 2026-10-02. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
NeteaseUrl/tests/test_register.py
T
snowy-yang 8446166120 refactor!: uv 管理环境 + 彻底删除技术债(Flask 与 requests 全部移除)
## uv 环境管理
- pyproject.toml 声明 dependencies + [dependency-groups].dev,uv.lock 精确锁定
- 删除 requirements.txt / requirements-fastapi.txt / requirements-dev.txt
- .python-version = 3.12;Dockerfile 改用 uv sync --frozen(可复现构建)
- 新增 jinja2(首页渲染)

## 删除 Flask 技术债
- 从 main.py 用 ast 精确剥离 56 个 Flask 节点(路由/中间件/错误处理/启动),
  框架无关的服务层落为 services/runtime.py(MusicAPIService、下载/打包 worker、
  任务监控、缓存清扫),零 Flask 依赖
- 删除 main.py(4527 行)与 auth_routes.py(1050 行)
- auth_system.py 移除会话/请求上下文层(login_session/current_user/login_required/
  admin_required/_client_ip 等),保留数据与业务层
- 新增 core/net.py(IP 解析)、web/auth_state.py(登录锁定/2FA 票据/发码限流)
- FastAPI 侧改直接依赖 services.runtime,不再 import main
- web/app.py 去掉 Flask fallback;入口默认根路径模式(API_PREFIX 可选)

## 删除 requests 技术债
- 新增 core/sync_http.py:requests 风格的同步门面(底层 aiohttp 连接池,
  流式读取经有界队列背压),含 Session/headers/(connect,read) 元组超时兼容
- core/utils、auth_system、podcast_api、music_downloader、services 全部切换
- 实测真实下载 5.2MB 音频完整成功

## 质量门禁归零
- ruff:0 错误(B904 全部修复,不再忽略)
- pyright:0 错误(类型收窄修复)
- pytest:140/140(含 golden 契约回归、root 模式 66 项路径覆盖)
- 真实 uvicorn 启动:/health、/、/static、受保护端鉴权全部正确

新增 tests/golden/responses.json:删除 Flask 前捕获的 32 例响应快照,
FastAPI 逐字段复现——删除巨石后行为回归仍有硬证据。
2026-09-26 11:10:17 +08:00

119 lines
4.5 KiB
Python

# -*- coding: utf-8 -*-
"""注册/找回/卡密端点的沙箱测试(不触碰生产 data/site.db)。
直接向沙箱库 email_codes 表播种验证码,绕过 SMTP,覆盖:
- 注册协议门槛、用户名/密码长度校验
- 注册成功路径:建号 + 赠送次数 + 签发可用会话 Cookie
- 验证码错误分支
- 找回密码:重置后可用新密码登录、旧会话失效
- 卡密充值
"""
import time
import pytest
from fastapi.testclient import TestClient
import auth_system as auth
import core.db as db
SECRET = 'register-test-secret'
@pytest.fixture()
def env(tmp_path, monkeypatch):
db_path = tmp_path / 'site.db'
monkeypatch.setattr(auth, 'DATA_DIR', tmp_path)
monkeypatch.setattr(auth, 'DB_PATH', db_path)
monkeypatch.setattr(auth, 'BACKUP_DIR', tmp_path / 'backups')
monkeypatch.setattr(auth, 'SECRET_KEY_PATH', tmp_path / 'secret.key')
monkeypatch.setattr(db, 'DATA_DIR', tmp_path)
monkeypatch.setattr(db, 'DB_PATH', db_path)
auth.init_db()
monkeypatch.setattr('web.deps.secret_key', lambda: SECRET)
import web.auth_state as auth_routes
auth_routes._SEND_CODE_IP.clear()
from web.app import create_app
return TestClient(create_app())
def _seed_code(email: str, code: str, purpose: str = 'register'):
conn = auth.get_conn()
conn.execute('DELETE FROM email_codes WHERE email = ? AND purpose = ?', (email, purpose))
conn.execute('INSERT INTO email_codes (email, code, expires_at, created_at, purpose) '
'VALUES (?, ?, ?, ?, ?)',
(email, code, int(time.time()) + 600, int(time.time()), purpose))
conn.commit()
conn.close()
def test_register_requires_agreement(env):
r = env.post('/auth/register', json={
'username': 'newuser', 'password': 'Passw0rd12', 'email': 'n@example.com',
'code': '000000', 'agree': '0'})
assert r.json()['message'].startswith('请先阅读并同意')
def test_register_success(env):
_seed_code('new@example.com', '123456')
r = env.post('/auth/register', json={
'username': 'newuser', 'password': 'Passw0rd12', 'email': 'new@example.com',
'code': '123456', 'agree': '1', 'device_id': 'dev-1'})
assert r.status_code == 200
body = r.json()
assert body['success'] is True
assert '已赠送' in body['message']
assert 'session' in r.cookies
# 会话可用
assert env.post('/auth/heartbeat', json={}).status_code == 200
# 用户名/邮箱已被占用
_seed_code('new@example.com', '222222')
r2 = env.post('/auth/register', json={
'username': 'newuser', 'password': 'Passw0rd12', 'email': 'new@example.com',
'code': '222222', 'agree': '1'})
assert '已被注册' in r2.json()['message']
def test_register_bad_code(env):
r = env.post('/auth/register', json={
'username': 'another', 'password': 'Passw0rd12', 'email': 'a@example.com',
'code': '999999', 'agree': '1'})
assert r.json()['message'] == '邮箱验证码错误或已过期'
def test_forgot_password_resets(env):
# 建一个用户
auth.create_user('forgetme', 'OldPass123', email='f@example.com', credits=5)
_seed_code('f@example.com', '654321', purpose='reset')
r = env.post('/auth/forgot_password', json={
'email': 'f@example.com', 'code': '654321', 'password': 'NewPass456'})
assert r.status_code == 200
assert r.json()['success'] is True
# 新密码可登录
r2 = env.post('/auth/login', json={'username': 'forgetme', 'password': 'NewPass456'})
assert r2.status_code == 200 and r2.json()['success'] is True
def test_forgot_password_admin_blocked(env):
conn = auth.get_conn()
conn.execute("UPDATE users SET role='admin', email='boss@example.com' WHERE id=1")
conn.commit()
conn.close()
_seed_code('boss@example.com', '111111', purpose='reset')
r = env.post('/auth/forgot_password', json={
'email': 'boss@example.com', 'code': '111111', 'password': 'NewPass456'})
# 管理员不走自助找回:统一防枚举文案
assert r.json()['message'] == '邮箱验证码错误或已过期'
def test_redeem_card(env):
# 造一张卡密并让用户登录
auth.create_user('buyer', 'Passw0rd12', email='b@example.com', credits=0)
code = auth.generate_cards(1, 10, note='test')[0]
env.post('/auth/login', json={'username': 'buyer', 'password': 'Passw0rd12'})
r = env.post('/auth/redeem', json={'code': code})
assert r.status_code == 200
assert r.json()['success'] is True
assert r.json()['data']['credits'] == 10