|
| 1 | +import pytest |
| 2 | +import pandas as pd |
| 3 | +from pathlib import Path |
| 4 | +from unittest.mock import patch |
| 5 | +from src.webapp.validation import validate_file_reader, HardValidationError |
| 6 | + |
| 7 | +# Minimal schema for testing |
| 8 | +MOCK_BASE_SCHEMA = { |
| 9 | + "base": { |
| 10 | + "data_models": { |
| 11 | + "test_model": { |
| 12 | + "columns": { |
| 13 | + "foo_col": { |
| 14 | + "dtype": "int", |
| 15 | + "nullable": False, |
| 16 | + "required": True, |
| 17 | + "aliases": ["foo"], |
| 18 | + }, |
| 19 | + "bar_col": { |
| 20 | + "dtype": "str", |
| 21 | + "nullable": True, |
| 22 | + "required": False, |
| 23 | + "aliases": ["bar"], |
| 24 | + }, |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +MOCK_EXT_SCHEMA = {"institutions": {"pdp": {"data_models": {}}}} |
| 32 | + |
| 33 | + |
| 34 | +@pytest.fixture |
| 35 | +def tmp_csv_file(tmp_path: Path): |
| 36 | + df = pd.DataFrame({"foo_col": [1, 2], "bar_col": ["a", "b"]}) |
| 37 | + file_path = tmp_path / "test.csv" |
| 38 | + df.to_csv(file_path, index=False) |
| 39 | + return str(file_path) |
| 40 | + |
| 41 | + |
| 42 | +def test_validate_file_reader_passes(tmp_csv_file): |
| 43 | + with ( |
| 44 | + patch("src.webapp.validation.load_json") as mock_load, |
| 45 | + patch("os.path.exists", return_value=True), |
| 46 | + ): |
| 47 | + mock_load.side_effect = ( |
| 48 | + lambda path: MOCK_BASE_SCHEMA if "base" in path else MOCK_EXT_SCHEMA |
| 49 | + ) |
| 50 | + result = validate_file_reader(tmp_csv_file, ["test_model"]) |
| 51 | + assert result["validation_status"] == "passed" |
| 52 | + assert result["schemas"] == ["test_model"] |
| 53 | + |
| 54 | + |
| 55 | +def test_validate_file_reader_fails_missing_required(tmp_path): |
| 56 | + df = pd.DataFrame({"bar_col": ["x", "y"]}) # Missing "foo_col" |
| 57 | + file_path = tmp_path / "invalid.csv" |
| 58 | + df.to_csv(file_path, index=False) |
| 59 | + |
| 60 | + with ( |
| 61 | + patch("src.webapp.validation.load_json") as mock_load, |
| 62 | + patch("os.path.exists", return_value=True), |
| 63 | + ): |
| 64 | + mock_load.side_effect = ( |
| 65 | + lambda path: MOCK_BASE_SCHEMA if "base" in path else MOCK_EXT_SCHEMA |
| 66 | + ) |
| 67 | + with pytest.raises(HardValidationError) as exc_info: |
| 68 | + validate_file_reader(str(file_path), ["test_model"]) |
| 69 | + assert "Missing required columns" in str(exc_info.value) |
0 commit comments