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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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
"""CLI integration tests.

These tests call mosaic.gradio_app.main() directly in-process with sys.argv
patched, while mocking only the heavy ML operations (model download, analyze_slide,
load_all_models).  Everything else — argument parsing, settings validation, output
file creation — runs for real.
"""

from __future__ import annotations

import sys
import tempfile
import textwrap
from pathlib import Path
from unittest.mock import MagicMock, patch

import pandas as pd
import pytest
from PIL import Image


# ---------------------------------------------------------------------------
# Shared fixtures
# ---------------------------------------------------------------------------

FAKE_CANCER_SUBTYPE_MAP = {
    "Unknown": "UNK",
    "Lung Adenocarcinoma (LUAD)": "LUAD",
}
FAKE_REVERSED_MAP = {v: k for k, v in FAKE_CANCER_SUBTYPE_MAP.items()}
FAKE_CANCER_SUBTYPES = ["LUAD"]


@pytest.fixture()
def fake_slide(tmp_path) -> Path:
    """A tiny 256×256 TIFF saved with an .svs extension."""
    path = tmp_path / "test_slide.svs"
    Image.new("RGB", (256, 256), color=(200, 180, 160)).save(str(path), format="TIFF")
    return path


@pytest.fixture()
def fake_mask() -> Image.Image:
    return Image.new("RGB", (256, 256), color=(0, 128, 0))


@pytest.fixture()
def fake_aeon_df() -> pd.DataFrame:
    # analyze_slide returns aeon_results with "Cancer Subtype" as the index
    # and "Confidence" as the only column (matching analysis.py set_index call)
    df = pd.DataFrame({"Cancer Subtype": ["LUAD", "LUSC"], "Confidence": [0.85, 0.15]})
    df.set_index("Cancer Subtype", inplace=True)
    return df


@pytest.fixture()
def fake_paladin_df() -> pd.DataFrame:
    # Same columns as mosaic.inference.paladin.RESULT_COLUMNS
    return pd.DataFrame(
        {
            "Cancer Subtype": ["LUAD"],
            "Biomarker": ["TP53"],
            "Prob. Present": [0.85],
            "Weights": ["Pan-cancer (ATS)"],
        },
    )


@pytest.fixture()
def output_dir(tmp_path) -> Path:
    d = tmp_path / "output"
    d.mkdir()
    return d


def _make_download_metadata_mock():
    """Return a side-effectful mock for download_metadata that also sets pipeline maps."""
    from mosaic.ui.pipeline import set_cancer_subtype_maps

    def _mock(*_args, **_kwargs):
        set_cancer_subtype_maps(
            FAKE_CANCER_SUBTYPE_MAP,
            FAKE_REVERSED_MAP,
            FAKE_CANCER_SUBTYPES,
        )
        return FAKE_CANCER_SUBTYPE_MAP, FAKE_REVERSED_MAP, FAKE_CANCER_SUBTYPES

    return _mock


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

COMMON_PATCHES = [
    # Prevent any real model/metadata downloads
    patch("mosaic.gradio_app.download_and_process_models"),
    patch("mosaic.gradio_app.download_metadata"),
    # Never hit HuggingFace
    patch("mosaic.model_download.snapshot_download", return_value="/fake/cache"),
    # Prevent oncotree HTTP calls in validate_settings
    patch(
        "mosaic.gradio_app.get_oncotree_code_name",
        side_effect=lambda code: f"Mock {code}",
    ),
]


def _apply_patches(patches):
    """Context manager that enters all patches and returns their mocks."""
    from contextlib import ExitStack

    stack = ExitStack()
    mocks = [stack.enter_context(p) for p in patches]
    return stack, mocks


# ---------------------------------------------------------------------------
# Single-slide CLI tests
# ---------------------------------------------------------------------------


