"""Seven-tier tests for ``muse/core/terminal.py`` — ``use_color``. Tiers ----- Unit — each branch: NO_COLOR set, TERM=dumb, isatty True/False. Integration — env var combinations, interaction with stdout redirection. End-to-end — CLI commands respect use_color (no ANSI in piped output). Stress — 100 000 calls; concurrent calls with env mutation. Data integrity — return value is strictly bool; NO_COLOR value doesn't matter. Security — hostile env var values do not crash or inject. Performance — 100 000 calls under 1 s. """ from __future__ import annotations import os import pathlib import subprocess import sys import threading import time from unittest import mock import pytest # ────────────────────────────────────────────────────────────────────────────── # Unit — branch-by-branch # ────────────────────────────────────────────────────────────────────────────── class TestUnit: def test_no_color_set_returns_false(self) -> None: from muse.core.terminal import use_color with mock.patch.dict(os.environ, {"NO_COLOR": "1"}, clear=False): assert use_color() is False def test_no_color_empty_string_returns_false(self) -> None: """NO_COLOR spec says any value (including empty) disables colour.""" from muse.core.terminal import use_color with mock.patch.dict(os.environ, {"NO_COLOR": ""}, clear=False): assert use_color() is False def test_term_dumb_returns_false(self) -> None: from muse.core.terminal import use_color env = {k: v for k, v in os.environ.items() if k != "NO_COLOR"} env["TERM"] = "dumb" with mock.patch.dict(os.environ, env, clear=True): assert use_color() is False def test_tty_true_no_inhibitors_returns_true(self) -> None: from muse.core.terminal import use_color env = {k: v for k, v in os.environ.items() if k not in ("NO_COLOR", "TERM")} with mock.patch.dict(os.environ, env, clear=True), \ mock.patch("sys.stdout") as mock_stdout: mock_stdout.isatty.return_value = True assert use_color() is True def test_tty_false_returns_false(self) -> None: from muse.core.terminal import use_color env = {k: v for k, v in os.environ.items() if k not in ("NO_COLOR", "TERM")} with mock.patch.dict(os.environ, env, clear=True), \ mock.patch("sys.stdout") as mock_stdout: mock_stdout.isatty.return_value = False assert use_color() is False def test_returns_bool_type(self) -> None: from muse.core.terminal import use_color with mock.patch.dict(os.environ, {"NO_COLOR": "1"}): result = use_color() assert type(result) is bool # ────────────────────────────────────────────────────────────────────────────── # Integration — env var combinations # ────────────────────────────────────────────────────────────────────────────── class TestIntegration: def test_no_color_beats_tty(self) -> None: """NO_COLOR must win even when stdout is a TTY.""" from muse.core.terminal import use_color with mock.patch.dict(os.environ, {"NO_COLOR": "1"}), \ mock.patch("sys.stdout") as mock_stdout: mock_stdout.isatty.return_value = True assert use_color() is False def test_term_dumb_beats_tty(self) -> None: from muse.core.terminal import use_color env = {k: v for k, v in os.environ.items() if k != "NO_COLOR"} env["TERM"] = "dumb" with mock.patch.dict(os.environ, env, clear=True), \ mock.patch("sys.stdout") as mock_stdout: mock_stdout.isatty.return_value = True assert use_color() is False def test_no_color_and_term_dumb_both_set_returns_false(self) -> None: from muse.core.terminal import use_color with mock.patch.dict(os.environ, {"NO_COLOR": "1", "TERM": "dumb"}): assert use_color() is False def test_term_xterm_not_dumb_does_not_inhibit(self) -> None: from muse.core.terminal import use_color env = {k: v for k, v in os.environ.items() if k != "NO_COLOR"} env["TERM"] = "xterm-256color" with mock.patch.dict(os.environ, env, clear=True), \ mock.patch("sys.stdout") as mock_stdout: mock_stdout.isatty.return_value = True assert use_color() is True def test_no_color_unset_term_non_dumb_tty_false_returns_false(self) -> None: from muse.core.terminal import use_color env = {k: v for k, v in os.environ.items() if k not in ("NO_COLOR",)} env["TERM"] = "xterm" with mock.patch.dict(os.environ, env, clear=True), \ mock.patch("sys.stdout") as mock_stdout: mock_stdout.isatty.return_value = False assert use_color() is False # ────────────────────────────────────────────────────────────────────────────── # End-to-end — subprocess with NO_COLOR; CLI output has no ANSI # ────────────────────────────────────────────────────────────────────────────── class TestEndToEnd: def test_no_color_env_prevents_ansi_in_subprocess(self, tmp_path: "pathlib.Path") -> None: """When NO_COLOR is set, use_color() returns False in a fresh process.""" script = "from muse.core.terminal import use_color; print(use_color())" result = subprocess.run( [sys.executable, "-c", script], env={**os.environ, "NO_COLOR": "1"}, capture_output=True, text=True, ) assert result.stdout.strip() == "False" def test_term_dumb_prevents_ansi_in_subprocess(self, tmp_path: "pathlib.Path") -> None: script = "from muse.core.terminal import use_color; print(use_color())" env = {k: v for k, v in os.environ.items() if k != "NO_COLOR"} env["TERM"] = "dumb" result = subprocess.run( [sys.executable, "-c", script], env=env, capture_output=True, text=True, ) assert result.stdout.strip() == "False" def test_piped_output_is_not_tty(self) -> None: """When stdout is redirected to a pipe, isatty() returns False.""" script = "import sys; print(sys.stdout.isatty())" result = subprocess.run( [sys.executable, "-c", script], capture_output=True, text=True, ) assert result.stdout.strip() == "False" # ────────────────────────────────────────────────────────────────────────────── # Stress # ────────────────────────────────────────────────────────────────────────────── class TestStress: def test_100000_calls_no_crash(self) -> None: from muse.core.terminal import use_color with mock.patch.dict(os.environ, {"NO_COLOR": "1"}): for _ in range(100_000): use_color() def test_concurrent_calls_consistent(self) -> None: """Concurrent calls with NO_COLOR=1 must all return False.""" from muse.core.terminal import use_color results: list[bool] = [] lock = threading.Lock() def _call() -> None: with mock.patch.dict(os.environ, {"NO_COLOR": "1"}): v = use_color() with lock: results.append(v) threads = [threading.Thread(target=_call) for _ in range(100)] for t in threads: t.start() for t in threads: t.join() assert all(v is False for v in results) assert len(results) == 100 def test_alternating_no_color_calls(self) -> None: from muse.core.terminal import use_color for i in range(10_000): with mock.patch.dict(os.environ, {"NO_COLOR": "1"} if i % 2 == 0 else {}): result = use_color() if i % 2 == 0: assert result is False # ────────────────────────────────────────────────────────────────────────────── # Data integrity # ────────────────────────────────────────────────────────────────────────────── class TestDataIntegrity: def test_return_is_always_bool(self) -> None: from muse.core.terminal import use_color for env_patch, isatty in [ ({"NO_COLOR": "1"}, True), ({}, False), ]: with mock.patch.dict(os.environ, env_patch), \ mock.patch("sys.stdout") as m: m.isatty.return_value = isatty result = use_color() assert type(result) is bool def test_no_color_any_value_returns_false(self) -> None: """NO_COLOR spec: any non-empty value disables colour.""" from muse.core.terminal import use_color for val in ("1", "true", "yes", "0", "false", "no", "anything"): with mock.patch.dict(os.environ, {"NO_COLOR": val}): assert use_color() is False def test_result_is_deterministic_for_same_env(self) -> None: from muse.core.terminal import use_color with mock.patch.dict(os.environ, {"NO_COLOR": "1"}): results = {use_color() for _ in range(1000)} assert results == {False} # ────────────────────────────────────────────────────────────────────────────── # Security # ────────────────────────────────────────────────────────────────────────────── class TestSecurity: def test_ansi_in_no_color_value_does_not_crash(self) -> None: from muse.core.terminal import use_color with mock.patch.dict(os.environ, {"NO_COLOR": "\x1b[31mred\x1b[0m"}): result = use_color() assert result is False # any value for NO_COLOR disables colour def test_null_byte_in_term_rejected_by_os(self) -> None: """os.environ rejects null bytes at the OS level — verify the ValueError.""" env = {k: v for k, v in os.environ.items() if k != "NO_COLOR"} env["TERM"] = "xterm\x00malicious" with pytest.raises((ValueError, TypeError)): mock.patch.dict(os.environ, env, clear=True).__enter__() def test_very_long_no_color_value_does_not_crash(self) -> None: from muse.core.terminal import use_color with mock.patch.dict(os.environ, {"NO_COLOR": "x" * 100_000}): assert use_color() is False def test_very_long_term_value_does_not_crash(self) -> None: from muse.core.terminal import use_color env = {k: v for k, v in os.environ.items() if k != "NO_COLOR"} env["TERM"] = "x" * 100_000 with mock.patch.dict(os.environ, env, clear=True), \ mock.patch("sys.stdout") as m: m.isatty.return_value = False result = use_color() assert type(result) is bool # ────────────────────────────────────────────────────────────────────────────── # Performance # ────────────────────────────────────────────────────────────────────────────── class TestPerformance: def test_100000_calls_under_1s(self) -> None: from muse.core.terminal import use_color with mock.patch.dict(os.environ, {"NO_COLOR": "1"}): start = time.perf_counter() for _ in range(100_000): use_color() elapsed = time.perf_counter() - start assert elapsed < 1.0, f"100 000 calls took {elapsed:.2f}s — expected < 1s" def test_single_call_under_1ms(self) -> None: from muse.core.terminal import use_color with mock.patch.dict(os.environ, {"NO_COLOR": "1"}): start = time.perf_counter() use_color() elapsed = time.perf_counter() - start assert elapsed < 0.001, f"Single call took {elapsed*1000:.2f}ms — expected < 1ms"