File size: 12,316 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
"""Tests for services.parser and services.notes_xml.

Both test decks are required for the full suite.  If they are absent (CI
without the binary assets), each test that needs them is skipped via
``pytest.skip``.

Test decks:
  - JACOBS: 33 slides  (Jacobs Assessment of Compensation Peers)
  - IDEXX:  24 slides  (IDEXX Peer Group Assessment, annotated speaker notes)
"""

from __future__ import annotations

import hashlib
import os
from pathlib import Path

import pytest

# ---------------------------------------------------------------------------
# Deck paths β€” resolved relative to this file's location (apps/api/tests/)
# The decks live at <repo_root>/Doc Reference/
# ---------------------------------------------------------------------------
_REPO_ROOT = Path(__file__).parent.parent.parent.parent  # β†’ project root
_DOC_REF = _REPO_ROOT / "Doc Reference"

JACOBS_PATH = _DOC_REF / "20260429 Jacobs Assessment of Compensation Peers - DRAFT 20260327 (3).pptx"
IDEXX_PATH = _DOC_REF / "Annotated_20260511 IDEXX Peer Group Assessment - DRAFT 20260330 (3).pptx"


def _skip_if_absent(path: Path) -> None:
    if not path.exists():
        pytest.skip(f"Test deck not found (CI): {path.name}")


