|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +import pytest |
| 4 | +from openpyxl import Workbook, load_workbook |
| 5 | +from openpyxl.worksheet.table import Table, TableStyleInfo |
| 6 | + |
| 7 | +from exstruct.core import cells |
| 8 | +from exstruct.core.cells import _coerce_numeric_preserve_format, detect_tables_openpyxl |
| 9 | + |
| 10 | + |
| 11 | +def test_coerce_numeric_preserve_format() -> None: |
| 12 | + assert _coerce_numeric_preserve_format("42") == 42 |
| 13 | + assert _coerce_numeric_preserve_format("-3.14") == -3.14 |
| 14 | + # non-numeric stays string |
| 15 | + assert _coerce_numeric_preserve_format("3.14e2") == "3.14e2" |
| 16 | + assert _coerce_numeric_preserve_format("abc") == "abc" |
| 17 | + |
| 18 | + |
| 19 | +def test_detect_tables_openpyxl_detects_tables(tmp_path: Path) -> None: |
| 20 | + path = tmp_path / "sample.xlsx" |
| 21 | + wb = Workbook() |
| 22 | + ws = wb.active |
| 23 | + ws.title = "Sheet1" |
| 24 | + ws.append(["A", "B"]) |
| 25 | + ws.append([1, 2]) |
| 26 | + tab = Table(displayName="Table1", ref="A1:B2") |
| 27 | + tab.tableStyleInfo = TableStyleInfo(name="TableStyleMedium9", showRowStripes=True) |
| 28 | + ws.add_table(tab) |
| 29 | + wb.save(path) |
| 30 | + wb.close() |
| 31 | + |
| 32 | + tables = detect_tables_openpyxl(path, "Sheet1") |
| 33 | + assert "A1:B2" in tables |
| 34 | + |
| 35 | + |
| 36 | +def test_detect_tables_openpyxl_respects_table_params(tmp_path: Path, monkeypatch) -> None: |
| 37 | + # Ensure detection still runs after modifying global thresholds |
| 38 | + path = tmp_path / "sample.xlsx" |
| 39 | + wb = Workbook() |
| 40 | + ws = wb.active |
| 41 | + ws.title = "Sheet1" |
| 42 | + ws.append(["A", "B"]) |
| 43 | + ws.append([1, 2]) |
| 44 | + tab = Table(displayName="Table1", ref="A1:B2") |
| 45 | + ws.add_table(tab) |
| 46 | + wb.save(path) |
| 47 | + wb.close() |
| 48 | + |
| 49 | + # Force density/coverage to high thresholds to ensure Table objects are still returned |
| 50 | + monkeypatch.setattr(cells, "_DETECTION_CONFIG", { |
| 51 | + "table_score_threshold": 0.99, |
| 52 | + "density_min": 0.99, |
| 53 | + "coverage_min": 0.99, |
| 54 | + "min_nonempty_cells": 1, |
| 55 | + }) |
| 56 | + tables = detect_tables_openpyxl(path, "Sheet1") |
| 57 | + assert "A1:B2" in tables |
0 commit comments