Files
thor/tests/fakes.py
T
jaredandClaude Opus 5.5 9f993dabf1
CI / Test (pytest) (pull_request) Successful in 1m13s
CI / Integration (MariaDB) (pull_request) Successful in 2m36s
CI / Security (bandit, pip-audit) (pull_request) Successful in 1m25s
CI / UI (screenshots) (pull_request) Failing after 8s
CI / Lint (flake8, house style) (pull_request) Successful in 58s
CI / Scan (secrets, workflows, shell, patterns) (pull_request) Failing after 1m26s
CI / Deploy (pull_request) Skipped
MCP v1: Thor's tools for Claude Code, behind Authelia OAuth (thor#1)
- thor/web/mcp.py: stateless Streamable HTTP at POST /mcp (JSON-RPC 2.0), RFC 9728 metadata at
  /.well-known/oauth-protected-resource[/mcp], 401 with resource_metadata. Tokens checked
  against Authelia's JWKS: RS256, iss, aud (this server), exp, typ at+jwt, client_id thor-mcp,
  scp array; group admin only; Remote-* headers never trusted; every tool call logged with the
  user.
- Read tools (thor:read): list_incidents, get_incident, what_covers, thor_status,
  list_known_conditions. Write tools (thor:write): add_known_condition, end_known_condition,
  attach_ticket, detach_ticket. Tools a token's scopes can't use aren't listed.
- Migration 4: incident_links (who attached which ticket to which incident). attach_ticket
  records an 'attach' action; in shadow nothing is sent, live sends a 'Root cause' comment.
- Incident page lists attached tickets. PyJWT[crypto] added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:28:37 -05:00

244 lines
8.8 KiB
Python

