File size: 11,462 Bytes
9b3af23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b420e00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b3af23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tests E2E API REST pour les champs B3-final de ``BenchmarkRunRequest``.

Phase D3 audit B3-final (mai 2026) β€” l'audit implacable a identifiΓ©
l'absence de couverture API REST pour les nouveaux champs ajoutΓ©s
en Phase B3-final corr-A/B/C :

- ``views``, ``profile``, ``partial_dir``, ``entity_extractor``,
  ``output_json`` (BenchmarkRunRequest)
- ``expose_alto`` (PipelineConfig)

Ces tests valident :
1. **Validation Pydantic positive** : payloads valides retournent 200
2. **Validation Pydantic nΓ©gative** : payloads malformΓ©s retournent 422
3. **SΓ©curitΓ© path traversal** : ``../../etc`` refusΓ© en 422
"""

from __future__ import annotations

import pytest
from fastapi.testclient import TestClient


@pytest.fixture
def client():
    from picarones.interfaces.web.app import app
    return TestClient(app)


def _valid_corpus_payload(tmp_path):
    """CrΓ©e un corpus zip mini valide pour les tests."""
    from PIL import Image

    img = Image.new("RGB", (50, 50), color=(255, 255, 255))
    img.save(tmp_path / "doc01.png")
    (tmp_path / "doc01.gt.txt").write_text("hello", encoding="utf-8")
    return str(tmp_path)


# ──────────────────────────────────────────────────────────────────────
# 1. Validation positive β€” payloads B3-final acceptΓ©s
# ──────────────────────────────────────────────────────────────────────


class TestB3FinalFieldsAccepted:
    """VΓ©rifie que ``BenchmarkRunRequest`` accepte tous les nouveaux
    champs B3-final ajoutΓ©s en Phase corr-A/B/C."""

    def test_request_accepts_views_field(self, client) -> None:
        """``views`` accepte la liste des vues canoniques."""
        from picarones.interfaces.web.models import BenchmarkRunRequest

        # Validation Pydantic isolΓ©e (sans HTTP, plus rapide).
        req = BenchmarkRunRequest(
            corpus_path="./corpus",
            competitors=[{"engine_name": "tesseract"}],
            views=["text_final", "alto_documentary", "searchability"],
        )
        assert list(req.views) == [
            "text_final", "alto_documentary", "searchability",
        ]

    def test_request_accepts_profile_field(self) -> None:
        from picarones.interfaces.web.models import BenchmarkRunRequest

        req = BenchmarkRunRequest(
            corpus_path="./corpus",
            competitors=[{"engine_name": "tesseract"}],
            profile="diagnostics",
        )
        assert req.profile == "diagnostics"

    def test_request_accepts_partial_dir_field(self) -> None:
        from picarones.interfaces.web.models import BenchmarkRunRequest

        req = BenchmarkRunRequest(
            corpus_path="./corpus",
            competitors=[{"engine_name": "tesseract"}],
            partial_dir="partial/checkpoints",
        )
        assert req.partial_dir == "partial/checkpoints"

    def test_request_accepts_entity_extractor_field(self) -> None:
        from picarones.interfaces.web.models import BenchmarkRunRequest

        req = BenchmarkRunRequest(
            corpus_path="./corpus",
            competitors=[{"engine_name": "tesseract"}],
            entity_extractor="picarones.adapters.ner:SpacyExtractor",
        )
        assert req.entity_extractor == "picarones.adapters.ner:SpacyExtractor"

    def test_request_accepts_output_json_field(self) -> None:
        from picarones.interfaces.web.models import BenchmarkRunRequest

        req = BenchmarkRunRequest(
            corpus_path="./corpus",
            competitors=[{"engine_name": "tesseract"}],
            output_json="bench_legacy.json",
        )
        assert req.output_json == "bench_legacy.json"

    def test_pipeline_config_accepts_expose_alto(self) -> None:
        from picarones.interfaces.web.models import PipelineConfig

        pc = PipelineConfig(
            engine_name="tesseract", expose_alto=True,
        )
        assert pc.expose_alto is True

    def test_pipeline_config_default_no_expose_alto(self) -> None:
        from picarones.interfaces.web.models import PipelineConfig

        pc = PipelineConfig(engine_name="tesseract")
        assert pc.expose_alto is False

    def test_expose_alto_with_non_tesseract_engine_warns(
        self, caplog: pytest.LogCaptureFixture,
    ) -> None:
        """Phase D4 audit B3-final β€” l'UI envoie ``expose_alto=true``
        mais le moteur cible n'est pas Tesseract.  Le flag est ignorΓ©
        mais on logue un warning explicite pour que l'utilisateur
        comprenne pourquoi son ``alto_documentary`` view ne fournit
        aucune mΓ©trique.
        """
        import logging
        from picarones.interfaces.web.benchmark_utils import (
            _engine_from_competitor,
        )
        from picarones.interfaces.web.models import PipelineConfig

        with caplog.at_level(logging.WARNING):
            try:
                _engine_from_competitor(PipelineConfig(
                    engine_name="precomputed_text", expose_alto=True,
                ))
            except Exception:
                # Le factory peut Γ©chouer car ``precomputed_text``
                # demande des kwargs supplΓ©mentaires β€” on capture mais
                # le warning doit Γͺtre Γ©mis AVANT cette erreur.
                pass

        warnings_text = "\n".join(
            r.getMessage() for r in caplog.records
            if r.levelno >= logging.WARNING
        )
        assert "expose_alto" in warnings_text or "alto" in warnings_text.lower()
        assert "precomputed_text" in warnings_text


# ──────────────────────────────────────────────────────────────────────
# 2. Validation nΓ©gative β€” payloads malformΓ©s rejetΓ©s
# ──────────────────────────────────────────────────────────────────────


class TestB3FinalFieldsValidation:
    def test_invalid_view_name_rejected(self) -> None:
        """``views`` n'accepte que les noms canoniques (Literal)."""
        from pydantic import ValidationError
        from picarones.interfaces.web.models import BenchmarkRunRequest

        with pytest.raises(ValidationError):
            BenchmarkRunRequest(
                corpus_path="./corpus",
                competitors=[{"engine_name": "tesseract"}],
                views=["not_a_canonical_view"],
            )

    def test_invalid_profile_rejected(self) -> None:
        """``profile`` n'accepte que les profils canoniques (Literal)."""
        from pydantic import ValidationError
        from picarones.interfaces.web.models import BenchmarkRunRequest

        with pytest.raises(ValidationError):
            BenchmarkRunRequest(
                corpus_path="./corpus",
                competitors=[{"engine_name": "tesseract"}],
                profile="not_a_real_profile",
            )


