Menixis Claude Fable 5 commited on
Commit
f50726e
·
1 Parent(s): 21d12df

test: pytest suite for the pure layers (data_source, ai_clean, form_logic, letter_builder) — 32 tests, no network, AI_BACKEND=off

Browse files

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NQMBLPhJZUBCX7io3uwEnR

tests/conftest.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import sys
4
+
5
+ # Repo root on sys.path so the app modules import directly.
6
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
7
+
8
+ # Deterministic AI backend — tests never hit the network.
9
+ os.environ["AI_BACKEND"] = "off"
tests/test_ai_clean.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """ai_clean — deterministic paths only (AI_BACKEND=off via conftest)."""
3
+ from datetime import date
4
+
5
+ import ai_clean
6
+
7
+ TOR_CLAUSE = ("7. การส่งมอบงาน\n"
8
+ "ผู้รับจ้างต้องส่งมอบงานภายใน 90 (เก้าสิบ) วัน นับถัดจากวันที่ได้รับหนังสือ"
9
+ "แจ้งให้เริ่มปฏิบัติงาน โดยไม่นับรวมวันหยุดราชการ ทั้งนี้ ผู้รับจ้างต้องแจ้งล่วงหน้า")
10
+
11
+ FIELDS = {
12
+ "procurement_type": "งานจ้างบริการ",
13
+ "work": "งานจ้างเหมาบำรุงรักษาระบบท่อ",
14
+ "vendor": "บริษัท ทดสอบ จำกัด",
15
+ "unit": "ส่วนบำรุงรักษาระบบท่อ",
16
+ "start_date": "20 กรกฎาคม 2569",
17
+ "days": 90,
18
+ "delivery_clause": TOR_CLAUSE,
19
+ }
20
+
21
+
22
+ # --- parse_nguad -------------------------------------------------------------
23
+ def test_parse_nguad_empty_is_single():
24
+ assert ai_clean.parse_nguad("") == [{"label": "งวดเดียว", "number": None}]
25
+ assert ai_clean.parse_nguad(None) == [{"label": "งวดเดียว", "number": None}]
26
+
27
+
28
+ def test_parse_nguad_multi_dedup_sorted():
29
+ clause = "งวดที่ 2 ส่งรายงาน ... งวดที่ 1 ส่งแผน ... งวดที่ 2 (ซ้ำ)"
30
+ assert ai_clean.parse_nguad(clause) == [
31
+ {"label": "งวดที่ 1", "number": 1},
32
+ {"label": "งวดที่ 2", "number": 2},
33
+ ]
34
+
35
+
36
+ def test_parse_nguad_unstructured_is_single():
37
+ assert ai_clean.parse_nguad("ส่งมอบภายใน 30 วัน") == \
38
+ [{"label": "งวดเดียว", "number": None}]
39
+
40
+
41
+ # --- _duration_from_tor ------------------------------------------------------
42
+ def test_duration_lifted_from_tor():
43
+ out = ai_clean._duration_from_tor(TOR_CLAUSE, None)
44
+ assert out.startswith("โดยกำหนดให้แล้วเสร็จภายใน 90 (เก้าสิบ) วัน")
45
+ assert "วันหยุดราชการ" in out
46
+ assert "ทั้งนี้" not in out # stops before the ทั้งนี้ tail
47
+
48
+
49
+ def test_duration_sla_fallback():
50
+ out = ai_clean._duration_from_tor("ส่งมอบ ณ คลังผู้ว่าจ้าง", "30")
51
+ assert out == ("โดยกำหนดให้แล้วเสร็จภายใน 30 วัน "
52
+ "นับถัดจาก วันที่ ปตท. มีหนังสือแจ้งให้ปฏิบัติงาน")
53
+
54
+
55
+ def test_duration_empty_when_no_source():
56
+ assert ai_clean._duration_from_tor("", "") == ""
57
+
58
+
59
+ # --- compose_body / generate_body -------------------------------------------
60
+ def test_compose_body_format():
61
+ body = ai_clean.compose_body(FIELDS)
62
+ paras = body.split("\n\n")
63
+ assert len(paras) == 2
64
+ assert paras[0].startswith("ตามที่ ส่วนบำรุงรักษาระบบท่อ บริษัท ปตท. จำกัด (มหาชน)")
65
+ assert "จัดจ้าง" in paras[0] # งานจ้าง → จัดจ้าง
66
+ assert "จึงขอแจ้งให้" in paras[1]
67
+ assert paras[1].endswith("นับถัดจากวันที่ 20 กรกฎาคม 2569 เป็นต้นไป")
68
+
69
+
70
+ def test_compose_body_buy_verb():
71
+ body = ai_clean.compose_body({**FIELDS, "procurement_type": "งานซื้อ"})
72
+ assert "จัดซื้อ" in body and "จัดจ้าง" not in body
73
+
74
+
75
+ def test_generate_body_off_backend_is_deterministic():
76
+ text, used_ai = ai_clean.generate_body(FIELDS)
77
+ assert used_ai is False
78
+ assert text == ai_clean.compose_body(FIELDS)
79
+
80
+
81
+ def test_clean_delivery_off_backend_uses_raw_fallback():
82
+ text, used_ai = ai_clean.clean_delivery(TOR_CLAUSE)
83
+ assert used_ai is False
84
+ assert text == ai_clean._raw_fallback(TOR_CLAUSE)
85
+ assert ai_clean.clean_delivery("") == ("", False)
86
+
87
+
88
+ # --- thai_date / _raw_fallback ----------------------------------------------
89
+ def test_thai_date():
90
+ assert ai_clean.thai_date(date(2026, 2, 27)) == "27 กุมภาพันธ์ 2569"
91
+ assert ai_clean.thai_date(None) == ""
92
+
93
+
94
+ def test_raw_fallback_drops_heading_and_filters_nguad():
95
+ clause = ("การส่งมอบงาน\n"
96
+ "แบ่งการส่งมอบเป็น 2 งวด\n"
97
+ "งวดที่ 1 ส่งแผนงานภายใน 15 วัน\n"
98
+ "งวดที่ 2 ส่งรายงานฉบับสมบูรณ์ภายใน 90 วัน")
99
+ out = ai_clean._raw_fallback(clause, "งวดที่ 2")
100
+ assert "การส่งมอบงาน" not in out.split()[0:1] # heading line dropped
101
+ assert "งวดที่ 2" in out
102
+ assert "งวดที่ 1" not in out
103
+ assert "แบ่งการส่งมอบเป็น 2 งวด" in out # lead-in kept
tests/test_data_source.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """data_source — repository layer, tested against the tracked sample workbook."""
3
+ import os
4
+ from io import BytesIO
5
+
6
+ import openpyxl
7
+ import pytest
8
+
9
+ import data_source
10
+
11
+ SAMPLE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
12
+ "sample_po_data.xlsx")
13
+ SAMPLE_PO = "4500987654"
14
+
15
+
16
+ @pytest.fixture(scope="module")
17
+ def sample_bytes():
18
+ with open(SAMPLE, "rb") as f:
19
+ return f.read()
20
+
21
+
22
+ def test_strip_col_wrapper_powerbi_header():
23
+ assert data_source._strip_col_wrapper("Data for Auto Form[poNo]") == "poNo"
24
+
25
+
26
+ def test_strip_col_wrapper_plain_and_none():
27
+ assert data_source._strip_col_wrapper("poNo") == "poNo"
28
+ assert data_source._strip_col_wrapper(" title ") == "title"
29
+ assert data_source._strip_col_wrapper(None) is None
30
+
31
+
32
+ def test_lookup_found(sample_bytes):
33
+ result, cols = data_source.lookup_po_in_bytes(SAMPLE_PO, sample_bytes)
34
+ assert isinstance(result, dict) and "__error__" not in result
35
+ assert str(result["poNo"]).startswith(SAMPLE_PO)
36
+ assert result.get("VendorName")
37
+ assert result.get("title")
38
+ assert "poNo" in cols
39
+
40
+
41
+ def test_lookup_not_found(sample_bytes):
42
+ result, cols = data_source.lookup_po_in_bytes("0000000000", sample_bytes)
43
+ assert result is None
44
+ assert "poNo" in cols
45
+
46
+
47
+ def test_lookup_missing_column(sample_bytes):
48
+ result, cols = data_source.lookup_po_in_bytes(SAMPLE_PO, sample_bytes,
49
+ po_column="no_such_column")
50
+ assert isinstance(result, dict) and "__error__" in result
51
+ assert cols == []
52
+
53
+
54
+ def _tiny_workbook(po_cell_value):
55
+ wb = openpyxl.Workbook()
56
+ ws = wb.active
57
+ ws.append(["Data for Auto Form[poNo]", "Data for Auto Form[title]"])
58
+ ws.append([po_cell_value, "งานทดสอบ"])
59
+ buf = BytesIO()
60
+ wb.save(buf)
61
+ return buf.getvalue()
62
+
63
+
64
+ def test_lookup_float_po_cell_matches():
65
+ """Power BI exports sometimes ship the PO number as a float (4500987654.0)."""
66
+ result, _ = data_source.lookup_po_in_bytes("4500987654",
67
+ _tiny_workbook(4500987654.0))
68
+ assert result and result["title"] == "งานทดสอบ"
69
+
70
+
71
+ def test_lookup_date_serial_converted():
72
+ """An Excel serial in a DATE_COLUMNS column comes back as 'YYYY-MM-DD'."""
73
+ wb = openpyxl.Workbook()
74
+ ws = wb.active
75
+ ws.append(["poNo", "poCreateDate"])
76
+ ws.append(["4500987654", 45658]) # 2025-01-01 as an Excel serial
77
+ buf = BytesIO()
78
+ wb.save(buf)
79
+ result, _ = data_source.lookup_po_in_bytes("4500987654", buf.getvalue())
80
+ assert result["poCreateDate"] == "2025-01-01"
81
+
82
+
83
+ def test_check_data_fail_without_url():
84
+ ok, detail = data_source.check_data("")
85
+ assert ok is False
86
+ assert detail # carries the error message
tests/test_form_logic.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """form_logic — pure docx/text helpers."""
3
+ import datetime
4
+
5
+ from docx import Document
6
+
7
+ import form_logic
8
+
9
+
10
+ # --- clean_vendor_name -------------------------------------------------------
11
+ def test_clean_vendor_name_strips_sap_code():
12
+ assert form_logic.clean_vendor_name(
13
+ "0010006270 บริษัท ลินเด้ (ประเทศไทย) จำกัด (มหาชน)"
14
+ ) == "บริษัท ลินเด้ (ประเทศไทย) จำกัด (มหาชน)"
15
+
16
+
17
+ def test_clean_vendor_name_passthrough():
18
+ assert form_logic.clean_vendor_name("บริษัท ทดสอบ จำกัด") == "บริษัท ทดสอบ จำกัด"
19
+ assert form_logic.clean_vendor_name(None) == ""
20
+ assert form_logic.clean_vendor_name("") == ""
21
+
22
+
23
+ def test_clean_vendor_name_all_digits_kept():
24
+ # stripping would leave nothing → the original value is returned
25
+ assert form_logic.clean_vendor_name("1234567890") == "1234567890"
26
+
27
+
28
+ # --- signer line -------------------------------------------------------------
29
+ def test_center_text_in_parens_width():
30
+ out = form_logic.center_text_in_parens("นายทดสอบ", total_width=44)
31
+ assert out.startswith("(") and out.endswith(")")
32
+ assert len(out) == 46 # 44 inner + the two parens
33
+ inner = out[1:-1]
34
+ assert inner.strip() == "นายทดสอบ"
35
+ left = len(inner) - len(inner.lstrip())
36
+ right = len(inner) - len(inner.rstrip())
37
+ assert abs(left - right) <= 1 # centered
38
+
39
+
40
+ def test_center_text_in_parens_overwidth_passthrough():
41
+ name = "x" * 50
42
+ assert form_logic.center_text_in_parens(name, total_width=44) == f"({name})"
43
+
44
+
45
+ # --- docx helpers (in-memory documents) --------------------------------------
46
+ def test_fill_letter_date():
47
+ doc = Document()
48
+ doc.add_paragraph("วันที่ เดือน พ.ศ.")
49
+ assert form_logic.fill_letter_date(doc, datetime.date(2026, 7, 16)) is True
50
+ assert "พ.ศ. 2569" in doc.paragraphs[0].text
51
+ assert "กรกฎาคม" in doc.paragraphs[0].text
52
+
53
+
54
+ def test_fill_letter_date_no_line():
55
+ doc = Document()
56
+ doc.add_paragraph("ไม่มีบรรทัดวันที่")
57
+ assert form_logic.fill_letter_date(doc, datetime.date(2026, 7, 16)) is False
58
+
59
+
60
+ def test_replace_text_across_split_runs():
61
+ doc = Document()
62
+ p = doc.add_paragraph()
63
+ p.add_run("เลขที่ PO_")
64
+ p.add_run("No ครับ") # placeholder split across two runs
65
+ n = form_logic.replace_text(doc, "PO_No", "4500987654")
66
+ assert n == 1
67
+ assert p.text == "เลขที่ 4500987654 ครับ"
68
+
69
+
70
+ def test_insert_body_paragraphs():
71
+ doc = Document()
72
+ doc.add_paragraph("หัวเรื่อง")
73
+ doc.add_paragraph("[เนื้อความ]")
74
+ n = form_logic.insert_body_paragraphs(doc, "[เนื้อความ]", "ย่อหน้าหนึ่ง\n\nย่อหน้าสอง")
75
+ assert n == 2
76
+ texts = [p.text for p in doc.paragraphs]
77
+ assert "[เนื้อความ]" not in " ".join(texts)
78
+ assert "ย่อหน้าหนึ่ง" in texts and "ย่อหน้าสอง" in texts
tests/test_letter_builder.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """letter_builder — the generate use-case, end-to-end with the real form1 template."""
3
+ from datetime import date, datetime
4
+ from io import BytesIO
5
+
6
+ from docx import Document
7
+
8
+ import letter_builder
9
+ from form_logic import DOC_TYPE_OPTIONS, FORM_TYPES
10
+
11
+ LOOKUP = {
12
+ "poNo": "4500987654",
13
+ "VendorName": "0010001234 บริษัท ทดสอบ จำกัด",
14
+ "title": "งานจ้างเหมาบำรุงรักษาระบบท่อ",
15
+ "procurementType": "งานจ้างบริการ",
16
+ "prCreatorUnitName": "ส่วนบำรุงรักษาระบบท่อ",
17
+ "daySLA": 90,
18
+ }
19
+
20
+
21
+ def test_default_doc_type():
22
+ assert letter_builder.default_doc_type("งานจ้างบริการ") == DOC_TYPE_OPTIONS[0]
23
+ assert letter_builder.default_doc_type("งานซื้อ") == DOC_TYPE_OPTIONS[1]
24
+ assert letter_builder.default_doc_type(None) == DOC_TYPE_OPTIONS[1]
25
+
26
+
27
+ def test_suffix_doc_type():
28
+ ng_num = {"label": "งวดที่ 2", "number": 2, "manual": False}
29
+ ng_manual = {"label": "งวดสุดท้าย", "number": None, "manual": True}
30
+ assert letter_builder.suffix_doc_type("แจ้งให้เริ่มเข้าทำงาน", ng_num) == \
31
+ "แจ้งให้เริ่มเข้าทำงาน (งวดที่ 2)"
32
+ assert letter_builder.suffix_doc_type("แจ้งให้เริ่มเข้าทำงาน", ng_manual) == \
33
+ "แจ้งให้เริ่มเข้าทำงาน (งวดสุดท้าย)"
34
+ assert letter_builder.suffix_doc_type("แจ้งให้เริ่มเข้าทำงาน", None) == \
35
+ "แจ้งให้เริ่มเข้าทำงาน"
36
+ # forms without a doc type stay empty — no งวด suffix appears from nowhere
37
+ assert letter_builder.suffix_doc_type("", ng_num) == ""
38
+
39
+
40
+ def test_build_letter_form1():
41
+ docx_bytes, filename, log, used_ai = letter_builder.build_letter(
42
+ selected_form=FORM_TYPES[0],
43
+ doc_number="PTT-001/2568",
44
+ po_number="4500987654",
45
+ doc_type=DOC_TYPE_OPTIONS[0],
46
+ signer="นายทดสอบ ระบบดี",
47
+ signer_position="ผู้จัดการฝ่ายทดสอบ",
48
+ lookup_data=LOOKUP,
49
+ start_date=date(2026, 7, 20),
50
+ delivery_raw="ส่งมอบงานภายใน 90 (เก้าสิบ) วัน นับถัดจากวันที่ได้รับหนังสือแจ้ง",
51
+ selected_nguad={"label": "งวดที่ 2", "number": 2, "manual": False},
52
+ now=datetime(2026, 7, 16, 12, 0, 0),
53
+ )
54
+ assert used_ai is False # AI_BACKEND=off
55
+ assert docx_bytes[:2] == b"PK"
56
+ assert filename == "form1_PTT-001-2568_20260716_120000.docx"
57
+ assert log # the render log is populated
58
+
59
+ doc = Document(BytesIO(docx_bytes))
60
+ all_text = "\n".join(p.text for p in doc.paragraphs)
61
+ assert "[เนื้อความ]" not in all_text # body placeholder replaced
62
+ assert "ตามที่" in all_text and "จึงขอแจ้งให้" in all_text
63
+ assert "บริษัท ทดสอบ จำกัด" in all_text # vendor code stripped
64
+ assert "(งวดที่ 2)" in all_text # งวด suffix landed in the doc type
65
+ assert "20 กรกฎาคม 2569" in all_text # start date in Thai