askrobots / foxray Public

Foxray: a light error tracker for the Sentry SDKs. Runs inside Django (the admin is the UI) or on its own; SQLite or Postgres, nothing else. Not affiliated with Sentry.

0 downloads

foxray/tests/helpers.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/foxray.git
HTTPS
https://gitstable.com/git/askrobots/foxray.git
SSH
ssh://git@gitstable.com:2222/askrobots/foxray.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 0.1.2: the first PyPI release (v0.1.1 is already tagged at 05cc354, before the PyPI metadata) 58507e3 4 weeks ago History
helpers.py · 3.6 KB · 102 lines
1"""Builders shared by the tests."""
2
3from __future__ import annotations
4
5import json
6import uuid
7from datetime import datetime, timedelta, timezone
8
9from foxray.core.alerts import Links, Outbox
10from foxray.core.ingest import Ingestor
11from foxray.core.maintenance import Housekeeper, Maintenance
12from foxray.core.settings import Settings
13
14
15class Clock:
16 def __init__(self, start: datetime | None = None):
17 self.now = start or datetime(2026, 10, 1, 12, 0, 0, tzinfo=timezone.utc)
18
19 def __call__(self) -> datetime:
20 return self.now
21
22 def advance(self, **kw) -> datetime:
23 self.now += timedelta(**kw)
24 return self.now
25
26
27def envelope(*items, header: dict | None = None, with_length: bool = True) -> bytes:
28 """items: (item_header_dict, payload) with payload a dict or bytes."""
29 out = [json.dumps(header or {}).encode()]
30 for item_header, payload in items:
31 data = payload if isinstance(payload, bytes) else json.dumps(payload).encode()
32 h = dict(item_header)
33 if with_length:
34 h["length"] = len(data)
35 out.append(json.dumps(h).encode())
36 out.append(data)
37 return b"\n".join(out) + b"\n"
38
39
40def make_event(exc_type="ValueError", value="boom", *, module="app.views", function="index",
41 in_app=True, lineno=10, event_id=None, **extra) -> dict:
42 ev = {
43 "event_id": event_id or uuid.uuid4().hex,
44 "platform": "python",
45 "level": "error",
46 "exception": {"values": [{
47 "type": exc_type, "value": value,
48 "stacktrace": {"frames": [
49 {"module": "django.core.handlers", "function": "inner", "lineno": 55, "in_app": False},
50 {"module": module, "function": function, "lineno": lineno, "in_app": in_app,
51 "context_line": " raise ValueError('boom')", "pre_context": ["def index():"],
52 "post_context": [""]},
53 ]},
54 }]},
55 }
56 ev.update(extra)
57 return ev
58
59
60def auth_headers(project, **extra) -> dict:
61 h = {"x-sentry-auth": f"Sentry sentry_key={project.public_key}, sentry_version=7, sentry_client=test/1"}
62 h.update({k.lower(): v for k, v in extra.items()})
63 return h
64
65
66class Recorder:
67 """A notifier channel that remembers what it sent."""
68
69 def __init__(self, fail: bool = False):
70 self.sent = []
71 self.fail = fail
72
73 def __call__(self, alert, project):
74 if self.fail:
75 raise RuntimeError("mail server down")
76 self.sent.append(alert)
77 return "recorded"
78
79
80def make_stack(store, settings: Settings | None = None, clock: Clock | None = None, channel: Recorder | None = None):
81 settings = settings or Settings()
82 clock = clock or Clock()
83 channel = channel or Recorder()
84 links = Links("http://foxray.test")
85 outbox = Outbox(store, settings, {"test": channel}, clock=clock)
86 maint = Maintenance(store, settings, links=links, global_channels=["test"], clock=clock)
87 hk = Housekeeper(store, settings, maintenance=maint, outbox=outbox, links=links,
88 channels_for=lambda p: ["test"], clock=clock)
89 ing = Ingestor(store, settings, links=links, channels_for=lambda p: ["test"], housekeeper=hk, clock=clock)
90 return ing, hk, outbox, channel, clock
91
92
93def close_thread_connections() -> None:
94 """Threads that used Django's connection must close it, or Postgres
95 keeps sessions open on the test database."""
96 try:
97 from django.conf import settings
98 if settings.configured:
99 from django.db import connections
100 connections.close_all()
101 except ImportError:
102 pass