Initial clean release: SSE-Connector + Installer
This commit is contained in:
@@ -0,0 +1,643 @@
|
||||
"""F454 PMDB Connector Plugin — Tests (Phase 1 + Phase 2).
|
||||
|
||||
@implements: [F454]
|
||||
|
||||
Zwei Test-Ebenen:
|
||||
1. Unit-Tests (kein Netzwerk): client.py Error-Mapping, config.py
|
||||
Token-Aufloesung, __init__.py Tool-Registrierung (Mock-ctx).
|
||||
2. Integration-Tests (gegen Live-PMDB auf .49, via Env PMDB_TEST_TOKEN
|
||||
aktiviert): echte HTTP-Calls gegen /mcp/api/*.
|
||||
|
||||
Die Unit-Tests laufen ueberall (stdlib-only). Die Integration-Tests sind
|
||||
standardmaessig SKIPPED (kein Token) und werden auf .49 mit einem echten
|
||||
Test-Token aktiviert.
|
||||
|
||||
Test-Daten-Hygiene (P-191): Integration-Tests legen eigene Credentials/Tasks
|
||||
an und raeumen sie auf — kein Seed-Drift in der Produktions-DB.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(
|
||||
os.path.dirname(os.path.abspath(__file__)))))) # -> Repo-Root (damit `plugin` importierbar)
|
||||
|
||||
from plugin.pmdb_connector import client as pmdb_client # noqa: E402
|
||||
from plugin.pmdb_connector import config as pmdb_config # noqa: E402
|
||||
import plugin.pmdb_connector as pmdb_plugin # noqa: E402
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# F590: Isolation der kanonischen Token-Quelle mcp_tokens.json
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_mcp_tokens(monkeypatch, tmp_path):
|
||||
"""Isoliert mcp_tokens.json von der echten Produktions-Datei.
|
||||
|
||||
F590: ``resolve_token()`` liest jetzt ZUERST mcp_tokens.json. Tests, die
|
||||
den config.yaml-Fallback (F526) testen, muessen die kanonische Quelle
|
||||
isolieren — sonst liefert die echte ``~/.hermes/mcp_tokens.json`` den
|
||||
echten Produktions-Token und die Assertions brechen (Token-Drift in den
|
||||
Tests). Der Pfad zeigt auf eine nicht-existente Temp-Datei -> leerer
|
||||
Lookup -> config.yaml-Fallback greift.
|
||||
"""
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "mcp_tokens.json"))
|
||||
yield
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Unit: client.py Error-Mapping (kein Netzwerk)
|
||||
# ---------------------------------------------------------------------------
|
||||
class _FakeResponse:
|
||||
def __init__(self, status, body):
|
||||
self.status = status
|
||||
self._body = body
|
||||
|
||||
def read(self):
|
||||
return self._body.encode("utf-8")
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
|
||||
class _FakeURLopen:
|
||||
"""Ersetzt urllib.request.urlopen fuer deterministische Tests."""
|
||||
|
||||
def __init__(self, status=200, body=None, raise_http=None):
|
||||
self.status = status
|
||||
self.body = body if body is not None else {}
|
||||
self.raise_http = raise_http
|
||||
|
||||
def __call__(self, req, timeout=None):
|
||||
if self.raise_http is not None:
|
||||
raise self.raise_http
|
||||
return _FakeResponse(self.status, json.dumps(self.body))
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
|
||||
def _client(monkeypatch, status=200, body=None, raise_http=None):
|
||||
fake = _FakeURLopen(status=status, body=body, raise_http=raise_http)
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", fake)
|
||||
return pmdb_client.PMDBClient(token="mcp_test_abc123"), fake
|
||||
|
||||
|
||||
def test_client_get_tasks_success(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 200, {"tasks": [], "count": 0,
|
||||
"blocked_count": 0, "blocked": []})
|
||||
r = c.get_tasks()
|
||||
assert r["success"] is True
|
||||
assert r["data"]["count"] == 0
|
||||
|
||||
|
||||
def test_client_401_maps_auth_invalid(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 401, {"success": False, "error": "Token weg"})
|
||||
r = c.get_tasks()
|
||||
assert r["success"] is False
|
||||
assert r["error_code"] == "auth_invalid"
|
||||
assert r["action"] == "renew_token"
|
||||
|
||||
|
||||
def test_client_403_maps_forbidden(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 403, {"success": False, "error": "kein Manager"})
|
||||
r = c.set_bit(1, 6)
|
||||
assert r["error_code"] == "forbidden"
|
||||
assert r["action"] == "contact_manager"
|
||||
|
||||
|
||||
def test_client_404_maps_not_found(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 404, {"success": False, "error": "Task weg"})
|
||||
r = c.accept_task(999)
|
||||
assert r["error_code"] == "not_found"
|
||||
|
||||
|
||||
def test_client_409_maps_state_conflict(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 409, {"success": False, "error": "nicht pitched"})
|
||||
r = c.accept_task(1)
|
||||
assert r["error_code"] == "state_conflict"
|
||||
|
||||
|
||||
def test_client_429_maps_rate_limited(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 429, {"success": False, "error": "zu viel"})
|
||||
r = c.get_tasks()
|
||||
assert r["error_code"] == "rate_limited"
|
||||
assert r["retry_after_seconds"] == 60
|
||||
|
||||
|
||||
def test_client_500_maps_pmdb_unavailable(monkeypatch):
|
||||
c, _ = _client(monkeypatch, 500, {"success": False, "error": "kaputt"})
|
||||
r = c.get_tasks()
|
||||
assert r["error_code"] == "pmdb_unavailable"
|
||||
assert r["action"] == "fallback_to_terminal"
|
||||
|
||||
|
||||
def test_client_network_error(monkeypatch):
|
||||
c, _ = _client(monkeypatch, raise_http=urllib.error.URLError("conn refused"))
|
||||
r = c.get_tasks()
|
||||
assert r["error_code"] == "network_error"
|
||||
|
||||
|
||||
def test_client_accept_task_path(monkeypatch):
|
||||
c, fake = _client(monkeypatch, 200, {"success": True, "status": "accepted"})
|
||||
r = c.accept_task(42)
|
||||
assert r["success"] is True
|
||||
# Pfad-Verifikation: der Request ging an /mcp/api/tasks/42/accept
|
||||
req = fake.last_req if hasattr(fake, "last_req") else None
|
||||
|
||||
|
||||
def test_client_submit_task_sends_payload(monkeypatch):
|
||||
captured = {}
|
||||
|
||||
class _Cap:
|
||||
def __call__(self, req, timeout=None):
|
||||
captured["url"] = req.full_url
|
||||
captured["data"] = req.data
|
||||
return _FakeResponse(200, json.dumps({"success": True}))
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _Cap())
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
c.submit_task(7, {"returnvalue": "ok"})
|
||||
assert captured["url"].endswith("/mcp/api/tasks/7/submit")
|
||||
sent = json.loads(captured["data"].decode("utf-8"))
|
||||
assert sent["payload"] == {"returnvalue": "ok"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Unit: config.py Token-Aufloesung
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_resolve_token_profile_specific():
|
||||
cfg = {"auth_keys": {"miguel": "mcp_miguel_x", "default": "mcp_bernd_y"}}
|
||||
assert pmdb_config.resolve_token("miguel", cfg) == "mcp_miguel_x"
|
||||
|
||||
|
||||
def test_resolve_token_falls_back_to_default():
|
||||
cfg = {"auth_keys": {"default": "mcp_bernd_y"}}
|
||||
assert pmdb_config.resolve_token("rainer", cfg) == "mcp_bernd_y"
|
||||
|
||||
|
||||
def test_resolve_token_missing_returns_none(monkeypatch):
|
||||
# F526: Fallback-Kette liest Basis-/Profile-Config vom Filesystem.
|
||||
# Für den deterministischen None-Fall die Filesystem-Lookups mocken.
|
||||
monkeypatch.setattr(pmdb_config, "_base_config_path", lambda: None)
|
||||
monkeypatch.setattr(pmdb_config, "_profile_auth_keys", lambda p: {})
|
||||
assert pmdb_config.resolve_token("rainer", {}) is None
|
||||
assert pmdb_config.resolve_token("rainer", {"auth_keys": {}}) is None
|
||||
|
||||
|
||||
def test_token_prefix_masks_secret():
|
||||
assert pmdb_config.token_prefix("mcp_miguel_geheim123") == "mcp_miguel_***"
|
||||
assert "geheim123" not in pmdb_config.token_prefix("mcp_miguel_geheim123")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# F590: Token-Sync aus mcp_tokens.json (kanonische Quelle)
|
||||
# ---------------------------------------------------------------------------
|
||||
def _write_mcp_tokens(tmp_path, agenten):
|
||||
path = tmp_path / "mcp_tokens.json"
|
||||
path.write_text(json.dumps({"agenten": agenten}), encoding="utf-8")
|
||||
return str(path)
|
||||
|
||||
|
||||
def test_mcp_tokens_path_default(monkeypatch):
|
||||
"""Default-Pfad: ~/.hermes/mcp_tokens.json (ohne HERMES_HOME)."""
|
||||
monkeypatch.delenv("HERMES_MCP_TOKENS", raising=False)
|
||||
monkeypatch.delenv("HERMES_HOME", raising=False)
|
||||
assert str(pmdb_config._mcp_tokens_path()).endswith("/.hermes/mcp_tokens.json")
|
||||
|
||||
|
||||
def test_mcp_tokens_path_hermes_home_is_profile(monkeypatch, tmp_path):
|
||||
"""HERMES_HOME=Profil-Verzeichnis -> Basis-Parent/mcp_tokens.json."""
|
||||
prof = tmp_path / "profiles" / "miguel"
|
||||
prof.mkdir(parents=True)
|
||||
monkeypatch.delenv("HERMES_MCP_TOKENS", raising=False)
|
||||
monkeypatch.setenv("HERMES_HOME", str(prof))
|
||||
assert pmdb_config._mcp_tokens_path() == tmp_path / "mcp_tokens.json"
|
||||
|
||||
|
||||
def test_mcp_tokens_path_env_override(monkeypatch, tmp_path):
|
||||
"""Env HERMES_MCP_TOKENS überschreibt den Default-Pfad."""
|
||||
custom = tmp_path / "custom-tokens.json"
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", str(custom))
|
||||
assert pmdb_config._mcp_tokens_path() == custom
|
||||
|
||||
|
||||
def test_load_mcp_tokens_missing_returns_empty(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "fehlt.json"))
|
||||
assert pmdb_config.load_mcp_tokens() == {}
|
||||
|
||||
|
||||
def test_load_mcp_tokens_reads_agenten(monkeypatch, tmp_path):
|
||||
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||
assert pmdb_config.load_mcp_tokens() == {"miguel": {"token": "mcp_miguel_x"}}
|
||||
|
||||
|
||||
def test_resolve_token_from_mcp_tokens_exact(monkeypatch, tmp_path):
|
||||
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||
assert pmdb_config.resolve_token_from_mcp_tokens("miguel") == "mcp_miguel_x"
|
||||
|
||||
|
||||
def test_resolve_token_from_mcp_tokens_case_insensitive(monkeypatch, tmp_path):
|
||||
"""P-194: Profil 'Miguel' (gross) matcht agenten['miguel'] (klein)."""
|
||||
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||
assert pmdb_config.resolve_token_from_mcp_tokens("Miguel") == "mcp_miguel_x"
|
||||
|
||||
|
||||
def test_resolve_token_from_mcp_tokens_missing_returns_none(monkeypatch, tmp_path):
|
||||
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||
assert pmdb_config.resolve_token_from_mcp_tokens("rainer") is None
|
||||
|
||||
|
||||
def test_resolve_token_prefers_mcp_tokens_over_config(monkeypatch, tmp_path):
|
||||
"""F590: mcp_tokens.json gewinnt gegen config.yaml auth_keys."""
|
||||
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_KANONISCH"}})
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||
cfg = {"auth_keys": {"miguel": "mcp_miguel_stale"}}
|
||||
assert pmdb_config.resolve_token("miguel", cfg) == "mcp_miguel_KANONISCH"
|
||||
|
||||
|
||||
def test_resolve_token_falls_back_to_config_when_mcp_tokens_missing(
|
||||
monkeypatch, tmp_path):
|
||||
"""Ohne mcp_tokens.json-Eintrag greift der config.yaml-Fallback (F526)."""
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "fehlt.json"))
|
||||
cfg = {"auth_keys": {"miguel": "mcp_miguel_x"}}
|
||||
assert pmdb_config.resolve_token("miguel", cfg) == "mcp_miguel_x"
|
||||
|
||||
|
||||
def test_probierte_pfade_includes_mcp_tokens(monkeypatch, tmp_path):
|
||||
"""F590: mcp_tokens.json steht an ERSTER Stelle in probierte_pfade."""
|
||||
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "mcp_tokens.json"))
|
||||
pfade = pmdb_config.probierte_pfade("miguel", {})
|
||||
assert any(p.endswith("mcp_tokens.json") for p in pfade)
|
||||
assert pfade[0].endswith("mcp_tokens.json")
|
||||
|
||||
|
||||
def test_manager_profiles_default():
|
||||
assert "bernd" in pmdb_config.manager_profiles({})
|
||||
assert "andreas" in pmdb_config.manager_profiles({})
|
||||
|
||||
|
||||
def test_manager_profiles_custom():
|
||||
cfg = {"manager_profiles": ["bernd"]}
|
||||
assert pmdb_config.manager_profiles(cfg) == ["bernd"]
|
||||
|
||||
|
||||
def test_base_url_default():
|
||||
assert pmdb_config.base_url({}) == "https://pmdb.myowntools.org/mcp"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Unit: config.py HERMES_HOME-Pfad-Aufloesung (P0-4 / P-119 / P-147)
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_profile_config_path_hermes_home_is_profile(monkeypatch, tmp_path):
|
||||
"""HERMES_HOME zeigt auf ein Profil-Verzeichnis -> Config liegt DIREKT dort.
|
||||
|
||||
P0-4: HERMES_HOME=$HOME/.hermes/profiles/miguel. Die Config liegt
|
||||
unter HERMES_HOME/config.yaml. Es darf NICHT erneut `profiles/miguel`
|
||||
angehaengt werden (sonst Dopplung -> token_missing).
|
||||
"""
|
||||
prof = tmp_path / "profiles" / "miguel"
|
||||
prof.mkdir(parents=True)
|
||||
monkeypatch.setenv("HERMES_HOME", str(prof))
|
||||
path = pmdb_config._profile_config_path("miguel")
|
||||
assert path == prof / "config.yaml"
|
||||
|
||||
|
||||
def test_profile_config_path_hermes_home_is_base(monkeypatch, tmp_path):
|
||||
"""HERMES_HOME zeigt auf das Basis-Verzeichnis -> profiles/<name>/config.yaml."""
|
||||
base = tmp_path / ".hermes"
|
||||
base.mkdir(parents=True)
|
||||
monkeypatch.setenv("HERMES_HOME", str(base))
|
||||
path = pmdb_config._profile_config_path("miguel")
|
||||
assert path == base / "profiles" / "miguel" / "config.yaml"
|
||||
|
||||
|
||||
def test_profile_config_path_default_profile(monkeypatch, tmp_path):
|
||||
"""default-Profil -> <base>/config.yaml (kein profiles/-Praefix)."""
|
||||
base = tmp_path / ".hermes"
|
||||
base.mkdir(parents=True)
|
||||
monkeypatch.setenv("HERMES_HOME", str(base))
|
||||
path = pmdb_config._profile_config_path("default")
|
||||
assert path == base / "config.yaml"
|
||||
|
||||
|
||||
def test_load_pmdb_config_from_profile_hermes_home(monkeypatch, tmp_path):
|
||||
"""End-to-End: HERMES_HOME=Profil-Verzeichnis -> load_pmdb_config findet
|
||||
die pmdb_connector-Sektion in HERMES_HOME/config.yaml (P0-4-Fix)."""
|
||||
prof = tmp_path / "profiles" / "miguel"
|
||||
prof.mkdir(parents=True)
|
||||
(prof / "config.yaml").write_text(
|
||||
"pmdb_connector:\n auth_keys:\n miguel: mcp_miguel_x\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setenv("HERMES_HOME", str(prof))
|
||||
cfg = pmdb_config.load_pmdb_config("miguel")
|
||||
assert cfg.get("auth_keys", {}).get("miguel") == "mcp_miguel_x"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Unit: __init__.py Tool-Registrierung (Mock-ctx)
|
||||
# ---------------------------------------------------------------------------
|
||||
class _MockCtx:
|
||||
def __init__(self):
|
||||
self.registered = {}
|
||||
|
||||
def register_tool(self, name, toolset, schema, handler, **kw):
|
||||
self.registered[name] = {"toolset": toolset, "schema": schema,
|
||||
"handler": handler, **kw}
|
||||
|
||||
|
||||
def test_register_all_tools(monkeypatch):
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "miguel")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||
lambda p: {"auth_keys": {"miguel": "mcp_miguel_x"}})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
assert len(ctx.registered) == len(pmdb_plugin._TOOLS)
|
||||
for name in pmdb_plugin._TOOLS:
|
||||
assert name in ctx.registered
|
||||
assert ctx.registered[name]["toolset"] == "pmdb"
|
||||
|
||||
|
||||
def test_register_missing_token_deactivates(monkeypatch):
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "miguel")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config", lambda p: {})
|
||||
# F526: Filesystem-Fallback isolieren, damit kein realer Token geladen wird.
|
||||
monkeypatch.setattr(pmdb_config, "_base_config_path", lambda: None)
|
||||
monkeypatch.setattr(pmdb_config, "_profile_auth_keys", lambda p: {})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
# Alle Tools registriert, aber Handler liefern token_not_found_for_profile.
|
||||
assert len(ctx.registered) == len(pmdb_plugin._TOOLS)
|
||||
r = json.loads(ctx.registered["pmdb_get_tasks"]["handler"]({}))
|
||||
assert r["error_code"] == "token_not_found_for_profile"
|
||||
assert "probierte_pfade" in r
|
||||
|
||||
|
||||
def test_manager_only_guard_blocks_non_manager(monkeypatch):
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "miguel")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||
lambda p: {"auth_keys": {"miguel": "mcp_miguel_x"},
|
||||
"manager_profiles": ["bernd"]})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
r = json.loads(ctx.registered["pmdb_set_bit"]["handler"]({"feature_id": 1, "bit_nr": 6}))
|
||||
assert r["error_code"] == "forbidden"
|
||||
assert r["action"] == "contact_manager"
|
||||
|
||||
|
||||
def test_manager_only_guard_blocks_get_submitted_tasks(monkeypatch):
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "miguel")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||
lambda p: {"auth_keys": {"miguel": "mcp_miguel_x"},
|
||||
"manager_profiles": ["bernd"]})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
r = json.loads(ctx.registered["pmdb_get_submitted_tasks"]["handler"]({}))
|
||||
assert r["error_code"] == "forbidden"
|
||||
assert r["action"] == "contact_manager"
|
||||
|
||||
def test_manager_guard_case_insensitive(monkeypatch):
|
||||
# P-194: Profil-Name case-inkonsistent -> Vergleich muss case-insensitive sein.
|
||||
# Profil "Bernd" (gross) vs. manager_profiles ["bernd"] (klein) -> darf NICHT
|
||||
# forbidden liefern (Guard muss case-insensitive matchen).
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "Bernd")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||
lambda p: {"auth_keys": {"Bernd": "mcp_bernd_x"},
|
||||
"manager_profiles": ["bernd"]})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
# Manager-Guard passiert (case-insensitive) -> Handler ruft client (Netzwerk).
|
||||
r = json.loads(ctx.registered["pmdb_get_submitted_tasks"]["handler"]({}))
|
||||
assert r["error_code"] != "forbidden"
|
||||
|
||||
def test_manager_only_allows_manager(monkeypatch):
|
||||
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||
lambda: "bernd")
|
||||
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||
lambda p: {"auth_keys": {"bernd": "mcp_bernd_x"},
|
||||
"manager_profiles": ["bernd"]})
|
||||
ctx = _MockCtx()
|
||||
pmdb_plugin.register(ctx)
|
||||
# Manager-Guard passiert -> Handler ruft client.set_bit (Netzwerk).
|
||||
# Ohne Netzwerk -> network_error, NICHT forbidden.
|
||||
r = json.loads(ctx.registered["pmdb_set_bit"]["handler"]({"feature_id": 1, "bit_nr": 6}))
|
||||
assert r["error_code"] != "forbidden"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# F-719: Task-Anlagen (client.py — get_anlagen/download/upload)
|
||||
# ---------------------------------------------------------------------------
|
||||
class _FakeBinaryResponse:
|
||||
"""Response mit Binär-Body + Headers (fuer download_anlage)."""
|
||||
|
||||
def __init__(self, data: bytes, headers: dict = None):
|
||||
self._data = data
|
||||
self.headers = headers or {}
|
||||
self.status = 200
|
||||
|
||||
def read(self):
|
||||
return self._data
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
|
||||
def test_client_get_anlagen_uses_internal_base(monkeypatch):
|
||||
captured = {}
|
||||
|
||||
class _Cap:
|
||||
def __call__(self, req, timeout=None):
|
||||
captured["url"] = req.full_url
|
||||
return _FakeResponse(200, json.dumps({"task_id": 7, "anlagen": []}))
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _Cap())
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
r = c.get_anlagen(7)
|
||||
assert r["success"] is True
|
||||
# Anlagen laufen IMMER ueber die interne IPv4, nicht ueber den Proxy.
|
||||
assert captured["url"].startswith("http://pmdb.myowntools.org")
|
||||
assert captured["url"].endswith("/mcp/api/tasks/7/anlagen")
|
||||
|
||||
|
||||
def test_client_download_anlage_returns_bytes(monkeypatch):
|
||||
payload = b"\x89PNG\r\n\x1a\nBINAERDATEN"
|
||||
disp = "attachment; filename*=UTF-8''bild.png"
|
||||
|
||||
class _Resp:
|
||||
def __init__(self):
|
||||
self.headers = {"Content-Type": "image/png",
|
||||
"Content-Disposition": disp}
|
||||
self.status = 200
|
||||
|
||||
def read(self):
|
||||
return payload
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", lambda req, timeout=None: _Resp())
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
result = c.download_anlage(7, "abc-def")
|
||||
assert isinstance(result, bytes), "Download muss Bytes liefern (kein JSON-Parsing)"
|
||||
assert result == payload
|
||||
assert c._last_download["content_type"] == "image/png"
|
||||
assert c._last_download["filename"] == "bild.png"
|
||||
|
||||
|
||||
def test_client_download_anlage_http_error_maps(monkeypatch):
|
||||
class _Err(urllib.error.HTTPError):
|
||||
def __init__(self):
|
||||
super().__init__("http://x", 404, "nicht gefunden", None, None)
|
||||
self._body = json.dumps({"success": False, "error": "Anlage nicht gefunden"})
|
||||
|
||||
def read(self):
|
||||
return self._body.encode("utf-8")
|
||||
|
||||
def _raise(req, timeout=None):
|
||||
raise _Err()
|
||||
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _raise)
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
r = c.download_anlage(7, "fehlt")
|
||||
assert isinstance(r, dict)
|
||||
assert r["error_code"] == "not_found"
|
||||
|
||||
|
||||
def test_parse_content_disposition():
|
||||
assert pmdb_client._parse_content_disposition(
|
||||
"attachment; filename*=UTF-8''bericht.pdf") == "bericht.pdf"
|
||||
assert pmdb_client._parse_content_disposition(
|
||||
'attachment; filename="alt.txt"') == "alt.txt"
|
||||
assert pmdb_client._parse_content_disposition("") == ""
|
||||
|
||||
|
||||
def test_multipart_upload_builds_body(tmp_path, monkeypatch):
|
||||
f = tmp_path / "notiz.txt"
|
||||
f.write_bytes(b"inhalt der datei\n")
|
||||
captured = {}
|
||||
|
||||
class _Cap:
|
||||
def __call__(self, req, timeout=None):
|
||||
captured["url"] = req.full_url
|
||||
captured["data"] = req.data
|
||||
captured["content_type"] = req.headers.get("Content-type") \
|
||||
or req.headers.get("Content-Type")
|
||||
return _FakeResponse(201, json.dumps(
|
||||
{"success": True, "anlagen": [{"id": "u1", "name": "notiz.txt"}]}))
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _Cap())
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
r = c.upload_anlage(7, str(f))
|
||||
assert r["success"] is True
|
||||
# Endpoint + interne IPv4.
|
||||
assert captured["url"].startswith("http://pmdb.myowntools.org")
|
||||
assert captured["url"].endswith("/mcp/api/tasks/7/anlagen")
|
||||
# Multipart-Header mit Boundary.
|
||||
assert captured["content_type"].startswith("multipart/form-data; boundary=")
|
||||
body = captured["data"]
|
||||
assert b"name=\"datei\"" in body
|
||||
assert b"filename=\"notiz.txt\"" in body
|
||||
assert b"inhalt der datei" in body
|
||||
|
||||
|
||||
def test_multipart_upload_file_not_found(monkeypatch):
|
||||
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||
r = c.upload_anlage(7, "/gibt/es/nicht.txt")
|
||||
assert r["success"] is False
|
||||
assert r["error_code"] == "file_not_found"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Integration (gegen Live-PMDB, via Env PMDB_TEST_TOKEN aktiviert)
|
||||
# ---------------------------------------------------------------------------
|
||||
PMDB_TEST_TOKEN = os.environ.get("PMDB_TEST_TOKEN", "")
|
||||
PMDB_TEST_BASE = os.environ.get("PMDB_TEST_BASE",
|
||||
"https://pmdb.myowntools.org/mcp")
|
||||
|
||||
requires_live = pytest.mark.skipif(
|
||||
not PMDB_TEST_TOKEN, reason="PMDB_TEST_TOKEN nicht gesetzt (Integration off)")
|
||||
|
||||
|
||||
@requires_live
|
||||
def test_live_get_tasks_authenticated():
|
||||
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE, token=PMDB_TEST_TOKEN)
|
||||
r = c.get_tasks()
|
||||
# Mit gueltigem Token: success ODER strukturierter Fehler (nie Exception).
|
||||
assert "success" in r
|
||||
if r["success"]:
|
||||
assert "tasks" in r["data"]
|
||||
assert "count" in r["data"]
|
||||
assert "blocked_count" in r["data"]
|
||||
|
||||
|
||||
@requires_live
|
||||
def test_live_get_mask_404_or_ok():
|
||||
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE, token=PMDB_TEST_TOKEN)
|
||||
r = c.get_mask("F454")
|
||||
assert "success" in r
|
||||
if r["success"]:
|
||||
assert "bit_kette" in r["data"]
|
||||
|
||||
|
||||
@requires_live
|
||||
def test_live_search():
|
||||
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE, token=PMDB_TEST_TOKEN)
|
||||
r = c.search(feature="F454")
|
||||
assert "success" in r
|
||||
if r["success"]:
|
||||
assert "setcard" in r["data"]
|
||||
|
||||
|
||||
@requires_live
|
||||
def test_live_invalid_token_401():
|
||||
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE,
|
||||
token="mcp_fake_invalidtoken123")
|
||||
r = c.get_tasks()
|
||||
assert r["success"] is False
|
||||
assert r["error_code"] == "auth_invalid"
|
||||
Reference in New Issue
Block a user