class TestSingleSlideCLI:
    """Integration tests for `mosaic --slide-path <file> --output-dir <dir>`."""

    def _run_single(
        self, fake_slide, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
    ):
        """Call main() with single-slide args; return the output dir path."""
        mock_download = _make_download_metadata_mock()

        argv = [
            "mosaic",
            "--slide-path",
            str(fake_slide),
            "--output-dir",
            str(output_dir),
            "--sex",
            "Male",
            "--site-type",
            "Primary",
            "--tissue-site",
            "Lung",
            "--cancer-subtype",
            "Unknown",
            "--segmentation-config",
            "Biopsy",
            "--skip-model-download",
        ]

        with (
            patch.object(sys, "argv", argv),
            patch(
                "mosaic.cli.runners.analyze_slide",
                return_value=(fake_mask, fake_aeon_df, fake_paladin_df),
            ),
            patch(
                "mosaic.gradio_app.get_oncotree_code_name",
                side_effect=lambda code: f"Mock {code}",
            ),
            patch(
                "mosaic.gradio_app.download_and_process_models",
                side_effect=mock_download,
            ),
            patch("mosaic.gradio_app.download_metadata", side_effect=mock_download),
            patch(
                "mosaic.data_directory.get_data_directory",
                return_value=str(Path(__file__).parent.parent / "data"),
            ),
            patch("mosaic.model_download.set_data_directory"),
        ):
            from mosaic.gradio_app import main

            main()

        return output_dir

    def test_mask_file_created(
        self, fake_slide, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
    ):
        """A PNG mask file is written to the output directory."""
        self._run_single(
            fake_slide, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
        )
        mask_path = output_dir / "test_slide_mask.png"
        assert mask_path.exists(), f"Expected mask at {mask_path}"

    def test_aeon_csv_created(
        self, fake_slide, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
    ):
        """An Aeon results CSV is written to the output directory."""
        self._run_single(
            fake_slide, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
        )
        aeon_path = output_dir / "test_slide_aeon_results.csv"
        assert aeon_path.exists(), f"Expected Aeon CSV at {aeon_path}"

    def test_aeon_csv_contains_cancer_subtype(
        self, fake_slide, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
    ):
        """Aeon results CSV contains the mocked cancer subtype."""
        self._run_single(
            fake_slide, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
        )
        df = pd.read_csv(output_dir / "test_slide_aeon_results.csv")
        assert "Cancer Subtype" in df.columns
        assert "LUAD" in df["Cancer Subtype"].values

    def test_paladin_csv_created(
        self, fake_slide, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
    ):
        """A Paladin results CSV is written to the output directory."""
        self._run_single(
            fake_slide, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
        )
        paladin_path = output_dir / "test_slide_paladin_results.csv"
        assert paladin_path.exists(), f"Expected Paladin CSV at {paladin_path}"

    def test_paladin_csv_contains_biomarkers(
        self, fake_slide, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
    ):
        """Paladin results CSV contains biomarker rows."""
        self._run_single(
            fake_slide, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
        )
        df = pd.read_csv(output_dir / "test_slide_paladin_results.csv")
        assert len(df) >= 1
        assert "Biomarker" in df.columns

    def test_missing_sex_raises(self, fake_slide, output_dir):
        """CLI raises ValueError when --sex is omitted for single-slide mode."""
        mock_download = _make_download_metadata_mock()
        argv = [
            "mosaic",
            "--slide-path",
            str(fake_slide),
            "--output-dir",
            str(output_dir),
            "--skip-model-download",
        ]
        with (
            patch.object(sys, "argv", argv),
            patch(
                "mosaic.gradio_app.download_and_process_models",
                side_effect=mock_download,
            ),
            patch("mosaic.gradio_app.download_metadata", side_effect=mock_download),
            patch(
                "mosaic.data_directory.get_data_directory",
                return_value=str(Path(__file__).parent.parent / "data"),
            ),
            patch("mosaic.model_download.set_data_directory"),
        ):
            with pytest.raises(ValueError, match="Sex is required"):
                from mosaic.gradio_app import main

                main()


# ---------------------------------------------------------------------------
# Batch CSV CLI tests
# ---------------------------------------------------------------------------