# ──────────────────────────────────────────────────────────────────────
# 3. SΓ©curitΓ© β€” path traversal refusΓ© (Phase D2 audit)
# ──────────────────────────────────────────────────────────────────────


class TestPathTraversalSecurity:
    def test_partial_dir_traversal_rejected(self) -> None:
        from pydantic import ValidationError
        from picarones.interfaces.web.models import BenchmarkRunRequest

        with pytest.raises(ValidationError, match="path traversal"):
            BenchmarkRunRequest(
                corpus_path="./corpus",
                competitors=[{"engine_name": "tesseract"}],
                partial_dir="../../etc/passwd",
            )

    def test_partial_dir_absolute_rejected(self) -> None:
        from pydantic import ValidationError
        from picarones.interfaces.web.models import BenchmarkRunRequest

        with pytest.raises(ValidationError, match="chemin absolu"):
            BenchmarkRunRequest(
                corpus_path="./corpus",
                competitors=[{"engine_name": "tesseract"}],
                partial_dir="/etc/passwd",
            )

    def test_output_json_traversal_rejected(self) -> None:
        from pydantic import ValidationError
        from picarones.interfaces.web.models import BenchmarkRunRequest

        with pytest.raises(ValidationError, match="path traversal"):
            BenchmarkRunRequest(
                corpus_path="./corpus",
                competitors=[{"engine_name": "tesseract"}],
                output_json="../../home/user/private.json",
            )

    def test_entity_extractor_traversal_rejected(self) -> None:
        from pydantic import ValidationError
        from picarones.interfaces.web.models import BenchmarkRunRequest

        with pytest.raises(ValidationError, match="interdits"):
            BenchmarkRunRequest(
                corpus_path="./corpus",
                competitors=[{"engine_name": "tesseract"}],
                entity_extractor="../../etc/passwd:Bad",
            )

    def test_entity_extractor_with_slash_rejected(self) -> None:
        from pydantic import ValidationError
        from picarones.interfaces.web.models import BenchmarkRunRequest

        with pytest.raises(ValidationError, match="interdits"):
            BenchmarkRunRequest(
                corpus_path="./corpus",
                competitors=[{"engine_name": "tesseract"}],
                entity_extractor="some/path:Class",
            )

    def test_entity_extractor_with_space_rejected(self) -> None:
        from pydantic import ValidationError
        from picarones.interfaces.web.models import BenchmarkRunRequest

        with pytest.raises(ValidationError, match="interdits"):
            BenchmarkRunRequest(
                corpus_path="./corpus",
                competitors=[{"engine_name": "tesseract"}],
                entity_extractor="my package:Class",
            )

    def test_entity_extractor_malformed_rejected(self) -> None:
        from pydantic import ValidationError
        from picarones.interfaces.web.models import BenchmarkRunRequest

        with pytest.raises(ValidationError, match="format invalide"):
            BenchmarkRunRequest(
                corpus_path="./corpus",
                competitors=[{"engine_name": "tesseract"}],
                entity_extractor="123invalid_start_with_digit",
            )

    def test_empty_string_path_fields_accepted(self) -> None:
        """``""`` est explicitement autorisΓ© (= feature dΓ©sactivΓ©e)."""
        from picarones.interfaces.web.models import BenchmarkRunRequest

        req = BenchmarkRunRequest(
            corpus_path="./corpus",
            competitors=[{"engine_name": "tesseract"}],
            partial_dir="",
            output_json="",
            entity_extractor="",
        )
        assert req.partial_dir == ""
        assert req.output_json == ""
        assert req.entity_extractor == ""