"""Test doubles: an in-memory Store, an HTTP session that serves canned replies, sources."""
import json
from typing import Any, Dict, List, Optional
import requests
from thor.clients import SourceError
from thor.db import DatabaseError
class FakeStore:
"""Same methods as thor.db.Store, kept in memory. Set ``down = True`` to simulate CT 149 away."""
def __init__(self):
self.down = False
self.state: Dict[str, Any] = {}
self.cycles: List[dict] = []
self.sources: Dict[str, dict] = {}
self.blind: List[dict] = []
self.calls: List[str] = []
self.incidents: Dict[str, dict] = {}
self.actions: List[dict] = []
self.observations: Dict[str, dict] = {}
self.links: List[dict] = []
self.known: List[dict] = [
{'id': 1, 'kind': 'reboot', 'subject': 'compute-storage-02', 'ticket_id': '693930698',
'reason': 'compute-storage-02 reboots every 2 to 3 days from a failing DIMM.'},
]
def _check(self, name):
self.calls.append(name)
if self.down:
raise DatabaseError('Lost connection to MySQL server')
def set_state(self, key, value, now):
self._check('set_state')
self.state[key] = json.loads(json.dumps(value, default=str))
def get_state(self, key, default=None):
self._check('get_state')
return self.state.get(key, default)
def record_cycle(self, **kw):
self._check('record_cycle')
self.cycles.append(kw)
return len(self.cycles)
def prune_cycles(self, older_than):
self._check('prune_cycles')
before = len(self.cycles)
self.cycles = [c for c in self.cycles if c['started'] >= older_than]
return before - len(self.cycles)
def source_statuses(self):
self._check('source_statuses')
return {k: dict(v) for k, v in self.sources.items()}
def save_source_status(self, name, up, since, last_ok, last_error, now):
self._check('save_source_status')
self.sources[name] = {'up': up, 'since': since, 'last_ok': last_ok, 'last_error': last_error}
def open_blind_period(self, source, started, reason):
self._check('open_blind_period')
self.blind.append({'source': source, 'started': started, 'ended': None, 'reason': reason})
def close_blind_period(self, source, ended):
self._check('close_blind_period')
for b in self.blind:
if b['source'] == source and b['ended'] is None:
b['ended'] = ended
def save_incident(self, inc, now):
self._check('save_incident')
self.incidents[inc['key']] = json.loads(json.dumps(inc, default=str))
def load_incidents(self, since):
self._check('load_incidents')
return [dict(i) for i in self.incidents.values()
if i['state'] in ('pending', 'open') or i['last_seen'] >= since]
def add_action(self, action):
self._check('add_action')
a = json.loads(json.dumps(action, default=str))
a.update(id=len(self.actions) + 1, status='pending' if a['mode'] == 'live' else 'shadow',
attempts=0, next_attempt_at=a['created'] if a['mode'] == 'live' else None, ticket_id=None)
self.actions.append(a)
return a['id']
def due_actions(self, now, limit=20):
self._check('due_actions')
return [a for a in self.actions if a['status'] == 'pending' and a['next_attempt_at'] <= now][:limit]
def mark_action_sent(self, action_id, ticket_id, now):
self._check('mark_action_sent')
a = self.actions[action_id - 1]
a.update(status='sent', ticket_id=ticket_id, sent_at=now)
def mark_action_failed(self, action_id, error, attempts, retry_at):
self._check('mark_action_failed')
a = self.actions[action_id - 1]
a.update(status='pending' if retry_at is not None else 'failed', attempts=attempts,
next_attempt_at=retry_at, error=error)
def incident_ticket(self, key):
self._check('incident_ticket')
ids = [a['ticket_id'] for a in self.actions if a['incident_key'] == key and a.get('ticket_id')]
return ids[-1] if ids else None
def save_observation(self, f, now):
self._check('save_observation')
o = self.observations.get(f['key'])
if o:
o['start'], o['end'] = min(o['start'], f['start']), max(o['end'], f['end'])
o['summary'], o['role'] = f['summary'], f['role']
else:
self.observations[f['key']] = json.loads(json.dumps(f, default=str))
def delete_incident(self, key):
self._check('delete_incident')
self.incidents.pop(key, None)
def get_incident(self, key):
self._check('get_incident')
return self.incidents.get(key)
def actions_for(self, key):
self._check('actions_for')
return [a for a in self.actions if a['incident_key'] == key]
def recent_actions(self, since, limit=200):
self._check('recent_actions')
return [a for a in reversed(self.actions) if a['created'] >= since][:limit]
def recent_observations(self, since):
self._check('recent_observations')
return [dict(o, first_seen=o['start'], last_seen=o['end'], k=o['key'])
for o in self.observations.values() if o['end'] >= since]
def add_known_condition(self, kind, subject, ticket_id, reason, created_by, now):
self._check('add_known_condition')
new = {'id': max([k['id'] for k in self.known] + [0]) + 1, 'kind': kind, 'subject': subject,
'ticket_id': ticket_id, 'reason': reason, 'created_by': created_by, 'created_at': now}
self.known.append(new)
return new['id']
def end_known_condition(self, condition_id, ended_by, now):
self._check('end_known_condition')
for k in self.known:
if k['id'] == condition_id and not k.get('ended'):
k['ended'] = now
return 1
return 0
def add_incident_link(self, key, ticket_id, who, now):
self._check('add_incident_link')
self.links.append({'incident_key': key, 'ticket_id': ticket_id, 'added_by': who, 'added_at': now})
return len(self.links)
def remove_incident_link(self, key, ticket_id, who, now):
self._check('remove_incident_link')
before = len(self.links)
self.links = [x for x in self.links if not (x['incident_key'] == key and x['ticket_id'] == ticket_id)]
return before - len(self.links)
def incident_links(self, key):
self._check('incident_links')
return [dict(x) for x in self.links if x['incident_key'] == key]
def known_conditions(self):
self._check('known_conditions')
return [dict(k) for k in self.known if not k.get('ended')]
def blind_periods(self, since):
self._check('blind_periods')
return [b for b in self.blind if b['ended'] is None or b['ended'] >= since]
class FakeResponse:
def __init__(self, status: int = 200, body: Any = None, text: Optional[str] = None):
self.status_code = status
self._body = body
self.text = text if text is not None else json.dumps(body)
def json(self):
if self._body is None:
raise ValueError('no JSON')
return self._body
def raise_for_status(self):
if self.status_code >= 400:
raise requests.HTTPError(f'HTTP {self.status_code}')
class FakeSession:
"""Serves replies in order for each (method, url-prefix). Records every request."""
def __init__(self):
self.routes: List[tuple] = []
self.requests: List[dict] = []
def add(self, method: str, url_prefix: str, *replies):
self.routes.append((method.upper(), url_prefix, list(replies)))
return self
def _serve(self, method, url, **kw):
self.requests.append({'method': method, 'url': url, **kw})
for m, prefix, replies in self.routes:
if m == method and url.startswith(prefix):
reply = replies[0] if len(replies) == 1 else replies.pop(0)
if isinstance(reply, Exception):
raise reply
return reply
raise requests.ConnectionError(f'no route for {method} {url}')
def get(self, url, **kw):
return self._serve('GET', url, **kw)
def post(self, url, **kw):
return self._serve('POST', url, **kw)
class FakeSource:
def __init__(self, name: str, up: bool = True, error: str = 'connection refused'):
self.name = name
self.up = up
self.error = error
self.pings = 0
def ping(self):
self.pings += 1
if not self.up:
raise SourceError(self.name, self.error)
class Clock:
def __init__(self, t: float = 1_795_575_600.0): # 2026-11-25 03:00:00 UTC
self.t = t
def __call__(self):
return self.t
def advance(self, seconds: float):
self.t += seconds