askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_migrate_from_object_primitive.py · 13.2 KB · 313 lines
| 1 | """Tests for scripts/migrate_from_object_primitive.py against a fake old server.""" |
| 2 | import hashlib |
| 3 | import importlib.util |
| 4 | import json |
| 5 | import threading |
| 6 | from http.server import BaseHTTPRequestHandler, HTTPServer |
| 7 | from pathlib import Path |
| 8 | from urllib.parse import parse_qs, urlparse |
| 9 | |
| 10 | import pytest |
| 11 | |
| 12 | SCRIPT = Path(__file__).resolve().parent.parent / "scripts" / "migrate_from_object_primitive.py" |
| 13 | spec = importlib.util.spec_from_file_location("migrate_tool", SCRIPT) |
| 14 | mig = importlib.util.module_from_spec(spec) |
| 15 | spec.loader.exec_module(mig) |
| 16 | |
| 17 | SECRET = "Basic c3VwZXItc2VjcmV0LXZhbHVl" |
| 18 | |
| 19 | |
| 20 | def _src(n): |
| 21 | return f"def GET(request):\n return {{'n': {n}}}\n" |
| 22 | |
| 23 | |
| 24 | def _versions(oid): |
| 25 | return [ |
| 26 | {"version_id": i, "timestamp": f"2026-01-0{i}T10:00:00", "author": a, "message": m, |
| 27 | "content": _src(i)} |
| 28 | for i, (a, m) in enumerate([("system", "Initial version"), ("alice", "tweak"), ("bob", "again")], 1) |
| 29 | ] |
| 30 | |
| 31 | |
| 32 | def make_fixture(): |
| 33 | objs = { |
| 34 | "basics_counter": ("basics/counter.py", "system", {"count": 7, "name": "hello", "ratio": 1.5}), |
| 35 | "tools_scan_ingest": ("tools/scan_ingest.py", "system", {"cfg": {"a": [1, 2]}, "flag": True}), |
| 36 | "u_1_deals": ("users/1/deals.py", "1", {"stage": "won", "amount": 120}), |
| 37 | "demo_stateless": ("demo/stateless.py", "system", {}), |
| 38 | "demo_other": ("demo/other.py", "system", {"x": "y"}), |
| 39 | } |
| 40 | out = {} |
| 41 | for oid, (path, owner, state) in objs.items(): |
| 42 | vs = _versions(oid) |
| 43 | out[oid] = {"path": path, "owner": owner, "state": state, "versions": vs, "source": vs[-1]["content"]} |
| 44 | return out |
| 45 | |
| 46 | |
| 47 | @pytest.fixture |
| 48 | def old_server(): |
| 49 | fixture = make_fixture() |
| 50 | # "limit": answer HTTP 429 to requests number `from`..`from + count - 1` |
| 51 | # (1-based), phrased the way the old server does. |
| 52 | seen = {"writes": 0, "auths": [], "requests": 0, "limited": 0, "limit": None} |
| 53 | |
| 54 | class H(BaseHTTPRequestHandler): |
| 55 | def log_message(self, *a): |
| 56 | pass |
| 57 | |
| 58 | def _send(self, code, body, headers=()): |
| 59 | data = json.dumps(body).encode() |
| 60 | self.send_response(code) |
| 61 | for name, value in headers: |
| 62 | self.send_header(name, value) |
| 63 | self.send_header("Content-Length", str(len(data))) |
| 64 | self.end_headers() |
| 65 | self.wfile.write(data) |
| 66 | |
| 67 | def do_GET(self): |
| 68 | seen["auths"].append(self.headers.get("Authorization")) |
| 69 | if self.headers.get("Authorization") != SECRET: |
| 70 | return self._send(401, {"error": "Authentication required"}) |
| 71 | seen["requests"] += 1 |
| 72 | limit = seen["limit"] |
| 73 | if limit and limit["from"] <= seen["requests"] < limit["from"] + limit["count"]: |
| 74 | seen["limited"] += 1 |
| 75 | secs = limit.get("seconds", 17) |
| 76 | headers = [("Retry-After", str(secs))] if limit.get("header", True) else [] |
| 77 | text = limit.get("text", f"Rate limit exceeded. Try again in {secs} seconds.") |
| 78 | return self._send(429, {"error": text}, headers) |
| 79 | u = urlparse(self.path) |
| 80 | q = {k: v[0] for k, v in parse_qs(u.query).items()} |
| 81 | if u.path == "/objects": |
| 82 | return self._send(200, {"status": "ok", "count": len(fixture), "objects": [ |
| 83 | {"object_id": k, "path": v["path"], "file": "x/" + v["path"], "owner": v["owner"]} |
| 84 | for k, v in fixture.items()]}) |
| 85 | oid = u.path.split("/objects/")[1] |
| 86 | o = fixture.get(oid) |
| 87 | if o is None: |
| 88 | return self._send(404, {"error": "nope"}) |
| 89 | if "version" in q: |
| 90 | v = next(v for v in o["versions"] if v["version_id"] == int(q["version"])) |
| 91 | return self._send(200, {"status": "ok", "version": {**v, "hash": "h"}}) |
| 92 | if "versions" in q: |
| 93 | return self._send(200, {"status": "ok", "versions": [ |
| 94 | {k: v[k] for k in ("version_id", "timestamp", "author", "message")} |
| 95 | for v in reversed(o["versions"])]}) |
| 96 | if "state" in q: |
| 97 | return self._send(200, {"status": "ok", "state": o["state"]}) |
| 98 | return self._send(200, {"status": "ok", "source": o["source"]}) |
| 99 | |
| 100 | def do_POST(self): |
| 101 | seen["writes"] += 1 |
| 102 | self._send(405, {}) |
| 103 | |
| 104 | do_PUT = do_DELETE = do_POST |
| 105 | |
| 106 | srv = HTTPServer(("127.0.0.1", 0), H) |
| 107 | threading.Thread(target=srv.serve_forever, daemon=True).start() |
| 108 | yield f"http://127.0.0.1:{srv.server_port}", fixture, seen |
| 109 | srv.shutdown() |
| 110 | |
| 111 | |
| 112 | @pytest.fixture |
| 113 | def env(tmp_path, monkeypatch, old_server): |
| 114 | monkeypatch.setenv("OLD_AUTH", SECRET) |
| 115 | url, fixture, seen = old_server |
| 116 | lines = [] |
| 117 | |
| 118 | def run(*extra): |
| 119 | lines.clear() |
| 120 | rc = mig.main(["--old-url", url, "--auth-env", "OLD_AUTH", |
| 121 | "--objects-dir", str(tmp_path / "objects"), "--data-dir", str(tmp_path / "data"), |
| 122 | "--report", str(tmp_path / "report.json"), *extra], out=lines.append) |
| 123 | return rc, "\n".join(lines) |
| 124 | |
| 125 | return run, tmp_path, fixture, seen |
| 126 | |
| 127 | |
| 128 | def test_dry_run_writes_nothing(env): |
| 129 | run, tmp, fixture, seen = env |
| 130 | rc, out = run() |
| 131 | assert rc == 0 and "DRY RUN" in out and "create=5" in out |
| 132 | assert not (tmp / "objects").exists() and not (tmp / "data").exists() |
| 133 | assert json.loads((tmp / "report.json").read_text())["apply"] is False |
| 134 | assert seen["writes"] == 0 |
| 135 | |
| 136 | |
| 137 | def test_apply_copies_everything_and_verifies(env): |
| 138 | run, tmp, fixture, _ = env |
| 139 | rc, out = run("--apply") |
| 140 | assert rc == 0, out |
| 141 | assert "5 match, 0 mismatch" in out |
| 142 | assert (tmp / "objects/basics/counter.py").read_text() == fixture["basics_counter"]["source"] |
| 143 | assert (tmp / "objects/users/1/deals.py").exists() |
| 144 | import object_state, object_versions |
| 145 | assert object_state.get_object_state("basics_counter", tmp / "data") == {"count": 7, "name": "hello", "ratio": 1.5} |
| 146 | st = object_state.get_object_state("tools_scan_ingest", tmp / "data") |
| 147 | assert st["flag"] == "true" and json.loads(st["cfg"]) == {"a": [1, 2]} |
| 148 | hist = object_versions.VersionManager(tmp / "data").get_history("u_1_deals") |
| 149 | assert [(v["version_id"], v["author"], v["message"]) for v in reversed(hist)] == [ |
| 150 | (1, "system", "Initial version"), (2, "alice", "tweak"), (3, "bob", "again")] |
| 151 | assert hist[0]["timestamp"] == "2026-01-03T10:00:00" |
| 152 | assert object_versions.VersionManager(tmp / "data").get_version("u_1_deals", 2)["content"] == _src(2) |
| 153 | |
| 154 | |
| 155 | def test_rerun_is_noop(env): |
| 156 | run, tmp, *_ = env |
| 157 | run("--apply") |
| 158 | before = {p: p.read_bytes() for p in tmp.rglob("*") if p.is_file() and p.name != "report.json"} |
| 159 | rc, out = run("--apply") |
| 160 | assert rc == 0 and "identical=5" in out |
| 161 | after = {p: p.read_bytes() for p in tmp.rglob("*") if p.is_file() and p.name != "report.json"} |
| 162 | assert before == after |
| 163 | |
| 164 | |
| 165 | def test_conflict_skipped_then_overwritten(env): |
| 166 | run, tmp, fixture, _ = env |
| 167 | (tmp / "objects/basics").mkdir(parents=True) |
| 168 | (tmp / "objects/basics/counter.py").write_text("def GET(r):\n return 'mine'\n") |
| 169 | rc, out = run("--apply") |
| 170 | assert "conflict=1" in out and "create=4" in out |
| 171 | assert (tmp / "objects/basics/counter.py").read_text().endswith("'mine'\n") |
| 172 | rc, out = run("--apply", "--overwrite") |
| 173 | assert rc == 0 and "overwrite=1" in out and "mismatch" in out and "0 mismatch" in out |
| 174 | assert (tmp / "objects/basics/counter.py").read_text() == fixture["basics_counter"]["source"] |
| 175 | |
| 176 | |
| 177 | def test_selection_flags(env): |
| 178 | run, tmp, *_ = env |
| 179 | _, out = run("--only", "tools_*", "--only", "users/*") |
| 180 | assert "2 object(s) selected" in out |
| 181 | _, out = run("--exclude", "demo_*") |
| 182 | assert "3 object(s) selected" in out |
| 183 | run("--apply", "--only", "basics_counter") |
| 184 | assert (tmp / "objects/basics/counter.py").exists() |
| 185 | assert not (tmp / "objects/tools").exists() |
| 186 | |
| 187 | |
| 188 | def test_auth_header_never_printed_and_required(env, capsys, tmp_path): |
| 189 | run, tmp, _, seen = env |
| 190 | rc, out = run("--apply") |
| 191 | assert SECRET not in out and "c3VwZXI" not in out |
| 192 | assert SECRET not in (tmp / "report.json").read_text() |
| 193 | assert set(seen["auths"]) == {SECRET} |
| 194 | # wrong auth: reports an error, exit non-zero, secret still not echoed |
| 195 | lines = [] |
| 196 | rc = mig.main(["--old-url", f"http://127.0.0.1:1", "--auth-env", "OLD_AUTH", |
| 197 | "--objects-dir", str(tmp / "o2"), "--data-dir", str(tmp / "d2"), |
| 198 | "--report", str(tmp / "r2.json")], out=lines.append) |
| 199 | assert rc == 2 and SECRET not in "\n".join(lines) |
| 200 | |
| 201 | |
| 202 | def test_unstorable_state_value_is_an_error_not_a_write(env, old_server): |
| 203 | run, tmp, fixture, _ = env |
| 204 | fixture["demo_other"]["state"] = {"x": "line1\nline2"} |
| 205 | rc, out = run("--apply") |
| 206 | assert rc == 1 and "error" in out |
| 207 | assert not (tmp / "objects/demo/other.py").exists() |
| 208 | assert (tmp / "objects/basics/counter.py").exists() |
| 209 | |
| 210 | |
| 211 | # ---------------------------------------------------------------- HTTP 429 |
| 212 | |
| 213 | @pytest.fixture |
| 214 | def sleeps(monkeypatch): |
| 215 | """Record the tool's waits instead of sleeping.""" |
| 216 | slept = [] |
| 217 | monkeypatch.setattr(mig.time, "sleep", slept.append) |
| 218 | return slept |
| 219 | |
| 220 | |
| 221 | def _requests_for_one_pass(env): |
| 222 | run, _, _, seen = env |
| 223 | run() |
| 224 | return seen["requests"] |
| 225 | |
| 226 | |
| 227 | def test_rate_limit_delay_reads_header_then_text_then_default(): |
| 228 | assert mig.rate_limit_delay("42", "") == 42 |
| 229 | assert mig.rate_limit_delay(None, '{"error": "Rate limit exceeded. Try again in 17 seconds."}') == 17 |
| 230 | assert mig.rate_limit_delay("9", "Try again in 17 seconds.") == 9 |
| 231 | assert mig.rate_limit_delay("Wed, 21 Oct 2026 07:28:00 GMT", "Try again in 1 second.") == 1 |
| 232 | assert mig.rate_limit_delay(None, "slow down") == mig.RATE_LIMIT_FALLBACK_WAIT |
| 233 | assert mig.rate_limit_delay("-5", "") == mig.RATE_LIMIT_FALLBACK_WAIT |
| 234 | |
| 235 | |
| 236 | def test_429_during_verify_is_waited_out_and_retried(env, sleeps): |
| 237 | run, tmp, fixture, seen = env |
| 238 | per_pass = _requests_for_one_pass(env) |
| 239 | # the first three requests of the verify pass are refused |
| 240 | seen["requests"] = 0 |
| 241 | seen["limit"] = {"from": per_pass + 1, "count": 3, "seconds": 17} |
| 242 | rc, out = run("--apply") |
| 243 | assert rc == 0, out |
| 244 | assert seen["limited"] == 3 and sleeps == [18.0, 18.0, 18.0] |
| 245 | assert "5 match, 0 mismatch, 0 could not verify" in out |
| 246 | assert "MISMATCH" not in out and "COULD NOT VERIFY" not in out |
| 247 | assert "waiting 18s" in out and "waited 54s in total" in out |
| 248 | report = json.loads((tmp / "report.json").read_text()) |
| 249 | assert report["unverified"] == {} and all(v == [] for v in report["verify"].values()) |
| 250 | |
| 251 | |
| 252 | def test_429_wait_comes_from_the_text_when_there_is_no_header(env, sleeps): |
| 253 | run, _, _, seen = env |
| 254 | seen["limit"] = {"from": 2, "count": 1, "seconds": 23, "header": False} |
| 255 | rc, out = run() |
| 256 | assert rc == 0 and sleeps == [24.0] and "create=5" in out |
| 257 | |
| 258 | |
| 259 | def test_429_past_the_wait_budget_is_could_not_verify_not_mismatch(env, sleeps): |
| 260 | run, tmp, fixture, seen = env |
| 261 | per_pass = _requests_for_one_pass(env) |
| 262 | seen["requests"] = 0 |
| 263 | seen["limit"] = {"from": per_pass + 1, "count": 10 ** 6, "seconds": 30} |
| 264 | rc, out = run("--apply", "--rate-limit-wait", "70") |
| 265 | assert rc == 3, out |
| 266 | assert sleeps == [31.0, 31.0] # 62s spent, a third wait would pass 70s |
| 267 | assert "verified 0 object(s): 0 match, 0 mismatch, 5 could not verify" in out |
| 268 | assert out.count("COULD NOT VERIFY") == 5 and "MISMATCH" not in out and "HTTP 429" in out |
| 269 | report = json.loads((tmp / "report.json").read_text()) |
| 270 | assert report["verify"] == {} and len(report["unverified"]) == 5 |
| 271 | # the copy itself happened; a later run verifies it |
| 272 | assert (tmp / "objects/basics/counter.py").read_text() == fixture["basics_counter"]["source"] |
| 273 | seen["limit"] = None |
| 274 | rc, out = run("--apply") |
| 275 | assert rc == 0 and "5 match, 0 mismatch, 0 could not verify" in out |
| 276 | |
| 277 | |
| 278 | def test_429_unverified_objects_are_never_counted_as_match(env, sleeps): |
| 279 | run, tmp, fixture, seen = env |
| 280 | per_pass = _requests_for_one_pass(env) |
| 281 | # verify re-reads 5 objects; refuse everything after the first object's reads |
| 282 | per_object = (per_pass - 1) // 5 |
| 283 | seen["requests"] = 0 |
| 284 | seen["limit"] = {"from": per_pass + per_object + 1, "count": 10 ** 6} |
| 285 | rc, out = run("--apply", "--rate-limit-wait", "0") |
| 286 | assert rc == 3 and sleeps == [] |
| 287 | assert "verified 1 object(s): 1 match, 0 mismatch, 4 could not verify" in out |
| 288 | |
| 289 | |
| 290 | def test_real_mismatch_still_exits_1_and_wins_over_could_not_verify(env, sleeps): |
| 291 | run, tmp, fixture, seen = env |
| 292 | per_pass = _requests_for_one_pass(env) |
| 293 | per_object = (per_pass - 1) // 5 |
| 294 | run("--apply") |
| 295 | (tmp / "objects/basics/counter.py").write_text("def GET(r):\n return 'changed'\n") |
| 296 | real = mig.plan_object |
| 297 | # plan sees it as identical, so nothing is rewritten and verify must catch it |
| 298 | mig_plan = lambda old, target, oid, overwrite: {**real(old, target, oid, True), "action": "identical"} |
| 299 | seen["requests"] = 0 |
| 300 | seen["limit"] = {"from": per_pass + per_object + 1, "count": 10 ** 6} |
| 301 | import unittest.mock |
| 302 | with unittest.mock.patch.object(mig, "plan_object", mig_plan): |
| 303 | rc, out = run("--apply", "--rate-limit-wait", "0") |
| 304 | assert rc == 1 |
| 305 | assert "MISMATCH basics_counter: source hash differs" in out |
| 306 | assert "0 match, 1 mismatch, 4 could not verify" in out |
| 307 | |
| 308 | |
| 309 | def test_429_on_the_listing_past_the_budget_exits_2(env, sleeps): |
| 310 | run, _, _, seen = env |
| 311 | seen["limit"] = {"from": 1, "count": 10 ** 6, "seconds": 40} |
| 312 | rc, out = run("--rate-limit-wait", "10") |
| 313 | assert rc == 2 and "HTTP 429" in out and sleeps == [] |