from io import StringIO import httpx import pytest from asgiref.sync import async_to_sync from django.core.management import call_command from django.core.management.base import CommandError from assessments.providers.flood import FloodProvider from assessments.providers.noise import NoiseProvider from assessments.providers.radon import RadonProvider from assessments.services import find_threshold from factors.management.commands.seed_thresholds import DEFAULTS from factors.models import Factor, ThresholdClass from .conftest import AIRPORT, FLOOD, RADON, RAIL, ROAD, WAL_LOCATION, arcgis from .test_api_assessments import factors_by_code, post def seed_thresholds(*args): call_command("seed_thresholds", *args, stdout=StringIO()) def fetch(provider): async def run(): async with httpx.AsyncClient() as client: return await provider.fetch(client, WAL_LOCATION) return async_to_sync(run)() def threshold_of(code, region, source_value): return find_threshold(Factor.objects.get(code=code), region, source_value) # Commande ------------------------------------------------------------------------------ def test_creates_the_default_classes(seeded): seed_thresholds() assert ThresholdClass.objects.count() == len(DEFAULTS) for code in ("noise", "air", "flood", "radon"): assert ThresholdClass.objects.filter(factor__code=code).exists() def test_is_idempotent(seeded): seed_thresholds() seed_thresholds() assert ThresholdClass.objects.count() == len(DEFAULTS) def test_never_overwrites_a_class_edited_in_the_admin(seeded): seed_thresholds() edited = ThresholdClass.objects.get(factor__code="flood", source_value="Aléa moyen") edited.level, edited.color, edited.label = 4, "red", "Libellé validé par la SSMG" edited.save() seed_thresholds() edited.refresh_from_db() assert (edited.level, edited.color, edited.label) == (4, "red", "Libellé validé par la SSMG") def test_force_resets_existing_classes(seeded): seed_thresholds() edited = ThresholdClass.objects.get(factor__code="flood", source_value="Aléa moyen") edited.level, edited.color = 4, "red" edited.save() seed_thresholds("--force") edited.refresh_from_db() assert (edited.level, edited.color) == (3, "orange") def test_requires_the_factors(db): with pytest.raises(CommandError, match="seed_factors"): seed_thresholds() def test_levels_and_colors_are_consistent(seeded): seed_thresholds() for threshold in ThresholdClass.objects.all(): assert 1 <= threshold.level <= 4 assert threshold.color == {1: "green", 2: "yellow", 3: "orange", 4: "red"}[threshold.level] # Les valeurs renvoyées par les modules ont toutes une classe ------------------------------ NOISE_CLASSES = [ # (DB_LOW, DB_HIGHT, CLASSE réelle de la couche, niveau attendu) (50, 54, "moins de 55", 1), (55, 59, "de 55 à 59", 2), (60, 64, "de 60 à 64", 2), (65, 69, "de 65 à 69", 3), (70, 74, "de 70 à 74", 3), (75, 100, "plus de 75", 4), # route (75, 89, "plus de 75", 4), # rail ] @pytest.mark.parametrize(("low", "high", "label", "level"), NOISE_CLASSES) def test_every_noise_class_has_a_level(seeded, mock_http, low, high, label, level): seed_thresholds() mock_http.get(ROAD).respond(json=arcgis({"DB_LOW": low, "DB_HIGHT": high, "CLASSE": label})) mock_http.get(RAIL).respond(json=arcgis()) mock_http.get(AIRPORT).respond(json=arcgis()) raw = fetch(NoiseProvider()) assert threshold_of("noise", "WAL", raw.source_value).level == level def test_noise_without_exposure_has_a_level(seeded, mock_http): seed_thresholds() for url in (ROAD, RAIL, AIRPORT): mock_http.get(url).respond(json=arcgis()) assert threshold_of("noise", "WAL", fetch(NoiseProvider()).source_value).level == 1 @pytest.mark.parametrize( ("hazard", "code", "level"), [("Aléa faible", 10, 2), ("Aléa moyen", 20, 3), ("Aléa élevé", 30, 4)], ) def test_every_flood_hazard_has_a_level(seeded, mock_http, hazard, code, level): seed_thresholds() mock_http.get(FLOOD).respond( json=arcgis({"VALEUR": hazard, "CODEALEA": code, "TYPEALEA": "Débordement"}) ) assert threshold_of("flood", "WAL", fetch(FloodProvider()).source_value).level == level def test_flood_outside_hazard_zone_has_a_level(seeded, mock_http): seed_thresholds() mock_http.get(FLOOD).respond(json=arcgis()) assert threshold_of("flood", "WAL", fetch(FloodProvider()).source_value).level == 1 @pytest.mark.parametrize(("code", "level"), [(1, 1), (2, 2), (3, 2), (4, 3), (5, 4)]) def test_every_radon_class_has_a_level(seeded, mock_http, code, level): seed_thresholds() mock_http.get(RADON).respond(json=arcgis({"gridcode": code})) assert threshold_of("radon", "WAL", fetch(RadonProvider()).source_value).level == level @pytest.mark.parametrize(("exceedances", "level"), [("0", 1), ("1", 2), ("2", 3), ("3", 4)]) def test_every_air_count_has_a_level(seeded, exceedances, level): seed_thresholds() assert threshold_of("air", "WAL", exceedances).level == level # Réponse de l'API -------------------------------------------------------------------------- def test_api_returns_levels_and_colors_once_seeded(api, seeded, wallonia): seed_thresholds() factors = factors_by_code(post(api)) assert (factors["noise"]["level"], factors["noise"]["color"]) == (3, "orange") assert (factors["air"]["level"], factors["air"]["color"]) == (3, "orange") assert (factors["radon"]["level"], factors["radon"]["color"]) == (2, "yellow") # L'inondation est en panne dans la fixture : pas de niveau. assert factors["flood"]["status"] == "unavailable" assert factors["flood"]["level"] is None def test_api_has_no_level_without_classes(api, seeded, wallonia): """Cause de la remarque de Julien M. : sans classe de seuil, `level` vaut null.""" factors = factors_by_code(post(api)) assert factors["noise"]["status"] == "ok" assert factors["noise"]["level"] is None assert factors["noise"]["color"] is None