File size: 2,389 Bytes
aad7814
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""Filesystem path safety for section IDs vs human labels."""

from __future__ import annotations

import pytest

from backend.core.rics_canonical_l3 import build_canonical_template_schema
from backend.core.section_mapper import section_debug_filename
from backend.core import template_discoverer
from backend.utils import tenant_store


def test_path_safe_label_replaces_slashes():
    assert tenant_store.path_safe_label("Gas/Oil") == "Gas_Oil"
    assert tenant_store.path_safe_label("service and terms of engagement") == (
        "service_and_terms_of_engagement"
    )


def test_path_safe_section_id_accepts_canonical_codes():
    assert tenant_store.path_safe_section_id("f2") == "F2"
    assert tenant_store.path_safe_section_id("M") == "M"
    assert tenant_store.path_safe_section_id("D1") == "D1"
    assert tenant_store.path_safe_section_id("UNASSIGNED") == "UNASSIGNED"


def test_path_safe_section_id_rejects_label_with_slash():
    with pytest.raises(ValueError, match="label"):
        tenant_store.path_safe_section_id("Gas/Oil")


def test_photo_section_dir_uses_id_not_label(tmp_path, monkeypatch):
    from backend.config import settings

    data_root = tmp_path / "data"
    monkeypatch.setattr(settings, "data_dir", str(data_root))
    d = tenant_store.photo_section_dir("tenant1", "draft-a", "F2")
    assert d == data_root / "tenants" / "tenant1" / "photo_drafts" / "draft-a" / "F2"
    assert d.is_dir()


def test_section_debug_filename_uses_id_only():
    assert section_debug_filename("F2") == "section_F2.txt"
    assert section_debug_filename("M", ext="json") == "section_M.json"
    with pytest.raises(ValueError):
        section_debug_filename("Gas/Oil")


def test_schema_save_path_is_tenant_scoped_only(tmp_path, monkeypatch):
    from backend.config import settings

    data_root = tmp_path / "data"
    monkeypatch.setattr(settings, "data_dir", str(data_root))
    schema = build_canonical_template_schema(source_filename="canonical.pdf")
    f2 = next(s for s in schema.sections if s.id == "F2")
    assert f2.title == "Gas and Oil"
    assert "/" not in f2.title

    template_discoverer.save_schema("demo", schema)
    schema_file = data_root / "tenants" / "demo" / "schema.json"
    assert schema_file.is_file()
    assert not (data_root / "tenants" / "demo" / "Gas").exists()
    assert "Gas and Oil" in schema_file.read_text(encoding="utf-8")