def _sha256(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


# ---------------------------------------------------------------------------
# Lazy imports so missing deps don't break collection
# ---------------------------------------------------------------------------
def _import_parser():
    import sys
    api_dir = Path(__file__).parent.parent
    if str(api_dir) not in sys.path:
        sys.path.insert(0, str(api_dir))
    from services.parser import parse_deck
    return parse_deck


def _import_notes_xml():
    import sys
    api_dir = Path(__file__).parent.parent
    if str(api_dir) not in sys.path:
        sys.path.insert(0, str(api_dir))
    from services.notes_xml import read_notes_xml
    return read_notes_xml


# ===========================================================================
# Slide count tests
# ===========================================================================


def test_idexx_slide_count():
    _skip_if_absent(IDEXX_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(IDEXX_PATH)
    assert deck.slide_count == 24, f"Expected 24, got {deck.slide_count}"


def test_jacobs_slide_count():
    _skip_if_absent(JACOBS_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(JACOBS_PATH)
    assert deck.slide_count == 33, f"Expected 33, got {deck.slide_count}"


# ===========================================================================
# Deck dimensions
# ===========================================================================


def test_deck_dimensions_jacobs():
    _skip_if_absent(JACOBS_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(JACOBS_PATH)
    assert deck.slide_width_emu > 0, "slide_width_emu must be positive"
    assert deck.slide_height_emu > 0, "slide_height_emu must be positive"
    assert isinstance(deck.slide_width_emu, int)
    assert isinstance(deck.slide_height_emu, int)


def test_deck_dimensions_idexx():
    _skip_if_absent(IDEXX_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(IDEXX_PATH)
    assert deck.slide_width_emu > 0
    assert deck.slide_height_emu > 0


# ===========================================================================
# File immutability (byte-hash before vs after parsing)
# ===========================================================================


def test_parser_does_not_modify_jacobs():
    _skip_if_absent(JACOBS_PATH)
    parse_deck = _import_parser()
    before = _sha256(JACOBS_PATH)
    parse_deck(JACOBS_PATH)
    after = _sha256(JACOBS_PATH)
    assert before == after, "Parser modified the Jacobs source file!"


def test_parser_does_not_modify_idexx():
    _skip_if_absent(IDEXX_PATH)
    parse_deck = _import_parser()
    before = _sha256(IDEXX_PATH)
    parse_deck(IDEXX_PATH)
    after = _sha256(IDEXX_PATH)
    assert before == after, "Parser modified the IDEXX source file!"


# ===========================================================================
# Acceptance-criteria text checks (Jacobs)
# ===========================================================================


def test_jacobs_slide1_contains_draft():
    _skip_if_absent(JACOBS_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(JACOBS_PATH)
    slide1 = deck.slides[0]
    combined = slide1.extracted_text + " " + slide1.notes_text
    assert "DRAFT" in combined, f"'DRAFT' not found in slide 1. Text: {slide1.extracted_text[:200]!r}"


def test_jacobs_slide6_contains_tw_question():
    _skip_if_absent(JACOBS_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(JACOBS_PATH)
    slide6 = deck.slides[5]  # 0-indexed
    combined = slide6.extracted_text + " " + slide6.notes_text
    assert "TW question" in combined, (
        f"'TW question' not found in slide 6. Text: {slide6.extracted_text[:200]!r}"
    )


def test_jacobs_slide7_contains_tw_question():
    _skip_if_absent(JACOBS_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(JACOBS_PATH)
    slide7 = deck.slides[6]  # 0-indexed
    combined = slide7.extracted_text + " " + slide7.notes_text
    assert "TW question" in combined, (
        f"'TW question' not found in slide 7. Text: {slide7.extracted_text[:200]!r}"
    )


def test_jacobs_slide23_contains_page_to_be_updated():
    _skip_if_absent(JACOBS_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(JACOBS_PATH)
    slide23 = deck.slides[22]  # 0-indexed
    combined = slide23.extracted_text + " " + slide23.notes_text
    assert "Page to be updated" in combined, (
        f"'Page to be updated' not found in slide 23. Text: {slide23.extracted_text[:200]!r}"
    )


def test_jacobs_slide24_contains_page_to_be_updated():
    _skip_if_absent(JACOBS_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(JACOBS_PATH)
    slide24 = deck.slides[23]  # 0-indexed
    combined = slide24.extracted_text + " " + slide24.notes_text
    assert "Page to be updated" in combined, (
        f"'Page to be updated' not found in slide 24. Text: {slide24.extracted_text[:200]!r}"
    )


# ===========================================================================
# Shape IDs and group flattening
# ===========================================================================


def test_shape_ids_are_stable_and_unique():
    """Every ShapeInfo has a unique shape_id within a slide."""
    _skip_if_absent(JACOBS_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(JACOBS_PATH)
    for slide in deck.slides:
        ids = [s.shape_id for s in slide.shapes]
        assert len(ids) == len(set(ids)), (
            f"Duplicate shape IDs on slide {slide.slide_number}: {ids}"
        )
        for sid in ids:
            assert sid.startswith(f"s{slide.slide_number}."), (
                f"shape_id {sid!r} does not start with 's{slide.slide_number}.'"
            )


def test_group_shapes_flattened():
    """Deck containing GROUP shapes returns all leaf shapes (no GROUP entries)."""
    _skip_if_absent(JACOBS_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(JACOBS_PATH)
    for slide in deck.slides:
        for shape in slide.shapes:
            assert shape.shape_type != "GROUP", (
                f"Slide {slide.slide_number}: GROUP shape not flattened: {shape.shape_id}"
            )


def test_group_children_have_slide_relative_coords():
    """Children of a group have coords >= the group's slide-relative offset."""
    _skip_if_absent(JACOBS_PATH)
    from pptx import Presentation
    from pptx.enum.shapes import MSO_SHAPE_TYPE

    parse_deck = _import_parser()
    prs = Presentation(JACOBS_PATH)

    # Find slide 9 which we know has a GROUP shape
    target_slide_idx = 8  # 0-indexed β†’ slide 9
    group_slide = list(prs.slides)[target_slide_idx]
    group_shape = None
    for sh in group_slide.shapes:
        if sh.shape_type == MSO_SHAPE_TYPE.GROUP:
            group_shape = sh
            break
    assert group_shape is not None, "Expected a GROUP on slide 9 of Jacobs"

    deck = parse_deck(JACOBS_PATH)
    slide9 = deck.slides[target_slide_idx]

    # Each child's left should be >= group.left (since child.left in group frame is >= 0)
    # and each child's top should be >= group.top
    g_left = group_shape.left or 0
    g_top = group_shape.top or 0
    # We can't directly identify which parsed shapes came from the group,
    # but we can check that all shapes on this slide have non-negative coords
    # (negative would indicate broken transform).
    # Also verify at least one shape has left near or beyond g_left.
    for shape in slide9.shapes:
        assert shape.left >= 0, f"Negative left on {shape.shape_id}: {shape.left}"
        assert shape.top >= 0, f"Negative top on {shape.shape_id}: {shape.top}"


# ===========================================================================
# notes_xml.py β€” raw zip reader
# ===========================================================================


def test_notes_xml_idexx_at_least_15_slides():
    """IDEXX notes are parseable via raw XML reader on at least 15 slides."""
    _skip_if_absent(IDEXX_PATH)
    read_notes_xml = _import_notes_xml()
    notes = read_notes_xml(IDEXX_PATH)
    assert len(notes) >= 15, (
        f"Expected >=15 slides with notes via notes_xml, got {len(notes)}: {sorted(notes.keys())}"
    )


def test_notes_xml_returns_dict_of_strings():
    _skip_if_absent(IDEXX_PATH)
    read_notes_xml = _import_notes_xml()
    notes = read_notes_xml(IDEXX_PATH)
    assert isinstance(notes, dict)
    for k, v in notes.items():
        assert isinstance(k, int), f"Key {k!r} is not int"
        assert isinstance(v, str), f"Value for key {k} is not str"
        assert v.strip(), f"Slide {k} notes value is blank"


def test_notes_xml_does_not_modify_idexx():
    _skip_if_absent(IDEXX_PATH)
    read_notes_xml = _import_notes_xml()
    before = _sha256(IDEXX_PATH)
    read_notes_xml(IDEXX_PATH)
    after = _sha256(IDEXX_PATH)
    assert before == after, "notes_xml reader modified the IDEXX source file!"


def test_notes_xml_slide_numbers_are_1indexed():
    _skip_if_absent(IDEXX_PATH)
    read_notes_xml = _import_notes_xml()
    notes = read_notes_xml(IDEXX_PATH)
    for k in notes:
        assert k >= 1, f"Slide number {k} is not 1-indexed"
        assert k <= 24, f"Slide number {k} exceeds deck size of 24"


# ===========================================================================
# Pydantic model validation
# ===========================================================================


def test_parsed_deck_model_is_valid():
    """ParsedDeck parses without Pydantic errors."""
    _skip_if_absent(JACOBS_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(JACOBS_PATH)
    # Re-serialize to dict and back to exercise model_validate
    from schemas.parsed import ParsedDeck
    data = deck.model_dump()
    deck2 = ParsedDeck.model_validate(data)
    assert deck2.slide_count == 33


def test_extra_fields_forbidden():
    """ParsedDeck has extra='forbid' β€” extra fields raise ValidationError."""
    import sys
    api_dir = Path(__file__).parent.parent
    if str(api_dir) not in sys.path:
        sys.path.insert(0, str(api_dir))
    from schemas.parsed import ParsedDeck
    import pydantic
    with pytest.raises(pydantic.ValidationError):
        ParsedDeck(slide_count=1, slide_width_emu=100, slide_height_emu=100,
                   slides=[], unexpected_field="oops")


# ===========================================================================
# IDEXX parser smoke test
# ===========================================================================


def test_idexx_notes_via_parser():
    """Parser-level notes extraction also works for IDEXX (has_notes_slide guard)."""
    _skip_if_absent(IDEXX_PATH)
    parse_deck = _import_parser()
    deck = parse_deck(IDEXX_PATH)
    non_empty_notes = [s for s in deck.slides if s.notes_text.strip()]
    assert len(non_empty_notes) >= 10, (
        f"Expected >=10 slides with notes via parser, got {len(non_empty_notes)}"
    )