"""Read-only completion checks; fixtures live under OS temp, never in dotfiles.""" import json import os from pathlib import Path import shutil import subprocess import sys import tempfile import unittest NU_DIR = Path(__file__).resolve().parents[1] NU = shutil.which("nu") def literal(value): return "r###'" + str(value) + "'###" class CompletionIntegration(unittest.TestCase): @classmethod def setUpClass(cls): if not NU or not shutil.which("mise"): raise unittest.SkipTest("Nu and Mise are required") # Resolve version-manager shims before applying isolated Mise settings. resolved = subprocess.run( [NU, "--no-config-file", "-c", "$nu.current-exe"], capture_output=True, text=True, timeout=20, ) if resolved.returncode != 0 or resolved.stderr: raise AssertionError(resolved.stderr or resolved.stdout) cls.nu = resolved.stdout.strip() parent = Path(tempfile.gettempdir()) / "pi-nu-completion-tests" parent.mkdir(exist_ok=True) cls.temporary = tempfile.TemporaryDirectory(dir=parent) cls.root = Path(cls.temporary.name) (cls.root / "folder with spaces").mkdir() (cls.root / "report with spaces.html").write_text("fixture", encoding="utf-8") (cls.root / "owner's report.html").write_text("fixture", encoding="utf-8") (cls.root / "plain.txt").write_text("fixture", encoding="utf-8") (cls.root / "alternate project").mkdir() cls.fake_mise = cls.root / "fake-mise" cls.fake_mise.mkdir() probe = cls.fake_mise / "probe.py" probe.write_text( "import json, os, sys\n" "if os.environ.get('COMPLETION_MODE') == 'files':\n" " print('\\x01files'); sys.exit(0)\n" "print('probe\\t' + json.dumps({" "'path': os.environ.get('PATH'), " "'converted': os.environ.get('COMPLETION_TEST')}))\n", encoding="utf-8", ) if os.name == "nt": (cls.fake_mise / "mise.cmd").write_text( f'@"{sys.executable}" "{probe}"\n', encoding="utf-8" ) (cls.root / "mise.toml").write_text( '[tasks.test]\n' 'description = "Fixture test task"\n' 'run = "echo unexpected > TASK_MUST_NOT_RUN"\n' 'usage = \'arg "" { choices "unit" "integration" }\'\n' '[tasks."build:docs"]\n' 'description = "Fixture docs task"\n' 'run = "echo unexpected > TASK_MUST_NOT_RUN"\n', encoding="utf-8", ) (cls.root / "alternate project" / "mise.toml").write_text( '[tasks.alternate]\nrun = "echo unexpected > TASK_MUST_NOT_RUN"\n', encoding="utf-8", ) cls.environment = os.environ.copy() cls.environment.update( MISE_TRUSTED_CONFIG_PATHS=str(cls.root), MISE_CONFIG_DIR=str(cls.root / "config"), MISE_CACHE_DIR=str(cls.root / "cache"), MISE_GLOBAL_CONFIG_FILE=str(cls.root / "empty-global.toml"), MISE_SYSTEM_CONFIG_FILE=str(cls.root / "empty-system.toml"), MISE_NO_HOOKS="1", MISE_NO_ENV="1", MISE_OFFLINE="1", ) # Test current production generation, never the user's stale autoload. cls.wrapper_config = cls.root / "nu-config" cls.wrapper_config.mkdir() generation = subprocess.run( [cls.nu, "--no-config-file", "--config-home", str(cls.wrapper_config), "-c", f"use {literal(NU_DIR / 'modules' / 'commands.nu')} *; generate-scoped-externals"], env=cls.environment, capture_output=True, text=True, timeout=20, ) if generation.returncode != 0 or generation.stderr: raise AssertionError(generation.stderr or generation.stdout) cls.wrappers = cls.wrapper_config / "autoload" / "90-work-scope.nu" if not cls.wrappers.exists(): raise AssertionError("Production wrapper generation produced no autoload") if os.name != "nt": # Completion must not enter the scope runner or contact user systemd. guard_bin = cls.root / "scope-tripwire" guard_bin.mkdir() guard = guard_bin / "systemd-run" guard.write_text( f"#!{sys.executable}\n" "from pathlib import Path\n" f"Path({str(cls.root / 'WRAPPER_MUST_NOT_RUN')!r}).touch()\n" "raise SystemExit(99)\n", encoding="utf-8", ) guard.chmod(0o700) cls.environment["PATH"] = str(guard_bin) + os.pathsep + cls.environment.get("PATH", "") @classmethod def tearDownClass(cls): try: if list(cls.root.rglob("TASK_MUST_NOT_RUN")): raise AssertionError("Completion executed a task") if (cls.root / "WRAPPER_MUST_NOT_RUN").exists(): raise AssertionError("Completion executed a generated wrapper") finally: cls.temporary.cleanup() def run_nu(self, code, *, environment=None): imports = ( f"source {literal(NU_DIR / 'autoload' / '30-carapace.nu')}; " f"source {literal(self.wrappers)}; " f"use {literal(NU_DIR / 'modules' / 'start.nu')}; " ) result = subprocess.run( [self.nu, "--no-config-file", "-c", imports + code], cwd=self.root, env=self.environment if environment is None else environment, capture_output=True, encoding="utf-8", timeout=20, check=False, ) self.assertEqual(0, result.returncode, result.stderr) self.assertNotIn("deprecated", result.stderr) return json.loads(result.stdout) def completions(self, text, setup=""): return self.run_nu( "do { " + setup + f"{literal(text)} | commandline complete }} | to json" ) def test_commands_and_nested_flags(self): self.assertIn("use", self.completions("mise us")) self.assertIn("--dry-run", self.completions("mise run --dr")) self.assertIn("nu", self.completions("mise env --shell n")) self.assertEqual([], self.completions("mise --not-a-real-flag")) def test_tasks_and_descriptions(self): self.assertIn("test", self.completions("mise run te")) self.assertIn("build:docs", self.completions("mise build:")) result = self.run_nu( "'mise run te' | commandline complete --detailed | to json" ) self.assertTrue(any("Fixture test" in x.get("description", "") for x in result)) def test_available_tools(self): self.assertIn("node@", self.completions("mise use no")) def test_task_arguments(self): self.assertIn("unit", self.completions("mise run test u")) self.assertIn("integration", self.completions("mise test i")) def test_wrapper_alias_and_pipeline(self): wrapper = ( "@complete external\ndef --wrapped mise [...args] { " "error make {msg: 'wrapper must not execute during completion'} }; " ) self.assertIn("--dry-run", self.completions("mise run --dr", wrapper)) self.assertIn("--dry-run", self.completions("m run --dr", wrapper + "alias m = mise; ")) self.assertIn("use", self.completions("'ignored' | mise us")) if os.name == "nt": self.assertIn("use", self.completions("mise.exe us")) def test_quoted_project_context(self): variants = [ '"alternate project"', "`alternate project`", "'" + str(self.root / "alternate project") + "'", ] for repeat in range(3): for directory in variants: with self.subTest(repeat=repeat + 1, directory=directory): self.assertIn( "alternate", self.completions("mise -C " + directory + " run alt"), ) @unittest.skipUnless(os.name == "nt", "Windows PATH casing regression") def test_path_casing_and_nested_scopes(self): text = "mise -C '" + str(self.root / "alternate project") + "' run alt" query = ( "$env.ENV_CONVERSIONS = ($env.ENV_CONVERSIONS | upsert COMPLETION_TEST " "{to_string: { 'preserved' }}); " "let before = ($env | select -o PATH Path path); " "let matches = (" + literal(text) + " | commandline complete); " "{matches: $matches, parent_unchanged: " "(($env | select -o PATH Path path) == $before), " "conversion_preserved: (do $env.ENV_CONVERSIONS.COMPLETION_TEST.to_string)}" ) for casing in ["PATH", "Path", "path"]: environment = { k: v for k, v in self.environment.items() if k.lower() != "path" } environment[casing] = os.environ["PATH"] for nested in [False, True]: code = query if nested: code = ( "do { load-env {path: ($env.PATH | prepend " + literal(self.root / "outer-path") + ")}; " "do { load-env {PATH: ($env.PATH | prepend " + literal(self.root / "inner-path") + ")}; " + code + " } }" ) for repeat in range(3): with self.subTest(casing=casing, nested=nested, repeat=repeat + 1): result = self.run_nu(code + " | to json", environment=environment) self.assertIn("alternate", result["matches"]) self.assertTrue(result["parent_unchanged"]) self.assertEqual("preserved", result["conversion_preserved"]) @unittest.skipUnless(os.name == "nt", "Windows PATH serialization regression") def test_child_path_serialization(self): semicolon = self.root / "tools;archive" query = ( "use " + literal(NU_DIR / "modules" / "mise-completions.nu") + "; " "let before = ($env | select -o PATH Path path); " "let captured = (with-env {PATH: ([" + literal(self.fake_mise) + " '~/nu-completion-missing' " + literal(semicolon) + "] ++ $env.PATH)} { " "mise-completions {command: [mise probe]} " "| get completions.0.description | from json }); " "{payload: $captured, parent_unchanged: " "(($env | select -o PATH Path path) == $before)} | to json" ) result = self.run_nu(query) self.assertIn('"' + str(semicolon) + '"', result["payload"]["path"]) self.assertIn(str(Path.home() / "nu-completion-missing"), result["payload"]["path"]) self.assertNotIn("~/", result["payload"]["path"]) self.assertTrue(result["parent_unchanged"]) @unittest.skipUnless(os.name == "nt", "Windows PATH conversion regression") def test_existing_child_conversions(self): custom = str(self.root / "custom-conversion") query = ( "use " + literal(NU_DIR / "modules" / "mise-completions.nu") + "; " "$env.ENV_CONVERSIONS = ($env.ENV_CONVERSIONS | merge {" "Path: {from_string: { split row ';' }, " "to_string: {|paths| $paths | prepend " + literal(custom) + " | str join (char esep)}}, " "COMPLETION_TEST: {to_string: { str join ':' }}}); " "$env.COMPLETION_TEST = [converted yes]; " "let before = (do $env.ENV_CONVERSIONS.Path.to_string $env.PATH); " "let captured = (with-env {PATH: ($env.PATH | prepend " + literal(self.fake_mise) + ")} { " "mise-completions {command: [mise probe]} " "| get completions.0.description | from json }); " "{payload: $captured, converter_unchanged: " "((do $env.ENV_CONVERSIONS.Path.to_string $env.PATH) == $before), " "from_string: ('a;b' | do $env.ENV_CONVERSIONS.Path.from_string 'a;b')} | to json" ) result = self.run_nu(query) self.assertIn(custom, result["payload"]["path"]) self.assertEqual("converted:yes", result["payload"]["converted"]) self.assertTrue(result["converter_unchanged"]) self.assertEqual(["a", "b"], result["from_string"]) def test_mise_directory_values(self): results = self.completions('mise -C "folder') self.assertTrue(any("folder with spaces" in value for value in results)) self.assertFalse(any("plain.txt" in value for value in results)) def test_start_files_and_multiple_arguments(self): for text in ["start report", "start plain.txt report", 'start "report']: results = self.completions(text) self.assertTrue(any("report with spaces.html" in value for value in results)) result = self.run_nu( "'start report' | commandline complete | first | to json" ) self.assertIn("report with spaces.html", result) self.assertIn(result[0], ['`', "'", '"']) self.assertTrue(any("owner's report" in x for x in self.completions("start owner"))) def test_start_replacement_spans(self): for text in ["start report", "start plain.txt report", 'start "report']: with self.subTest(input=text): records = self.run_nu( literal(text) + " | commandline complete --detailed | to json" ) suggestion = next(x for x in records if "report with spaces" in x["value"]) span = suggestion["span"] completed = text[:span["start"]] + suggestion["value"] + text[span["end"]:] expected_prefix = "start plain.txt " if "plain.txt" in text else "start " self.assertTrue(completed.startswith(expected_prefix), completed) @unittest.skipUnless(os.name == "nt", "Windows mock Mise launcher") def test_mise_path_hint_spans(self): text = "mise probe report" records = self.run_nu( "with-env {PATH: ($env.PATH | prepend " + literal(self.fake_mise) + "), COMPLETION_MODE: files} { " + literal(text) + " | commandline complete --detailed } | to json" ) suggestion = next(x for x in records if "report with spaces" in x["value"]) self.assertEqual(len("mise probe "), suggestion["span"]["start"]) self.assertEqual(len(text), suggestion["span"]["end"]) def test_start_urls(self): for url in ["https://example.com/report", "mailto:person@example.com", "file:///report"]: self.assertEqual([], self.completions("start " + url)) self.assertTrue(self.completions("start https://example.com report")) def test_missing_mise_declines(self): result = self.run_nu( "use " + literal(NU_DIR / "modules" / "mise-completions.nu") + "; " "let place = ('mise us' | commandline complete --input | get place); " "with-env {Path: [], PATH: []} { " "mise-completions $place } | to json" ) self.assertIsNone(result) if __name__ == "__main__": unittest.main()