File size: 10,151 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
"""
test_renderer.py — Tests for the LibreOffice slide renderer.

Live-render tests are skipped when soffice is not on $PATH.
When soffice IS available:
  - Both supplied decks render with the correct slide counts.
  - At least 95% of slides in each deck render successfully.
  - PNG dimensions are consistent within each deck.
  - Two concurrent render_deck() calls do not collide.

When soffice is NOT available:
  - render_deck() returns skipped=True without raising.
"""
from __future__ import annotations

import concurrent.futures
import shutil
import tempfile
from pathlib import Path

import pytest

from services.lo_runner import soffice_available
from services.renderer import RenderResult, render_deck, warmup

# ---------------------------------------------------------------------------
# Paths to supplied test decks
# ---------------------------------------------------------------------------

_REPO_ROOT = Path(__file__).parent.parent.parent.parent  # …/Farient Case Study - (RobinBot)
_DOC_REF = _REPO_ROOT / "Doc Reference"

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

IDEXX_SLIDE_COUNT = 24
JACOBS_SLIDE_COUNT = 33

SOFFICE_AVAILABLE = soffice_available()

requires_soffice = pytest.mark.skipif(
    not SOFFICE_AVAILABLE,
    reason="soffice not found on $PATH — live-render tests skipped",
)


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _render_into_tmpdir(pptx_path: Path) -> tuple[RenderResult, Path]:
    """Render *pptx_path* into a fresh temp directory; return (result, tmp_dir)."""
    tmp = Path(tempfile.mkdtemp(prefix="test_render_"))
    result = render_deck(pptx_path, tmp)
    return result, tmp


# ---------------------------------------------------------------------------
# soffice-absent tests (always run)
# ---------------------------------------------------------------------------


class TestNoSoffice:
    """Tests that must pass regardless of whether soffice is installed."""

    def test_skipped_when_soffice_absent(self, monkeypatch):
        """render_deck returns skipped=True and does not raise when soffice is missing."""
        # Force soffice_available() to return False inside renderer
        import services.lo_runner as lo_mod

        monkeypatch.setattr(lo_mod, "soffice_available", lambda: False)

        # Re-import renderer to pick up monkeypatched dependency
        import importlib

        import services.renderer as rend_mod

        monkeypatch.setattr(rend_mod, "soffice_available", lambda: False)

        with tempfile.TemporaryDirectory() as tmp:
            result = render_deck(JACOBS_PPTX, Path(tmp))

        assert result.skipped is True
        assert result.reason is not None
        assert "unavailable" in result.reason.lower()
        assert result.render_failed is False
        assert result.slide_paths == []

    def test_result_model_forbids_extra_fields(self):
        """RenderResult with extra='forbid' raises on unknown fields."""
        import pydantic

        with pytest.raises((pydantic.ValidationError, TypeError)):
            RenderResult(unknown_field="oops")  # type: ignore[call-arg]

    def test_warmup_does_not_raise_when_soffice_absent(self, monkeypatch):
        """warmup() must not raise even when soffice is missing."""
        import services.renderer as rend_mod

        monkeypatch.setattr(rend_mod, "soffice_available", lambda: False)
        warmup()  # must not raise


# ---------------------------------------------------------------------------
# Live-render tests (skipped when soffice absent)
# ---------------------------------------------------------------------------


