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/test_sdk_standalone.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
test_sdk_standalone.py · 7.2 KB · 158 lines
1"""The key test: the real Sentry SDK against the standalone server."""
2
3import http.cookiejar
4import json
5import os
6import socket
7import subprocess
8import sys
9import time
10import urllib.parse
11import urllib.request
12from pathlib import Path
13
14import pytest
15
16from foxray.standalone.store import open_store
17from tests.sdk_checks import check_sdk_run
18
19ROOT = Path(__file__).resolve().parent.parent
20ENV = {**os.environ, "PYTHONPATH": str(ROOT)}
21
22
23def free_port() -> int:
24 with socket.socket() as s:
25 s.bind(("127.0.0.1", 0))
26 return s.getsockname()[1]
27
28
29def foxray(*args, **kw):
30 return subprocess.run([sys.executable, "-m", "foxray", *args], cwd=ROOT, env=ENV, capture_output=True,
31 text=True, timeout=60, check=True, **kw).stdout
32
33
34@pytest.fixture(params=["sqlite", "postgres"])
35def server(request, tmp_path):
36 db = str(tmp_path / "foxray.db") if request.param == "sqlite" else request.getfixturevalue("pg_fresh_url")
37 port = free_port()
38 base = f"http://127.0.0.1:{port}"
39 proc = subprocess.Popen([sys.executable, "-m", "foxray", "--db", db, "serve", "--host", "127.0.0.1",
40 "--port", str(port), "--base-url", base], cwd=ROOT, env=ENV,
41 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
42 line = proc.stdout.readline()
43 assert "listening" in line, line
44 try:
45 yield {"db": db, "base": base, "proc": proc}
46 finally:
47 proc.terminate()
48 proc.wait(timeout=10)
49
50
51def _has_brotli() -> bool:
52 try:
53 import brotli # noqa: F401
54 return True
55 except ImportError:
56 return False
57
58
59@pytest.mark.slow
60@pytest.mark.parametrize("compression", ["gzip", pytest.param("br", marks=pytest.mark.skipif(
61 not _has_brotli(), reason="Brotli not installed"))])
62def test_real_sentry_sdk_against_standalone(server, compression):
63 dsn = foxray("--db", server["db"], "create-project", "shop", "--base-url", server["base"]).strip()
64 assert dsn.startswith("http://") and dsn.endswith("/1")
65 out = subprocess.run([sys.executable, str(ROOT / "tests" / "sdk_client.py"), dsn], cwd=ROOT,
66 env={**ENV, "SDK_COMPRESSION": compression},
67 capture_output=True, text=True, timeout=60, check=True).stdout
68 ids = json.loads(out.strip().splitlines()[-1])
69 store = open_store(server["db"])
70 project = store.get_project(1)
71 deadline = time.time() + 10
72 while time.time() < deadline and len(store.list_monitors(project.id)) < 3:
73 time.sleep(0.1)
74 check_sdk_run(store, project, ids)
75
76 # The UI, behind its login.
77 subprocess.run([sys.executable, "-m", "foxray", "--db", server["db"], "create-user", "dev@example.com",
78 "--password-stdin"], cwd=ROOT, env=ENV, input="correct horse battery\n", text=True,
79 check=True, capture_output=True, timeout=60)
80 jar = http.cookiejar.CookieJar()
81 opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
82 base = server["base"]
83 with opener.open(base + "/issues") as r: # redirected to the login page
84 assert "/login" in r.url
85 with pytest.raises(urllib.error.HTTPError) as e:
86 opener.open(base + "/login", urllib.parse.urlencode({"email": "dev@example.com", "password": "nope"}).encode())
87 assert e.value.code == 401
88 with opener.open(base + "/login", urllib.parse.urlencode(
89 {"email": "dev@example.com", "password": "correct horse battery", "next": "/issues"}).encode()) as r:
90 listing = r.read().decode()
91 assert "ZeroDivisionError" in listing and "Payment provider slow" in listing
92 zero = [i for i in store.list_issues()[0] if i.title.startswith("ZeroDivisionError")][0]
93 with opener.open(f"{base}/issues/{zero.id}") as r:
94 detail = r.read().decode()
95 assert "checkout" in detail and "10 / n" in detail and "shop@1.2.3" in detail
96 for path in ("/monitors", "/projects", "/projects/1", "/alerts", "/storage",
97 "/issues?status=all&level=warning&sort=count&q=payment"):
98 with opener.open(base + path) as r:
99 assert r.status == 200, path
100 with opener.open(base + "/monitors") as r:
101 assert "nightly-report" in r.read().decode()
102 # Resolve from the UI (with the CSRF token from the page).
103 token = detail.split('name="csrf" value="')[1].split('"')[0]
104 with opener.open(f"{base}/issues/{zero.id}", urllib.parse.urlencode({"csrf": token, "action": "resolve"}).encode()):
105 pass
106 assert store.get_issue(zero.id).status == "resolved"
107 with pytest.raises(urllib.error.HTTPError) as e:
108 opener.open(f"{base}/issues/{zero.id}", urllib.parse.urlencode({"csrf": "bad", "action": "reopen"}).encode())
109 assert e.value.code == 403
110
111
112@pytest.mark.slow
113def test_standalone_http_edges(server):
114 dsn = foxray("--db", server["db"], "create-project", "edge", "--base-url", server["base"]).strip()
115 key = dsn.split("//")[1].split("@")[0]
116 url = server["base"] + "/api/1/envelope/"
117
118 def post(body, headers):
119 req = urllib.request.Request(url, data=body, headers=headers, method="POST")
120 try:
121 with urllib.request.urlopen(req) as r:
122 return r.status, dict(r.headers), r.read()
123 except urllib.error.HTTPError as e:
124 return e.code, dict(e.headers), e.read()
125
126 auth = {"X-Sentry-Auth": f"Sentry sentry_key={key}, sentry_version=7"}
127 status, headers, body = post(b'{}\n{"type":"session"}\n{}\n', auth)
128 assert status == 200 and headers["Access-Control-Allow-Origin"] == "*"
129 assert post(b"x", {**auth, "Content-Encoding": "br" if False else "zstd"})[0] == 415
130 assert post(b"{}\n", {})[0] == 401
131 req = urllib.request.Request(url, method="OPTIONS")
132 with urllib.request.urlopen(req) as r:
133 assert r.status == 200 and "X-Sentry-Auth" in r.headers["Access-Control-Allow-Headers"]
134 with urllib.request.urlopen(server["base"] + "/healthz") as r:
135 assert r.read() == b"ok\n"
136 # query-string auth and the legacy store endpoint
137 req = urllib.request.Request(server["base"] + f"/api/1/store/?sentry_key={key}&sentry_version=7",
138 data=json.dumps({"message": "legacy"}).encode(), method="POST")
139 with urllib.request.urlopen(req) as r:
140 assert "id" in json.loads(r.read())
141
142
143@pytest.mark.slow
144def test_login_does_not_redirect_off_site(server):
145 subprocess.run([sys.executable, "-m", "foxray", "--db", server["db"], "create-user", "dev@example.com",
146 "--password-stdin"], cwd=ROOT, env=ENV, input="correct horse battery\n", text=True,
147 check=True, capture_output=True, timeout=60)
148
149 class NoRedirect(urllib.request.HTTPRedirectHandler):
150 def redirect_request(self, *a, **k):
151 return None
152 opener = urllib.request.build_opener(NoRedirect)
153 for evil in ("https://evil.example/", "//evil.example/", "/\\evil.example"):
154 data = urllib.parse.urlencode({"email": "dev@example.com", "password": "correct horse battery",
155 "next": evil}).encode()
156 with pytest.raises(urllib.error.HTTPError) as e:
157 opener.open(server["base"] + "/login", data)
158 assert e.value.code == 303 and e.value.headers["Location"] == "/issues", evil