Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

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

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
conftest.py · 7.8 KB · 178 lines
1import json
2import os
3import sys
4from pathlib import Path
5
6import pytest
7
8
9ROOT = Path(__file__).resolve().parents[1]
10if str(ROOT) not in sys.path:
11 sys.path.insert(0, str(ROOT))
12
13PACKAGES = ROOT / "packages"
14
15
16# --- running as if an optional extra were not installed -----------------------
17#
18# DBBASIC_TEST_WITHOUT=cryptography (comma-separated top-level module names)
19# runs the suite as a plain `pip install -e ".[test]"` box would, with those
20# packages absent even though this environment has them: an import raises
21# exactly the ModuleNotFoundError an uninstalled package does. Tests that
22# need an extra must skip under it, not fail -- that is the check. (A None
23# in sys.modules is not a faithful stand-in: on 3.15 formatting that error
24# re-imports the package and crashes pytest's reporting.)
25
26class _Uninstalled:
27 def __init__(self, names):
28 self.names = names
29
30 def find_spec(self, name, path=None, target=None):
31 top = name.partition(".")[0]
32 if top in self.names:
33 raise ModuleNotFoundError(f"No module named {top!r}", name=top)
34 return None
35
36
37_WITHOUT = {name.strip() for name in os.environ.get("DBBASIC_TEST_WITHOUT", "").split(",") if name.strip()}
38if _WITHOUT:
39 for _name in [n for n in sys.modules if n.partition(".")[0] in _WITHOUT]:
40 del sys.modules[_name]
41 sys.meta_path.insert(0, _Uninstalled(_WITHOUT))
42
43
44_CURRENT = {"monkeypatch": None}
45
46# User objects (u_<uid>_*) run only behind Landlock, as a separate OS user
47# started by the root launcher (object_sandbox, object_sandbox_launcher).
48# Where either is missing (macOS, CI runners, a Linux box without the
49# launcher) the suite runs them through the same worker and proxies without
50# the kernel wall, so tests about user-object *behaviour* still run
51# everywhere. The sandbox's own tests (tests/test_object_sandbox*.py) set or
52# clear this themselves and skip the wall checks where there is no wall.
53import object_sandbox as _object_sandbox # noqa: E402
54
55_NEEDS_UNSAFE_DEV = (_object_sandbox.landlock_abi() < _object_sandbox.MIN_LANDLOCK_ABI
56 or _object_sandbox.launcher_info() is None)
57
58
59# Settings a deployed box (or its container image) exports. A test that
60# inherits one reads that box's objects, packages or admin token instead of
61# its own: seven tests failed that way inside the Docker image and passed
62# everywhere else. Cleared once, here, before any test or fixture runs: a
63# test or a module-scoped fixture that wants one sets it itself, and a
64# per-test delenv would take a module-scoped fixture's value away.
65for _name in ("DBBASIC_OBJECTS_DIR", "DBBASIC_PACKAGES_DIR", "DBBASIC_ADMIN_TOKEN"):
66 os.environ.pop(_name, None)
67
68
69@pytest.fixture(autouse=True)
70def isolated_default_data_dir(monkeypatch, tmp_path):
71 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
72 if _NEEDS_UNSAFE_DEV:
73 monkeypatch.setenv(_object_sandbox.ISOLATION_ENV, _object_sandbox.UNSAFE_DEV)
74 _CURRENT["monkeypatch"] = monkeypatch
75 yield
76 _CURRENT["monkeypatch"] = None
77
78
79# --- shared TSV fixture staging ---------------------------------------------
80#
81# A cluster of tests build a data_dir by hand: copy a real package schema
82# into schemas/, then write collections/<name>/records.tsv themselves. Many
83# of them used to hand-type that header as a literal tab-separated string.
84# That string has no connection to the schema it claims to describe, so
85# when a field is added to the real schema, the hand-typed header silently
86# stops matching field order -- the test keeps passing while exercising a
87# column layout that no longer exists in production. schema_header() and
88# stage_collection() derive the header from the schema itself so drift is
89# structurally impossible.
90#
91# These are plain functions, not fixtures: `from conftest import
92# schema_header, stage_collection` at each call site, so a test's fixture
93# setup still reads as ordinary, narrative code rather than disappearing
94# behind fixture injection.
95
96def schema_header(package_id, collection):
97 """The TSV header line (with trailing newline) for one package
98 collection, in the exact field order its real schema declares."""
99 schema = json.loads(
100 (PACKAGES / package_id / "schemas" / f"{collection}.json").read_text())
101 return "\t".join(f["name"] for f in schema["fields"]) + "\n"
102
103
104def stage_collection(data_dir, package_id, collection, *, rows="", seed=False):
105 """Stage one real package collection under `data_dir`: copy its schema
106 JSON into schemas/, then create collections/<collection>/records.tsv.
107
108 seed=True copies the package's seed/<collection>.tsv verbatim -- for
109 tests that need the seeded reference rows themselves (e.g.
110 denominations), not just an empty, correctly-shaped collection.
111 Otherwise the file is schema_header() plus `rows`, a caller-supplied
112 TSV body already in schema field order (empty for a collection a test
113 only needs to exist).
114 """
115 schema_dir = data_dir / "schemas"
116 schema_dir.mkdir(parents=True, exist_ok=True)
117 (schema_dir / f"{collection}.json").write_text(
118 (PACKAGES / package_id / "schemas" / f"{collection}.json").read_text())
119
120 coll_dir = data_dir / "collections" / collection
121 coll_dir.mkdir(parents=True, exist_ok=True)
122 records_path = coll_dir / "records.tsv"
123 if seed:
124 records_path.write_text(
125 (PACKAGES / package_id / "seed" / f"{collection}.tsv").read_text())
126 else:
127 records_path.write_text(schema_header(package_id, collection) + rows)
128 _stage_locked_check_objects(data_dir, package_id, collection)
129 return records_path
130
131
132def _stage_locked_check_objects(data_dir, package_id, collection):
133 """A schema that declares `locked_checks` names objects the record layer
134 calls on every write, and refuses the write when they are missing (a
135 gate that is not there is not "no gate"). Staging the schema without
136 them would stage a deployment that cannot write the collection at all,
137 so they are staged too: into an override root beside the data dir
138 (DBBASIC_OVERRIDES_DIR, searched before any object root), so they are
139 found whatever object root the test points at afterwards. The copies
140 are the package's own files, byte for byte, so a test that also
141 installs the package resolves the same code either way."""
142 import os
143
144 schema = json.loads((PACKAGES / package_id / "schemas" / f"{collection}.json").read_text())
145 wanted = {check["object"] for check in schema.get("locked_checks") or []}
146 if not wanted:
147 return
148 manifest = json.loads((PACKAGES / package_id / "dbbasic-package.json").read_text())
149 sources = {entry["id"]: PACKAGES / package_id / entry["path"]
150 for entry in manifest.get("objects", [])}
151 configured = os.environ.get("DBBASIC_OVERRIDES_DIR")
152 if configured:
153 root = Path(configured)
154 try:
155 root.resolve().relative_to(ROOT)
156 return # an override root inside this repository is never written
157 except ValueError:
158 pass
159 else:
160 root = Path(data_dir).parent / "staged-check-objects"
161 _CURRENT["monkeypatch"].setenv("DBBASIC_OVERRIDES_DIR", str(root))
162 for object_id in sorted(wanted):
163 relative = Path(*Path(sources[object_id].relative_to(PACKAGES / package_id)).parts[1:])
164 destination = root / relative
165 if not destination.exists():
166 destination.parent.mkdir(parents=True, exist_ok=True)
167 destination.write_text(sources[object_id].read_text())
168
169
170# The e2e browser lane needs playwright, which the per-commit Tests
171# environment deliberately does not install. Deselection via the marker is
172# not enough: pytest still IMPORTS a module to collect it, and an import
173# error fails the whole run. Where the dependency is absent, the lane
174# should be invisible, not broken.
175try:
176 import playwright # noqa: F401
177except ImportError:
178 collect_ignore_glob = ["e2e/*"]