Files
project-sss/tests/test_app.py
T
optimxandCursor dd281e1bd0 Initial commit: SSS 50-week LAN check-in app.
Ship the Synology/Mac deployable player with curriculum mapping, stats, and resource library.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 23:11:42 +08:00

540 lines
25 KiB
Python

import sqlite3
import tempfile
import unittest
from contextlib import closing
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
import app
BASE_TIME = datetime(2026, 10, 12, 2, 0, tzinfo=timezone.utc)
class SSSAppTests(unittest.TestCase):
def make_database(self, directory: str, at: datetime = BASE_TIME) -> Path:
db_path = Path(directory) / "sss.db"
app.initialize_database(db_path, at)
return db_path
def bind(self, connection, device="device-test0001", actor="妈妈", at=BASE_TIME):
app.bind_device(connection, device, actor, at)
return device
def play_and_complete(
self,
connection,
device,
song_id,
at,
study_date="2026-10-12",
media_type="video",
):
play_id = app.start_playback_event(
connection, device, song_id, study_date, media_type, at
)
result = app.complete_playback_event(
connection, device, play_id, 90, at + timedelta(minutes=1)
)
return play_id, result
def test_curriculum_has_all_three_asset_types(self):
self.assertEqual(app.CURRICULUM["meta"]["week_count"], 50)
self.assertEqual(app.CURRICULUM["meta"]["song_count"], 100)
song = app.CURRICULUM["songs_by_id"]["28-3"]
self.assertEqual(song["video_file"], "28-3 The Shape Song.mp4")
self.assertEqual(song["audio_file"], "28-3 The Shape Song.mp3")
self.assertEqual(song["lyrics_file"], "28-3 The Shape Song.jpg")
def test_active_asset_root_finds_macos_suffixed_study_mount(self):
with tempfile.TemporaryDirectory() as temp_dir:
volumes_root = Path(temp_dir) / "Volumes"
configured_root = volumes_root / "study" / "Assets" / "SSS50"
fallback_root = volumes_root / "study-1" / "Assets" / "SSS50"
(fallback_root / "视频").mkdir(parents=True)
self.assertEqual(
app.active_asset_root(configured_root, volumes_root), fallback_root
)
def test_resource_catalog_lists_every_song_and_three_lazy_assets(self):
with tempfile.TemporaryDirectory() as temp_dir:
payload = app.resources_payload(Path(temp_dir))
self.assertEqual(payload["summary"]["songs"], 100)
self.assertEqual(len(payload["songs"]), 100)
first = payload["songs"][0]
self.assertEqual(first["id"], "1-1")
self.assertEqual(first["week"], 1)
self.assertEqual(set(first["urls"]), {"video", "audio", "lyrics"})
self.assertFalse(any(first["available"].values()))
resource_html = (app.PUBLIC_DIR / "resources.html").read_text(encoding="utf-8")
resource_js = (app.PUBLIC_DIR / "resources.js").read_text(encoding="utf-8")
self.assertNotIn('id="resource-viewer"', resource_html)
self.assertIn('data-resource-detail', resource_js)
self.assertIn('data-resource-video data-video-url=', resource_js)
self.assertIn('data-resource-audio data-audio-url=', resource_js)
self.assertIn('video.src = video.dataset.videoUrl', resource_js)
self.assertIn('audio.src = audio.dataset.audioUrl', resource_js)
self.assertNotIn('mode: "info"', resource_js)
self.assertNotIn('songs[0]?.id', resource_js)
def test_home_uses_one_lazy_media_card_per_song(self):
home_html = (app.PUBLIC_DIR / "index.html").read_text(encoding="utf-8")
home_js = (app.PUBLIC_DIR / "app.js").read_text(encoding="utf-8")
resource_js = (app.PUBLIC_DIR / "resources.js").read_text(encoding="utf-8")
stats_js = (app.PUBLIC_DIR / "stats.js").read_text(encoding="utf-8")
self.assertIn('id="song-cards"', home_html)
self.assertNotIn('id="current-song-id"', home_html)
self.assertNotIn('id="audio-previous"', home_html)
self.assertNotIn('id="loop-toggle"', home_html)
self.assertIn('data-video-url="${song.video_url}"', home_js)
self.assertIn('data-audio-url="${song.audio_url}"', home_js)
self.assertIn('player.src = player.dataset[urlKey]', home_js)
self.assertIn('const urlKey = mediaType === "audio" ? "audioUrl" : "videoUrl"', home_js)
self.assertNotIn("独立播放", home_html)
self.assertNotIn("一首歌一个窗口", home_html)
self.assertIn('id="round-hint"', home_html)
self.assertIn('"上午领取", "下午领取", "晚上领取"', home_js)
self.assertIn('id="playlist-loop-button"', home_html)
self.assertIn('id="weekly-loop-player"', home_html)
self.assertIn('loop playsinline webkit-playsinline', home_html)
self.assertIn('id="child-mode"', home_html)
self.assertIn("async function startPlaylistAt", home_js)
self.assertIn('playCardMedia(song.id, "audio", "single")', home_js)
self.assertIn('player.src = `/api/week-audio/${weekNumber}`', home_js)
self.assertIn('mode: "weekly-loop"', home_js)
self.assertIn('elements.weeklyLoopPlayer.pause()', home_js)
self.assertIn('function isIPhone5sOnIOS10()', home_js)
self.assertIn('function childSongCardMarkup(song, index)', home_js)
self.assertIn('appState.childMode ? "audio"', home_js)
self.assertIn('course_week: appState.data.week.number', home_js)
self.assertIn('data-week-number=', home_js)
self.assertIn('<title>SSS 50 周打卡</title>', home_html)
self.assertIn('id="identity-button"', home_html)
self.assertIn('id="bottom-settings-button"', home_html)
self.assertIn('id="start-date" name="start_date" type="date" value="2026-10-12" disabled', home_html)
self.assertNotIn('id="settings-button"', home_html)
self.assertNotIn('if (mode !== "video") video.pause()', home_js)
self.assertNotIn('if (mode !== "audio") audio.pause()', home_js)
self.assertNotIn("<dialog", home_html)
self.assertIn('class="modal identity-dialog"', home_html)
self.assertIn("webkit-playsinline", home_js)
self.assertIn("function forEachNode", home_js)
self.assertNotIn("querySelectorAll(\"[data-actor]\").forEach", home_js)
for script in (home_js, resource_js, stats_js):
self.assertNotIn("?.", script)
self.assertNotIn("??", script)
self.assertNotIn(".replaceAll(", script)
self.assertNotIn("...", script)
self.assertNotIn("URLSearchParams", home_js)
def test_future_week_can_be_previewed_without_checkin_progress(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
device = self.bind(connection)
state = app.state_payload(
connection,
device,
"2026-10-12",
BASE_TIME,
view_week_value=2,
)
self.assertEqual(state["week"]["number"], 2)
self.assertTrue(state["viewing_future"])
self.assertFalse(state["can_checkin"])
self.assertTrue(all(not song["can_checkin"] for song in state["week"]["songs"]))
self.assertTrue(all(week["unlocked"] for week in state["weeks"]))
def test_future_preview_play_is_recorded_but_never_unlocks_checkin(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
device = self.bind(connection)
play_id = app.start_playback_event(
connection,
device,
"2-1",
"2026-10-12",
"audio",
BASE_TIME,
course_week_value=2,
)
result = app.complete_playback_event(
connection,
device,
play_id,
90,
BASE_TIME + timedelta(minutes=1),
)
row = connection.execute(
"SELECT course_week, study_date FROM playback_events WHERE id = ?",
(play_id,),
).fetchone()
with self.assertRaisesRegex(ValueError, "not part"):
app.claim_song_checkin(
connection,
device,
"2-1",
"2026-10-12",
BASE_TIME + timedelta(minutes=2),
)
self.assertEqual((row["course_week"], row["study_date"]), (2, "2026-10-12"))
self.assertFalse(result["checkin_eligible"])
self.assertFalse(result["round_ready"])
def test_course_week_is_computed_from_start_date(self):
start = date(2026, 9, 28)
self.assertEqual(app.week_for_date(start, date(2026, 9, 28)), 1)
self.assertEqual(app.week_for_date(start, date(2026, 10, 4)), 1)
self.assertEqual(app.week_for_date(start, date(2026, 10, 5)), 2)
self.assertEqual(app.week_for_date(start, date(2027, 12, 31)), 50)
def test_database_migration_is_idempotent_and_sets_start_date(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
app.initialize_database(db_path, BASE_TIME)
with sqlite3.connect(db_path) as connection:
settings = connection.execute(
"SELECT start_date, checkin_window_minutes FROM household_settings"
).fetchall()
tables = {
row[0]
for row in connection.execute(
"SELECT name FROM sqlite_master WHERE type = 'table'"
)
}
round_columns = {
row[1] for row in connection.execute("PRAGMA table_info(round_checkins)")
}
self.assertEqual(settings, [("2026-10-12", 60)])
self.assertIn("song_checkins", tables)
self.assertIn("round_checkins", tables)
self.assertIn("round_number", round_columns)
def test_device_identity_can_be_changed(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
app.bind_device(connection, "device-12345678", "妈妈", BASE_TIME)
app.bind_device(connection, "device-12345678", "爸爸", BASE_TIME)
state = app.state_payload(
connection,
"device-12345678",
"2026-10-12",
BASE_TIME,
)
self.assertEqual(state["device"]["actor"], "爸爸")
self.assertEqual(state["settings"]["current_week"], 1)
self.assertEqual(state["study_date"], "2026-10-12")
def test_completed_play_unlocks_manual_flower_but_does_not_claim_it(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
device = self.bind(connection)
self.play_and_complete(connection, device, "1-1", BASE_TIME)
progress = app.song_progress(
connection, "1-1", 1, date(2026, 10, 12), BASE_TIME, 60
)
count = connection.execute("SELECT COUNT(*) FROM song_checkins").fetchone()[0]
self.assertEqual(count, 0)
self.assertEqual(progress["ready_count"], 1)
self.assertTrue(progress["can_checkin"])
def test_manual_flowers_are_throttled_per_song_not_globally(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
device = self.bind(connection)
self.play_and_complete(connection, device, "1-1", BASE_TIME)
first = app.claim_song_checkin(
connection, device, "1-1", "2026-10-12", BASE_TIME + timedelta(minutes=2)
)
self.play_and_complete(
connection, device, "1-1", BASE_TIME + timedelta(minutes=10)
)
with self.assertRaisesRegex(ValueError, "等待"):
app.claim_song_checkin(
connection,
device,
"1-1",
"2026-10-12",
BASE_TIME + timedelta(minutes=12),
)
self.play_and_complete(
connection, device, "1-2", BASE_TIME + timedelta(minutes=10)
)
second_song = app.claim_song_checkin(
connection,
device,
"1-2",
"2026-10-12",
BASE_TIME + timedelta(minutes=12),
)
self.assertEqual(first["checkin_count"], 1)
self.assertEqual(second_song["checkin_count"], 1)
def test_song_can_collect_three_flowers_with_three_plays_and_intervals(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
device = self.bind(connection)
for index in range(3):
moment = BASE_TIME + timedelta(minutes=index * 61)
self.play_and_complete(connection, device, "1-1", moment)
result = app.claim_song_checkin(
connection,
device,
"1-1",
"2026-10-12",
moment + timedelta(minutes=1),
)
count = connection.execute(
"SELECT COUNT(*) FROM song_checkins WHERE song_id = '1-1'"
).fetchone()[0]
self.assertEqual(result["checkin_count"], 3)
self.assertEqual(count, 3)
def test_full_playlist_unlocks_round_flower_for_manual_claim(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
device = self.bind(connection)
results = []
for index, song_id in enumerate(("1-1", "1-2", "1-3")):
_, result = self.play_and_complete(
connection,
device,
song_id,
BASE_TIME + timedelta(minutes=index * 3),
)
results.append(result)
count = connection.execute("SELECT COUNT(*) FROM round_checkins").fetchone()[0]
claimed = app.claim_round_checkin(
connection,
device,
"2026-10-12",
BASE_TIME + timedelta(minutes=10),
)
claimed_count = connection.execute(
"SELECT COUNT(*) FROM round_checkins"
).fetchone()[0]
self.assertFalse(results[0]["round_ready"])
self.assertFalse(results[1]["round_ready"])
self.assertTrue(results[2]["round_ready"])
self.assertEqual(count, 0)
self.assertEqual(claimed["round_number"], 1)
self.assertEqual(claimed_count, 1)
def test_three_full_playlists_can_collect_three_round_flowers(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
device = self.bind(connection)
for round_index in range(3):
start = BASE_TIME + timedelta(minutes=round_index * 64)
for song_index, song_id in enumerate(("1-1", "1-2", "1-3")):
self.play_and_complete(
connection,
device,
song_id,
start + timedelta(minutes=song_index),
)
result = app.claim_round_checkin(
connection,
device,
"2026-10-12",
start + timedelta(minutes=4),
)
rows = connection.execute(
"SELECT round_number FROM round_checkins ORDER BY round_number"
).fetchall()
self.assertEqual(result["round_number"], 3)
self.assertEqual([row["round_number"] for row in rows], [1, 2, 3])
def test_round_cooldown_is_shared_across_devices(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
dad = self.bind(connection, "device-dad00001", "爸爸")
mom = self.bind(connection, "device-mom00001", "妈妈")
for song_index, song_id in enumerate(("1-1", "1-2", "1-3")):
self.play_and_complete(
connection,
dad,
song_id,
BASE_TIME + timedelta(minutes=song_index),
)
app.claim_round_checkin(
connection, dad, "2026-10-12", BASE_TIME + timedelta(minutes=4)
)
for song_index, song_id in enumerate(("1-1", "1-2", "1-3")):
self.play_and_complete(
connection,
mom,
song_id,
BASE_TIME + timedelta(minutes=10 + song_index),
)
with self.assertRaisesRegex(ValueError, "等待"):
app.claim_round_checkin(
connection,
mom,
"2026-10-12",
BASE_TIME + timedelta(minutes=14),
)
count = connection.execute(
"SELECT COUNT(*) FROM round_checkins"
).fetchone()[0]
self.assertEqual(count, 1)
def test_round_cooldown_cannot_be_bypassed_with_another_study_date(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
connection.execute(
"UPDATE household_settings SET start_date = '2026-10-05' WHERE id = 1"
)
connection.commit()
dad = self.bind(connection, "device-dad00001", "爸爸")
mom = self.bind(connection, "device-mom00001", "妈妈")
for song_index, song in enumerate(
app.playlist_for_week(app.CURRICULUM["weeks_by_no"][2])
):
self.play_and_complete(
connection,
dad,
song["id"],
BASE_TIME + timedelta(minutes=song_index),
"2026-10-12",
)
app.claim_round_checkin(
connection, dad, "2026-10-12", BASE_TIME + timedelta(minutes=4)
)
for song_index, song in enumerate(
app.playlist_for_week(app.CURRICULUM["weeks_by_no"][1])
):
self.play_and_complete(
connection,
mom,
song["id"],
BASE_TIME + timedelta(minutes=10 + song_index),
"2026-10-11",
)
with self.assertRaisesRegex(ValueError, "等待"):
app.claim_round_checkin(
connection,
mom,
"2026-10-11",
BASE_TIME + timedelta(minutes=14),
)
def test_pending_flower_is_recovered_on_next_state_load(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
device = self.bind(connection)
self.play_and_complete(connection, device, "1-1", BASE_TIME)
state = app.state_payload(
connection,
device,
"2026-10-12",
BASE_TIME + timedelta(minutes=2),
recover=True,
)
self.assertEqual(state["week"]["songs"][0]["checkin_count"], 1)
self.assertEqual(state["recovered_awards"][0]["kind"], "song")
def test_makeup_flower_is_recovered_when_next_visit_opens_today(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
connection.execute(
"UPDATE household_settings SET start_date = '2026-09-21' WHERE id = 1"
)
connection.commit()
device = self.bind(connection)
self.play_and_complete(
connection,
device,
"3-1",
BASE_TIME - timedelta(hours=2),
study_date="2026-10-11",
)
state = app.state_payload(
connection,
device,
"2026-10-12",
BASE_TIME,
recover=True,
)
recovered = connection.execute(
"SELECT song_id, study_date, source FROM song_checkins"
).fetchone()
self.assertEqual(state["week"]["number"], 4)
self.assertEqual(
(recovered["song_id"], recovered["study_date"], recovered["source"]),
("3-1", "2026-10-11", "recovery"),
)
self.assertEqual(state["recovered_awards"][0]["study_date"], "2026-10-11")
def test_progress_calendar_has_two_dynamic_rows_ending_today(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
connection.execute(
"UPDATE household_settings SET start_date = '2026-09-21' WHERE id = 1"
)
connection.commit()
state = app.state_payload(
connection,
None,
"2026-10-05",
BASE_TIME,
recover=False,
)
self.assertEqual(len(state["progress_14d"]), 14)
self.assertEqual(state["week"]["number"], 3)
self.assertEqual(state["progress_14d"][-1]["date"], "2026-10-12")
self.assertEqual(state["progress_14d"][-1]["weekday"], "一")
self.assertTrue(any(day["status"] == "missed" for day in state["progress_14d"]))
def test_statistics_include_song_and_round_flowers(self):
with tempfile.TemporaryDirectory() as temp_dir:
db_path = self.make_database(temp_dir)
with closing(app.connect_db(db_path)) as connection:
device = self.bind(connection)
for index, song_id in enumerate(("1-1", "1-2", "1-3")):
self.play_and_complete(
connection,
device,
song_id,
BASE_TIME + timedelta(minutes=index * 3),
)
app.claim_song_checkin(
connection,
device,
"1-1",
"2026-10-12",
BASE_TIME + timedelta(minutes=12),
)
app.claim_round_checkin(
connection,
device,
"2026-10-12",
BASE_TIME + timedelta(minutes=12),
)
stats = app.statistics_payload(connection, BASE_TIME + timedelta(minutes=15))
song = next(item for item in stats["songs"] if item["id"] == "1-1")
self.assertEqual(stats["summary"]["song_checkins"], 1)
self.assertEqual(stats["summary"]["round_checkins"], 1)
self.assertEqual(stats["summary"]["checkins"], 2)
self.assertEqual(song["checkins"], 1)
if __name__ == "__main__":
unittest.main()