Silent ticks (empty stdout, exit 0), one line per stable fingerprint, cumulative union-only seen-set at ~/.hermes/cron/netsec-scan-state.json, memoized sensor- degradation line, daily baseline report. Stdlib only; reads the collector's JSONL over SSH with per-file byte offsets and Prometheus via the k8s API proxy. 40 unit tests against fixtures recorded from the live collector.
51 lines
1.6 KiB
Python
51 lines
1.6 KiB
Python
"""Shared helpers for the tests: a fake Prometheus and fixture loading."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
from typing import Dict, List, Tuple
|
|
|
|
FIXTURES = Path(__file__).parent / "fixtures"
|
|
|
|
|
|
def fixture_lines(name: str) -> List[str]:
|
|
return [ln for ln in (FIXTURES / name).read_text().splitlines() if ln.strip()]
|
|
|
|
|
|
def fixture_flows(name: str):
|
|
from netsec_scan.flows import parse_flow
|
|
|
|
return [parse_flow(json.loads(ln)) for ln in fixture_lines(name)]
|
|
|
|
|
|
class FakeProm:
|
|
"""Substring-matched query/scalar responses; no network, no kubectl.
|
|
|
|
Keys are matched by `key in expr`, so the tests assert *which* rule query
|
|
ran without pinning the exact PromQL text.
|
|
"""
|
|
|
|
def __init__(self, scalars: Dict[str, float] = None,
|
|
vectors: Dict[str, List[Tuple[dict, float]]] = None):
|
|
self.scalars = scalars or {}
|
|
self.vectors = vectors or {}
|
|
self.queries: List[str] = []
|
|
|
|
def _lookup(self, table, expr: str):
|
|
# Longest matching key wins, so `...[5m]))[6h:5m]` beats `...[5m]`
|
|
# when both are substrings of a 6h subquery expression.
|
|
hits = [(key, value) for key, value in table.items() if key in expr]
|
|
if not hits:
|
|
return None
|
|
return max(hits, key=lambda kv: len(kv[0]))[1]
|
|
|
|
def query(self, expr: str):
|
|
self.queries.append(expr)
|
|
value = self._lookup(self.vectors, expr)
|
|
return value if value is not None else []
|
|
|
|
def scalar(self, expr: str) -> float:
|
|
self.queries.append(expr)
|
|
value = self._lookup(self.scalars, expr)
|
|
return float(value) if value is not None else 0.0
|