import importlib.util from pathlib import Path import unittest import sqlite3 import io from contextlib import redirect_stdout from types import SimpleNamespace SCRIPT = Path(__file__).with_name("pageswiki-cli") SPEC = importlib.util.spec_from_file_location("pageswiki_cli", SCRIPT) if SPEC is None or SPEC.loader is None: from importlib.machinery import SourceFileLoader SPEC = importlib.util.spec_from_loader( "pageswiki_cli", SourceFileLoader("pageswiki_cli", str(SCRIPT)), ) assert SPEC is not None and SPEC.loader is not None pageswiki_cli = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(pageswiki_cli) class ContentTypeDetectionTest(unittest.TestCase): def test_extensionless_shell(self) -> None: content_type = pageswiki_cli.detect_content_type( b"#!/usr/bin/env bash\necho hello\n", ) self.assertEqual(content_type, "application/x-sh; charset=utf-8") def test_extensionless_utf8_text(self) -> None: content_type = pageswiki_cli.detect_content_type( "拡張子なしの文書\n".encode(), ) self.assertEqual(content_type, "text/plain; charset=utf-8") def test_magic_number_wins_over_text_analysis(self) -> None: content_type = pageswiki_cli.detect_content_type( b"%PDF-1.7\nsample", ) self.assertEqual(content_type, "application/pdf") def test_shift_jis_text(self) -> None: content_type = pageswiki_cli.detect_content_type( "日本語の文書\n".encode("shift_jis"), ) self.assertEqual(content_type, "text/plain; charset=shift_jis") class ExtensionDefaultTest(unittest.TestCase): def test_gecko_is_opt_in(self) -> None: db = sqlite3.connect(":memory:") self.addCleanup(db.close) db.execute("CREATE TABLE config(domain_uuid TEXT,key TEXT,value TEXT,updated_at INTEGER,UNIQUE(domain_uuid,key))") # Exercise the CLI command without reading any deployment database. owner = next(value for value in vars(pageswiki_cli).values() if isinstance(value, type) and hasattr(value, "command_extension")) fixture = SimpleNamespace(db=db, domain_uuid="synthetic") output = io.StringIO() with redirect_stdout(output): owner.command_extension(fixture, ["viewer.gecko"]) owner.command_extension(fixture, ["viewer.gecko", "on"]) owner.command_extension(fixture, ["viewer.gecko"]) owner.command_extension(fixture, ["viewer.gecko", "off"]) owner.command_extension(fixture, ["viewer.gecko"]) self.assertEqual(output.getvalue().splitlines(), ["viewer.gecko\tdisabled", "viewer.gecko\ton", "viewer.gecko\tenabled", "viewer.gecko\toff", "viewer.gecko\tdisabled"]) if __name__ == "__main__": unittest.main()