10 Commits
Author SHA1 Message Date
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
14 changed files with 419 additions and 42 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
*.jpg
.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).
- **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
@@ -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:
1. Run linters, formatters, and type checks: `nix develop --command ruff check .` and `nix develop --command pyright`.
2. Run test suites when tests are present: `nix develop --command pytest`.
3. Report: (1) What changed, (2) Files modified/created, (3) Verification performed, (4) Unverified areas/risks.
Every task and commit must pass automated verification inside `nix develop`:
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. **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. **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.
+1 -3
View File
@@ -205,9 +205,7 @@ async def verify_subscriptions(ip: str, port: int, key_file: Path) -> dict[str,
)
)
await ws.send(
json.dumps(
{"id": "req_info", "type": "request", "uri": "ssap://system/getSystemInfo"}
)
json.dumps({"id": "req_info", "type": "request", "uri": "ssap://system/getSystemInfo"})
)
frames: list[dict[str, Any]] = []
+26 -10
View File
@@ -9,29 +9,42 @@
let
system = "x86_64-linux";
pkgs = import nixpkgs { inherit system; };
pythonEnv = pkgs.python3.withPackages (ps: [
ps = pkgs.python3Packages;
runtimeDeps = [
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
{
packages.${system}.default = pkgs.python3Packages.buildPythonApplication {
packages.${system}.default = ps.buildPythonApplication {
pname = "lg-smtv-mcp";
version = "0.1.0";
src = ./.;
pyproject = true;
build-system = [ pkgs.python3Packages.setuptools ];
dependencies = with pkgs.python3Packages; [
websockets
mcp
asyncssh
uvicorn
];
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 {
@@ -42,6 +55,9 @@
];
shellHook = ''
export PYTHONPATH="$PWD/src:${PYTHONPATH:-}"
if [ -d .git ] && [ -d .githooks ]; then
git config core.hooksPath .githooks
fi
'';
};
};
+10 -3
View File
@@ -6,10 +6,11 @@ build-backend = "setuptools.build_meta"
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.11"
requires-python = ">=3.14"
dependencies = [
"websockets",
"mcp",
"pydantic",
"asyncssh",
"uvicorn",
]
@@ -29,9 +30,15 @@ line-length = 100
target-version = "py314"
[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.pyright]
include = ["src", "tests"]
typeCheckingMode = "standard"
typeCheckingMode = "strict"
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
+220
View File
@@ -0,0 +1,220 @@
"""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
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:
if not isinstance(value, str) or not value.strip():
raise PydanticCustomError(
"missing_tv_ip",
"TV_IP is required and must be a non-empty IPv4 address",
)
cleaned = value.strip()
try:
ipaddress.IPv4Address(cleaned)
except ValueError as exc:
raise PydanticCustomError(
"invalid_tv_ip",
"TV_IP must be a valid IPv4 address, got {tv_ip!r}",
{"tv_ip": cleaned},
) from exc
return cleaned
@field_validator("wol_broadcast", mode="before")
@classmethod
def _validate_wol_broadcast(cls, value: Any) -> str:
if not isinstance(value, str) or not value.strip():
raise PydanticCustomError(
"invalid_wol_broadcast",
"WOL_BROADCAST must be a valid IPv4 address",
)
cleaned = value.strip()
try:
ipaddress.IPv4Address(cleaned)
except ValueError as exc:
raise PydanticCustomError(
"invalid_wol_broadcast",
"WOL_BROADCAST must be a valid IPv4 address, got {ip!r}",
{"ip": cleaned},
) from exc
return cleaned
@field_validator("port", mode="before")
@classmethod
def _validate_port(cls, value: Any) -> int:
if isinstance(value, bool):
raise PydanticCustomError(
"invalid_port",
"PORT must be an integer between 1 and 65535, got {val!r}",
{"val": value},
)
try:
parsed = int(value.strip()) if isinstance(value, str) else int(value)
except (ValueError, TypeError) as exc:
raise PydanticCustomError(
"invalid_port",
"PORT must be an integer between 1 and 65535, got {val!r}",
{"val": value},
) from exc
if not (1 <= parsed <= 65535):
raise PydanticCustomError(
"invalid_port_range",
"PORT must be between 1 and 65535, got {val}",
{"val": parsed},
)
return parsed
@field_validator("max_volume", mode="before")
@classmethod
def _validate_max_volume(cls, value: Any) -> int:
if isinstance(value, bool):
raise PydanticCustomError(
"invalid_max_volume",
"MAX_VOLUME must be an integer between 0 and 100, got {val!r}",
{"val": value},
)
try:
parsed = int(value.strip()) if isinstance(value, str) else int(value)
except (ValueError, TypeError) as exc:
raise PydanticCustomError(
"invalid_max_volume",
"MAX_VOLUME must be an integer between 0 and 100, got {val!r}",
{"val": value},
) from exc
if not (0 <= parsed <= 100):
raise PydanticCustomError(
"invalid_max_volume_range",
"MAX_VOLUME must be between 0 and 100, got {val}",
{"val": parsed},
)
return parsed
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
+40 -21
View File
@@ -1,12 +1,10 @@
from __future__ import annotations
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 ErrorCode, TvError
from lg_smtv_mcp.errors import ConfigError, ErrorCode, TvError
def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -28,7 +26,7 @@ def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv(key, raising=False)
def test_error_code_and_tv_error() -> None:
def test_error_taxonomy_defines_codes_and_decouples_config_error() -> None:
expected = {
"TV_OFFLINE_STANDBY",
"PAIRING_REQUIRED",
@@ -47,8 +45,14 @@ def test_error_code_and_tv_error() -> None:
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_defaults(
def test_load_config_uses_expected_defaults_when_optional_vars_unset(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_clear_tv_env(monkeypatch)
@@ -78,11 +82,7 @@ def test_dotenv_fallback_does_not_overwrite_existing_env(
_clear_tv_env(monkeypatch)
env_file = tmp_path / ".env"
env_file.write_text(
"# comment line\n"
"TV_IP=192.0.2.20\n"
"PORT='9000'\n"
'HOST="0.0.0.0"\n'
"ENABLE_RAW_SSAP=true\n",
"# 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")
@@ -100,6 +100,8 @@ def test_dotenv_fallback_does_not_overwrite_existing_env(
[
({}, "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"),
@@ -108,7 +110,7 @@ def test_dotenv_fallback_does_not_overwrite_existing_env(
({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"),
],
)
def test_load_config_validation_errors(
def test_load_config_rejects_invalid_env_values_with_config_error(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
env_overrides: dict[str, str],
@@ -118,14 +120,33 @@ def test_load_config_validation_errors(
for k, v in env_overrides.items():
monkeypatch.setenv(k, v)
with pytest.raises(TvError) as exc_info:
with pytest.raises(ConfigError) as exc_info:
load_config(env_path=tmp_path / "missing.env")
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
assert expected_substr in exc_info.value.message
def test_allowed_hosts_comma_separated(
@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", "max_volume": 150}, "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)
@@ -147,10 +168,10 @@ def test_require_bearer_token_rejects_missing_or_blank(
monkeypatch.setenv("MCP_BEARER_TOKEN", token)
cfg = load_config(env_path=tmp_path / "missing.env")
with pytest.raises(TvError) as exc_info:
with pytest.raises(ConfigError) as exc_info:
require_bearer_token(cfg)
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
assert "MCP_BEARER_TOKEN" in exc_info.value.message
def test_require_bearer_token_returns_trimmed_value(
@@ -174,15 +195,13 @@ def test_require_mac_rejects_missing_or_blank(
monkeypatch.setenv("TV_MAC", mac)
cfg = load_config(env_path=tmp_path / "missing.env")
with pytest.raises(TvError) as exc_info:
with pytest.raises(ConfigError) as exc_info:
require_mac(cfg)
assert exc_info.value.code is ErrorCode.INVALID_ARGUMENT
assert "TV_MAC" in exc_info.value.message
def test_require_mac_returns_trimmed_value(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
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 ")