# -*- coding: utf-8 -*- """data_source — repository layer, tested against the tracked sample workbook.""" import os from io import BytesIO import openpyxl import pytest import data_source SAMPLE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "sample_po_data.xlsx") SAMPLE_PO = "4500987654" @pytest.fixture(scope="module") def sample_bytes(): with open(SAMPLE, "rb") as f: return f.read() def test_strip_col_wrapper_powerbi_header(): assert data_source._strip_col_wrapper("Data for Auto Form[poNo]") == "poNo" def test_strip_col_wrapper_plain_and_none(): assert data_source._strip_col_wrapper("poNo") == "poNo" assert data_source._strip_col_wrapper(" title ") == "title" assert data_source._strip_col_wrapper(None) is None def test_lookup_found(sample_bytes): result, cols = data_source.lookup_po_in_bytes(SAMPLE_PO, sample_bytes) assert isinstance(result, dict) and "__error__" not in result assert str(result["poNo"]).startswith(SAMPLE_PO) assert result.get("VendorName") assert result.get("title") assert "poNo" in cols def test_lookup_not_found(sample_bytes): result, cols = data_source.lookup_po_in_bytes("0000000000", sample_bytes) assert result is None assert "poNo" in cols def test_lookup_missing_column(sample_bytes): result, cols = data_source.lookup_po_in_bytes(SAMPLE_PO, sample_bytes, po_column="no_such_column") assert isinstance(result, dict) and "__error__" in result assert cols == [] def _tiny_workbook(po_cell_value): wb = openpyxl.Workbook() ws = wb.active ws.append(["Data for Auto Form[poNo]", "Data for Auto Form[title]"]) ws.append([po_cell_value, "งานทดสอบ"]) buf = BytesIO() wb.save(buf) return buf.getvalue() def test_lookup_float_po_cell_matches(): """Power BI exports sometimes ship the PO number as a float (4500987654.0).""" result, _ = data_source.lookup_po_in_bytes("4500987654", _tiny_workbook(4500987654.0)) assert result and result["title"] == "งานทดสอบ" def test_lookup_date_serial_converted(): """An Excel serial in a DATE_COLUMNS column comes back as 'YYYY-MM-DD'.""" wb = openpyxl.Workbook() ws = wb.active ws.append(["poNo", "poCreateDate"]) ws.append(["4500987654", 45658]) # 2025-01-01 as an Excel serial buf = BytesIO() wb.save(buf) result, _ = data_source.lookup_po_in_bytes("4500987654", buf.getvalue()) assert result["poCreateDate"] == "2025-01-01" def test_check_data_fail_without_url(): ok, detail = data_source.check_data("") assert ok is False assert detail # carries the error message