@requires_soffice
class TestLiveRender:
    """Tests that run only when soffice is available."""

    def test_idexx_slide_count(self):
        """IDEXX deck renders to exactly 24 PNGs (or per-slide errors summing to 24)."""
        result, tmp = _render_into_tmpdir(IDEXX_PPTX)
        try:
            assert not result.skipped, "unexpected skip"
            assert not result.render_failed, f"render failed: {result.reason}"
            total = result.total
            assert total == IDEXX_SLIDE_COUNT, (
                f"Expected {IDEXX_SLIDE_COUNT} slides total, got {total} "
                f"({result.success_count} ok, {len(result.slide_errors)} errors)"
            )
        finally:
            shutil.rmtree(tmp, ignore_errors=True)

    def test_jacobs_slide_count(self):
        """Jacobs deck renders to exactly 33 PNGs (or per-slide errors summing to 33)."""
        result, tmp = _render_into_tmpdir(JACOBS_PPTX)
        try:
            assert not result.skipped, "unexpected skip"
            assert not result.render_failed, f"render failed: {result.reason}"
            total = result.total
            assert total == JACOBS_SLIDE_COUNT, (
                f"Expected {JACOBS_SLIDE_COUNT} slides total, got {total} "
                f"({result.success_count} ok, {len(result.slide_errors)} errors)"
            )
        finally:
            shutil.rmtree(tmp, ignore_errors=True)

    def test_idexx_success_rate(self):
        """At least 95% of IDEXX slides render successfully."""
        result, tmp = _render_into_tmpdir(IDEXX_PPTX)
        try:
            assert not result.skipped and not result.render_failed
            rate = result.success_count / result.total
            assert rate >= 0.95, (
                f"IDEXX success rate {rate:.1%} below 95% "
                f"({result.success_count}/{result.total})"
            )
        finally:
            shutil.rmtree(tmp, ignore_errors=True)

    def test_jacobs_success_rate(self):
        """At least 95% of Jacobs slides render successfully."""
        result, tmp = _render_into_tmpdir(JACOBS_PPTX)
        try:
            assert not result.skipped and not result.render_failed
            rate = result.success_count / result.total
            assert rate >= 0.95, (
                f"Jacobs success rate {rate:.1%} below 95% "
                f"({result.success_count}/{result.total})"
            )
        finally:
            shutil.rmtree(tmp, ignore_errors=True)

    def test_idexx_consistent_dimensions(self):
        """All successfully rendered IDEXX slides must have the same pixel dimensions."""
        from PIL import Image

        result, tmp = _render_into_tmpdir(IDEXX_PPTX)
        try:
            assert not result.skipped and not result.render_failed
            assert len(result.slide_paths) > 0, "no slides rendered"
            sizes = set()
            for p in result.slide_paths:
                with Image.open(p) as img:
                    sizes.add(img.size)
            assert len(sizes) == 1, f"Inconsistent PNG dimensions in IDEXX deck: {sizes}"
        finally:
            shutil.rmtree(tmp, ignore_errors=True)

    def test_jacobs_consistent_dimensions(self):
        """All successfully rendered Jacobs slides must have the same pixel dimensions."""
        from PIL import Image

        result, tmp = _render_into_tmpdir(JACOBS_PPTX)
        try:
            assert not result.skipped and not result.render_failed
            assert len(result.slide_paths) > 0, "no slides rendered"
            sizes = set()
            for p in result.slide_paths:
                with Image.open(p) as img:
                    sizes.add(img.size)
            assert len(sizes) == 1, f"Inconsistent PNG dimensions in Jacobs deck: {sizes}"
        finally:
            shutil.rmtree(tmp, ignore_errors=True)

    def test_concurrent_renders_do_not_collide(self):
        """Two concurrent render_deck() calls must both succeed without interfering."""
        tmps: list[Path] = []
        try:
            with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
                fut_idexx = pool.submit(_render_into_tmpdir, IDEXX_PPTX)
                fut_jacobs = pool.submit(_render_into_tmpdir, JACOBS_PPTX)

                result_idexx, tmp_idexx = fut_idexx.result(timeout=180)
                result_jacobs, tmp_jacobs = fut_jacobs.result(timeout=180)
                tmps.extend([tmp_idexx, tmp_jacobs])

            # Both must succeed
            assert not result_idexx.skipped and not result_idexx.render_failed, (
                f"IDEXX concurrent render failed: {result_idexx.reason}"
            )
            assert not result_jacobs.skipped and not result_jacobs.render_failed, (
                f"Jacobs concurrent render failed: {result_jacobs.reason}"
            )

            # Both must produce the right number of slides
            assert result_idexx.total == IDEXX_SLIDE_COUNT, (
                f"IDEXX: expected {IDEXX_SLIDE_COUNT}, got {result_idexx.total}"
            )
            assert result_jacobs.total == JACOBS_SLIDE_COUNT, (
                f"Jacobs: expected {JACOBS_SLIDE_COUNT}, got {result_jacobs.total}"
            )
        finally:
            for t in tmps:
                shutil.rmtree(t, ignore_errors=True)

    def test_png_files_are_named_correctly(self):
        """PNG files must follow the slide_NNN.png zero-padded naming convention."""
        result, tmp = _render_into_tmpdir(IDEXX_PPTX)
        try:
            assert not result.skipped and not result.render_failed
            for path in result.slide_paths:
                name = path.name
                assert name.startswith("slide_"), f"Unexpected filename: {name}"
                assert name.endswith(".png"), f"Unexpected extension: {name}"
                idx_str = name[len("slide_") : -len(".png")]
                assert len(idx_str) == 3 and idx_str.isdigit(), (
                    f"Expected 3-digit zero-padded index, got: {idx_str!r}"
                )
        finally:
            shutil.rmtree(tmp, ignore_errors=True)

    def test_warmup_runs_without_error(self):
        """warmup() must complete without raising when soffice is available."""
        warmup()  # must not raise