Initialise le back-end Django de la Phase 1

- Modèles : utilisateur (e-mail comme identifiant, statut, n° INAMI),
  traces d'e-mails, facteurs, sources, classes de seuil, contenus
  validés avec historique et références numérotées ; rôles par groupes.
- Modules de facteur appelés en parallèle (httpx) : bruit et inondation
  Wallonie via WalOnMap, qualité de l'air via irCELine ; Bruxelles et
  radon signalés indisponibles en attendant leurs sources.
- Géocodage Nominatim (Best Address à raccorder), région déduite du
  code postal ; aucune adresse stockée ni journalisée.
- API REST : POST /api/v1/assessments/, GET /api/v1/factors/,
  documentation OpenAPI sur /api/docs/.
- Docker Compose (Python 3.12, PostgreSQL 17, Mailpit), uv, ruff,
  pytest (66 tests, HTTP mocké avec respx), CLAUDE.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
boris.waaubandClaude Opus 5.5 committed 2026-11-24 10:40:58 +01:00
1 parent 30186d8cf2
commit 22bddcf202
55 files changed
+3198 -1

No files matched your search

View File
Whitespace-only changes.
+83
View File
@@ -0,0 +1,83 @@
import pytest
import respx
from django.core.management import call_command
from rest_framework.test import APIClient
from accounts.models import User
from assessments.geocoding import Location
WAL_LOCATION = Location(lat=50.668, lon=4.617, postal_code="1348", region="WAL")
BXL_LOCATION = Location(lat=50.846, lon=4.352, postal_code="1000", region="BXL")
NOMINATIM = "https://nominatim.openstreetmap.org/search"
IRCELINE = "https://geo.irceline.be/rio/wms"
WALONMAP = "https://geoservices.wallonie.be/arcgis/rest/services"
ROAD = f"{WALONMAP}/INDUSTRIES_SERVICES/BRUIT_MROAD_2017/MapServer/1/query"
RAIL = f"{WALONMAP}/INDUSTRIES_SERVICES/BRUIT_MRAIL_2017/MapServer/1/query"
AIRPORT = f"{WALONMAP}/INDUSTRIES_SERVICES/BRUIT_AEROPORTS/MapServer/1/query"
FLOOD = f"{WALONMAP}/EAU/ALEA_INOND/MapServer/2/query"
def arcgis(*attributes):
return {"features": [{"attributes": a} for a in attributes]}
def irceline(value):
features = [] if value is None else [{"properties": {"value": value}}]
return {"type": "FeatureCollection", "features": features}
def nominatim(postcode, lat="50.6696831", lon="4.6159504"):
return [{"lat": lat, "lon": lon, "address": {"postcode": postcode}}]
@pytest.fixture
def mock_http():
with respx.mock(assert_all_called=False) as router:
yield router
@pytest.fixture
def mock_irceline(mock_http):
"""irCELine : PM2,5 7,1 (> 5), PM10 12 (ok), NO2 27 (> 10), O3 50,1."""
values = {"pm25": 7.1, "pm10": 12.0, "no2": 27.0, "o3": 50.1}
def respond(request):
layer = request.url.params["LAYERS"].split("_")[0]
return respx.MockResponse(200, json=irceline(values[layer]))
mock_http.get(IRCELINE).mock(side_effect=respond)
return mock_http
@pytest.fixture
def seeded(db):
call_command("seed_factors", stdout=open("/dev/null", "w")) # noqa: SIM115
@pytest.fixture
def user(db):
return User.objects.create_user(
"medecin@exemple.be",
"un-mot-de-passe-solide",
first_name="Jean",
last_name="Dupont",
status=User.Status.ACTIVE,
)
@pytest.fixture
def api(user):
client = APIClient()
client.force_authenticate(user)
return client
@pytest.fixture(autouse=True)
def clear_cache():
"""Le compteur de limitation de débit de DRF est stocké dans le cache."""
from django.core.cache import cache
cache.clear()
yield
cache.clear()
+37
View File
@@ -0,0 +1,37 @@
import pytest
from django.contrib.auth.models import Group
from accounts.models import User
@pytest.mark.django_db
def test_only_active_accounts_can_log_in(client):
user = User.objects.create_user(
"Medecin@Exemple.be", "un-mot-de-passe-solide", first_name="A", last_name="B"
)
assert user.email == "medecin@exemple.be"
assert user.status == User.Status.EMAIL_PENDING
assert not client.login(email="medecin@exemple.be", password="un-mot-de-passe-solide")
user.status = User.Status.ACTIVE
user.save()
assert client.login(email="medecin@exemple.be", password="un-mot-de-passe-solide")
@pytest.mark.django_db
def test_superuser_is_active():
admin = User.objects.create_superuser("admin@exemple.be", "un-mot-de-passe-solide")
assert admin.is_active
@pytest.mark.django_db
def test_roles_exist():
assert set(Group.objects.values_list("name", flat=True)) >= {
"Médecin",
"Cellule SSMG",
"Admin",
}
def test_argon2_is_default(settings):
assert settings.PASSWORD_HASHERS[0].endswith("Argon2PasswordHasher")
+308
View File
@@ -0,0 +1,308 @@
"""POST /api/v1/assessments/"""
import logging
import pytest
from rest_framework.test import APIClient
from rest_framework.throttling import ScopedRateThrottle
from factors.models import ContentBlock, ContentReference, Factor, Reference, ThresholdClass
from .conftest import AIRPORT, FLOOD, IRCELINE, NOMINATIM, RAIL, ROAD, arcgis, irceline, nominatim
URL = "/api/v1/assessments/"
ADDRESS = "Place de l'Université 1, 1348 Louvain-la-Neuve"
pytestmark = pytest.mark.django_db
@pytest.fixture
def wallonia(mock_irceline):
"""Adresse wallonne : bruit 65-69 dB, air 2 dépassements, inondation en panne."""
mock_irceline.get(NOMINATIM).respond(json=nominatim("1348"))
mock_irceline.get(ROAD).respond(
json=arcgis({"DB_LOW": 65, "DB_HIGHT": 69, "CLASSE": "de 65 à 69"})
)
mock_irceline.get(RAIL).respond(json=arcgis())
mock_irceline.get(AIRPORT).respond(json=arcgis())
mock_irceline.get(FLOOD).respond(503)
return mock_irceline
@pytest.fixture
def brussels(mock_irceline):
mock_irceline.get(NOMINATIM).respond(json=nominatim("1000", lat="50.846", lon="4.352"))
return mock_irceline
def post(client, address=ADDRESS):
return client.post(URL, {"address": address}, format="json")
def factors_by_code(response):
return {f["code"]: f for f in response.json()["factors"]}
# Accès et validation de la requête ------------------------------------------------
def test_anonymous_is_rejected(seeded):
assert post(APIClient()).status_code == 403
def test_get_is_not_allowed(api, seeded):
assert api.get(URL).status_code == 405
@pytest.mark.parametrize(
"payload",
[{}, {"address": ""}, {"address": " "}, {"address": "x" * 301}, {"adresse": ADDRESS}],
ids=["vide", "chaine-vide", "espaces", "trop-longue", "mauvais-champ"],
)
def test_invalid_payload(api, seeded, payload):
response = api.post(URL, payload, format="json")
assert response.status_code == 400
assert "address" in response.json()
def test_geocoder_is_not_called_for_invalid_payload(api, seeded, mock_http):
route = mock_http.get(NOMINATIM)
api.post(URL, {"address": ""}, format="json")
assert not route.called
# Réponse ---------------------------------------------------------------------------
def test_response_shape(api, seeded, wallonia):
response = post(api)
assert response.status_code == 200
body = response.json()
assert set(body) == {"location", "factors"}
assert body["location"] == {"lat": 50.6696831, "lon": 4.6159504, "region": "WAL"}
for factor in body["factors"]:
assert set(factor) == {
"code",
"label",
"status",
"level",
"color",
"summary",
"details",
"tabs",
"references",
}
assert set(factor["tabs"]) == {"health_effects", "actions", "legend"}
assert set(factor["tabs"]["legend"]) == {"source", "text", "scale"}
def test_address_is_not_echoed(api, seeded, wallonia):
assert "Université" not in post(api).content.decode()
def test_factors_follow_admin_order(api, seeded, wallonia):
Factor.objects.filter(code="radon").update(order=0)
assert list(factors_by_code(post(api))) == ["radon", "noise", "air", "flood"]
def test_inactive_factor_is_omitted(api, seeded, wallonia):
Factor.objects.filter(code="air").update(active=False)
assert "air" not in factors_by_code(post(api))
def test_factor_without_module_is_unavailable(api, seeded, wallonia):
Factor.objects.create(code="soil", label="Pollution des sols", order=9)
assert factors_by_code(post(api))["soil"]["status"] == "unavailable"
def test_failing_source_does_not_block_others(api, seeded, wallonia):
factors = factors_by_code(post(api))
assert factors["flood"]["status"] == "unavailable"
assert factors["flood"]["level"] is None
assert factors["noise"]["status"] == "ok"
assert factors["air"]["status"] == "ok"
def test_no_data(api, seeded, wallonia):
wallonia.get(IRCELINE).respond(json=irceline(None))
assert factors_by_code(post(api))["air"]["status"] == "no_data"
def test_brussels_sources_not_connected(api, seeded, brussels):
response = post(api, "Rue de la Loi 16, 1000 Bruxelles")
factors = factors_by_code(response)
assert response.json()["location"]["region"] == "BXL"
assert factors["noise"]["status"] == "unavailable"
assert factors["flood"]["status"] == "unavailable"
assert factors["air"]["status"] == "ok"
# Seuils et contenus ---------------------------------------------------------------
def test_without_threshold_raw_summary_is_returned(api, seeded, wallonia):
noise = factors_by_code(post(api))["noise"]
assert noise["level"] is None
assert noise["color"] is None
assert noise["summary"] == "Lden de 65 à 69 dB(A)"
def test_threshold_sets_level_color_and_label(api, seeded, wallonia):
ThresholdClass.objects.create(
factor=Factor.objects.get(code="noise"),
region="WAL",
source_value="65-69",
label="65–69 dB",
level=3,
color="orange",
)
noise = factors_by_code(post(api))["noise"]
assert (noise["level"], noise["color"], noise["summary"]) == (3, "orange", "65–69 dB")
def test_threshold_of_other_region_is_ignored(api, seeded, wallonia):
ThresholdClass.objects.create(
factor=Factor.objects.get(code="noise"),
region="BXL",
source_value="65-69",
level=3,
color="orange",
)
assert factors_by_code(post(api))["noise"]["level"] is None
def test_regional_threshold_wins_over_national(api, seeded, wallonia):
air = Factor.objects.get(code="air")
ThresholdClass.objects.create(
factor=air, region="BE", source_value="2", level=3, color="orange"
)
ThresholdClass.objects.create(factor=air, region="WAL", source_value="2", level=4, color="red")
assert factors_by_code(post(api))["air"]["level"] == 4
def test_national_threshold_as_fallback(api, seeded, wallonia):
air = Factor.objects.get(code="air")
ThresholdClass.objects.create(
factor=air, region="BE", source_value="2", level=3, color="orange"
)
assert factors_by_code(post(api))["air"]["color"] == "orange"
def test_class_specific_validated_content(api, seeded, wallonia):
noise = Factor.objects.get(code="noise")
orange = ThresholdClass.objects.create(
factor=noise, region="WAL", source_value="65-69", level=3, color="orange"
)
ContentBlock.objects.create(
factor=noise, actions="Commun", status=ContentBlock.Status.VALIDATED
)
content = ContentBlock.objects.create(
factor=noise,
threshold_class=orange,
health_effects="Troubles du sommeil¹ ².",
actions="Isolation acoustique.",
legend_text="Lden, cartographie 2017.",
status=ContentBlock.Status.VALIDATED,
)
ContentReference.objects.create(
content=content, reference=Reference.objects.create(title="OMS 2018"), order=1
)
ContentReference.objects.create(
content=content,
reference=Reference.objects.create(title="EEA 2020", url="https://eea.europa.eu"),
order=2,
)
noise_result = factors_by_code(post(api))["noise"]
assert noise_result["tabs"]["health_effects"] == "Troubles du sommeil¹ ²."
assert noise_result["tabs"]["actions"] == "Isolation acoustique."
assert noise_result["tabs"]["legend"]["text"] == "Lden, cartographie 2017."
assert noise_result["references"] == [
{"n": 1, "title": "OMS 2018", "url": ""},
{"n": 2, "title": "EEA 2020", "url": "https://eea.europa.eu"},
]
def test_common_content_as_fallback(api, seeded, wallonia):
ContentBlock.objects.create(
factor=Factor.objects.get(code="noise"),
actions="Commun",
status=ContentBlock.Status.VALIDATED,
)
assert factors_by_code(post(api))["noise"]["tabs"]["actions"] == "Commun"
def test_draft_content_is_hidden(api, seeded, wallonia):
ContentBlock.objects.create(factor=Factor.objects.get(code="noise"), actions="Brouillon")
noise = factors_by_code(post(api))["noise"]
assert noise["tabs"]["actions"] == ""
assert noise["references"] == []
def test_legend_lists_sources_and_scale(api, seeded, wallonia):
noise = Factor.objects.get(code="noise")
ThresholdClass.objects.create(
factor=noise, region="WAL", source_value="aucune", level=1, color="green"
)
ThresholdClass.objects.create(
factor=noise, region="WAL", source_value="65-69", label="65–69 dB", level=3, color="orange"
)
legend = factors_by_code(post(api))["noise"]["tabs"]["legend"]
assert legend["source"] == "WalOnMap"
assert legend["scale"] == [
{"level": 1, "color": "green", "label": "aucune"},
{"level": 3, "color": "orange", "label": "65–69 dB"},
]
# Erreurs globales -----------------------------------------------------------------
def test_unknown_address(api, seeded, mock_http):
mock_http.get(NOMINATIM).respond(json=[])
response = post(api, "nulle part")
assert response.status_code == 404
assert response.json() == {"code": "address_not_found", "detail": "Adresse introuvable."}
def test_out_of_coverage(api, seeded, mock_http):
mock_http.get(NOMINATIM).respond(json=nominatim("9000"))
response = post(api, "Korenmarkt 1, 9000 Gent")
assert response.status_code == 422
assert response.json()["code"] == "out_of_coverage"
def test_geocoding_unavailable(api, seeded, mock_http):
mock_http.get(NOMINATIM).respond(500)
response = post(api)
assert response.status_code == 503
assert response.json()["code"] == "geocoding_unavailable"
def test_factor_sources_not_called_when_address_unknown(api, seeded, mock_http):
mock_http.get(NOMINATIM).respond(json=[])
road = mock_http.get(ROAD)
post(api, "nulle part")
assert not road.called
# Limitation de débit et confidentialité -------------------------------------------
def test_throttling(api, seeded, wallonia, monkeypatch):
monkeypatch.setattr(ScopedRateThrottle, "THROTTLE_RATES", {"assessments": "2/hour"})
assert post(api).status_code == 200
assert post(api).status_code == 200
assert post(api).status_code == 429
def test_address_is_not_logged(api, seeded, wallonia, caplog):
with caplog.at_level(logging.DEBUG):
post(api)
logs = caplog.text
assert "Université" not in logs
assert "1348" not in logs
assert "50.66" not in logs
assert "Facteur flood indisponible (HTTPStatusError)" in logs
+77
View File
@@ -0,0 +1,77 @@
"""GET /api/v1/factors/"""
import pytest
from rest_framework.test import APIClient
from factors.models import Factor, ThresholdClass
URL = "/api/v1/factors/"
pytestmark = pytest.mark.django_db
def test_anonymous_is_rejected(seeded):
assert APIClient().get(URL).status_code == 403
def test_post_is_not_allowed(api, seeded):
assert api.post(URL, {}, format="json").status_code == 405
def test_empty_without_factors(api):
response = api.get(URL)
assert response.status_code == 200
assert response.json() == []
def test_lists_active_factors_in_order(api, seeded):
Factor.objects.filter(code="radon").update(active=False)
Factor.objects.filter(code="flood").update(order=0)
body = api.get(URL).json()
assert [(f["code"], f["label"]) for f in body] == [
("flood", "Risque d'inondation"),
("noise", "Pollution sonore"),
("air", "Qualité de l'air"),
]
def test_legends_per_region(api, seeded):
noise = Factor.objects.get(code="noise")
ThresholdClass.objects.create(
factor=noise, region="WAL", source_value="65-69", label="65–69 dB", level=3, color="orange"
)
ThresholdClass.objects.create(
factor=noise, region="WAL", source_value="aucune", level=1, color="green"
)
ThresholdClass.objects.create(
factor=noise, region="BXL", source_value="Classe 8", level=4, color="red"
)
legends = {f["code"]: f["legends"] for f in api.get(URL).json()}["noise"]
assert set(legends) == {"WAL", "BXL"}
assert legends["WAL"]["source"] == "WalOnMap"
assert legends["WAL"]["scale"] == [
{"level": 1, "color": "green", "label": "aucune"},
{"level": 3, "color": "orange", "label": "65–69 dB"},
]
assert legends["BXL"]["source"] == "Bruxelles Environnement"
assert legends["BXL"]["scale"] == [{"level": 4, "color": "red", "label": "Classe 8"}]
def test_national_classes_appear_in_both_regions(api, seeded):
ThresholdClass.objects.create(
factor=Factor.objects.get(code="air"), region="BE", source_value="0", level=1, color="green"
)
legends = {f["code"]: f["legends"] for f in api.get(URL).json()}["air"]
assert legends["WAL"]["source"] == legends["BXL"]["source"] == "irCELine"
assert (
legends["WAL"]["scale"]
== legends["BXL"]["scale"]
== [{"level": 1, "color": "green", "label": "0"}]
)
def test_does_not_call_external_services(api, seeded, mock_http):
api.get(URL)
assert not mock_http.calls
+29
View File
@@ -0,0 +1,29 @@
"""GET /api/schema/ et /api/docs/"""
import pytest
from rest_framework.test import APIClient
pytestmark = pytest.mark.django_db
def test_schema_is_public():
response = APIClient().get("/api/schema/", HTTP_ACCEPT="application/vnd.oai.openapi+json")
assert response.status_code == 200
schema = response.json()
assert schema["info"]["title"] == "PRISM API"
def test_schema_documents_every_route():
schema = APIClient().get("/api/schema/?format=json").json()
paths = schema["paths"]
assert set(paths) == {"/api/v1/assessments/", "/api/v1/factors/"}
assessments = paths["/api/v1/assessments/"]["post"]
assert set(assessments["responses"]) == {"200", "404", "422", "503"}
assert "requestBody" in assessments
assert "get" in paths["/api/v1/factors/"]
def test_docs_page():
response = APIClient().get("/api/docs/")
assert response.status_code == 200
assert b"swagger" in response.content.lower()
+53
View File
@@ -0,0 +1,53 @@
import httpx
import pytest
from assessments.geocoding import AddressNotFound, GeocodingError, OutOfCoverage, geocode
from assessments.geocoding.base import region_from_postal_code
from .conftest import NOMINATIM, nominatim
@pytest.mark.parametrize(
("postal_code", "region"),
[
("1000", "BXL"),
("1210", "BXL"),
("1348", "WAL"),
("4000", "WAL"),
("7999", "WAL"),
("2000", None),
("9000", None),
("", None),
],
)
def test_region_from_postal_code(postal_code, region):
assert region_from_postal_code(postal_code) == region
async def test_geocode_wallonia(mock_http):
mock_http.get(NOMINATIM).respond(json=nominatim("1348"))
async with httpx.AsyncClient() as client:
location = await geocode(client, "Place de l'Université 1, 1348 Louvain-la-Neuve")
assert location.region == "WAL"
assert location.lat == pytest.approx(50.6697)
async def test_geocode_not_found(mock_http):
mock_http.get(NOMINATIM).respond(json=[])
async with httpx.AsyncClient() as client:
with pytest.raises(AddressNotFound):
await geocode(client, "rue inexistante")
async def test_geocode_flanders_is_out_of_coverage(mock_http):
mock_http.get(NOMINATIM).respond(json=nominatim("9000"))
async with httpx.AsyncClient() as client:
with pytest.raises(OutOfCoverage):
await geocode(client, "Korenmarkt 1, 9000 Gent")
async def test_geocode_service_down(mock_http):
mock_http.get(NOMINATIM).respond(503)
async with httpx.AsyncClient() as client:
with pytest.raises(GeocodingError):
await geocode(client, "Place de l'Université 1, 1348 Louvain-la-Neuve")
+96
View File
@@ -0,0 +1,96 @@
import httpx
import pytest
from assessments.providers.air import AirProvider
from assessments.providers.base import SourceUnavailable
from assessments.providers.flood import FloodProvider
from assessments.providers.noise import NoiseProvider
from assessments.providers.radon import RadonProvider
from .conftest import AIRPORT, BXL_LOCATION, FLOOD, RAIL, ROAD, WAL_LOCATION, arcgis
async def fetch(provider, location=WAL_LOCATION):
async with httpx.AsyncClient() as client:
return await provider.fetch(client, location)
async def test_noise_takes_loudest_source(mock_http):
mock_http.get(ROAD).respond(
json=arcgis(
{"DB_LOW": 55, "DB_HIGHT": 59, "CLASSE": "de 55 à 59"},
{"DB_LOW": 65, "DB_HIGHT": 69, "CLASSE": "de 65 à 69"},
)
)
mock_http.get(RAIL).respond(json=arcgis({"DB_LOW": 60, "DB_HIGHT": 64, "CLASSE": "de 60 à 64"}))
mock_http.get(AIRPORT).respond(json=arcgis())
result = await fetch(NoiseProvider())
assert result.status == "ok"
assert result.source_value == "65-69"
assert result.details[0] == {"label": "Route", "value": "de 65 à 69 dB(A)"}
assert result.details[2]["value"] == "aucune exposition détectée"
async def test_noise_without_exposure(mock_http):
for url in (ROAD, RAIL, AIRPORT):
mock_http.get(url).respond(json=arcgis())
result = await fetch(NoiseProvider())
assert (result.status, result.source_value) == ("ok", "aucune")
async def test_noise_arcgis_error_raises(mock_http):
mock_http.get(ROAD).respond(json={"error": {"code": 400}})
mock_http.get(RAIL).respond(json=arcgis())
mock_http.get(AIRPORT).respond(json=arcgis())
with pytest.raises(SourceUnavailable):
await fetch(NoiseProvider())
async def test_noise_brussels_not_connected():
with pytest.raises(SourceUnavailable):
await fetch(NoiseProvider(), BXL_LOCATION)
async def test_air_counts_who_exceedances(mock_irceline):
result = await fetch(AirProvider())
assert result.status == "ok"
assert result.source_value == "2"
assert result.summary == "2 dépassements des valeurs OMS"
assert result.details[0] == {
"label": "PM2,5",
"value": "7,1 µg/m³ (valeur guide OMS 5 : dépassée)",
}
assert result.details[3] == {"label": "O3", "value": "50,1 µg/m³"}
async def test_air_wms_exception_raises(mock_http):
from .conftest import IRCELINE
mock_http.get(IRCELINE).respond(200, text="<ServiceExceptionReport/>")
with pytest.raises(SourceUnavailable):
await fetch(AirProvider())
async def test_flood_takes_highest_hazard(mock_http):
mock_http.get(FLOOD).respond(
json=arcgis(
{"VALEUR": "Aléa faible", "CODEALEA": 10, "TYPEALEA": "Ruissellement"},
{"VALEUR": "Aléa élevé", "CODEALEA": 30, "TYPEALEA": "Débordement"},
)
)
result = await fetch(FloodProvider())
assert result.source_value == "Aléa élevé"
assert result.details[0] == {"label": "Débordement", "value": "Aléa élevé"}
async def test_flood_outside_hazard_zone(mock_http):
mock_http.get(FLOOD).respond(json=arcgis())
result = await fetch(FloodProvider())
assert (result.status, result.source_value) == ("ok", "aucun")
async def test_radon_not_connected():
with pytest.raises(SourceUnavailable):
await fetch(RadonProvider())