"""Offline, high-level checks: python -m unittest discover -s test -v.""" from __future__ import annotations import contextlib import importlib.util import io import json from pathlib import Path import sys import tempfile import unittest from unittest.mock import patch ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) import build_app import build_audio import build_licenses import build_progress import data import games_build import games_audio_matrix import games_gen_audio_zhuyin import sort_dicts import update_dicts import update_sentences from lib import common from index_snapshot import FIXTURE, clean_index_build, snapshot class BuildSanityTests(unittest.TestCase): def test_subject_and_progress_indexes_match_baseline(self): baseline = json.loads(FIXTURE.read_text()) with clean_index_build() as gen: actual = snapshot(gen) self.assertEqual(set(actual), set(baseline)) for rel, expected in baseline.items(): with self.subTest(file=rel): self.assertEqual(actual[rel], expected) first = {p: p.read_bytes() for p in gen.glob("lang/*/zh_*.json")} build_app.main() self.assertEqual(first, {p: p.read_bytes() for p in first}) # Exercise the incremental contract with explicit, reproducible # input instead of relying on locally generated retired subjects. path = gen / "lang/en/zh_TW.json" subjects = json.loads(path.read_text()) active = subjects[0] active["id"] = "preserved-id" active["hiddenAt"] = "2000-01-01T00:00:00.000Z" active["learnCards"] = ["readings"] active["quizCards"] = ["meanings"] active["data"].update(srsId=42, meaningHint="Manual hint", meanings=[{"value": "Manual meaning"}]) retired = {"id": "retired-id", "hiddenAt": "2001-01-01T00:00:00.000Z", "learnCards": ["meanings"], "quizCards": ["readings"], "data": {"slug": "retired-test-subject", "type": "Vocabulary", "level": 3, "position": 4, "srsId": 7, "readings": [], "requiredSubjects": []}} subjects.append(retired) path.write_text(json.dumps(subjects, ensure_ascii=False)) build_app.main() result = {s["id"]: s for s in json.loads(path.read_text())} preserved = result["preserved-id"] self.assertNotIn("hiddenAt", preserved) for field in ["learnCards", "quizCards"]: self.assertEqual(preserved[field], active[field]) for field in ["srsId", "meaningHint", "meanings", "slug"]: self.assertEqual(preserved["data"][field], active["data"][field]) retired["data"].update(level=0, position=0) self.assertEqual(result["retired-id"], retired) first = path.read_bytes() build_app.main() self.assertEqual(path.read_bytes(), first) def test_game_decks_keep_order_and_string_fields(self): with tempfile.TemporaryDirectory() as directory, contextlib.redirect_stdout(io.StringIO()): out = Path(directory) games_build.build_hiragana(ROOT / "data/games/hiragana", out / "hiragana", True) games_build.build_zhuyin(ROOT / "data/games/zhuyin", out / "zhuyin", True) for game, rows, field in [("hiragana", games_build.HIRAGANA_ROWS, "kana"), ("zhuyin", games_build.ZHUYIN_ROWS, "zhuyin")]: decks = json.loads((out / game / "decks.json").read_text()) self.assertEqual(list(decks), [label for label, _ in rows]) for label, filename in rows: self.assertEqual(decks[label]["filename"], filename) self.assertTrue(decks[label]["cards"]) for card in decks[label]["cards"]: self.assertIsInstance(card[field], str) self.assertIsInstance(card["english"], str) def test_dispatcher_routes_every_command(self): commands = {"sort:dicts": "sort_dicts.py", "update:dicts": "update_dicts.py", "update:sentences": "update_sentences.py", "games:audio-matrix": "games_audio_matrix.py"} for command, script in commands.items(): with self.subTest(command=command), patch.object(sys, "argv", ["data", command]), \ patch.object(data, "run_script") as run: data.main() run.assert_called_once_with(script) for flags in [[], ["--prod"]]: with self.subTest(flags=flags), patch.object(sys, "argv", ["data", "build-data", *flags]), \ patch("builtins.input", side_effect=AssertionError("Audio prompt without --audio")), \ patch.object(data, "run_script") as run, contextlib.redirect_stdout(io.StringIO()): data.main() self.assertEqual([c.args for c in run.call_args_list], [(s, *flags) for s in ["build_app.py", "build_progress.py", "build_licenses.py", "games_build.py"]]) def test_build_data_audio_runs_before_indexes_and_games(self): with patch.object(sys, "argv", ["data", "build-data", "--audio", "--prod"]), \ patch("builtins.input", side_effect=["zh_CN", "character", "3"]) as prompt, \ patch.object(data, "run_script") as run, contextlib.redirect_stdout(io.StringIO()): data.main() self.assertEqual(prompt.call_count, 3) self.assertEqual([c.args for c in run.call_args_list], [ ("build_audio.py", "zh_CN", "character", "3"), ("games_gen_audio_zhuyin.py",), ("build_app.py", "--prod"), ("build_progress.py", "--prod"), ("build_licenses.py", "--prod"), ("games_build.py", "--prod"), ]) def test_audio_prompts_validate_inputs_and_default_limit(self): with patch("builtins.input", side_effect=["bad", " ja ", "bad", "vocabulary", "-1", "bad", ""]), \ contextlib.redirect_stdout(io.StringIO()): self.assertEqual(data.prompt_audio_args(), ("ja", "vocabulary", "0")) class StudioSanityTests(unittest.TestCase): def test_updates_preserve_existing_ids_and_values(self): with tempfile.TemporaryDirectory() as directory, contextlib.redirect_stdout(io.StringIO()): root = Path(directory) path = root / "readings.tsv" # Deliberately reordered headers: values must be looked up by name. common.write_tsv_rows(path, ["pinyin", "id"], [["manual", "c-1"]]) defs = [{"id": "c-1"}, {"id": "c-2"}] with patch.object(common, "DATA_ROOT", root), patch.object(update_dicts, "DATA_ROOT", root): update_dicts.update_readings("readings.tsv", ["id", "pinyin"], lambda d: [d["id"], "new"], defs, []) self.assertEqual(common.read_tsv_rows(path), (["id", "pinyin"], [["c-1", "manual"], ["c-2", "new"]])) first = path.read_bytes() update_dicts.update_readings("readings.tsv", ["id", "pinyin"], lambda d: self.fail("existing reading recomputed"), defs, []) self.assertEqual(path.read_bytes(), first) with patch.object(sort_dicts, "DATA_ROOT", root): sort_dicts.sort_file("readings.tsv", {"c-2": 0}) self.assertEqual(common.read_tsv_rows(path)[1], [["c-2", "new"], ["c-1", "manual"]]) def test_pinyin_source_precedence(self): with patch.object(update_dicts, "chinese_to_pinyin", side_effect=AssertionError): self.assertEqual(update_dicts.get_pinyin({"你": "manual"}, {"hans": "你"}), "manual") def test_sentence_parser_and_curriculum_levels(self): self.assertEqual(common.parse_records('\ufeff1\t"a"bare"\t2\t你\r\n'), [["1", 'a"bare', "2", "你"]]) self.assertEqual(common.parse_records('1\t"a\nb"\t2\t你\n'), [["1", "a\nb", "2", "你"]]) self.assertEqual(update_sentences.compute_sentence_level("你好!123", {"你": 1, "好": 3}), 3) self.assertIsNone(update_sentences.compute_sentence_level("你未知", {"你": 1})) values = [{"id": 1, "value": "你"}, {"id": 3, "value": "好"}, {"id": 2, "value": "你"}] self.assertEqual([s["id"] for s in update_sentences.dedupe_and_sort(values, {"你": 0, "好": 1})], [2, 3]) def test_audio_filenames_and_region_positions(self): filename = build_audio.audio_filename("c-00001", "zh_CN", ("pinyin", "nǐ")) self.assertEqual(filename, "c-00001_zh-CN_zh-CN-XiaoxiaoNeural_pinyin_nǐ.mp3") self.assertEqual(build_audio.audio_filename("c-00001", "zh_TW", None), "c-00001_zh-TW_zh-TW-YunJheNeural.mp3") regions = games_audio_matrix.tsv_to_region_csv("kana\tromaji\nあ\ta\nい\ti\n") self.assertEqual(regions, "#,name,start,end,length\r\nR0,あ,1.1.00,2.1.00,1.0.00\r\nR1,い,2.1.00,3.1.00,1.0.00\r\n") with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "cards.tsv" path.write_text("zhuyin\tpinyin\tenglish\thant\nㄅ\tb\n") self.assertEqual(games_gen_audio_zhuyin.read_flashcard_tsv(path), [("ㄅ", "")]) def test_license_schema_without_network(self): response = unittest.mock.MagicMock() response.read.return_value = b"License text" response.headers.get_content_charset.return_value = "utf-8" response.__enter__.return_value = response with tempfile.TemporaryDirectory() as directory, patch.object(common, "GEN_ROOT", Path(directory)), \ patch.object(build_licenses, "read_tsv", return_value=[{"name": "Example", "href": "https://example.org/license"}]), \ patch.object(build_licenses.urllib.request, "urlopen", return_value=response) as urlopen, \ patch.object(sys, "argv", ["licenses"]), contextlib.redirect_stdout(io.StringIO()): build_licenses.main() request = urlopen.call_args.args[0] self.assertEqual(request.full_url, "https://example.org/license") self.assertEqual(request.get_header("User-agent"), "Mozilla/5.0") self.assertEqual(urlopen.call_args.kwargs, {"timeout": 30}) self.assertEqual(json.loads((Path(directory) / "licenses.json").read_text()), [{"name": "Example", "href": "https://example.org/license", "text": "License text"}]) def requires_package(module): return unittest.skipUnless( importlib.util.find_spec(module) is not None, f"optional integration check needs {module}; install requirements.txt with the test interpreter", ) class LanguageDependencyTests(unittest.TestCase): @requires_package("opencc") def test_opencc_converter(self): self.assertEqual(build_progress.hant_to_hans_converter()("乾淨"), "干净") converter = update_sentences.ChineseConverter() self.assertEqual(converter.zh_cn("你好嗎"), "你好吗") self.assertEqual(converter.zh_tw("你好吗"), "你好嗎") @requires_package("pinyin_jyutping") def test_jyutping_adapter(self): self.assertEqual(update_dicts.to_jyutping("你好"), "nei5 hou2") @requires_package("pyzhuyin") def test_zhuyin_adapter(self): self.assertEqual(update_dicts.pinyin_to_zhuyin("nǐ hǎo"), "ㄋㄧˇ ㄏㄠˇ") self.assertEqual(update_dicts.pinyin_to_zhuyin("yuè"), "ㄩㄝˋ") self.assertEqual(update_dicts.pinyin_to_zhuyin("invalid"), "") if __name__ == "__main__": unittest.main()