13 Commits
Author SHA1 Message Date
kiskaadee 61de44425a Merge pull request 'feat(config): bootstrap Nix package, Pydantic TvConfig, and error taxonomy' (#6) from feat/issue-1-config-bootstrap into main
Core Architecture & Invariant CI / validate (push) Successful in 16s
2026-11-15 14:11:16 -05:00
kiskaadee 290c1a1f6a refactor(config): deduplicate IPv4/bounded-int validators and exclude docs/poc from ruff format
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
- Extract shared _parse_ipv4 and _parse_bounded_int helpers in config.py and reject float/non-int values instead of truncating (CR-01)
- Add direct TvConfig float rejection tests in tests/test_config.py
- Exclude docs/poc/** under [tool.ruff.format] in pyproject.toml and revert formatting churn in docs/poc/tv_test.py (CR-02)
2026-11-15 14:02:23 -05:00
kiskaadee 80cb7594c3 docs(agents): codify validation, error domain, dependency, and Python 3.14 SOPs
Core Architecture & Invariant CI / validate (pull_request) Successful in 16s
- Add section 3.2 covering Pydantic v2 boundary validation vs dataclasses, Exception subclassing, ConfigError vs TvError separation, and explicit single-sourced Nix/pyproject dependencies
- Add rule 5.4 documenting Python 3.14 native PEP 649 typing (TID251) and strict pyright expectations
2026-11-15 13:47:25 -05:00
kiskaadee b8dc476f38 docs(agents): enforce behavior-driven test_<unit>_<behavior> naming rule
- Add rule 5.3 in AGENTS.md requiring consistent test_<unit>_<behavior> test function names
2026-11-15 13:39:07 -05:00
kiskaadee 6ea84db8e1 test(config): standardize behavior-driven test names in test_config.py
- Rename broad test functions to follow consistent test_<unit>_<behavior> convention
2026-11-15 13:37:12 -05:00
kiskaadee 28d3a8cbab feat(config): enforce Pydantic v2 TvConfig validation and raise ConfigError
- Add standalone ConfigError(Exception) in errors.py decoupled from runtime TvError
- Convert TvConfig from dataclass to frozen Pydantic v2 BaseModel with field_validator hooks using PydanticCustomError
- Validate TV_IP and WOL_BROADCAST as IPv4 addresses, PORT in 1..65535, and MAX_VOLUME in 0..100 on both load_config() and direct TvConfig instantiation
- Redirect Pydantic ValidationError to ConfigError in TvConfig.__init__ and raise ConfigError from require_bearer_token/require_mac
- Declare pydantic explicitly in flake.nix runtimeDeps and pyproject.toml dependencies
- Expand tests/test_config.py to cover ConfigError and direct TvConfig validation
2026-11-15 13:20:41 -05:00
kiskaadee 7ec752d4ac refactor(typing): drop __future__.annotations on Python 3.14 and enable strict pyright
- Set requires-python = ">=3.14" in pyproject.toml to match the Nix Python 3.14 runtime and PEP 649 native deferred annotation semantics
- Remove redundant from __future__ import annotations across src/lg_smtv_mcp/ and tests/test_config.py
- Add ruff TID251 rule banning __future__.annotations in package and test modules (ignoring docs/poc/*)
- Switch pyright typeCheckingMode from basic to strict in pyproject.toml
2026-11-15 12:59:51 -05:00
kiskaadee a5d69eb37d ci(lint): enforce ruff format --check in pre-commit hook and flake check
- .githooks/pre-commit: add ruff format --check . alongside ruff check, pyright, and pytest
- flake.nix: add ruff format --check . to packages.default preCheck
- AGENTS.md: update Section 5 verification rules to include ruff format --check
2026-11-15 12:43:57 -05:00
kiskaadee 165a6c28da style(lint): apply automated ruff formatting 2026-11-15 12:36:36 -05:00
kiskaadee 7ea45c3d3b ci(nix): wire ruff and pyright into flake check and add Gitea Actions workflow
- flake.nix: add ruff and pyright to packages.default nativeCheckInputs and preCheck so nix build / nix flake check enforce lint, types, and pytest in the Nix sandbox
- .githooks/pre-commit: keep local pre-commit hook fast (<0.5s) running ruff, pyright, and pytest
- .gitea/workflows/ci.yaml: run nix flake check on push and pull_request to main
- AGENTS.md: document .githooks/pre-commit, @pytest.mark.xfail(strict=True) Red-phase rule, and .gitea/workflows/ci.yaml expectations
2026-11-15 12:21:01 -05:00
kiskaadee 98ffc65cb1 build(nix): deduplicate runtime/test deps and add pre-commit check hook
- flake.nix: extract shared runtimeDeps and testDeps lists for packages.default (with pytestCheckHook) and devShells.default, and configure git core.hooksPath in shellHook
- .githooks/pre-commit: run ruff check, pyright, pytest, and nix flake check before each commit
2026-11-15 12:11:53 -05:00
kiskaadee c549c83e2c feat(config): implement ErrorCode, TvConfig, load_config, CLI stub, and secret hygiene
- src/lg_smtv_mcp/errors.py: define ErrorCode(StrEnum) and TvError(code, message) domain error taxonomy
- src/lg_smtv_mcp/config.py: add frozen TvConfig, stdlib .env fallback in load_config(), range/required validations, ALLOWED_HOSTS parsing, require_bearer_token(), and require_mac()
- src/lg_smtv_mcp/{__init__,__main__,cli}.py: add package root, module entrypoint, and minimal main() CLI stub
- .gitignore & .env.example: exclude SSH key artifacts and provide placeholder runtime config template
2026-11-15 11:03:18 -05:00
kiskaadee 35a66bd456 test(config): add Nix packaging, pyproject, and Red-phase config/error tests
- flake.nix: expose packages.default (buildPythonApplication) and expand devShell with mcp, asyncssh, uvicorn, httpx, pytest, pytest-asyncio, and PYTHONPATH shellHook
- pyproject.toml: configure setuptools build-system, project metadata/dependencies, lg-smtv-mcp script entrypoint, pytest asyncio/pythonpath, and pyright include paths
- tests/test_config.py: add Red-phase unit tests for ErrorCode, TvError, load_config(), .env fallback, validation, ALLOWED_HOSTS, require_bearer_token(), and require_mac()
2026-11-15 10:51:07 -05:00
13 changed files with 609 additions and 9 deletions

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
TV_IP=<TV_IP>
TV_MAC=<TV_MAC>
WOL_BROADCAST=255.255.255.255
CLIENT_KEY_PATH=.client_key.json
SSH_KEY_PATH=
WEBOS_SSH_PASSPHRASE=
SSH_KNOWN_HOSTS_PATH=
HOST=127.0.0.1
PORT=8765
ALLOWED_HOSTS=
MCP_BEARER_TOKEN=<GENERATE_TOKEN>
MAX_VOLUME=40
ENABLE_RAW_SSAP=false
+27
View File
@@ -0,0 +1,27 @@
name: Core Architecture & Invariant CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
validate:
runs-on: ubuntu-latest
container:
image: nixery.dev/shell/coreutils/git/nix/nodejs:latest
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Configure Git Safe Directory & Nix Flakes
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
mkdir -p ~/.config/nix
echo "experimental-features = nix-command flakes" >> ~/.config/nix/nix.conf
echo "build-users-group =" >> ~/.config/nix/nix.conf
- name: Run Architecture & Security Invariant Checks
run: |
nix flake check
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
set -euo pipefail
if command -v ruff >/dev/null 2>&1 && command -v pyright >/dev/null 2>&1 && command -v pytest >/dev/null 2>&1; then
ruff check .
ruff format --check .
pyright
pytest
else
nix develop --command bash -c "ruff check . && ruff format --check . && pyright && pytest"
fi
+6
View File
@@ -7,3 +7,9 @@ __pycache__/
.tv_state.json .tv_state.json
*.jpg *.jpg
.internal/ .internal/
webos_rsa
.webos_rsa
*.pem
*.key
id_rsa*
id_ed25519*
+13 -5
View File
@@ -29,6 +29,11 @@ The working tree represents the user's active work.
- **Contracts Without Code Duplication:** Avoid pasting Python class or dataclass blocks into architecture/design docs. Model relationships with a Mermaid `classDiagram` (or `erDiagram`), summarize exact signatures in a concise table, and link directly to the authoritative source file (label as *(planned)* if not yet created). - **Contracts Without Code Duplication:** Avoid pasting Python class or dataclass blocks into architecture/design docs. Model relationships with a Mermaid `classDiagram` (or `erDiagram`), summarize exact signatures in a concise table, and link directly to the authoritative source file (label as *(planned)* if not yet created).
- **Policy vs. Mechanism in Diagrams:** Keep flowcharts at the domain-policy level (e.g., *"Is the TV in standby (`1008`)?"*) rather than mirroring low-level library syntax. Capture mandatory mechanism invariants in prose or the detailed implementation manifest. - **Policy vs. Mechanism in Diagrams:** Keep flowcharts at the domain-policy level (e.g., *"Is the TV in standby (`1008`)?"*) rather than mirroring low-level library syntax. Capture mandatory mechanism invariants in prose or the detailed implementation manifest.
### 3.2 Validation, Error Boundaries & Dependency Hygiene
- **Boundary Validation vs. Internal State:** Any class representing external/operator input or wire schemas (e.g., `TvConfig`, MCP tool inputs) must use Pydantic v2 `BaseModel` (`ConfigDict(frozen=True, extra="forbid")`) with validators on the class itself so invalid state cannot be constructed by bypassing a factory function. Pure internal state containers (such as `TvState`) may use stdlib `@dataclass`. Never decorate `Exception` subclasses with `@dataclass`—always write an explicit `__init__` calling `super().__init__(...)` so `Exception.args` and `str(err)` remain intact.
- **Error Domain Separation (`ConfigError` vs. `TvError`):** Raise `ConfigError` for startup, environment, and operator configuration failures (caught by the CLI entrypoint to exit cleanly; never returned as an MCP tool payload). Raise `TvError(ErrorCode, message)` exclusively for runtime TV, SSAP, pointer, WoL, or Dev Mode SSH failures during tool execution so the MCP server can surface actionable recovery hints to the calling agent.
- **Single-Source & Explicit Dependencies:** Keep `runtimeDeps` and `testDeps` single-sourced in `flake.nix` (`pythonEnv = runtimeDeps ++ testDeps`, `packages.default.dependencies = runtimeDeps`). Never rely on implicit transitive dependencies: if any module under `src/` imports a third-party package directly, declare it explicitly in both `pyproject.toml` (`dependencies`) and `flake.nix` (`runtimeDeps`).
--- ---
## 4. Operational & Protocol Invariants ## 4. Operational & Protocol Invariants
@@ -42,9 +47,12 @@ The working tree represents the user's active work.
--- ---
## 5. Verification & Completion ## 5. Verification, Hooks & CI Expectations
Every task must be verified inside `nix develop` before declaring completion: Every task and commit must pass automated verification inside `nix develop`:
1. Run linters, formatters, and type checks: `nix develop --command ruff check .` and `nix develop --command pyright`. 1. **Local Pre-Commit Hook (`.githooks/pre-commit`):** Configured automatically by `flake.nix` `shellHook` (`git config core.hooksPath .githooks`). Runs `ruff check .`, `ruff format --check .`, `pyright`, and `pytest` before every commit. Never bypass hooks with `--no-verify`.
2. Run test suites when tests are present: `nix develop --command pytest`. 2. **TDD Red-Phase Commits (`@pytest.mark.xfail`):** When committing Red-phase tests before the feature implementation exists, provide typed symbol stubs (`raise NotImplementedError`) so `pyright` passes, and decorate unimplemented tests with `@pytest.mark.xfail(strict=True, reason="Red phase: ...")` so `pytest` and `.githooks/pre-commit` exit `0` while still failing if a Red test passes tautologically. Remove `xfail` in the Green-phase commit.
3. Report: (1) What changed, (2) Files modified/created, (3) Verification performed, (4) Unverified areas/risks. 3. **Behavior-Driven Test Naming:** Name all test functions using the consistent `test_<unit>_<behavior>` convention (e.g., `test_load_config_rejects_invalid_env_values_with_config_error` rather than broad names like `test_load_config_defaults`) so `pytest -v` output reads as a clear specification of expected behavior.
4. **Python 3.14 & Strict Typing:** Target Python `>=3.14` (PEP 649 lazy annotations are native—never add `from __future__ import annotations`, enforced by Ruff `TID251`). All code in `src/` and `tests/` must pass `pyright` in `strict` mode without untyped parameters or implicit `Any`.
5. **Server-Side Gitea Actions CI (`.gitea/workflows/ci.yaml`):** Runs `nix flake check` on every push and pull request targeting `main`, executing `ruff check .`, `ruff format --check .`, `pyright`, `pytestCheckHook`, and `buildPythonApplication` inside the isolated Nix sandbox. Verify `nix flake check` locally before opening or updating a pull request.
6. **Completion Reporting:** Report: (1) What changed, (2) Files modified/created, (3) Verification performed, (4) Unverified areas/risks.
+41 -2
View File
@@ -9,17 +9,56 @@
let let
system = "x86_64-linux"; system = "x86_64-linux";
pkgs = import nixpkgs { inherit system; }; pkgs = import nixpkgs { inherit system; };
pythonEnv = pkgs.python3.withPackages (ps: [ ps = pkgs.python3Packages;
runtimeDeps = [
ps.websockets ps.websockets
]); ps.mcp
ps.pydantic
ps.asyncssh
ps.uvicorn
];
testDeps = [
ps.httpx
ps.pytest
ps.pytest-asyncio
];
pythonEnv = pkgs.python3.withPackages (_: runtimeDeps ++ testDeps);
in in
{ {
packages.${system}.default = ps.buildPythonApplication {
pname = "lg-smtv-mcp";
version = "0.1.0";
src = ./.;
pyproject = true;
build-system = [ ps.setuptools ];
dependencies = runtimeDeps;
nativeCheckInputs = [
ps.pytestCheckHook
pkgs.ruff
pkgs.pyright
] ++ testDeps;
preCheck = ''
ruff check .
ruff format --check .
pyright
'';
};
devShells.${system}.default = pkgs.mkShell { devShells.${system}.default = pkgs.mkShell {
packages = [ packages = [
pythonEnv pythonEnv
pkgs.pyright pkgs.pyright
pkgs.ruff pkgs.ruff
]; ];
shellHook = ''
export PYTHONPATH="$PWD/src:${PYTHONPATH:-}"
if [ -d .git ] && [ -d .githooks ]; then
git config core.hooksPath .githooks
fi
'';
}; };
}; };
} }
+39 -2
View File
@@ -1,10 +1,47 @@
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
[project]
name = "lg-smtv-mcp"
version = "0.1.0"
description = "MCP server for controlling an LG webOS Smart TV over the local network"
requires-python = ">=3.14"
dependencies = [
"websockets",
"mcp",
"pydantic",
"asyncssh",
"uvicorn",
]
[project.scripts]
lg-smtv-mcp = "lg_smtv_mcp.cli:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
pythonpath = ["src"]
[tool.ruff] [tool.ruff]
line-length = 100 line-length = 100
target-version = "py314" target-version = "py314"
[tool.ruff.lint] [tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"] select = ["E", "F", "I", "UP", "B", "TID"]
[tool.ruff.lint.per-file-ignores]
"docs/poc/*" = ["TID251"]
[tool.ruff.lint.flake8-tidy-imports.banned-api]
"__future__.annotations".msg = "Python 3.14 evaluates annotations lazily by default (PEP 649); omit from __future__ import annotations."
[tool.ruff.format]
exclude = ["docs/poc/**"]
[tool.pyright] [tool.pyright]
typeCheckingMode = "standard" include = ["src", "tests"]
typeCheckingMode = "strict"
pythonVersion = "3.14" pythonVersion = "3.14"
+5
View File
@@ -0,0 +1,5 @@
"""LG webOS Smart TV MCP server package."""
__all__ = ["__version__"]
__version__ = "0.1.0"
+6
View File
@@ -0,0 +1,6 @@
"""Module entrypoint for `python -m lg_smtv_mcp`."""
from lg_smtv_mcp.cli import main
if __name__ == "__main__":
raise SystemExit(main())
+9
View File
@@ -0,0 +1,9 @@
"""CLI entrypoint stub for lg-smtv-mcp (expanded in Issue #3)."""
from collections.abc import Sequence
def main(argv: Sequence[str] | None = None) -> int:
"""CLI entrypoint stub."""
_ = argv
return 0
+195
View File
@@ -0,0 +1,195 @@
"""Runtime configuration loader, Pydantic v2 validation model, and stdlib .env parser."""
import ipaddress
import os
from pathlib import Path
from typing import Any
from pydantic import BaseModel, ConfigDict, ValidationError, field_validator
from pydantic_core import PydanticCustomError
from lg_smtv_mcp.errors import ConfigError
def _parse_ipv4(env_name: str, value: Any) -> str:
if not isinstance(value, str) or not value.strip():
raise PydanticCustomError(
"invalid_ipv4",
"{name} is required and must be a valid IPv4 address",
{"name": env_name},
)
cleaned = value.strip()
try:
ipaddress.IPv4Address(cleaned)
except ValueError as exc:
raise PydanticCustomError(
"invalid_ipv4",
"{name} must be a valid IPv4 address, got {ip!r}",
{"name": env_name, "ip": cleaned},
) from exc
return cleaned
def _parse_bounded_int(env_name: str, value: Any, *, min_val: int, max_val: int) -> int:
if isinstance(value, bool) or not isinstance(value, (int, str)):
raise PydanticCustomError(
"invalid_int",
"{name} must be an integer between {min_val} and {max_val}, got {val!r}",
{"name": env_name, "min_val": min_val, "max_val": max_val, "val": value},
)
try:
parsed = int(value.strip()) if isinstance(value, str) else value
except ValueError as exc:
raise PydanticCustomError(
"invalid_int",
"{name} must be an integer between {min_val} and {max_val}, got {val!r}",
{"name": env_name, "min_val": min_val, "max_val": max_val, "val": value},
) from exc
if not (min_val <= parsed <= max_val):
raise PydanticCustomError(
"int_out_of_range",
"{name} must be between {min_val} and {max_val}, got {val}",
{"name": env_name, "min_val": min_val, "max_val": max_val, "val": parsed},
)
return parsed
class TvConfig(BaseModel):
"""Validated runtime configuration for lg-smtv-mcp."""
model_config = ConfigDict(frozen=True, extra="forbid")
tv_ip: str
tv_mac: str | None = None
wol_broadcast: str = "255.255.255.255"
client_key_path: Path = Path(".client_key.json")
ssh_key_path: Path | None = None
webos_ssh_passphrase: str | None = None
ssh_known_hosts_path: Path | None = None
host: str = "127.0.0.1"
port: int = 8765
allowed_hosts: tuple[str, ...] = ()
mcp_bearer_token: str | None = None
max_volume: int = 40
enable_raw_ssap: bool = False
def __init__(self, **data: Any) -> None:
try:
super().__init__(**data)
except ValidationError as exc:
messages = "; ".join(err["msg"] for err in exc.errors())
raise ConfigError(messages) from exc
@field_validator("tv_ip", mode="before")
@classmethod
def _validate_tv_ip(cls, value: Any) -> str:
return _parse_ipv4("TV_IP", value)
@field_validator("wol_broadcast", mode="before")
@classmethod
def _validate_wol_broadcast(cls, value: Any) -> str:
return _parse_ipv4("WOL_BROADCAST", value)
@field_validator("port", mode="before")
@classmethod
def _validate_port(cls, value: Any) -> int:
return _parse_bounded_int("PORT", value, min_val=1, max_val=65535)
@field_validator("max_volume", mode="before")
@classmethod
def _validate_max_volume(cls, value: Any) -> int:
return _parse_bounded_int("MAX_VOLUME", value, min_val=0, max_val=100)
def _load_dotenv(env_path: Path) -> None:
"""Populate unset os.environ keys from a .env file using stdlib only."""
if not env_path.is_file():
return
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[len("export ") :].strip()
if "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
if not key:
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
value = value[1:-1]
# Never overwrite variables already present in the process environment.
os.environ.setdefault(key, value)
def _optional_str(name: str) -> str | None:
raw = os.environ.get(name)
if raw is None:
return None
stripped = raw.strip()
return stripped or None
def _optional_path(name: str) -> Path | None:
val = _optional_str(name)
return Path(val) if val is not None else None
def load_config(env_path: Path | None = Path(".env")) -> TvConfig:
"""Load and validate TvConfig from environment variables with optional .env fallback."""
if env_path is not None:
_load_dotenv(env_path)
tv_ip = _optional_str("TV_IP") or ""
port_raw = _optional_str("PORT")
max_volume_raw = _optional_str("MAX_VOLUME")
host = _optional_str("HOST") or "127.0.0.1"
wol_broadcast = _optional_str("WOL_BROADCAST") or "255.255.255.255"
client_key_path = _optional_path("CLIENT_KEY_PATH") or Path(".client_key.json")
allowed_raw = os.environ.get("ALLOWED_HOSTS", "")
allowed_hosts = tuple(part.strip() for part in allowed_raw.split(",") if part.strip())
enable_raw_raw = (os.environ.get("ENABLE_RAW_SSAP") or "").strip().lower()
enable_raw_ssap = enable_raw_raw in {"1", "true", "yes", "on"}
kwargs: dict[str, Any] = {
"tv_ip": tv_ip,
"tv_mac": _optional_str("TV_MAC"),
"wol_broadcast": wol_broadcast,
"client_key_path": client_key_path,
"ssh_key_path": _optional_path("SSH_KEY_PATH"),
"webos_ssh_passphrase": os.environ.get("WEBOS_SSH_PASSPHRASE") or None,
"ssh_known_hosts_path": _optional_path("SSH_KNOWN_HOSTS_PATH"),
"host": host,
"allowed_hosts": allowed_hosts,
"mcp_bearer_token": _optional_str("MCP_BEARER_TOKEN"),
"enable_raw_ssap": enable_raw_ssap,
}
if port_raw is not None:
kwargs["port"] = port_raw
if max_volume_raw is not None:
kwargs["max_volume"] = max_volume_raw
return TvConfig(**kwargs)
def require_bearer_token(config: TvConfig) -> str:
"""Return a non-empty MCP_BEARER_TOKEN or raise ConfigError."""
if config.mcp_bearer_token is None or not config.mcp_bearer_token.strip():
raise ConfigError("MCP_BEARER_TOKEN is required when running streamable-http transport")
return config.mcp_bearer_token.strip()
def require_mac(config: TvConfig) -> str:
"""Return a non-empty TV_MAC or raise ConfigError."""
if config.tv_mac is None or not config.tv_mac.strip():
raise ConfigError("TV_MAC is required for Wake-on-LAN (tv_wake)")
return config.tv_mac.strip()
+32
View File
@@ -0,0 +1,32 @@
"""Typed domain error taxonomy for lg-smtv-mcp."""
from enum import StrEnum
class ErrorCode(StrEnum):
"""Canonical error codes mapped to MCP tool errors."""
TV_OFFLINE_STANDBY = "TV_OFFLINE_STANDBY"
PAIRING_REQUIRED = "PAIRING_REQUIRED"
SCREENSHOT_UNAVAILABLE = "SCREENSHOT_UNAVAILABLE"
LOCK_TIMEOUT = "LOCK_TIMEOUT"
WAKE_TIMEOUT = "WAKE_TIMEOUT"
COMMAND_FAILED = "COMMAND_FAILED"
INVALID_ARGUMENT = "INVALID_ARGUMENT"
class TvError(Exception):
"""Domain error carrying a structured ErrorCode and message."""
def __init__(self, code: ErrorCode, message: str) -> None:
super().__init__(f"{code.value}: {message}")
self.code = code
self.message = message
class ConfigError(Exception):
"""Raised when runtime configuration is missing or fails validation."""
def __init__(self, message: str) -> None:
super().__init__(message)
self.message = message
+212
View File
@@ -0,0 +1,212 @@
from enum import StrEnum
from pathlib import Path
import pytest
from lg_smtv_mcp.config import TvConfig, load_config, require_bearer_token, require_mac
from lg_smtv_mcp.errors import ConfigError, ErrorCode, TvError
def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None:
for key in (
"TV_IP",
"TV_MAC",
"WOL_BROADCAST",
"CLIENT_KEY_PATH",
"SSH_KEY_PATH",
"WEBOS_SSH_PASSPHRASE",
"SSH_KNOWN_HOSTS_PATH",
"HOST",
"PORT",
"ALLOWED_HOSTS",
"MCP_BEARER_TOKEN",
"MAX_VOLUME",
"ENABLE_RAW_SSAP",
):
monkeypatch.delenv(key, raising=False)
def test_error_taxonomy_defines_codes_and_decouples_config_error() -> None:
expected = {
"TV_OFFLINE_STANDBY",
"PAIRING_REQUIRED",
"SCREENSHOT_UNAVAILABLE",
"LOCK_TIMEOUT",
"WAKE_TIMEOUT",
"COMMAND_FAILED",
"INVALID_ARGUMENT",
}
assert issubclass(ErrorCode, StrEnum)
assert {member.value for member in ErrorCode} == expected
err = TvError(ErrorCode.INVALID_ARGUMENT, "bad input")
assert isinstance(err, Exception)
assert err.code is ErrorCode.INVALID_ARGUMENT
assert err.message == "bad input"
assert "bad input" in str(err)
cfg_err = ConfigError("invalid TV_IP")
assert isinstance(cfg_err, Exception)
assert not isinstance(cfg_err, TvError)
assert cfg_err.message == "invalid TV_IP"
assert str(cfg_err) == "invalid TV_IP"
def test_load_config_uses_expected_defaults_when_optional_vars_unset(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_clear_tv_env(monkeypatch)
monkeypatch.setenv("TV_IP", "192.0.2.10")
cfg = load_config(env_path=tmp_path / "missing.env")
assert isinstance(cfg, TvConfig)
assert cfg.tv_ip == "192.0.2.10"
assert cfg.host == "127.0.0.1"
assert cfg.port == 8765
assert cfg.max_volume == 40
assert cfg.wol_broadcast == "255.255.255.255"
assert cfg.client_key_path == Path(".client_key.json")
assert cfg.enable_raw_ssap is False
assert cfg.ssh_key_path is None
assert cfg.webos_ssh_passphrase is None
assert cfg.ssh_known_hosts_path is None
assert cfg.allowed_hosts == ()
assert cfg.tv_mac is None
assert cfg.mcp_bearer_token is None
def test_dotenv_fallback_does_not_overwrite_existing_env(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_clear_tv_env(monkeypatch)
env_file = tmp_path / ".env"
env_file.write_text(
"# comment line\nTV_IP=192.0.2.20\nPORT='9000'\nHOST=\"0.0.0.0\"\nENABLE_RAW_SSAP=true\n",
encoding="utf-8",
)
monkeypatch.setenv("TV_IP", "192.0.2.99")
cfg = load_config(env_path=env_file)
assert cfg.tv_ip == "192.0.2.99"
assert cfg.port == 9000
assert cfg.host == "0.0.0.0"
assert cfg.enable_raw_ssap is True
@pytest.mark.parametrize(
("env_overrides", "expected_substr"),
[
({}, "TV_IP"),
({"TV_IP": " "}, "TV_IP"),
({"TV_IP": "999.999.999.999"}, "TV_IP"),
({"TV_IP": "192.0.2.10", "WOL_BROADCAST": "not-an-ip"}, "WOL_BROADCAST"),
({"TV_IP": "192.0.2.10", "MAX_VOLUME": "-1"}, "MAX_VOLUME"),
({"TV_IP": "192.0.2.10", "MAX_VOLUME": "101"}, "MAX_VOLUME"),
({"TV_IP": "192.0.2.10", "MAX_VOLUME": "loud"}, "MAX_VOLUME"),
({"TV_IP": "192.0.2.10", "PORT": "0"}, "PORT"),
({"TV_IP": "192.0.2.10", "PORT": "65536"}, "PORT"),
({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"),
],
)
def test_load_config_rejects_invalid_env_values_with_config_error(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
env_overrides: dict[str, str],
expected_substr: str,
) -> None:
_clear_tv_env(monkeypatch)
for k, v in env_overrides.items():
monkeypatch.setenv(k, v)
with pytest.raises(ConfigError) as exc_info:
load_config(env_path=tmp_path / "missing.env")
assert expected_substr in exc_info.value.message
@pytest.mark.parametrize(
("kwargs", "expected_substr"),
[
({"tv_ip": ""}, "TV_IP"),
({"tv_ip": "not-an-ip"}, "TV_IP"),
({"tv_ip": "192.0.2.10", "port": 70000}, "PORT"),
({"tv_ip": "192.0.2.10", "port": 8000.5}, "PORT"),
({"tv_ip": "192.0.2.10", "max_volume": 150}, "MAX_VOLUME"),
({"tv_ip": "192.0.2.10", "max_volume": 12.5}, "MAX_VOLUME"),
({"tv_ip": "192.0.2.10", "wol_broadcast": "bad-ip"}, "WOL_BROADCAST"),
],
)
def test_tv_config_rejects_invalid_direct_arguments_with_config_error(
kwargs: dict[str, object],
expected_substr: str,
) -> None:
with pytest.raises(ConfigError) as exc_info:
TvConfig(**kwargs) # type: ignore[arg-type]
assert expected_substr in exc_info.value.message
def test_load_config_parses_comma_separated_allowed_hosts(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_clear_tv_env(monkeypatch)
monkeypatch.setenv("TV_IP", "192.0.2.10")
monkeypatch.setenv("ALLOWED_HOSTS", "tv.local, 192.0.2.5:8765 , , localhost")
cfg = load_config(env_path=tmp_path / "missing.env")
assert cfg.allowed_hosts == ("tv.local", "192.0.2.5:8765", "localhost")
@pytest.mark.parametrize("token", [None, "", " "])
def test_require_bearer_token_rejects_missing_or_blank(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, token: str | None
) -> None:
_clear_tv_env(monkeypatch)
monkeypatch.setenv("TV_IP", "192.0.2.10")
if token is not None:
monkeypatch.setenv("MCP_BEARER_TOKEN", token)
cfg = load_config(env_path=tmp_path / "missing.env")
with pytest.raises(ConfigError) as exc_info:
require_bearer_token(cfg)
assert "MCP_BEARER_TOKEN" in exc_info.value.message
def test_require_bearer_token_returns_trimmed_value(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_clear_tv_env(monkeypatch)
monkeypatch.setenv("TV_IP", "192.0.2.10")
monkeypatch.setenv("MCP_BEARER_TOKEN", " secret-token ")
cfg = load_config(env_path=tmp_path / "missing.env")
assert require_bearer_token(cfg) == "secret-token"
@pytest.mark.parametrize("mac", [None, "", " "])
def test_require_mac_rejects_missing_or_blank(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, mac: str | None
) -> None:
_clear_tv_env(monkeypatch)
monkeypatch.setenv("TV_IP", "192.0.2.10")
if mac is not None:
monkeypatch.setenv("TV_MAC", mac)
cfg = load_config(env_path=tmp_path / "missing.env")
with pytest.raises(ConfigError) as exc_info:
require_mac(cfg)
assert "TV_MAC" in exc_info.value.message
def test_require_mac_returns_trimmed_value(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
_clear_tv_env(monkeypatch)
monkeypatch.setenv("TV_IP", "192.0.2.10")
monkeypatch.setenv("TV_MAC", " AA:BB:CC:DD:EE:FF ")
cfg = load_config(env_path=tmp_path / "missing.env")
assert require_mac(cfg) == "AA:BB:CC:DD:EE:FF"