|
| 1 | +"""Fields the models type as integers must hold integers in the seed JSON.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import subprocess |
| 7 | +import sys |
| 8 | +from pathlib import Path |
| 9 | +from types import NoneType, UnionType |
| 10 | +from typing import Any, Union, get_args, get_origin |
| 11 | + |
| 12 | +import pytest |
| 13 | +from pydantic import BaseModel |
| 14 | + |
| 15 | +from app import validate |
| 16 | +from app.models.brand import Brand |
| 17 | +from app.models.cpu import CPU |
| 18 | +from app.models.device_catalog import DeviceCatalog |
| 19 | +from app.models.gpu import DiscreteGPU |
| 20 | +from app.models.laptop import Laptop |
| 21 | +from app.models.mobile_device import PDA, Tablet, Watch |
| 22 | +from app.models.monitor import Monitor |
| 23 | +from app.models.smartphone import Smartphone |
| 24 | +from app.models.soc import SoC |
| 25 | +from app.models.software import Software |
| 26 | +from app.models.website import Website |
| 27 | +from app.schemas import ( |
| 28 | + BrandRead, |
| 29 | + DeviceCatalogRead, |
| 30 | + LaptopRead, |
| 31 | + MonitorRead, |
| 32 | + SmartphoneRead, |
| 33 | + SoCRead, |
| 34 | + SoftwareRead, |
| 35 | +) |
| 36 | +from app.schemas.cpu import CPURead |
| 37 | +from app.schemas.gpu import GPURead |
| 38 | +from app.schemas.mobile_device import MobileDeviceRead |
| 39 | +from app.schemas.website import WebsiteRead |
| 40 | + |
| 41 | +REPO = Path(__file__).resolve().parents[2] |
| 42 | + |
| 43 | +MODELS: dict[str, type[BaseModel]] = dict(zip(validate.CATEGORIES, ( |
| 44 | + Brand, SoC, Smartphone, Tablet, Watch, PDA, DiscreteGPU, CPU, |
| 45 | + Laptop, Monitor, Software, Website, DeviceCatalog, |
| 46 | +), strict=True)) |
| 47 | +READ_SCHEMAS: dict[str, type[BaseModel]] = { |
| 48 | + "brand": BrandRead, "soc": SoCRead, "smartphone": SmartphoneRead, |
| 49 | + "tablet": MobileDeviceRead, "watch": MobileDeviceRead, "pda": MobileDeviceRead, |
| 50 | + "gpu": GPURead, "cpu": CPURead, "laptop": LaptopRead, "monitor": MonitorRead, |
| 51 | + "software": SoftwareRead, "website": WebsiteRead, "device_catalog": DeviceCatalogRead, |
| 52 | +} |
| 53 | + |
| 54 | +# One record path and one integer field per category that has any. |
| 55 | +SAMPLES = [ |
| 56 | + ("brand/us/acme.json", "founded_year"), |
| 57 | + ("soc/acme/c1.json", "gpu_cores"), |
| 58 | + ("smartphone/acme/2020/p.json", "battery_mah"), |
| 59 | + ("tablet/acme/2020/t/t.json", "battery_mah"), |
| 60 | + ("watch/acme/2020/w/w.json", "msrp_usd"), |
| 61 | + ("pda/acme/2020/d/d.json", "battery_mah"), |
| 62 | + ("gpu/acme/g1.json", "tdp_w"), |
| 63 | + ("cpu/acme/x1.json", "tdp_w"), |
| 64 | + ("laptop/acme/2020/l.json", "ram_gb"), |
| 65 | + ("monitor/acme/2020/m.json", "refresh_hz"), |
| 66 | + ("device_catalog/acme/acme-x.json", "android_sdk_min"), |
| 67 | +] |
| 68 | + |
| 69 | + |
| 70 | +def _put(root: Path, rel: str, rec: dict[str, Any]) -> None: |
| 71 | + path = root / rel |
| 72 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 73 | + path.write_text(json.dumps(rec), encoding="utf-8") |
| 74 | + |
| 75 | + |
| 76 | +def _integer_errors(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, rel: str, |
| 77 | + rec: dict[str, Any], only: set[str] | None = None) -> list[str]: |
| 78 | + monkeypatch.setattr(validate, "DATA_DIR", tmp_path) |
| 79 | + _put(tmp_path, rel, rec) |
| 80 | + return [e for e in validate.validate(only) if "must be an integer" in e |
| 81 | + or "must be a list of integers" in e] |
| 82 | + |
| 83 | + |
| 84 | +def _integer_fields(model: type[BaseModel]) -> tuple[set[str], set[str]]: |
| 85 | + """Fields a model types as ``int`` and as ``list[int]``. |
| 86 | +
|
| 87 | + Primary and foreign keys are skipped: seed fills them in, the JSON carries |
| 88 | + slugs instead. |
| 89 | + """ |
| 90 | + scalars: set[str] = set() |
| 91 | + lists: set[str] = set() |
| 92 | + for field, info in model.model_fields.items(): |
| 93 | + if getattr(info, "primary_key", None) is True or isinstance( |
| 94 | + getattr(info, "foreign_key", None), str |
| 95 | + ): |
| 96 | + continue |
| 97 | + annotation = info.annotation |
| 98 | + options = get_args(annotation) if get_origin(annotation) in (Union, UnionType) else ( |
| 99 | + annotation, |
| 100 | + ) |
| 101 | + kinds = {option for option in options if option is not NoneType} |
| 102 | + if kinds == {int}: |
| 103 | + scalars.add(field) |
| 104 | + elif kinds == {list[int]}: |
| 105 | + lists.add(field) |
| 106 | + return scalars, lists |
| 107 | + |
| 108 | + |
| 109 | +def test_validator_imports_with_the_standard_library_only() -> None: |
| 110 | + """TechAPI's PR checks run the validator without installing the engine.""" |
| 111 | + code = f"import sys; sys.path.insert(0, {str(REPO)!r}); import app.validate" |
| 112 | + # -S keeps site-packages off the path, -I ignores PYTHONPATH and the cwd |
| 113 | + done = subprocess.run([sys.executable, "-I", "-S", "-c", code], |
| 114 | + capture_output=True, text=True) |
| 115 | + assert done.returncode == 0, done.stderr |
| 116 | + |
| 117 | + |
| 118 | +def test_every_category_is_mapped() -> None: |
| 119 | + assert set(validate.INTEGER_FIELDS) == set(validate.CATEGORIES) |
| 120 | + |
| 121 | + |
| 122 | +@pytest.mark.parametrize("category", validate.CATEGORIES) |
| 123 | +def test_mapping_matches_the_model(category: str) -> None: |
| 124 | + """Fails when a model gains or loses an integer column the validator does not list.""" |
| 125 | + assert validate.INTEGER_FIELDS[category] == _integer_fields(MODELS[category]) |
| 126 | + |
| 127 | + |
| 128 | +def test_keys_floats_and_bools_are_not_integer_fields() -> None: |
| 129 | + scalars, _ = _integer_fields(CPU) |
| 130 | + assert not {"id", "manufacturer_id", "base_clock_ghz", "verified"} & scalars |
| 131 | + assert "ram_gb" in _integer_fields(Laptop)[0] |
| 132 | + assert "ram_gb" not in _integer_fields(Smartphone)[0] |
| 133 | + |
| 134 | + |
| 135 | +@pytest.mark.parametrize("category", validate.CATEGORIES) |
| 136 | +def test_read_schema_integers_are_covered(category: str) -> None: |
| 137 | + """A read schema must not type a seed field as int unless the model does.""" |
| 138 | + schema_scalars, schema_lists = _integer_fields(READ_SCHEMAS[category]) |
| 139 | + scalars, lists = validate.INTEGER_FIELDS[category] |
| 140 | + assert schema_scalars - {"id"} <= scalars |
| 141 | + assert schema_lists <= lists |
| 142 | + |
| 143 | + |
| 144 | +@pytest.mark.parametrize("rel,field", SAMPLES) |
| 145 | +@pytest.mark.parametrize("value", [11.5, True, "12", "12.0", [12], float("nan")]) |
| 146 | +def test_non_integer_rejected(tmp_path, monkeypatch, rel, field, value) -> None: |
| 147 | + errs = _integer_errors(tmp_path, monkeypatch, rel, {"slug": "s", field: value}) |
| 148 | + assert errs == [f"{rel}: {field}={value!r} must be an integer"] |
| 149 | + |
| 150 | + |
| 151 | +@pytest.mark.parametrize("rel,field", SAMPLES) |
| 152 | +@pytest.mark.parametrize("value", [12, 0, 65.0, None]) |
| 153 | +def test_integer_and_null_accepted(tmp_path, monkeypatch, rel, field, value) -> None: |
| 154 | + assert _integer_errors(tmp_path, monkeypatch, rel, {"slug": "s", field: value}) == [] |
| 155 | + |
| 156 | + |
| 157 | +def test_absent_field_accepted(tmp_path, monkeypatch) -> None: |
| 158 | + assert _integer_errors(tmp_path, monkeypatch, "cpu/acme/x1.json", {"slug": "s"}) == [] |
| 159 | + |
| 160 | + |
| 161 | +def test_float_typed_field_keeps_fractions(tmp_path, monkeypatch) -> None: |
| 162 | + rec = {"slug": "s", "ram_gb": 0.5, "weight_g": 180.5} |
| 163 | + assert _integer_errors(tmp_path, monkeypatch, "smartphone/acme/2020/p.json", rec) == [] |
| 164 | + assert _integer_errors(tmp_path, monkeypatch, "cpu/acme/x1.json", |
| 165 | + {"slug": "s", "base_clock_ghz": 3.5, "l3_cache_mb": 1.5}) == [] |
| 166 | + |
| 167 | + |
| 168 | +@pytest.mark.parametrize("value,ok", [ |
| 169 | + ([], True), ([64, 128], True), ([64.0], True), (None, True), |
| 170 | + ([64, 128.5], False), (["64"], False), ([True], False), (64, False), ("64", False), |
| 171 | +]) |
| 172 | +def test_integer_list(tmp_path, monkeypatch, value, ok) -> None: |
| 173 | + rel = "tablet/acme/2020/t/t.json" |
| 174 | + errs = _integer_errors(tmp_path, monkeypatch, rel, {"slug": "s", "storage_options_gb": value}) |
| 175 | + expected = [] if ok else [f"{rel}: storage_options_gb={value!r} must be a list of integers"] |
| 176 | + assert errs == expected |
| 177 | + |
| 178 | + |
| 179 | +def test_scoped_run_checks_changed_and_fk_records_only(tmp_path, monkeypatch) -> None: |
| 180 | + _put(tmp_path, "laptop/acme/2020/old.json", {"slug": "old", "ram_gb": 7.5}) |
| 181 | + _put(tmp_path, "cpu/acme/x1.json", {"slug": "x1", "tdp_w": 5.9}) |
| 182 | + rel = "laptop/acme/2020/new.json" |
| 183 | + errs = _integer_errors(tmp_path, monkeypatch, rel, {"slug": "new", "ram_gb": 15.5}, {rel}) |
| 184 | + # cpu is a foreign-key target, so a scoped run still reads all of it |
| 185 | + assert errs == [ |
| 186 | + "cpu/acme/x1.json: tdp_w=5.9 must be an integer", |
| 187 | + f"{rel}: ram_gb=15.5 must be an integer", |
| 188 | + ] |
| 189 | + assert len(_integer_errors(tmp_path, monkeypatch, rel, {"slug": "new"})) == 2 |
0 commit comments