upload to gitea
This commit is contained in:
commit
e50b59d88a
59 files changed
+4308
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,65 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from PIL import Image
|
||||
|
||||
from app import auth, clock, config, mailer, totp
|
||||
|
||||
ADMIN_LOGIN = "sthkm3"
|
||||
ADMIN_TOTP = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP" # 測試用密鑰
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self):
|
||||
self.value = datetime(2026, 11, 21, 3, 0, tzinfo=timezone.utc) # 台灣時間 11:00
|
||||
|
||||
def set(self, iso: str):
|
||||
self.value = datetime.fromisoformat(iso).astimezone(timezone.utc)
|
||||
|
||||
def __call__(self):
|
||||
return self.value
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_clock(monkeypatch):
|
||||
c = Clock()
|
||||
monkeypatch.setattr(clock, "now", c)
|
||||
return c
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sent(monkeypatch):
|
||||
"""攔截寄信,回傳 {email: 最後一個驗證碼}。"""
|
||||
box = {}
|
||||
monkeypatch.setattr(mailer, "send_code", lambda email, code, lang: box.__setitem__(email, code))
|
||||
return box
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(tmp_path, monkeypatch, fake_clock, sent):
|
||||
memes = tmp_path / "memes"
|
||||
memes.mkdir()
|
||||
Image.new("RGB", (640, 480), (200, 80, 80)).save(memes / "test.png")
|
||||
monkeypatch.setattr(config, "DATA_DIR", tmp_path / "data")
|
||||
monkeypatch.setattr(config, "MEME_DIR", memes)
|
||||
monkeypatch.setattr(config, "ADMIN_LOGIN", ADMIN_LOGIN)
|
||||
monkeypatch.setattr(config, "ADMIN_TOTP", ADMIN_TOTP)
|
||||
auth._ip_hits.clear()
|
||||
from app.main import app
|
||||
with TestClient(app, headers={"X-INMU": "1"}) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def login(client, sent, email="[email protected]", lang="zh-TW"):
|
||||
r = client.post("/api/auth/request-code", json={"email": email, "lang": lang})
|
||||
assert r.status_code == 200, r.text
|
||||
r = client.post("/api/auth/verify", json={"email": email, "code": sent[email.lower()], "lang": lang})
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def admin_code(fake_clock, offset_steps=0):
|
||||
"""用假時鐘算出管理員的 TOTP。"""
|
||||
step = int(fake_clock.value.timestamp()) // totp.PERIOD + offset_steps
|
||||
return totp.code_at(totp.decode_secret(ADMIN_TOTP), step)
|
||||
@@ -0,0 +1,129 @@
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import admin, config, db, totp
|
||||
|
||||
from .conftest import ADMIN_LOGIN, admin_code, login
|
||||
|
||||
|
||||
def admin_login(client, code, login_name=ADMIN_LOGIN):
|
||||
return client.post("/api/auth/verify", json={"email": login_name, "code": code})
|
||||
|
||||
|
||||
def test_totp_rfc6238_vector():
|
||||
# RFC 6238 附錄 B(SHA1,密鑰 "12345678901234567890"),取後 6 碼
|
||||
secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
|
||||
assert totp.code_at(totp.decode_secret(secret), 59 // 30) == "287082"
|
||||
assert totp.code_at(totp.decode_secret(secret), 1111111109 // 30) == "081804"
|
||||
assert totp.verify(secret, "287082", 59) == 1
|
||||
assert totp.verify(secret, "287082", 59 + 30) == 1 # 前一個時間窗也接受
|
||||
assert totp.verify(secret, "287082", 59 + 90) is None # 太舊
|
||||
assert totp.verify(secret, "abc", 59) is None
|
||||
|
||||
|
||||
def test_admin_request_code_does_not_send(client, sent):
|
||||
r = client.post("/api/auth/request-code", json={"email": "STHKM3"})
|
||||
assert r.status_code == 200 and r.json()["status"] == "sent"
|
||||
assert sent == {}
|
||||
|
||||
|
||||
def test_admin_login(client, fake_clock):
|
||||
r = admin_login(client, admin_code(fake_clock))
|
||||
assert r.status_code == 200, r.text
|
||||
user = r.json()["user"]
|
||||
assert user["uid"] == 0 and user["uid_str"] == "00000000"
|
||||
assert user["is_admin"] is True and user["uid_tier"] == "admin" and "title" not in user
|
||||
assert "Max-Age=604800" in r.headers["set-cookie"] # 管理員 session 7 天
|
||||
me = client.get("/api/me").json()
|
||||
assert me["is_admin"] is True
|
||||
# 管理員也能簽到,小卡會畫頭銜
|
||||
c = client.post("/api/checkin").json()
|
||||
assert c["card_url"].startswith("/card/00000000/")
|
||||
assert client.get(c["card_url"]).status_code == 200
|
||||
|
||||
|
||||
def test_admin_code_single_use(client, fake_clock):
|
||||
code = admin_code(fake_clock)
|
||||
assert admin_login(client, code).status_code == 200
|
||||
# 登出後馬上用同一組碼再登入:拒絕,但不算失敗,重試幾次都不會鎖
|
||||
for _ in range(5):
|
||||
r = admin_login(client, code)
|
||||
assert r.status_code == 400 and r.json()["detail"] == "code_used"
|
||||
# 前一個時間窗的碼也不能用(時間步不能倒退)
|
||||
assert admin_login(client, admin_code(fake_clock, -1)).json()["detail"] == "code_used"
|
||||
conn = db.connect()
|
||||
assert db.get_meta(conn, "admin_fails") == 0 and db.get_meta(conn, "admin_lock_until") == 0
|
||||
# Aegis 換下一組碼就能登入
|
||||
fake_clock.value += timedelta(seconds=30)
|
||||
assert admin_login(client, admin_code(fake_clock)).status_code == 200
|
||||
|
||||
|
||||
def test_admin_lockout(client, fake_clock):
|
||||
good = admin_code(fake_clock)
|
||||
wrong = "000000" if good != "000000" else "111111"
|
||||
assert admin_login(client, wrong).json()["detail"] == "wrong_code"
|
||||
assert admin_login(client, wrong).json()["detail"] == "wrong_code"
|
||||
r = admin_login(client, wrong) # 第 3 次就鎖
|
||||
assert r.status_code == 429
|
||||
# 鎖定中,正確的碼也不行
|
||||
assert admin_login(client, good).status_code == 429
|
||||
|
||||
# 15 分鐘後解鎖
|
||||
fake_clock.value += timedelta(minutes=15)
|
||||
assert admin_login(client, admin_code(fake_clock)).status_code == 200
|
||||
|
||||
|
||||
def test_admin_lock_doubles(client, fake_clock):
|
||||
for minutes in (15, 30, 60):
|
||||
for _ in range(3):
|
||||
admin_login(client, "000000" if admin_code(fake_clock) != "000000" else "111111")
|
||||
fake_clock.value += timedelta(minutes=minutes) - timedelta(seconds=1)
|
||||
assert admin_login(client, admin_code(fake_clock)).status_code == 429
|
||||
fake_clock.value += timedelta(seconds=1)
|
||||
conn = db.connect()
|
||||
assert db.get_meta(conn, "admin_lock_level") == 3
|
||||
|
||||
|
||||
def test_admin_unlock_command(client, fake_clock):
|
||||
for _ in range(3):
|
||||
admin_login(client, "000000" if admin_code(fake_clock) != "000000" else "111111")
|
||||
assert admin_login(client, admin_code(fake_clock)).status_code == 429
|
||||
admin.main(["unlock"])
|
||||
assert admin_login(client, admin_code(fake_clock)).status_code == 200
|
||||
|
||||
|
||||
def test_admin_disabled_without_secret(client, sent, fake_clock, monkeypatch):
|
||||
monkeypatch.setattr(config, "ADMIN_TOTP", "")
|
||||
db.init()
|
||||
r = client.post("/api/auth/request-code", json={"email": ADMIN_LOGIN})
|
||||
assert r.status_code == 400 and r.json()["detail"] == "invalid_email"
|
||||
assert admin_login(client, admin_code(fake_clock)).json()["detail"] == "invalid_email"
|
||||
|
||||
|
||||
def test_admin_login_renamed(client, fake_clock, monkeypatch):
|
||||
monkeypatch.setattr(config, "ADMIN_LOGIN", "boss")
|
||||
db.init()
|
||||
assert admin_login(client, admin_code(fake_clock), "sthkm3").json()["detail"] == "invalid_email"
|
||||
r = admin_login(client, admin_code(fake_clock), "boss")
|
||||
assert r.status_code == 200 and r.json()["user"]["uid"] == 0
|
||||
|
||||
|
||||
def test_admin_login_clash_disables(client, sent, fake_clock, monkeypatch):
|
||||
login(client, sent, "[email protected]")
|
||||
monkeypatch.setattr(config, "ADMIN_LOGIN", "[email protected]")
|
||||
db.init()
|
||||
assert db.admin_ok is False
|
||||
|
||||
|
||||
def test_totp_uri(capsys, client):
|
||||
admin.main(["totp-uri"])
|
||||
last = capsys.readouterr().out.strip().splitlines()[-1]
|
||||
assert last.startswith("otpauth://totp/My%20INMU%3Asthkm3?secret=")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("uid", ["0", "-1"])
|
||||
def test_cannot_grant_admin_uid(client, sent, uid):
|
||||
login(client, sent)
|
||||
with pytest.raises(SystemExit):
|
||||
admin.main(["grant-uid", "[email protected]", uid])
|
||||
@@ -0,0 +1,260 @@
|
||||
import io
|
||||
from datetime import timedelta
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from PIL import Image
|
||||
|
||||
from app import db
|
||||
from app.main import app
|
||||
|
||||
from .conftest import login
|
||||
|
||||
|
||||
# ---------- 登入 ----------
|
||||
|
||||
def test_register_and_login(client, sent):
|
||||
data = login(client, sent, "[email protected]")
|
||||
assert data["user"]["uid"] == 1
|
||||
assert data["user"]["uid_str"] == "00000001"
|
||||
assert data["user"]["display_name"] == "INMU_1"
|
||||
assert data["user"]["is_admin"] is False
|
||||
assert data["user"]["email"] == "[email protected]"
|
||||
assert data["token"]
|
||||
assert client.get("/api/me").json()["uid"] == 1
|
||||
|
||||
# 同一個信箱再登入一次是同一個帳號
|
||||
client.cookies.clear()
|
||||
client.post("/api/auth/request-code", json={"email": "[email protected]"}) # 別人註冊不影響
|
||||
assert login(client, sent, "[email protected]")["user"]["uid"] == 1
|
||||
|
||||
|
||||
def test_bearer_token(client, sent):
|
||||
token = login(client, sent)["token"]
|
||||
client.cookies.clear()
|
||||
assert client.get("/api/me").status_code == 401
|
||||
# Bearer 不需要 X-INMU
|
||||
bare = TestClient(app)
|
||||
r = bare.post("/api/checkin", headers={"Authorization": f"Bearer {token}"})
|
||||
assert r.status_code == 200
|
||||
|
||||
|
||||
def test_csrf_header_required(client, sent):
|
||||
login(client, sent)
|
||||
r = client.post("/api/checkin", headers={"X-INMU": ""})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_resend_limit(client, sent, fake_clock):
|
||||
client.post("/api/auth/request-code", json={"email": "[email protected]"})
|
||||
r = client.post("/api/auth/request-code", json={"email": "[email protected]"})
|
||||
assert r.status_code == 429
|
||||
fake_clock.value += timedelta(seconds=61)
|
||||
assert client.post("/api/auth/request-code", json={"email": "[email protected]"}).status_code == 200
|
||||
|
||||
|
||||
def test_wrong_code_five_times(client, sent):
|
||||
client.post("/api/auth/request-code", json={"email": "[email protected]"})
|
||||
right = sent["[email protected]"]
|
||||
wrong = "000000" if right != "000000" else "111111"
|
||||
for _ in range(4):
|
||||
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": wrong})
|
||||
assert r.json()["detail"] == "wrong_code"
|
||||
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": wrong})
|
||||
assert r.json()["detail"] == "expired"
|
||||
# 作廢後正確的碼也不能用
|
||||
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": right})
|
||||
assert r.json()["detail"] == "not_requested"
|
||||
|
||||
|
||||
def test_code_expires(client, sent, fake_clock):
|
||||
client.post("/api/auth/request-code", json={"email": "[email protected]"})
|
||||
fake_clock.value += timedelta(minutes=5, seconds=1)
|
||||
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": sent["[email protected]"]})
|
||||
assert r.json()["detail"] == "expired"
|
||||
|
||||
|
||||
def test_invalid_email(client):
|
||||
r = client.post("/api/auth/request-code", json={"email": "not-an-email"})
|
||||
assert r.status_code == 400 and r.json()["detail"] == "invalid_email"
|
||||
|
||||
|
||||
def test_logout(client, sent):
|
||||
login(client, sent)
|
||||
assert client.post("/api/auth/logout").status_code == 200
|
||||
client.cookies.clear()
|
||||
assert client.get("/api/me").status_code == 401
|
||||
|
||||
|
||||
# ---------- 簽到 ----------
|
||||
|
||||
def test_checkin_once_per_jst_day(client, sent, fake_clock):
|
||||
login(client, sent)
|
||||
fake_clock.set("2026-11-21T12:00:00+08:00")
|
||||
r = client.post("/api/checkin").json()
|
||||
assert r["already"] is False and r["total_days"] == 1 and r["streak"] == 1
|
||||
assert r["day"] == "2026-11-21"
|
||||
assert r["card_url"] == "/card/00000001/2026-11-21.png"
|
||||
assert r["share_url"].endswith("/c/00000001/2026-11-21")
|
||||
|
||||
r = client.post("/api/checkin").json()
|
||||
assert r["already"] is True and r["total_days"] == 1
|
||||
|
||||
# 台灣時間隔天 03:59 還算同一天
|
||||
fake_clock.set("2026-11-22T03:59:59+08:00")
|
||||
assert client.post("/api/checkin").json()["already"] is True
|
||||
|
||||
# 日本時間 00:00 換日
|
||||
fake_clock.set("2026-11-22T04:00:00+08:00")
|
||||
r = client.post("/api/checkin").json()
|
||||
assert r["already"] is False and r["total_days"] == 2 and r["streak"] == 2
|
||||
|
||||
|
||||
def test_streak_breaks(client, sent, fake_clock):
|
||||
login(client, sent)
|
||||
for day in ("2026-11-01", "2026-11-02", "2026-11-04"):
|
||||
fake_clock.set(f"{day}T09:00:00+08:00")
|
||||
client.post("/api/checkin")
|
||||
r = client.get("/api/checkin/today").json()
|
||||
assert r["total_days"] == 3 and r["streak"] == 1
|
||||
|
||||
# 隔天還沒簽到時,連續天數保留昨天的紀錄
|
||||
fake_clock.set("2026-11-05T09:00:00+08:00")
|
||||
r = client.get("/api/checkin/today").json()
|
||||
assert r["checked_in"] is False and r["streak"] == 1
|
||||
assert r["next_reset"] == "2026-11-06T04:00:00+08:00"
|
||||
# 凌晨 02:00 時還沒換日,下次換日是當天 04:00
|
||||
fake_clock.set("2026-11-06T02:00:00+08:00")
|
||||
r = client.get("/api/checkin/today").json()
|
||||
assert r["day"] == "2026-11-05" and r["next_reset"] == "2026-11-06T04:00:00+08:00"
|
||||
|
||||
|
||||
def test_checkin_requires_login(client):
|
||||
assert client.post("/api/checkin").status_code == 401
|
||||
|
||||
|
||||
# ---------- UID ----------
|
||||
|
||||
def test_uid_sequence_skips_granted(client, sent):
|
||||
from app import admin
|
||||
|
||||
login(client, sent, "[email protected]")
|
||||
admin.main(["grant-uid", "[email protected]", "99999999"])
|
||||
# 下一位仍然拿到正常的下一號
|
||||
assert login(client, sent, "[email protected]")["user"]["uid"] == 2
|
||||
|
||||
|
||||
def test_uid_tier_by_substring(client, sent):
|
||||
conn = db.connect()
|
||||
conn.execute("UPDATE meta SET value = 114514 WHERE key = 'next_uid'")
|
||||
u = login(client, sent, "[email protected]")["user"]
|
||||
assert u["uid_str"] == "00114514" and u["uid_tier"] == "114514"
|
||||
assert login(client, sent, "[email protected]")["user"]["uid_tier"] is None # 00114515
|
||||
conn.execute("UPDATE meta SET value = 51919810 WHERE key = 'next_uid'")
|
||||
u = login(client, sent, "[email protected]")["user"]
|
||||
assert u["uid_str"] == "51919810" and u["uid_tier"] == "1919810"
|
||||
assert client.get("/api/users/51919810").json()["uid_tier"] == "1919810"
|
||||
# 小卡也能正常產生(會畫頭銜)
|
||||
client.cookies.clear()
|
||||
login(client, sent, "[email protected]")
|
||||
r = client.post("/api/checkin").json()
|
||||
assert client.get(r["card_url"]).status_code == 200
|
||||
|
||||
|
||||
def test_grant_uid_range(client, sent):
|
||||
import pytest
|
||||
from app import admin
|
||||
|
||||
login(client, sent, "[email protected]")
|
||||
for bad in ("0", "100000000"):
|
||||
with pytest.raises(SystemExit):
|
||||
admin.main(["grant-uid", "[email protected]", bad])
|
||||
|
||||
|
||||
def test_granted_uid_keeps_checkins(client, sent):
|
||||
from app import admin
|
||||
|
||||
login(client, sent, "[email protected]")
|
||||
client.post("/api/checkin")
|
||||
admin.main(["grant-uid", "[email protected]", "114514"])
|
||||
me = client.get("/api/me").json() # session 也跟著改 uid
|
||||
assert me["uid_str"] == "00114514" and me["total_days"] == 1
|
||||
|
||||
|
||||
def test_old_default_name_migrated(client, sent):
|
||||
login(client, sent)
|
||||
conn = db.connect()
|
||||
conn.execute("UPDATE users SET display_name = 'INMU1' WHERE uid = 1")
|
||||
db.init()
|
||||
assert client.get("/api/me").json()["display_name"] == "INMU_1"
|
||||
|
||||
|
||||
# ---------- 個人資料 ----------
|
||||
|
||||
def _png(w, h, color=(10, 200, 30)):
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (w, h), color).save(buf, "PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_avatar_resized(client, sent):
|
||||
login(client, sent)
|
||||
r = client.put("/api/me/avatar", files={"file": ("a.png", _png(1600, 900), "image/png")})
|
||||
assert r.status_code == 200, r.text
|
||||
url = r.json()["avatar_url"]
|
||||
img = Image.open(io.BytesIO(client.get(url).content))
|
||||
assert img.format == "WEBP" and img.size == (1024, 1024)
|
||||
|
||||
|
||||
def test_avatar_rejects_non_image(client, sent):
|
||||
login(client, sent)
|
||||
r = client.put("/api/me/avatar", files={"file": ("a.png", b"<script>alert(1)</script>", "image/png")})
|
||||
assert r.status_code == 400 and r.json()["detail"] == "invalid_image"
|
||||
|
||||
|
||||
def test_profile_patch_and_markdown_escape(client, sent):
|
||||
login(client, sent)
|
||||
r = client.patch("/api/me", json={"display_name": " 野獸\n先輩 ", "bio_md": "**hi** <script>x</script>"})
|
||||
data = r.json()
|
||||
assert data["display_name"] == "野獸先輩"
|
||||
assert "<strong>hi</strong>" in data["bio_html"]
|
||||
assert "<script>" not in data["bio_html"]
|
||||
assert client.patch("/api/me", json={"display_name": "x" * 33}).json()["detail"] == "name_invalid"
|
||||
assert client.patch("/api/me", json={"bio_md": "x" * 2001}).json()["detail"] == "bio_too_long"
|
||||
assert client.patch("/api/me", json={"lang": "fr"}).json()["detail"] == "invalid_lang"
|
||||
|
||||
|
||||
def test_public_profile_hides_email(client, sent):
|
||||
login(client, sent)
|
||||
data = client.get("/api/users/1").json()
|
||||
assert "email" not in data and data["uid"] == 1
|
||||
assert client.get("/api/users/999").status_code == 404
|
||||
|
||||
|
||||
# ---------- 小卡與分享 ----------
|
||||
|
||||
def test_card_and_share_page(client, sent):
|
||||
login(client, sent)
|
||||
r = client.post("/api/checkin").json()
|
||||
png = client.get(r["card_url"])
|
||||
assert png.status_code == 200
|
||||
img = Image.open(io.BytesIO(png.content))
|
||||
assert img.size == (1080, 1350)
|
||||
|
||||
page = client.get(f"/c/1/{r['day']}")
|
||||
assert page.status_code == 200 and 'property="og:image"' in page.text
|
||||
assert client.get("/card/1/2000-01-01.png").status_code == 404
|
||||
assert client.get("/c/1/not-a-day").status_code == 404
|
||||
|
||||
|
||||
def test_card_rerendered_after_rename(client, sent):
|
||||
login(client, sent)
|
||||
r = client.post("/api/checkin").json()
|
||||
first = client.get(r["card_url"]).content
|
||||
client.patch("/api/me", json={"display_name": "New Name"})
|
||||
assert client.get(r["card_url"]).content != first
|
||||
|
||||
|
||||
def test_index_served(client):
|
||||
assert client.get("/").status_code == 200
|
||||
assert client.get("/u/1").status_code == 200
|
||||
assert client.get("/healthz").json() == {"status": "ok"}
|
||||
@@ -0,0 +1,60 @@
|
||||
import pytest
|
||||
|
||||
from app import admin, config, db
|
||||
from app.titles import uid_tier
|
||||
|
||||
from .conftest import login
|
||||
|
||||
|
||||
@pytest.mark.parametrize("uid,tier", [
|
||||
(0, "admin"), (114514, "114514"), (51919810, "1919810"), (1919810, "1919810"),
|
||||
(11451400, "114514"), (1, None), (11451, None), (99999999, None),
|
||||
])
|
||||
def test_uid_tier(uid, tier):
|
||||
assert uid_tier(uid) == tier
|
||||
|
||||
|
||||
@pytest.mark.parametrize("beta", [True, False])
|
||||
def test_beta_switch(client, sent, monkeypatch, beta):
|
||||
monkeypatch.setattr(config, "BETA", beta)
|
||||
html = client.get("/").text
|
||||
assert ("(Beta)" in html) is beta
|
||||
assert "<!--BETA" not in html
|
||||
login(client, sent)
|
||||
r = client.post("/api/checkin").json()
|
||||
page = client.get(f"/c/00000001/{r['day']}").text
|
||||
assert ('content="My INMU (Beta)"' in page) is beta
|
||||
assert client.get(r["card_url"]).status_code == 200
|
||||
|
||||
|
||||
def test_reset_progress(client, sent, capsys):
|
||||
login(client, sent)
|
||||
client.patch("/api/me", json={"display_name": "Beta tester"})
|
||||
first = client.post("/api/checkin").json()
|
||||
assert client.get(first["card_url"]).status_code == 200
|
||||
|
||||
# 沒有 --yes 不做任何事
|
||||
admin.main(["reset-progress"])
|
||||
assert client.get("/api/checkin/today").json()["total_days"] == 1
|
||||
|
||||
admin.main(["reset-progress", "--yes"])
|
||||
today = client.get("/api/checkin/today").json()
|
||||
assert today["total_days"] == 0 and today["checked_in"] is False
|
||||
me = client.get("/api/me").json() # 帳號、名稱、session 都還在
|
||||
assert me["display_name"] == "Beta tester" and me["uid_str"] == "00000001"
|
||||
assert list(config.DATA_DIR.glob("inmu.db.bak-*"))
|
||||
assert not any((config.DATA_DIR / "cards").iterdir())
|
||||
# 同一天可以重新簽到
|
||||
again = client.post("/api/checkin").json()
|
||||
assert again["already"] is False and again["total_days"] == 1
|
||||
assert db.connect().execute("SELECT value FROM meta WHERE key = 'next_uid'").fetchone()[0] == 2
|
||||
|
||||
|
||||
def test_assets_versioned_and_not_cached_by_proxies(client):
|
||||
html = client.get("/").text
|
||||
assert "__ASSET_VERSION__" not in html
|
||||
assert '/assets/app.js?v=' in html and '/assets/style.css?v=' in html
|
||||
r = client.get("/assets/app.js")
|
||||
assert r.headers["cache-control"] == "no-cache"
|
||||
etag = r.headers["etag"]
|
||||
assert client.get("/assets/app.js", headers={"If-None-Match": etag}).status_code == 304
|
||||
@@ -0,0 +1,59 @@
|
||||
from app import config, mailer
|
||||
|
||||
|
||||
class FakeSMTP:
|
||||
instances = []
|
||||
|
||||
def __init__(self, host, port, timeout=None, context=None):
|
||||
self.host, self.port, self.sent, self.tls = host, port, [], False
|
||||
FakeSMTP.instances.append(self)
|
||||
|
||||
def starttls(self, context=None):
|
||||
self.tls = True
|
||||
|
||||
def login(self, user, password):
|
||||
self.login_as = (user, password)
|
||||
|
||||
def send_message(self, msg):
|
||||
self.sent.append(msg)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
|
||||
def _setup(monkeypatch, port):
|
||||
FakeSMTP.instances.clear()
|
||||
monkeypatch.setattr(mailer.smtplib, "SMTP_SSL", FakeSMTP)
|
||||
monkeypatch.setattr(mailer.smtplib, "SMTP", FakeSMTP)
|
||||
monkeypatch.setattr(config, "SMTP_HOST", "smtp.example.com")
|
||||
monkeypatch.setattr(config, "SMTP_PORT", port)
|
||||
monkeypatch.setattr(config, "SMTP_USER", "[email protected]")
|
||||
monkeypatch.setattr(config, "SMTP_PASSWORD", "app-password")
|
||||
monkeypatch.setattr(config, "MAIL_FROM", "[email protected]")
|
||||
|
||||
|
||||
def test_sends_from_noreply(monkeypatch):
|
||||
_setup(monkeypatch, 465)
|
||||
mailer.send_code("[email protected]", "123456", "ja")
|
||||
smtp = FakeSMTP.instances[0]
|
||||
assert (smtp.host, smtp.port, smtp.tls) == ("smtp.example.com", 465, False)
|
||||
msg = smtp.sent[0]
|
||||
assert msg["From"] == "My INMU <[email protected]>"
|
||||
assert msg["To"] == "[email protected]"
|
||||
assert "123456" in msg["Subject"] and "認証コード" in msg["Subject"]
|
||||
assert msg["Message-ID"].endswith("@inmu.sthkm3.org>")
|
||||
|
||||
|
||||
def test_starttls_on_587(monkeypatch):
|
||||
_setup(monkeypatch, 587)
|
||||
mailer.send_code("[email protected]", "123456", "en")
|
||||
assert FakeSMTP.instances[0].tls is True
|
||||
|
||||
|
||||
def test_dev_mode_prints(monkeypatch, capsys):
|
||||
monkeypatch.setattr(config, "SMTP_USER", "")
|
||||
mailer.send_code("[email protected]", "654321", "en")
|
||||
assert "654321" in capsys.readouterr().out
|
||||
@@ -0,0 +1,178 @@
|
||||
import io
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from app import admin, checkin, config, db
|
||||
|
||||
from .conftest import ADMIN_LOGIN, admin_code, login
|
||||
|
||||
|
||||
def _img(fmt="PNG", color=(10, 200, 30), size=(300, 200), **kw):
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", size, color).save(buf, fmt, **kw)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def bearer(token):
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def upload(client, token, data=None, name="a.png"):
|
||||
return client.post("/api/submissions", headers=bearer(token),
|
||||
files={"file": (name, data or _img(), "image/png")})
|
||||
|
||||
|
||||
def admin_token(client, fake_clock):
|
||||
r = client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": admin_code(fake_clock)})
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()["token"]
|
||||
|
||||
|
||||
def test_upload_and_daily_quota(client, sent, fake_clock):
|
||||
tok = login(client, sent)["token"]
|
||||
r = upload(client, tok)
|
||||
assert r.status_code == 200, r.text
|
||||
data = r.json()
|
||||
assert data["item"]["status"] == "pending" and data["remaining"] == 4 and data["limit"] == 5
|
||||
for _ in range(4):
|
||||
assert upload(client, tok).status_code == 200
|
||||
r = upload(client, tok)
|
||||
assert r.status_code == 429 and r.json()["detail"] == "quota_exceeded"
|
||||
|
||||
# 台灣時間隔天 03:59 還是同一天,04:00 才重置
|
||||
fake_clock.set("2026-11-22T03:59:00+08:00")
|
||||
assert upload(client, tok).status_code == 429
|
||||
fake_clock.set("2026-11-22T04:00:00+08:00")
|
||||
assert upload(client, tok).json()["remaining"] == 4
|
||||
|
||||
mine = client.get("/api/submissions", headers=bearer(tok)).json()
|
||||
assert mine["used"] == 1 and len(mine["items"]) == 6
|
||||
|
||||
|
||||
def test_rejected_still_counts(client, sent, fake_clock):
|
||||
tok = login(client, sent)["token"]
|
||||
adm = admin_token(client, fake_clock)
|
||||
for _ in range(5):
|
||||
sid = upload(client, tok).json()["item"]["id"]
|
||||
assert client.post(f"/api/admin/submissions/{sid}/reject", headers=bearer(adm)).status_code == 200
|
||||
assert upload(client, tok).json()["detail"] == "quota_exceeded"
|
||||
|
||||
|
||||
def test_upload_validation(client, sent):
|
||||
tok = login(client, sent)["token"]
|
||||
r = upload(client, tok, b"<script>alert(1)</script>")
|
||||
assert r.status_code == 400 and r.json()["detail"] == "invalid_image"
|
||||
r = upload(client, tok, b"x" * (config.SUBMIT_MAX_BYTES + 1))
|
||||
assert r.status_code == 413 and r.json()["detail"] == "file_too_large"
|
||||
# 失敗的不算額度
|
||||
assert client.get("/api/submissions", headers=bearer(tok)).json()["used"] == 0
|
||||
|
||||
|
||||
def test_upload_strips_exif_and_shrinks(client, sent):
|
||||
tok = login(client, sent)["token"]
|
||||
exif = Image.Exif()
|
||||
exif[0x010F] = "SecretCam"
|
||||
item = upload(client, tok, _img("JPEG", size=(4000, 1000), exif=exif), "a.jpg").json()["item"]
|
||||
saved = config.DATA_DIR / "submissions" / f"{item['id']}.jpg"
|
||||
with Image.open(saved) as im:
|
||||
assert im.format == "JPEG" and len(im.getexif()) == 0
|
||||
assert im.size == (2048, 512)
|
||||
|
||||
|
||||
def test_png_with_alpha_stays_png(client, sent):
|
||||
tok = login(client, sent)["token"]
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGBA", (50, 50), (0, 0, 0, 0)).save(buf, "PNG")
|
||||
item = upload(client, tok, buf.getvalue()).json()["item"]
|
||||
assert (config.DATA_DIR / "submissions" / f"{item['id']}.png").is_file()
|
||||
|
||||
|
||||
def test_permissions(client, sent, fake_clock):
|
||||
a = login(client, sent, "[email protected]")["token"]
|
||||
b = login(client, sent, "[email protected]")["token"]
|
||||
sid = upload(client, a).json()["item"]["id"]
|
||||
url = f"/api/submissions/{sid}/image"
|
||||
assert client.get(url, headers=bearer(a)).status_code == 200
|
||||
assert client.get(url, headers=bearer(b)).status_code == 404 # 別人的投稿當作不存在
|
||||
for method, path in (("get", "/api/admin/submissions"),
|
||||
("post", f"/api/admin/submissions/{sid}/approve"),
|
||||
("post", f"/api/admin/submissions/{sid}/reject")):
|
||||
assert getattr(client, method)(path, headers=bearer(b)).status_code == 403
|
||||
adm = admin_token(client, fake_clock)
|
||||
assert client.get(url, headers=bearer(adm)).status_code == 200
|
||||
assert "pending_reviews" not in client.get("/api/me", headers=bearer(a)).json()
|
||||
assert client.get("/api/me", headers=bearer(adm)).json()["pending_reviews"] == 1
|
||||
|
||||
|
||||
def test_approve_names_like_image_folder(client, sent, fake_clock):
|
||||
for name in ("inmu_0.png", "inmu_7.jpg"):
|
||||
Image.new("RGB", (10, 10)).save(config.MEME_DIR / name)
|
||||
tok = login(client, sent)["token"]
|
||||
first = upload(client, tok).json()["item"]["id"]
|
||||
second = upload(client, tok).json()["item"]["id"]
|
||||
adm = admin_token(client, fake_clock)
|
||||
|
||||
# 一張一張審:先拿到最舊的
|
||||
r = client.get("/api/admin/submissions", headers=bearer(adm)).json()
|
||||
assert r["pending"] == 2 and r["item"]["id"] == first
|
||||
assert r["item"]["uploader"]["uid_str"] == "00000001"
|
||||
|
||||
r = client.post(f"/api/admin/submissions/{first}/approve", headers=bearer(adm))
|
||||
assert r.status_code == 200 and r.json()["meme"] == "inmu_8.jpg" and r.json()["pending"] == 1
|
||||
assert (config.MEME_DIR / "inmu_8.jpg").is_file()
|
||||
assert not (config.DATA_DIR / "submissions" / f"{first}.jpg").exists()
|
||||
assert "inmu_8.jpg" in checkin.list_memes()
|
||||
assert client.post(f"/api/admin/submissions/{first}/approve", headers=bearer(adm)).status_code == 409
|
||||
assert client.post(f"/api/admin/submissions/{first}/reject", headers=bearer(adm)).status_code == 409
|
||||
|
||||
assert client.post(f"/api/admin/submissions/{second}/approve",
|
||||
headers=bearer(adm)).json()["meme"] == "inmu_9.jpg"
|
||||
assert client.get("/api/admin/submissions", headers=bearer(adm)).json() == {"item": None, "pending": 0}
|
||||
# 已同意的投稿,本人還是看得到圖
|
||||
assert client.get(f"/api/submissions/{first}/image", headers=bearer(tok)).status_code == 200
|
||||
# 沒有暫存檔留在迷因資料夾
|
||||
assert not [p for p in config.MEME_DIR.iterdir() if p.name.startswith(".")]
|
||||
|
||||
|
||||
def test_approved_meme_shows_on_card(client, sent, fake_clock, monkeypatch):
|
||||
for p in config.MEME_DIR.iterdir():
|
||||
p.unlink()
|
||||
tok = login(client, sent)["token"]
|
||||
sid = upload(client, tok).json()["item"]["id"]
|
||||
adm = admin_token(client, fake_clock)
|
||||
client.post(f"/api/admin/submissions/{sid}/approve", headers=bearer(adm))
|
||||
assert checkin.list_memes() == ["inmu_0.jpg"]
|
||||
r = client.post("/api/checkin", headers=bearer(tok)).json()
|
||||
conn = db.connect()
|
||||
assert conn.execute("SELECT meme FROM checkins WHERE uid = 1").fetchone()[0] == "inmu_0.jpg"
|
||||
assert client.get(r["card_url"]).status_code == 200
|
||||
|
||||
|
||||
def test_reject_deletes_file(client, sent, fake_clock):
|
||||
tok = login(client, sent)["token"]
|
||||
sid = upload(client, tok).json()["item"]["id"]
|
||||
adm = admin_token(client, fake_clock)
|
||||
assert client.post(f"/api/admin/submissions/{sid}/reject", headers=bearer(adm)).json()["status"] == "rejected"
|
||||
assert not (config.DATA_DIR / "submissions" / f"{sid}.png").exists()
|
||||
item = client.get("/api/submissions", headers=bearer(tok)).json()["items"][0]
|
||||
assert item["status"] == "rejected" and item["image_url"] is None
|
||||
assert client.get(f"/api/submissions/{sid}/image", headers=bearer(tok)).status_code == 404
|
||||
assert client.post("/api/admin/submissions/9999/reject", headers=bearer(adm)).status_code == 404
|
||||
|
||||
|
||||
def test_reset_progress_keeps_submissions(client, sent):
|
||||
tok = login(client, sent)["token"]
|
||||
upload(client, tok)
|
||||
admin.main(["reset-progress", "--yes"])
|
||||
assert client.get("/api/submissions", headers=bearer(tok)).json()["used"] == 1
|
||||
|
||||
|
||||
def test_upload_and_review_pages_served(client):
|
||||
assert client.get("/upload").status_code == 200
|
||||
assert client.get("/review").status_code == 200
|
||||
|
||||
|
||||
def test_media_content_types(client):
|
||||
for path, ctype in (("/assets/media/checkin-0.webp", "image/webp"), ("/assets/media/114514.m4a", "audio/mp4")):
|
||||
r = client.get(path)
|
||||
assert r.status_code == 200 and r.headers["content-type"].startswith(ctype)
|
||||
Reference in new issue
Block a user