class TestBatchCLI:
    """Integration tests for `mosaic --slide-csv <file> --output-dir <dir>`."""

    @pytest.fixture()
    def batch_csv(self, fake_slide, tmp_path) -> Path:
        """A minimal batch CSV referencing our fake slide by name only."""
        csv_path = tmp_path / "batch_settings.csv"
        # Use just the filename (not absolute path) so output files land in output_dir
        csv_path.write_text(
            textwrap.dedent(
                f"""\
                Slide,Site Type,Sex,Tissue Site,Cancer Subtype,Segmentation Config
                {fake_slide.name},Primary,Male,Lung,Unknown,Biopsy
            """
            )
        )
        return csv_path

    def _run_batch(
        self, batch_csv, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
    ):
        mock_download = _make_download_metadata_mock()
        mock_model_cache = MagicMock()

        argv = [
            "mosaic",
            "--slide-csv",
            str(batch_csv),
            "--output-dir",
            str(output_dir),
            "--skip-model-download",
        ]

        with (
            patch.object(sys, "argv", argv),
            patch(
                "mosaic.cli.runners.analyze_slide",
                return_value=(fake_mask, fake_aeon_df, fake_paladin_df),
            ),
            patch("mosaic.cli.runners.load_all_models", return_value=mock_model_cache),
            patch(
                "mosaic.gradio_app.get_oncotree_code_name",
                side_effect=lambda code: f"Mock {code}",
            ),
            patch(
                "mosaic.gradio_app.download_and_process_models",
                side_effect=mock_download,
            ),
            patch("mosaic.gradio_app.download_metadata", side_effect=mock_download),
            patch(
                "mosaic.data_directory.get_data_directory",
                return_value=str(Path(__file__).parent.parent / "data"),
            ),
            patch("mosaic.model_download.set_data_directory"),
        ):
            from mosaic.gradio_app import main

            main()

        return output_dir

    def test_mask_file_created(
        self,
        batch_csv,
        output_dir,
        fake_mask,
        fake_aeon_df,
        fake_paladin_df,
        fake_slide,
    ):
        """A PNG mask is created for the slide in the batch."""
        self._run_batch(batch_csv, output_dir, fake_mask, fake_aeon_df, fake_paladin_df)
        # Batch code prefixes idx (000) to avoid collisions between same-basename slides
        slide_stem = f"000_{fake_slide.stem}"
        mask_path = output_dir / f"{slide_stem}_mask.png"
        assert (
            mask_path.exists()
        ), f"Expected mask at {mask_path}; found: {list(output_dir.iterdir())}"

    def test_aeon_csv_created(
        self, batch_csv, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
    ):
        """An Aeon CSV is written per-slide and a combined CSV is written."""
        self._run_batch(batch_csv, output_dir, fake_mask, fake_aeon_df, fake_paladin_df)
        combined = output_dir / "combined_aeon_results.csv"
        assert (
            combined.exists()
        ), f"Expected combined Aeon CSV; found: {list(output_dir.iterdir())}"

    def test_paladin_csv_created(
        self,
        batch_csv,
        output_dir,
        fake_mask,
        fake_aeon_df,
        fake_paladin_df,
        fake_slide,
    ):
        """A Paladin CSV is written per sample (Sample ID defaults to the slide stem)."""
        self._run_batch(batch_csv, output_dir, fake_mask, fake_aeon_df, fake_paladin_df)
        paladin_path = output_dir / f"{fake_slide.stem}_paladin_results.csv"
        assert (
            paladin_path.exists()
        ), f"Expected Paladin CSV; found: {list(output_dir.iterdir())}"

    def test_load_all_models_called_once(
        self, batch_csv, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
    ):
        """Models are loaded exactly once for the entire batch."""
        mock_download = _make_download_metadata_mock()
        mock_model_cache = MagicMock()
        mock_load = MagicMock(return_value=mock_model_cache)

        argv = [
            "mosaic",
            "--slide-csv",
            str(batch_csv),
            "--output-dir",
            str(output_dir),
            "--skip-model-download",
        ]

        with (
            patch.object(sys, "argv", argv),
            patch(
                "mosaic.cli.runners.analyze_slide",
                return_value=(fake_mask, fake_aeon_df, fake_paladin_df),
            ),
            patch("mosaic.cli.runners.load_all_models", mock_load),
            patch(
                "mosaic.gradio_app.get_oncotree_code_name",
                side_effect=lambda code: f"Mock {code}",
            ),
            patch(
                "mosaic.gradio_app.download_and_process_models",
                side_effect=mock_download,
            ),
            patch("mosaic.gradio_app.download_metadata", side_effect=mock_download),
            patch(
                "mosaic.data_directory.get_data_directory",
                return_value=str(Path(__file__).parent.parent / "data"),
            ),
            patch("mosaic.model_download.set_data_directory"),
        ):
            from mosaic.gradio_app import main

            main()

        mock_load.assert_called_once()

    def test_model_cache_cleanup_called(
        self, batch_csv, output_dir, fake_mask, fake_aeon_df, fake_paladin_df
    ):
        """Model cache cleanup is called after batch processing."""
        mock_download = _make_download_metadata_mock()
        mock_model_cache = MagicMock()

        argv = [
            "mosaic",
            "--slide-csv",
            str(batch_csv),
            "--output-dir",
            str(output_dir),
            "--skip-model-download",
        ]

        with (
            patch.object(sys, "argv", argv),
            patch(
                "mosaic.cli.runners.analyze_slide",
                return_value=(fake_mask, fake_aeon_df, fake_paladin_df),
            ),
            patch("mosaic.cli.runners.load_all_models", return_value=mock_model_cache),
            patch(
                "mosaic.gradio_app.get_oncotree_code_name",
                side_effect=lambda code: f"Mock {code}",
            ),
            patch(
                "mosaic.gradio_app.download_and_process_models",
                side_effect=mock_download,
            ),
            patch("mosaic.gradio_app.download_metadata", side_effect=mock_download),
            patch(
                "mosaic.data_directory.get_data_directory",
                return_value=str(Path(__file__).parent.parent / "data"),
            ),
            patch("mosaic.model_download.set_data_directory"),
        ):
            from mosaic.gradio_app import main

            main()

        mock_model_cache.cleanup.assert_called_once()