okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-web: the served web chat page for 0.2.75d9f47922

main
4.6 KiB108 linesraw
1"""The web page's translations: the mechanism (node, serve/test_web_i18n.js), the files the server hands out for it
2(serve/web/locales, serve/web/vendor), and the catalogs against the text in the code (tools/web_i18n.py)."""
3from __future__ import annotations
4
5import shutil
6import subprocess
7import sys
8import unittest
9import urllib.error
10import urllib.request
11from pathlib import Path
12
13ROOT = Path(__file__).resolve().parents[1]
14sys.path.insert(0, str(ROOT / "tools"))
15
16import web_i18n  # noqa: E402
17from serve.frontend import ChatTemplate  # noqa: E402
18from serve.server import ByteTokenizer, MockEngine, Service, serve  # noqa: E402
19from serve.webfiles import subtree_file  # noqa: E402
20
21
22def run_node(script: str, *args: str) -> None:
23    result = subprocess.run([shutil.which("node"), str(Path(__file__).with_name(script)), *args],
24                            capture_output=True, text=True, timeout=60)
25    if result.returncode:
26        raise AssertionError((result.stdout + result.stderr).strip())
27
28
29@unittest.skipUnless(shutil.which("node"), "node is not installed")
30class Mechanism(unittest.TestCase):
31    def test_tr_apply_and_set_language(self):
32        run_node("test_web_i18n.js")
33
34
35class WhatTheServerHandsOut(unittest.TestCase):
36    """/web/locales and /web/vendor: whitelisted names and types, nothing outside those folders."""
37
38    def test_names_and_types(self):
39        web = Path(__file__).parent / "web"
40        locales = web / "locales"
41        if (locales / "de.json").is_file():
42            self.assertEqual(subtree_file("/web/locales/de.json")[1], "application/json; charset=utf-8")
43        for bad in ("/web/locales/de.js", "/web/locales/DE.json", "/web/locales/../app.js", "/web/locales/x/y.json",
44                    "/web/locales/%2e%2e%2fapp.json", "/web/locales/de.json%00.js", "/web/locales/missing.json",
45                    "/web/locales/C:\\x.json", "/web/vendor/katex/../../app.js", "/web/vendor/katex/dist/katex.min.js.map",
46                    "/web/vendor/other/dist/katex.min.js", "/web/vendor/katex/dist/fonts/x.ttf", "/web/vendor/katex/dist/"):
47            with self.subTest(bad=bad):
48                self.assertIsNone(subtree_file(bad))
49
50    def test_a_link_out_of_the_folder_is_refused(self):
51        import tempfile
52        with tempfile.TemporaryDirectory() as d:
53            web = Path(d) / "web"
54            (web / "vendor" / "katex").mkdir(parents=True)
55            (web / "locales").mkdir()
56            (web / "secret.js").write_text("secret")
57            (web / "vendor" / "katex" / "ok.js").write_text("ok")
58            self.assertEqual(subtree_file("/web/vendor/katex/ok.js", web)[1], "text/javascript; charset=utf-8")
59            try:
60                (web / "vendor" / "katex" / "link.js").symlink_to(web / "secret.js")
61            except (OSError, NotImplementedError):
62                self.skipTest("symlinks need a privilege here")
63            self.assertIsNone(subtree_file("/web/vendor/katex/link.js", web))
64
65
66class Served(unittest.TestCase):
67    @classmethod
68    def setUpClass(cls):
69        tok = ByteTokenizer()
70        cls.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(ROOT / "serve" / "chat_template.jinja"))
71        cls.httpd = serve(cls.svc, port=0)
72        cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
73
74    @classmethod
75    def tearDownClass(cls):
76        cls.httpd.shutdown()
77        cls.httpd.server_close()
78
79    def get(self, path):
80        try:
81            with urllib.request.urlopen(self.base + path, timeout=10) as r:
82                return r.status, r.headers.get("Content-Type", ""), r.read()
83        except urllib.error.HTTPError as e:
84            return e.code, e.headers.get("Content-Type", ""), e.read()
85
86    def test_i18n_script_and_refusals(self):
87        code, ctype, body = self.get("/web/i18n.js")
88        self.assertEqual(code, 200)
89        self.assertIn(b"StrataI18n", body)
90        for path in ("/web/locales/../server.py", "/web/locales/nope.json", "/web/vendor/katex/../../app.js",
91                     "/web/vendor/katex/dist/missing.js", "/web/locales/de.json%00"):
92            with self.subTest(path=path):
93                self.assertEqual(self.get(path)[0], 404)
94
95
96@unittest.skipUnless((Path(__file__).parent / "web" / "locales" / "en.json").is_file(), "no catalogs yet")
97class Catalogs(unittest.TestCase):
98    """Every language in serve/web/i18n.js has a catalog with exactly the keys and {placeholders} of the code."""
99
100    def test_the_text_in_the_code_is_plain_literals(self):
101        self.assertTrue(web_i18n.english())
102
103    def test_catalogs_are_complete(self):
104        self.assertEqual(web_i18n.check(), [])
105
106
107if __name__ == "__main__":
108    unittest.main()