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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407"""Unit tests for the empty-content guard in PipelineViewerService.
When Docling extraction produces zero extractable text (scanned/image-only PDFs),
the pipeline should skip all LLM phases and return early to avoid wasting tokens.
"""
from __future__ import annotations
from unittest.mock import AsyncMock, patch
import pytest
from src.services.pipeline_viewer import PipelineViewerService
from src.services.pipeline_viewer_models import (
PipelineViewerResult,
StepResult,
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def service():
"""Create a PipelineViewerService instance."""
return PipelineViewerService()
def _make_result_with_chars(total_chars: int) -> PipelineViewerResult:
"""Build a PipelineViewerResult that looks like _step_docling just ran."""
result = PipelineViewerResult(
filename="scanned.pdf",
total_pages=3,
versions={"v0": ""},
page_images={"1": "AAAA", "2": "BBBB", "3": "CCCC"},
page_markdowns={"v0": {"1": "", "2": "", "3": ""}},
figures=[],
steps=[
StepResult(
name="docling",
display_name="Docling Extraction",
version_before=None,
version_after="v0",
elapsed_ms=500,
changes=[],
metadata={},
),
],
stats={
"total_chars": total_chars,
"figure_count": 0,
"is_likely_scanned": total_chars == 0,
},
)
return result
# ---------------------------------------------------------------------------
# Mock helpers
# ---------------------------------------------------------------------------
def _patch_classify():
"""Return patches that stub out classify_pdf and enrich_classification."""
from unittest.mock import MagicMock
mock_classification = MagicMock()
mock_classification.has_errors = False
mock_classification.warning_messages = []
mock_classification.error_messages = []
mock_classification.document_type.value = "course_material"
mock_classification.findings = []
mock_classification.elapsed_ms = 10
mock_classification.metadata.model_dump.return_value = {}
return (
patch(
"src.services.pdf_classifier.classify_pdf",
return_value=mock_classification,
),
patch("src.services.pdf_classifier.enrich_classification"),
)
def _patch_docling(total_chars: int):
"""Patch _step_docling to populate the result with the given char count."""
async def fake_step_docling(self, result, *args, **kwargs):
result.total_pages = 3
result.versions["v0"] = "" if total_chars == 0 else "x" * total_chars
result.page_images = {"1": "AAAA", "2": "BBBB", "3": "CCCC"}
result.page_markdowns = {"v0": {"1": "", "2": "", "3": ""}}
result.stats["total_chars"] = total_chars
result.stats["figure_count"] = 0
result.stats["is_likely_scanned"] = total_chars == 0
result.steps.append(
StepResult(
name="docling",
display_name="Docling Extraction",
version_before=None,
version_after="v0",
elapsed_ms=500,
changes=[],
metadata={},
)
)
return patch.object(PipelineViewerService, "_step_docling", fake_step_docling)
# ---------------------------------------------------------------------------
# Tests โ Zero-chars triggers skip
# ---------------------------------------------------------------------------
class TestEmptyContentGuardTriggered:
"""When total_chars == 0, all enabled LLM phases must be skipped."""
@pytest.mark.asyncio
async def test_all_phases_skipped_when_zero_chars(self, service):
"""All structure, page-content, and boundary steps are skipped."""
classify_patch, enrich_patch = _patch_classify()
with classify_patch, enrich_patch, _patch_docling(0):
result = await service.process(
b"fake-pdf",
"scanned.pdf",
enable_structure=True,
enable_page_content=True,
enable_boundaries=True,
)
step_names = [s.name for s in result.steps]
assert step_names == [
"docling",
"structure",
"heading_reconciliation",
"heading_levels",
"page_content",
"code_blocks",
"boundaries",
"cleanup",
]
# All steps after docling should be skipped
for step in result.steps[1:]:
assert step.skipped is True
assert step.elapsed_ms == 0
assert step.metadata["reason"] == "empty_content"
@pytest.mark.asyncio
async def test_only_structure_skipped_when_only_structure_enabled(self, service):
"""Only structure-related steps are skipped when only structure is enabled."""
classify_patch, enrich_patch = _patch_classify()
with classify_patch, enrich_patch, _patch_docling(0):
result = await service.process(
b"fake-pdf",
"scanned.pdf",
enable_structure=True,
enable_page_content=False,
enable_boundaries=False,
)
step_names = [s.name for s in result.steps]
assert step_names == [
"docling",
"structure",
"heading_reconciliation",
"heading_levels",
]
for step in result.steps[1:]:
assert step.skipped is True
@pytest.mark.asyncio
async def test_no_llm_steps_when_no_phases_enabled(self, service):
"""With no phases enabled, only the docling step remains."""
classify_patch, enrich_patch = _patch_classify()
with classify_patch, enrich_patch, _patch_docling(0):
result = await service.process(
b"fake-pdf",
"scanned.pdf",
enable_structure=False,
enable_page_content=False,
enable_boundaries=False,
)
step_names = [s.name for s in result.steps]
assert step_names == ["docling"]
@pytest.mark.asyncio
async def test_warning_appended(self, service):
"""A warning about empty content must appear in the result."""
classify_patch, enrich_patch = _patch_classify()
with classify_patch, enrich_patch, _patch_docling(0):
result = await service.process(
b"fake-pdf",
"scanned.pdf",
enable_structure=True,
enable_page_content=True,
enable_boundaries=True,
)
assert any("zero extractable text" in w for w in result.warnings)
# ---------------------------------------------------------------------------
# Tests โ Low chars does NOT trigger skip
# ---------------------------------------------------------------------------
class TestEmptyContentGuardNotTriggered:
"""When total_chars > 0, the guard must not fire โ pipeline continues."""
@pytest.mark.asyncio
async def test_low_chars_does_not_skip(self, service):
"""A document with 100 chars should proceed to structure analysis."""
classify_patch, enrich_patch = _patch_classify()
# Mock _step_structure to verify it was actually called
mock_structure = AsyncMock(return_value=AsyncMock(outline=[], page_attributes={}, footnotes=[]))
with (
classify_patch,
enrich_patch,
_patch_docling(100),
patch.object(PipelineViewerService, "_step_structure", mock_structure),
patch.object(PipelineViewerService, "_step_heading_reconciliation", AsyncMock(return_value=AsyncMock(outline=[]))),
patch.object(PipelineViewerService, "_step_heading_levels", AsyncMock()),
):
result = await service.process(
b"fake-pdf",
"test.pdf",
enable_structure=True,
enable_page_content=False,
enable_boundaries=False,
)
# _step_structure must have been called โ the guard did not fire
mock_structure.assert_called_once()
@pytest.mark.asyncio
async def test_single_char_does_not_skip(self, service):
"""Even 1 char of text should not trigger the guard."""
classify_patch, enrich_patch = _patch_classify()
mock_structure = AsyncMock(return_value=AsyncMock(outline=[], page_attributes={}, footnotes=[]))
with (
classify_patch,
enrich_patch,
_patch_docling(1),
patch.object(PipelineViewerService, "_step_structure", mock_structure),
patch.object(PipelineViewerService, "_step_heading_reconciliation", AsyncMock(return_value=AsyncMock(outline=[]))),
patch.object(PipelineViewerService, "_step_heading_levels", AsyncMock()),
):
result = await service.process(
b"fake-pdf",
"test.pdf",
enable_structure=True,
enable_page_content=False,
enable_boundaries=False,
)
mock_structure.assert_called_once()
# ---------------------------------------------------------------------------
# Tests โ Skipped step metadata
# ---------------------------------------------------------------------------
class TestSkippedStepMetadata:
"""Skipped StepResult entries should have the correct shape."""
@pytest.mark.asyncio
async def test_skipped_steps_have_correct_fields(self, service):
"""Each skipped step must have version_before/after, zero elapsed, and metadata."""
classify_patch, enrich_patch = _patch_classify()
with classify_patch, enrich_patch, _patch_docling(0):
result = await service.process(
b"fake-pdf",
"scanned.pdf",
enable_structure=True,
enable_page_content=True,
enable_boundaries=True,
)
for step in result.steps[1:]:
assert step.skipped is True
assert step.elapsed_ms == 0
assert step.version_before == "v0"
assert step.version_after == "v0"
assert step.changes == []
assert step.metadata["reason"] == "empty_content"
assert step.metadata["total_chars"] == 0
assert step.error is None
assert step.input_tokens == 0
assert step.output_tokens == 0
assert step.cost_cents == 0.0
@pytest.mark.asyncio
async def test_skipped_steps_display_names(self, service):
"""Each skipped step should carry the correct display_name."""
classify_patch, enrich_patch = _patch_classify()
with classify_patch, enrich_patch, _patch_docling(0):
result = await service.process(
b"fake-pdf",
"scanned.pdf",
enable_structure=True,
enable_page_content=True,
enable_boundaries=True,
)
expected_display = {
"structure": "Structure Analysis",
"heading_reconciliation": "Heading Reconciliation",
"heading_levels": "Heading Levels",
"page_content": "Page Content Corrections",
"code_blocks": "Code Block Languages",
"boundaries": "Cross-Page Fixes",
"cleanup": "Final Cleanup",
}
for step in result.steps[1:]:
assert step.display_name == expected_display[step.name], (
f"Step '{step.name}' has wrong display_name: {step.display_name}"
)
# ---------------------------------------------------------------------------
# Tests โ Docling step and classification preserved
# ---------------------------------------------------------------------------
class TestResultPreservation:
"""The guard must not discard the docling step or classification data."""
@pytest.mark.asyncio
async def test_docling_step_preserved(self, service):
"""The first step should always be the docling extraction."""
classify_patch, enrich_patch = _patch_classify()
with classify_patch, enrich_patch, _patch_docling(0):
result = await service.process(
b"fake-pdf",
"scanned.pdf",
enable_structure=True,
enable_page_content=True,
enable_boundaries=True,
)
docling_step = result.steps[0]
assert docling_step.name == "docling"
assert docling_step.display_name == "Docling Extraction"
assert docling_step.skipped is False
assert docling_step.elapsed_ms > 0
@pytest.mark.asyncio
async def test_classification_stats_preserved(self, service):
"""Classification stats should be present even when guard fires."""
classify_patch, enrich_patch = _patch_classify()
with classify_patch, enrich_patch, _patch_docling(0):
result = await service.process(
b"fake-pdf",
"scanned.pdf",
enable_structure=True,
)
assert "classification" in result.stats
assert result.stats["classification"]["document_type"] == "course_material"
@pytest.mark.asyncio
async def test_page_images_preserved(self, service):
"""Page images should still be available (useful for viewer display)."""
classify_patch, enrich_patch = _patch_classify()
with classify_patch, enrich_patch, _patch_docling(0):
result = await service.process(
b"fake-pdf",
"scanned.pdf",
)
assert len(result.page_images) == 3
@pytest.mark.asyncio
async def test_total_pages_preserved(self, service):
"""Total page count should be set even for empty documents."""
classify_patch, enrich_patch = _patch_classify()
with classify_patch, enrich_patch, _patch_docling(0):
result = await service.process(
b"fake-pdf",
"scanned.pdf",
)
assert result.total_pages == 3
@pytest.mark.asyncio
async def test_stats_total_chars_zero(self, service):
"""Stats should reflect the zero char count."""
classify_patch, enrich_patch = _patch_classify()
with classify_patch, enrich_patch, _patch_docling(0):
result = await service.process(
b"fake-pdf",
"scanned.pdf",
)
assert result.stats["total_chars"] == 0