From d2a612a37e730051cacc9d19f6c2365f2273d3bc Mon Sep 17 00:00:00 2001 From: Markus Graf Date: Fri, 23 Oct 2026 08:49:49 +0200 Subject: [PATCH] Add pytest suite, uv project setup and ruff compliance - pyproject.toml: dev deps via uv (pytest, ruff), pytest and ruff config - tests/: 24 tests for extend_pins (helpers + mocked main flow) and glutz_api.load_env; no network access - translate source code to English per AGENT.md - fix ruff findings (unused import, max() simplification, shebang) --- .gitignore | 1 + README.md | 8 ++ extend_pins.py | 135 +++++++++++++++----------- glutz_api.py | 24 ++--- pyproject.toml | 21 ++++ tests/conftest.py | 60 ++++++++++++ tests/test_extend_pins.py | 198 ++++++++++++++++++++++++++++++++++++++ tests/test_glutz_api.py | 31 ++++++ uv.lock | 108 +++++++++++++++++++++ 9 files changed, 519 insertions(+), 67 deletions(-) create mode 100644 pyproject.toml create mode 100644 tests/conftest.py create mode 100644 tests/test_extend_pins.py create mode 100644 tests/test_glutz_api.py create mode 100644 uv.lock diff --git a/.gitignore b/.gitignore index d50a09f..2cadb00 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .env __pycache__/ +.venv/ diff --git a/README.md b/README.md index a3ccb03..b495a27 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,14 @@ den Buchungsbeginn ab. ./extend_pins.py --apply --only-code 123456 # Schreibtest auf einzelnen Code ``` +## Entwicklung + +- Dependencies via **uv**: `uv sync` (nur Dev-Abhängigkeiten: pytest, ruff — + das Script selbst ist reine Stdlib, der systemd-Lauf braucht kein venv) +- Tests: `uv run pytest` +- Lint/Format: `uv run ruff check` / `uv run ruff format` +- Konventionen: siehe `AGENT.md` (Source code Englisch, README Deutsch) + ## Deployment ```bash diff --git a/extend_pins.py b/extend_pins.py index 94a4fab..3dbb083 100755 --- a/extend_pins.py +++ b/extend_pins.py @@ -1,27 +1,29 @@ #!/usr/bin/env python3 -"""Erweitert wyby-Buchungs-PINs auf tageweise Gültigkeit. +"""Extend wyby booking PINs to full-day validity. -Problem: Die wyby-Schnittstelle legt pro Buchung einen Benutzer und PIN an, -gültig nur ±15 min um die Reservierungszeit. Die Mieter mieten aber tageweise -und wollen bereits früher hinein. +Problem: the wyby booking interface creates a user and a PIN per booking, +valid only +/-15 min around the reservation time. But renters book by the +day and want to enter earlier. -Lösung: Alle Benutzer mit wyby-Label-Muster « <6-stellige Transaktion>» -(z.B. «Graf Markus 225313», siehe ../glutz-eaccess-api/wyby-glutz-integration.md) - werden gesucht; deren Codes werden auf ganze Tage erweitert: +Solution: find all users matching the wyby label pattern " <6-digit +transaction>" (e.g. "Graf Markus 225313", see +../glutz-eaccess-api/wyby-glutz-integration.md) and widen their codes to +whole days: - validFrom = Startdatum 00:00:00 - validTo = Enddatum 23:59:59 + validFrom = start date 00:00:00 + validTo = end date 23:59:59 -Start-/Enddatum werden aus dem vorhandenen Code-Fenster abgeleitet: -wyby schreibt Buchungszeit ± WYBY_BUFFER_MIN (Default 15 min) hinein. +Start/end dates are derived from the existing code window, which wyby fills +with booking time +/- WYBY_BUFFER_MIN (default 15 min). -Idempotent: bereits tageweise gültige, persönliche (fensterlose) und -abgelaufene Codes bleiben unangetastet — stündliche Läufe sind gefahrlos. +Idempotent: already full-day codes, personal codes (no window) and expired +codes are skipped - so hourly runs are safe. Until the next run, wyby's own ++/-15 min window covers the start of the booking. -Aufruf: - ./extend_pins.py # Dry-Run (nur lesen, nichts schreiben) - ./extend_pins.py --apply # Änderungen schreiben - ./extend_pins.py --apply --only-code 123456 # Schreibtest auf einen einzigen Code +Usage: + ./extend_pins.py # dry run (read-only) + ./extend_pins.py --apply # write changes + ./extend_pins.py --apply --only-code 123456 # write test on a single code """ from __future__ import annotations @@ -30,17 +32,17 @@ import argparse import os import re import sys -from datetime import date, datetime, time, timedelta +from datetime import datetime, time, timedelta import glutz_api as g -# Wyby-Benutzer: Label « <6 Ziffern der Transaktion>» +# wyby user label: " <6-digit transaction>" LABEL_RE = re.compile(r"^.+\s\d{6}$") END_OF_DAY = time(23, 59, 59) def parse_ts(raw: str | None) -> datetime | None: - """Glutz-Zeitstempel (z.B. «2026-10-24T17:45:00.000») → naive datetime.""" + """Parse a Glutz timestamp (e.g. "2099-02-18T17:45:00.000") into a naive datetime.""" if not raw: return None try: @@ -54,7 +56,7 @@ def fmt_ts(dt: datetime) -> str: def wyby_users(users: list[dict]) -> dict[str, str]: - """{userId: label} aller Benutzer mit wyby-Label-Muster.""" + """{userId: label} of all users matching the wyby label pattern.""" return { str(u["id"]): u["label"] for u in users @@ -62,13 +64,13 @@ def wyby_users(users: list[dict]) -> dict[str, str]: } -def full_day_window(valid_from: datetime, valid_to: datetime, - buffer_min: int) -> tuple[datetime, datetime]: - """Aus dem Code-Fenster (Buchung ± Puffer) die tageweise Gültigkeit bauen.""" +def full_day_window( + valid_from: datetime, valid_to: datetime, buffer_min: int +) -> tuple[datetime, datetime]: + """Turn a code window (booking +/- buffer) into full-day validity.""" start_date = (valid_from + timedelta(minutes=buffer_min)).date() end_date = (valid_to - timedelta(minutes=buffer_min)).date() - if end_date < start_date: # Schutz bei widersprüchlichen Daten - end_date = start_date + end_date = max(end_date, start_date) # guard against contradictory data return ( datetime.combine(start_date, time.min), datetime.combine(end_date, END_OF_DAY), @@ -77,28 +79,49 @@ def full_day_window(valid_from: datetime, valid_to: datetime, def main() -> None: g.load_env() - ap = argparse.ArgumentParser(description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--apply", action="store_true", - help="Änderungen schreiben (ohne: Dry-Run)") - ap.add_argument("--only-code", metavar="XXXXXX", - help="nur diesen Code berücksichtigen (für Schreibtests)") - ap.add_argument("--buffer-min", type=int, - default=int(os.environ.get("WYBY_BUFFER_MIN", "15")), - help="wyby-Puffer um Buchungszeiten (Default: 15)") + ap = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + ap.add_argument( + "--apply", action="store_true", help="write changes (without: dry run)" + ) + ap.add_argument( + "--only-code", + metavar="XXXXXX", + help="only consider this code (for write tests)", + ) + ap.add_argument( + "--buffer-min", + type=int, + default=int(os.environ.get("WYBY_BUFFER_MIN", "15")), + help="wyby buffer around booking times (default: 15)", + ) args = ap.parse_args() users = g.rpc("eAccess.getModel", ["UsersGroups", {}, ["id", "label", "class"]]) if not isinstance(users, list): - sys.exit(f"Unerwartete Antwort bei UsersGroups: {users!r}") + sys.exit(f"Unexpected response for UsersGroups: {users!r}") targets = wyby_users(users) - print(f"wyby-Benutzer erkannt: {len(targets)}") + print(f"wyby users detected: {len(targets)}") - codes = g.rpc("eAccess.getModel", - ["Codes", {}, ["id", "userId", "code", "description", - "actionProfileId", "validFrom", "validTo"]]) + codes = g.rpc( + "eAccess.getModel", + [ + "Codes", + {}, + [ + "id", + "userId", + "code", + "description", + "actionProfileId", + "validFrom", + "validTo", + ], + ], + ) if not isinstance(codes, list): - sys.exit(f"Unerwartete Antwort bei Codes: {codes!r}") + sys.exit(f"Unexpected response for Codes: {codes!r}") if args.only_code: codes = [c for c in codes if str(c.get("code")) == args.only_code] @@ -112,34 +135,36 @@ def main() -> None: vf, vt = parse_ts(c.get("validFrom")), parse_ts(c.get("validTo")) if not vf or not vt: - skipped.append(f"{ctx} — kein Gültigkeitsfenster (persönlicher Code)") + skipped.append(f"{ctx} - no validity window (personal code)") continue new_vf, new_vt = full_day_window(vf, vt, args.buffer_min) if (vf, vt) == (new_vf, new_vt): - skipped.append(f"{ctx} — bereits tageweise gültig") + skipped.append(f"{ctx} - already full-day") continue if new_vt < now: - skipped.append(f"{ctx} — bereits abgelaufen") + skipped.append(f"{ctx} - already expired") continue planned.append((c, new_vf, new_vt)) - print(f"PLAN {ctx}: {fmt_ts(vf)} → {fmt_ts(vt)}" - f" ⇒ {fmt_ts(new_vf)} → {fmt_ts(new_vt)}") + print( + f"PLAN {ctx}: {fmt_ts(vf)} -> {fmt_ts(vt)}" + f" => {fmt_ts(new_vf)} -> {fmt_ts(new_vt)}" + ) for s in skipped: print(f"SKIP {s}") if not planned: - print(f"Keine Änderungen nötig ({len(skipped)} Codes geprüft/übersprungen).") + print(f"No changes needed ({len(skipped)} codes checked/skipped).") return if not args.apply: - print(f"\nDRY-RUN: {len(planned)} Änderung(en) geplant, nichts geschrieben.") + print(f"\nDRY-RUN: {len(planned)} change(s) planned, nothing written.") return print() for c, new_vf, new_vt in planned: - # Bestehende Felder bewahren, nur Gültigkeit ändern. + # Preserve existing fields, only change validity. data = { "userId": str(c["userId"]), "code": str(c["code"]), @@ -150,22 +175,22 @@ def main() -> None: data["description"] = str(c["description"]) data["actionProfileId"] = str(c.get("actionProfileId") or "1") if c.get("id"): - data["id"] = str(c["id"]) # Update statt Duplicate (Modus «id») + data["id"] = str(c["id"]) # update instead of duplicate (mode "id") ctx = f"user={targets[str(c['userId'])]!r} code={c.get('code')}" try: res = g.rpc("eAccess.setModel", ["Codes", data]) - except SystemExit as err: # rpc() meldet Fehler per sys.exit + except SystemExit as err: # rpc() reports errors via sys.exit failed.append(ctx) - print(f"FEHLER {ctx}: {err}") + print(f"ERROR {ctx}: {err}") continue if res.get("id"): - print(f"OK {ctx}: → {fmt_ts(new_vf)} … {fmt_ts(new_vt)}") + print(f"OK {ctx}: -> {fmt_ts(new_vf)} ... {fmt_ts(new_vt)}") else: failed.append(ctx) - print(f"UNKLAR {ctx}: Antwort ohne id: {res!r}") + print(f"UNCLEAR {ctx}: response without id: {res!r}") - print(f"\n{len(planned) - len(failed)}/{len(planned)} geändert.") + print(f"\n{len(planned) - len(failed)}/{len(planned)} changed.") if failed: sys.exit(1) diff --git a/glutz_api.py b/glutz_api.py index 1ae3067..192e0b6 100644 --- a/glutz_api.py +++ b/glutz_api.py @@ -1,13 +1,12 @@ -#!/usr/bin/env python3 -"""Glutz eAccess Cloud — minimaler JSON-RPC-Client (nur Stdlib). +"""Glutz eAccess Cloud — minimal JSON-RPC client (stdlib only). -Übernommen aus ../glutz-eaccess-api/glutz_api.py (auf Client-Funktionen -reduziert), damit dieses Deployment selbst-contained ist. +Taken from ../glutz-eaccess-api/glutz_api.py (reduced to the client +functions) so that this deployment is self-contained. - * Endpunkt: https://.eaccess.glutz.com/rpc - * Auth: HTTP Basic (GLUTZ_USER / GLUTZ_PASS aus .env) - * Lesen: eAccess.getModel params=[Collection, Filter, Fields] - * Schreiben: eAccess.setModel params=[Collection, DataObject] + * Endpoint: https://.eaccess.glutz.com/rpc + * Auth: HTTP Basic (GLUTZ_USER / GLUTZ_PASS from .env) + * Read: eAccess.getModel params=[Collection, Filter, Fields] + * Write: eAccess.setModel params=[Collection, DataObject] """ from __future__ import annotations @@ -24,7 +23,8 @@ RPC_ID = 4711 def load_env(path: Path | None = None) -> None: - """Lädt KEY=VALUE aus .env (neben diesem Script), ohne bestehende ENV zu überschreiben.""" + """Load KEY=VALUE pairs from .env (next to this script); never overrides + variables already present in the environment.""" env_file = path or Path(__file__).resolve().parent / ".env" if not env_file.is_file(): return @@ -39,7 +39,7 @@ def load_env(path: Path | None = None) -> None: def rpc(method: str, params: list) -> dict: - """Einzelner JSON-RPC-Aufruf; bei Fehler sys.exit mit Meldung.""" + """Single JSON-RPC call; exits with an error message on failure.""" host = os.environ["GLUTZ_HOST"].rstrip("/") user = os.environ["GLUTZ_USER"] password = os.environ["GLUTZ_PASS"] @@ -62,7 +62,7 @@ def rpc(method: str, params: list) -> dict: except urllib.error.HTTPError as err: sys.exit(f"HTTP {err.code}: {err.read().decode(errors='replace')[:400]}") except urllib.error.URLError as err: - sys.exit(f"Netzwerkfehler bei {method}: {err}") + sys.exit(f"Network error during {method}: {err}") if "error" in data: - sys.exit(f"RPC-Fehler bei {method}: {json.dumps(data['error'])}") + sys.exit(f"RPC error during {method}: {json.dumps(data['error'])}") return data.get("result", {}) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..b420943 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,21 @@ +[project] +name = "glutz-maintenances" +version = "0.1.0" +description = "Extend wyby booking PINs on a Glutz eAccess system to full-day validity" +readme = "README.md" +requires-python = ">=3.12" +dependencies = [] + +[dependency-groups] +dev = [ + "pytest>=8.0", + "ruff>=0.8", +] + +[tool.ruff] +line-length = 88 +target-version = "py312" + +[tool.pytest.ini_options] +testpaths = ["tests"] +pythonpath = ["."] diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..f66a356 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,60 @@ +"""Shared fixtures: canned Glutz API data and a fake rpc().""" + +import sys + +import pytest + +import glutz_api +from extend_pins import main + +USERS = [ + {"id": 50, "label": "Graf Markus 225313", "class": 1}, # wyby booking user + {"id": 42, "label": "Markus", "class": 1}, # manual user -> excluded + {"id": 33, "label": "Forum", "class": 1}, # manual user -> excluded + {"id": 12, "label": "Gr. Gemeinschaftsraum Hueb. 8a", "class": 2}, # group +] + +FUTURE_FROM = "2099-02-18T17:45:00.000" +FUTURE_TO = "2099-02-20T22:15:00.000" + + +def code_row(**overrides): + """A wyby code row: booking Fri 18:00 - Sun 22:00 with +/-15 min window.""" + row = { + "id": 77, + "userId": 50, + "code": "225313", + "description": "reservation", + "actionProfileId": "2", + "validFrom": FUTURE_FROM, + "validTo": FUTURE_TO, + } + row.update(overrides) + return row + + +@pytest.fixture +def install_rpc(monkeypatch): + """Install a fake glutz_api.rpc; returns (calls, set_calls) lists.""" + calls = [] + + def _install(users=USERS, codes=None, write_result=None, write_error=None): + codes = [] if codes is None else codes + + def fake_rpc(method, params): + calls.append((method, params)) + if method == "eAccess.getModel": + return {"UsersGroups": users, "Codes": codes}[params[0]] + if write_error is not None: + raise SystemExit(write_error) + return {"id": "99"} if write_result is None else write_result + + monkeypatch.setattr(glutz_api, "rpc", fake_rpc) + return calls + + return _install + + +def run_main(monkeypatch, *argv): + monkeypatch.setattr(sys, "argv", ["extend_pins.py", *argv]) + main() diff --git a/tests/test_extend_pins.py b/tests/test_extend_pins.py new file mode 100644 index 0000000..da02fa3 --- /dev/null +++ b/tests/test_extend_pins.py @@ -0,0 +1,198 @@ +"""Unit tests for extend_pins.py (helpers and main() flow, rpc mocked).""" + +from datetime import datetime + +import pytest +from conftest import USERS, code_row, run_main + +import glutz_api +from extend_pins import fmt_ts, full_day_window, parse_ts, wyby_users + + +@pytest.fixture(autouse=True) +def no_env(monkeypatch): + """Never touch the real .env / environment from tests.""" + monkeypatch.setattr(glutz_api, "load_env", lambda *a, **k: None) + + +# --- helpers --------------------------------------------------------------- + + +class TestWybyUsers: + def test_detects_label_ending_in_six_digits(self): + assert wyby_users(USERS) == {str(u["id"]): u["label"] for u in USERS[:1]} + + def test_ignores_single_digit_labels_and_groups(self): + users = [ + {"id": 1, "label": "Hueb 8a - Gast 1", "class": 1}, + {"id": 2, "label": "Unused Media", "class": 3}, + {"id": 3, "label": None, "class": 1}, + ] + assert wyby_users(users) == {} + + +class TestParseTs: + def test_parses_milliseconds(self): + assert parse_ts("2026-10-24T17:45:00.000") == datetime(2026, 10, 24, 17, 45) + + @pytest.mark.parametrize("raw", [None, "", "not-a-date"]) + def test_returns_none_for_missing_or_invalid(self, raw): + assert parse_ts(raw) is None + + def test_fmt_ts_roundtrip(self): + dt = datetime(2099, 2, 18, 0, 0, 0) + assert parse_ts(fmt_ts(dt)) == dt + + +class TestFullDayWindow: + def test_single_day_booking(self): + vf, vt = ( + parse_ts("2099-02-18T17:45:00.000"), + parse_ts("2099-02-18T22:15:00.000"), + ) + assert full_day_window(vf, vt, 15) == ( + datetime(2099, 2, 18, 0, 0), + datetime(2099, 2, 18, 23, 59, 59), + ) + + def test_multi_day_booking(self): + vf, vt = ( + parse_ts("2099-02-18T17:45:00.000"), + parse_ts("2099-02-20T22:15:00.000"), + ) + assert full_day_window(vf, vt, 15) == ( + datetime(2099, 2, 18, 0, 0), + datetime(2099, 2, 20, 23, 59, 59), + ) + + def test_start_at_midnight_buffer_crosses_back(self): + # Booking starts 00:00 -> wyby window reaches to previous day 23:45. + vf, vt = ( + parse_ts("2099-02-17T23:45:00.000"), + parse_ts("2099-02-18T20:15:00.000"), + ) + start, _ = full_day_window(vf, vt, 15) + assert start == datetime(2099, 2, 18, 0, 0) + + def test_end_shortly_after_midnight_buffer_crosses_forward(self): + # Booking ends 23:50 -> wyby window reaches into next day 00:05. + vf, vt = ( + parse_ts("2099-02-18T16:45:00.000"), + parse_ts("2099-02-19T00:05:00.000"), + ) + _, end = full_day_window(vf, vt, 15) + assert end == datetime(2099, 2, 18, 23, 59, 59) + + def test_end_before_start_is_clamped(self): + vf, vt = parse_ts("2099-02-18T10:00:00"), parse_ts("2099-02-18T10:01:00") + start, end = full_day_window(vf, vt, 15) + assert (start, end) == ( + datetime(2099, 2, 18, 0, 0), + datetime(2099, 2, 18, 23, 59, 59), + ) + + def test_zero_buffer_falls_back_to_plain_dates(self): + vf, vt = parse_ts("2099-02-18T00:00:00"), parse_ts("2099-02-19T23:59:59") + assert full_day_window(vf, vt, 0) == ( + datetime(2099, 2, 18, 0, 0), + datetime(2099, 2, 19, 23, 59, 59), + ) + + +# --- main() flow ----------------------------------------------------------- + + +class TestMainDryRun: + def test_plans_but_writes_nothing(self, install_rpc, monkeypatch, capsys): + calls = install_rpc(codes=[code_row()]) + run_main(monkeypatch) + + out = capsys.readouterr().out + assert not any(m == "eAccess.setModel" for m, _ in calls) + assert "DRY-RUN" in out + assert "PLAN" in out + assert "2099-02-18T00:00:00" in out + assert "2099-02-20T23:59:59" in out + + def test_no_wyby_users_nothing_to_do(self, install_rpc, monkeypatch, capsys): + install_rpc(codes=[code_row(userId=42)]) + run_main(monkeypatch) + + out = capsys.readouterr().out + assert "No changes needed" in out + assert "PLAN" not in out + + +class TestMainApply: + def test_writes_update_with_preserved_fields( + self, install_rpc, monkeypatch, capsys + ): + calls = install_rpc(codes=[code_row()]) + run_main(monkeypatch, "--apply") + + writes = [p for m, p in calls if m == "eAccess.setModel"] + assert len(writes) == 1 + collection, data = writes[0] + assert collection == "Codes" + assert data == { + "id": "77", + "userId": "50", + "code": "225313", + "description": "reservation", + "actionProfileId": "2", + "validFrom": "2099-02-18T00:00:00", + "validTo": "2099-02-20T23:59:59", + } + assert "1/1 changed" in capsys.readouterr().out + + def test_action_profile_defaults_to_1_when_missing(self, install_rpc, monkeypatch): + calls = install_rpc(codes=[code_row(actionProfileId=None)]) + run_main(monkeypatch, "--apply") + + _, data = next(p for m, p in calls if m == "eAccess.setModel") + assert data["actionProfileId"] == "1" + + def test_skip_reasons(self, install_rpc, monkeypatch, capsys): + codes = [ + code_row(id=1), # planned + code_row(id=2, userId=50, code="111111", validFrom=None, validTo=None), + code_row( + id=3, + validFrom="2099-03-01T00:00:00.000", + validTo="2099-03-01T23:59:59.000", + ), + code_row( + id=4, validFrom="2020-01-01T17:45:00", validTo="2020-01-01T22:15:00" + ), + ] + calls = install_rpc(codes=codes) + run_main(monkeypatch, "--apply") + + out = capsys.readouterr().out + writes = [p for m, p in calls if m == "eAccess.setModel"] + assert len(writes) == 1 + assert writes[0][1]["id"] == "1" + assert "no validity window" in out + assert "already full-day" in out + assert "already expired" in out + + def test_only_code_filter(self, install_rpc, monkeypatch, capsys): + codes = [code_row(id=1, code="225313"), code_row(id=2, code="999999")] + calls = install_rpc(codes=codes) + run_main(monkeypatch, "--apply", "--only-code", "999999") + + writes = [p for m, p in calls if m == "eAccess.setModel"] + assert len(writes) == 1 + assert writes[0][1]["code"] == "999999" + + def test_write_result_without_id_counts_as_failure(self, install_rpc, monkeypatch): + install_rpc(codes=[code_row()], write_result={}) + with pytest.raises(SystemExit) as excinfo: + run_main(monkeypatch, "--apply") + assert excinfo.value.code == 1 + + def test_rpc_error_during_write_exits_nonzero(self, install_rpc, monkeypatch): + install_rpc(codes=[code_row()], write_error="HTTP 500: boom") + with pytest.raises(SystemExit) as excinfo: + run_main(monkeypatch, "--apply") + assert excinfo.value.code == 1 diff --git a/tests/test_glutz_api.py b/tests/test_glutz_api.py new file mode 100644 index 0000000..f49c111 --- /dev/null +++ b/tests/test_glutz_api.py @@ -0,0 +1,31 @@ +"""Tests for glutz_api.load_env (rpc() itself needs a live system).""" + +import os + +import glutz_api + + +def test_load_env_reads_keys(tmp_path, monkeypatch): + monkeypatch.delenv("GLUTZ_TEST_KEY", raising=False) + monkeypatch.delenv("GLUTZ_TEST_QUOTED", raising=False) + env = tmp_path / ".env" + env.write_text('# comment\n\nGLUTZ_TEST_KEY=plain\nGLUTZ_TEST_QUOTED="in quotes"\n') + + glutz_api.load_env(env) + + assert os.environ["GLUTZ_TEST_KEY"] == "plain" + assert os.environ["GLUTZ_TEST_QUOTED"] == "in quotes" + + +def test_load_env_does_not_override_existing(tmp_path, monkeypatch): + monkeypatch.setenv("GLUTZ_TEST_KEY", "from-env") + env = tmp_path / ".env" + env.write_text("GLUTZ_TEST_KEY=from-file\n") + + glutz_api.load_env(env) + + assert os.environ["GLUTZ_TEST_KEY"] == "from-env" + + +def test_load_env_missing_file_is_a_noop(tmp_path): + glutz_api.load_env(tmp_path / "does-not-exist") # must not raise diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000..fb62e8d --- /dev/null +++ b/uv.lock @@ -0,0 +1,108 @@ +version = 1 +revision = 3 +requires-python = ">=3.12" + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "glutz-maintenances" +version = "0.1.0" +source = { virtual = "." } + +[package.dev-dependencies] +dev = [ + { name = "pytest" }, + { name = "ruff" }, +] + +[package.metadata] + +[package.metadata.requires-dev] +dev = [ + { name = "pytest", specifier = ">=8.0" }, + { name = "ruff", specifier = ">=0.8" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pluggy" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, +] + +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "ruff" +version = "0.17.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ae/58/690cf56da80c8f2c8bf12042b6017beac2c34fe961f65420bcb3fb7fac38/ruff-0.17.2.tar.gz", hash = "sha256:84d632402d14c23b488f941db23712d6736a013225162062d34558c3f3c780eb", size = 5333400, upload-time = "2026-10-22T18:38:00.181Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/b8/8b6d69c57e8fe1cc6af1aa7493b72a1a5b5a8afe34694e302025441729d4/ruff-0.17.2-py3-none-linux_armv6l.whl", hash = "sha256:96a65e755d8dba094707fb23ab602111d9a31ec2835b3a6992a1914a8fcb211e", size = 10183857, upload-time = "2026-10-22T18:37:14.956Z" }, + { url = "https://files.pythonhosted.org/packages/e8/61/12cc2ff7b2fa90a268ce1e2162c23aaf76e601d22623f6a31b0eeaa764b0/ruff-0.17.2-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:39c5b55c960515cdb32be16e69efb5734c589c06a0eb38a22694524a336b889d", size = 10210904, upload-time = "2026-10-22T18:37:17.985Z" }, + { url = "https://files.pythonhosted.org/packages/e8/7c/b8850a8e4ad29f64a827dd6c6902db4a9aa538fb2b9eef4e26084001a3bb/ruff-0.17.2-py3-none-macosx_11_0_arm64.whl", hash = "sha256:92a80d2f44584dabb0189b3a6c393e37e525e04942838482010575cb81945be7", size = 9408439, upload-time = "2026-10-22T18:37:20.964Z" }, + { url = "https://files.pythonhosted.org/packages/b7/b6/6a64fae86ca5e5e29d5adc311e5481de726cedf9aee607435a16c31c442a/ruff-0.17.2-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b7d0906677d89bbf3cf73cde64b5bbe2ab35df3ae43e49ee2627301e91265bac", size = 10047078, upload-time = "2026-10-22T18:37:23.717Z" }, + { url = "https://files.pythonhosted.org/packages/10/19/23d376547715175aa1bd46df48df6aacc7c6439d9daf19cac15975180aa5/ruff-0.17.2-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7cfd783590edf2b77317882631900f6a13ea2e8eacefe6ebf2370d2715299160", size = 9990478, upload-time = "2026-10-22T18:37:26.584Z" }, + { url = "https://files.pythonhosted.org/packages/93/6c/34cda32cbe13adac5c6b291a307a5570d8ebd37c0c86339f0fe628e55632/ruff-0.17.2-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:122258f6ecde0e0dd1bb60b24263c3edde4338caf723fca711cc729f9bfd414a", size = 10673624, upload-time = "2026-10-22T18:37:29.767Z" }, + { url = "https://files.pythonhosted.org/packages/bf/10/5d762a4dbc851d8bb47863cf3a28a61bf31c804d393b70d891fac899f5d1/ruff-0.17.2-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7f8fba429d6ac4128ab29cfb8fa6240d2fa671d04adf7f84d3b22fc7b6b6bea4", size = 11351797, upload-time = "2026-10-22T18:37:32.535Z" }, + { url = "https://files.pythonhosted.org/packages/3f/04/a0e92a81faf5c81c1c98d4374c8401734ccf2b8cca7d0170cb0fec08c6e2/ruff-0.17.2-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:583bd67bb9e7061dd09bc46a0a884bae2bbd214dbcd48e509813612619683869", size = 10949414, upload-time = "2026-10-22T18:37:35.501Z" }, + { url = "https://files.pythonhosted.org/packages/c3/d8/59894cf630d2d86882457a2a6a0a1533410c5c805bfbac6f6eb4b5aef69d/ruff-0.17.2-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c60f93fec7142dba5b8f487f94bf2f6231dae24dc11e4c48648347c8b0720004", size = 10528000, upload-time = "2026-10-22T18:37:37.88Z" }, + { url = "https://files.pythonhosted.org/packages/ab/95/d6e30c51e851d37e10762ad91fa1e76ddaad998589b5667962a3cfbc9edd/ruff-0.17.2-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:c555a877f8f41447e318101cfefea9bf12dfa9f82eedf90c376e57e069f917d0", size = 10571779, upload-time = "2026-10-22T18:37:40.444Z" }, + { url = "https://files.pythonhosted.org/packages/f4/5a/a7e1d74fb464250137d3d4eca645d323536533b672004d04ee0e46e0caf3/ruff-0.17.2-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:ba405cbd5ec7bda1f555d5e52be1fd68d02608d4d95d24591bdac92cfacb579f", size = 10051707, upload-time = "2026-10-22T18:37:42.812Z" }, + { url = "https://files.pythonhosted.org/packages/6e/f2/02fca29ca7999380f0350a7212fe755c11ab9c22d61327356cce8decdbc6/ruff-0.17.2-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:8c21b4ab24485358f17291a4f8dc5399b834e963b8efedd920fe4fdb02081bb4", size = 9998227, upload-time = "2026-10-22T18:37:45.224Z" }, + { url = "https://files.pythonhosted.org/packages/d1/00/55aa604a093dfdc1526e570fae0bb7d37a2221c7b4728d5f080b2add16ba/ruff-0.17.2-py3-none-musllinux_1_2_i686.whl", hash = "sha256:5875a16b0de70b43cb81eabea5ae5e8f5d1b2fd1b5e6ed07f80cfe5019d0bd5a", size = 10377692, upload-time = "2026-10-22T18:37:47.704Z" }, + { url = "https://files.pythonhosted.org/packages/e4/5a/a7a640f47bb906ec8fa233ea84319d503e6dee02b59e3901bd312ebd1f9b/ruff-0.17.2-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:2d086be452eed686aa51271ecf2cbe5037956517cc6ee39a17b4489ac12f8bbe", size = 10790587, upload-time = "2026-10-22T18:37:50.191Z" }, + { url = "https://files.pythonhosted.org/packages/2c/d4/c3b74e1b4808438ea7f14bb914478025e2d51261f60774a54a0fa222ec46/ruff-0.17.2-py3-none-win32.whl", hash = "sha256:6bce7d1f5165701ae18f5df85c65afe78cddfa6c5fb4b9bdb0014d60388f3edd", size = 9870537, upload-time = "2026-10-22T18:37:52.486Z" }, + { url = "https://files.pythonhosted.org/packages/1c/9a/c7da96c2c96d20704cf9027f7a5121da272a8c05f1d1531ba949e3b3df04/ruff-0.17.2-py3-none-win_amd64.whl", hash = "sha256:1b59d447f197bef9ef48a22ba1a6016137753c6099e9bac9c36eb566e422424c", size = 10282826, upload-time = "2026-10-22T18:37:55.2Z" }, + { url = "https://files.pythonhosted.org/packages/81/60/a3604c79cb02777b6cb84da894104021986f06c4bc41375102cc95049a32/ruff-0.17.2-py3-none-win_arm64.whl", hash = "sha256:195ad918027f817c119310ca89a42d347887dfc28934aaa869325e9c5dc9d962", size = 9827036, upload-time = "2026-10-22T18:37:58.031Z" }, +]