|
| 1 | +import importlib |
| 2 | +import json |
| 3 | + |
| 4 | + |
| 5 | +def test_store_read_corrupt_and_missing(tmp_path, monkeypatch): |
| 6 | + monkeypatch.chdir(tmp_path) |
| 7 | + # Corrupt metrics file -> get_all returns {} |
| 8 | + mdir = tmp_path / "data/metrics" |
| 9 | + mdir.mkdir(parents=True) |
| 10 | + (mdir / "metrics.json").write_text("not-json", encoding="utf-8") |
| 11 | + import src.metrics.store as store |
| 12 | + importlib.reload(store) |
| 13 | + assert store.get_all() == {} |
| 14 | + # Decisions missing file -> tail returns [] |
| 15 | + import src.metrics.decisions as dec |
| 16 | + importlib.reload(dec) |
| 17 | + assert dec.tail(5) == [] |
| 18 | + |
| 19 | + |
| 20 | +def test_loader_skips_on_exception(tmp_path, monkeypatch): |
| 21 | + monkeypatch.chdir(tmp_path) |
| 22 | + bad = [ |
| 23 | + {"id": "ok", "target": "table", "selector": "dbo.T", "action": "allow"}, |
| 24 | + {"id": "oops", "target": "table", "selector": "dbo.X", "action": "block", "unknown": 1}, |
| 25 | + ] |
| 26 | + (tmp_path / "config").mkdir(parents=True) |
| 27 | + (tmp_path / "config/rules.json").write_text(json.dumps(bad), encoding="utf-8") |
| 28 | + from src.policy.loader import load_rules |
| 29 | + out = load_rules(str(tmp_path / "config/rules.json")) |
| 30 | + ids = [r.id for r in out] |
| 31 | + assert ids == ["ok"] |
| 32 | + |
| 33 | + |
| 34 | +def test_api_metrics_html_no_decs(tmp_path, monkeypatch): |
| 35 | + monkeypatch.chdir(tmp_path) |
| 36 | + # Prepare metrics only |
| 37 | + mdir = tmp_path / "data/metrics" |
| 38 | + mdir.mkdir(parents=True) |
| 39 | + (mdir / "metrics.json").write_text(json.dumps({"allowed": 1}), encoding="utf-8") |
| 40 | + api = importlib.import_module("src.api") |
| 41 | + importlib.reload(api) |
| 42 | + html = api.metrics_html(limit=3) |
| 43 | + assert "Metrics" in html and "Recent Decisions" in html |
| 44 | + |
| 45 | + |
| 46 | +def test_dryrun_json_empty(tmp_path, monkeypatch): |
| 47 | + monkeypatch.chdir(tmp_path) |
| 48 | + api = importlib.import_module("src.api") |
| 49 | + importlib.reload(api) |
| 50 | + out = api.dryrun_json() |
| 51 | + assert isinstance(out, dict) and isinstance(out.get("rules"), dict) and len(out.get("rules")) == 0 |
| 52 | + |
| 53 | + |
| 54 | +def test_rules_list_add_cycle(tmp_path, monkeypatch): |
| 55 | + monkeypatch.setenv("RULES_PATH", str(tmp_path / "rules.json")) |
| 56 | + api = importlib.import_module("src.api") |
| 57 | + importlib.reload(api) |
| 58 | + assert api.list_rules() == [] |
| 59 | + r = api.Rule(id="a1", target="table", selector="dbo.T", action="allow") |
| 60 | + api.add_rule(r) |
| 61 | + assert any(x.id == "a1" for x in api.list_rules()) |
| 62 | + |
0 commit comments