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:
1 parent
30186d8cf2
commit
22bddcf202
55 files changed
+3198
-1
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user