fix(recovery): restore source removed by production documentation merge

This commit is contained in:
2026-11-10 03:42:10 +01:00
parent 585bdd4b44
commit 3d2fc6f913
957 changed files with 115754 additions and 0 deletions
@@ -0,0 +1,77 @@
"""
P014: adaptive_router.py previously had ZERO test coverage and a docstring
("all methods, no compliance restrictions. See b0ts for scraping") that
directly contradicted this product's own compliance stance and pointed at a
forbidden, separate, non-compliant repo. This file tests the corrected
version: plan_for_market's static per-market plan, and the new block-
tracking (record_blocked/is_blocked/cooldown) that makes the engine actually
back off a source that just told it to stop, instead of retrying it with no
memory at all.
"""
from __future__ import annotations
from workers.adaptive_router import AdaptiveRouter, MARKET_SOURCES, plan_for_market
class TestPlanForMarket:
def test_returns_the_full_static_plan_when_nothing_is_blocked(self):
router = AdaptiveRouter()
assert plan_for_market("GB", router=router) == MARKET_SOURCES["GB"]
def test_unknown_market_falls_back_to_gleif_only(self):
router = AdaptiveRouter()
assert plan_for_market("ZZ", router=router) == ["gleif"]
def test_defaults_to_the_process_wide_router_when_none_is_passed(self):
# Just proves the call doesn't blow up and returns a real plan --
# not asserting anything about global state here (other tests use
# their own injected router precisely to avoid cross-test pollution
# of the shared default_router).
assert plan_for_market("FI") == MARKET_SOURCES["FI"]
class TestBlockTracking:
def test_a_freshly_blocked_source_is_excluded_from_the_plan(self):
router = AdaptiveRouter()
router.record_blocked("GB", "companies_house")
plan = plan_for_market("GB", router=router)
assert "companies_house" not in plan
assert "gleif" in plan # only the blocked source is removed, not the whole market
def test_is_blocked_is_false_before_any_block_is_recorded(self):
router = AdaptiveRouter()
assert router.is_blocked("GB", "companies_house") is False
def test_blocking_is_scoped_per_market_not_global_to_the_source_id(self):
# gleif appears in every market's plan -- blocking it for GB must not
# silently remove it from FI/SE/etc too.
router = AdaptiveRouter()
router.record_blocked("GB", "gleif")
assert "gleif" not in plan_for_market("GB", router=router)
assert "gleif" in plan_for_market("FI", router=router)
assert "gleif" in plan_for_market("SE", router=router)
def test_cooldown_expires_and_the_source_becomes_eligible_again(self):
router = AdaptiveRouter(cooldown_seconds=60.0)
router.record_blocked("GB", "companies_house", now=1000.0)
assert router.is_blocked("GB", "companies_house", now=1030.0) is True # still within cooldown
assert router.is_blocked("GB", "companies_house", now=1061.0) is False # cooldown elapsed
# And the plan reflects that:
assert "companies_house" in plan_for_market("GB", router=router)
def test_clear_forgets_every_recorded_block(self):
router = AdaptiveRouter()
router.record_blocked("GB", "companies_house")
router.record_blocked("NO", "brreg")
router.clear()
assert plan_for_market("GB", router=router) == MARKET_SOURCES["GB"]
assert plan_for_market("NO", router=router) == MARKET_SOURCES["NO"]
def test_two_router_instances_never_share_state(self):
# Regression guard for a shared-mutable-default bug class: each
# AdaptiveRouter() must own its own dict, not a class-level one.
a = AdaptiveRouter()
b = AdaptiveRouter()
a.record_blocked("GB", "companies_house")
assert a.is_blocked("GB", "companies_house") is True
assert b.is_blocked("GB", "companies_house") is False
@@ -0,0 +1,104 @@
"""
P014: every connector used by pipeline.py's adaptive plan (gleif, brreg,
companies_house, prh, cvr) used to collapse EVERY non-200 response into a
bare `None`, indistinguishable from "record genuinely doesn't exist". This
tests that the block-status subset (401/403/429/451) now raises
SourceBlockedError instead, while every other non-200 status (404, 500, ...)
still returns None exactly as before -- this is an ADDITIVE signal, not a
behavior change for the non-block case.
"""
from __future__ import annotations
import httpx
import pytest
import respx
from sources.connectors import (
SourceBlockedError,
brreg_by_orgnr,
companies_house_by_number,
cvr_by_number,
gleif_by_lei,
prh_by_businessid,
)
GLEIF_URL = "https://api.gleif.org/api/v1/lei-records/5493001KJTIIGC8Y1R12"
BRREG_URL = "https://data.brreg.no/enhetsregisteret/api/enheter/923609016"
COMPANIES_HOUSE_URL = "https://api.company-information.service.gov.uk/company/00000006"
PRH_URL = "https://avoindata.prh.fi/opendata-ytj-api/v3/companies?businessId=2077474-0"
CVR_URL = "https://cvrapi.dk/api?search=10150817&country=dk"
@pytest.mark.asyncio
@respx.mock
@pytest.mark.parametrize("status", [401, 403, 429, 451])
async def test_gleif_raises_source_blocked_on_block_statuses(status):
respx.get(GLEIF_URL).mock(return_value=httpx.Response(status, json={}))
with pytest.raises(SourceBlockedError) as exc_info:
await gleif_by_lei("5493001KJTIIGC8Y1R12")
assert exc_info.value.source_id == "gleif"
assert exc_info.value.status_code == status
@pytest.mark.asyncio
@respx.mock
async def test_gleif_a_404_still_returns_none_not_blocked(monkeypatch):
respx.get(GLEIF_URL).mock(return_value=httpx.Response(404, json={}))
result = await gleif_by_lei("5493001KJTIIGC8Y1R12")
assert result is None # unchanged pre-P014 behavior for a genuine "not found"
@pytest.mark.asyncio
@respx.mock
async def test_brreg_raises_source_blocked_on_429():
respx.get(BRREG_URL).mock(return_value=httpx.Response(429, json={}))
with pytest.raises(SourceBlockedError) as exc_info:
await brreg_by_orgnr("923609016")
assert exc_info.value.source_id == "brreg"
@pytest.mark.asyncio
@respx.mock
async def test_companies_house_raises_source_blocked_on_403(monkeypatch):
monkeypatch.setenv("COMPANIES_HOUSE_API_KEY", "test-key")
respx.get(COMPANIES_HOUSE_URL).mock(return_value=httpx.Response(403, json={}))
with pytest.raises(SourceBlockedError) as exc_info:
await companies_house_by_number("00000006")
assert exc_info.value.source_id == "companies_house"
@pytest.mark.asyncio
async def test_companies_house_missing_key_still_delivers_honest_level_0_not_a_block():
# No COMPANIES_HOUSE_API_KEY set -- this is a config gap, not a source
# block, and must keep returning the honest "unavailable" result it
# already did (never raise SourceBlockedError for a problem on OUR side).
result = await companies_house_by_number("00000006")
assert result is not None
assert result.provenance[0].level == 0
assert result.provenance[0].transform == "unavailable_no_key"
@pytest.mark.asyncio
@respx.mock
async def test_prh_raises_source_blocked_on_401():
respx.get(PRH_URL).mock(return_value=httpx.Response(401, json={}))
with pytest.raises(SourceBlockedError) as exc_info:
await prh_by_businessid("2077474-0")
assert exc_info.value.source_id == "prh"
@pytest.mark.asyncio
@respx.mock
async def test_cvr_raises_source_blocked_on_451():
respx.get(CVR_URL).mock(return_value=httpx.Response(451, json={}))
with pytest.raises(SourceBlockedError) as exc_info:
await cvr_by_number("10150817")
assert exc_info.value.source_id == "cvr"
@pytest.mark.asyncio
@respx.mock
async def test_cvr_a_500_still_returns_none_not_blocked():
respx.get(CVR_URL).mock(return_value=httpx.Response(500, json={}))
result = await cvr_by_number("10150817")
assert result is None
@@ -0,0 +1,58 @@
"""
Verifies the P010 provenance additions (BEFORE_STATE.md §3: source,
retrieval timestamp, transform, version, producer were absent from the real
dataflow) land correctly on every real connector's output — mocked HTTP,
real parsing code.
"""
from __future__ import annotations
import httpx
import pytest
import respx
from sources.connectors import brreg_by_orgnr, make_provenance, CONNECTOR_VERSIONS
class TestMakeProvenanceFactory:
def test_populates_all_new_fields_honestly_and_leaves_the_rest_none(self):
p = make_provenance("name", "brreg", 0.97, 3)
assert p.field_name == "name"
assert p.source_id == "brreg"
assert p.retrieved_at is not None
assert p.freshness == p.retrieved_at[:10] # date prefix of the same instant
assert p.transform == "raw_fetch"
assert p.connector_version == CONNECTOR_VERSIONS["brreg"]
assert p.producer == "0pt-engine"
# Never guessed — these are filled by later pipeline stages, not at fetch time.
assert p.quality is None
assert p.entity_resolution is None
assert p.artifact_ref is None
def test_transform_override_is_honored(self):
p = make_provenance("name", "companies_house", 0.0, 0, transform="unavailable_no_key")
assert p.transform == "unavailable_no_key"
def test_unknown_source_id_has_no_fabricated_version(self):
p = make_provenance("x", "some_future_source", 0.5, 1)
assert p.connector_version is None # honestly unknown, not guessed
class TestBrregConnectorProvenance:
@pytest.mark.asyncio
@respx.mock
async def test_real_parsing_path_produces_fully_populated_provenance(self):
respx.get("https://data.brreg.no/enhetsregisteret/api/enheter/923609016").mock(
return_value=httpx.Response(200, json={
"navn": "Volvo Personvagnar Norge AS", "konkurs": False,
"forretningsadresse": {"adresse": ["Storgata 1"]},
})
)
res = await brreg_by_orgnr("923609016")
assert res is not None
assert len(res.provenance) == 3 # name, status, address
for p in res.provenance:
assert p.source_id == "brreg"
assert p.connector_version == "brreg-connector@1"
assert p.producer == "0pt-engine"
assert p.retrieved_at is not None
assert p.transform == "raw_fetch"
@@ -0,0 +1,93 @@
from workers.entity_resolution import (
EntityCandidate,
ResolutionDecision,
rank_resolution_candidates,
resolve_entity_pair,
)
def organization(entity_id: str, **overrides):
values = {
"entity_id": entity_id,
"entity_type": "organization",
"name": "Example Technology AB",
"source_ref": f"source:{entity_id}",
"registration_country": "SE",
"registration_number": None,
"website": None,
"city": "Stockholm",
}
values.update(overrides)
return EntityCandidate(**values)
def person(entity_id: str, **overrides):
values = {
"entity_id": entity_id,
"entity_type": "person",
"name": "Anna Andersson",
"source_ref": f"source:{entity_id}",
"email": None,
"organization_id": None,
}
values.update(overrides)
return EntityCandidate(**values)
def test_registration_number_is_a_strong_organization_identifier():
result = resolve_entity_pair(
organization("left", registration_number="556123-4567"),
organization("right", registration_number="5561234567"),
)
assert result.decision is ResolutionDecision.EXACT_LINK
assert result.score == 1.0
assert result.requires_human_review is False
def test_conflicting_registration_numbers_fail_distinct_even_when_names_match():
result = resolve_entity_pair(
organization("left", registration_number="5561234567"),
organization("right", registration_number="5569999999"),
)
assert result.decision is ResolutionDecision.DISTINCT
assert result.score == 0.0
def test_same_person_email_is_exact_link():
result = resolve_entity_pair(
person("left", email="Anna@example.com"),
person("right", email=" anna@EXAMPLE.com "),
)
assert result.decision is ResolutionDecision.EXACT_LINK
assert result.requires_human_review is False
def test_fuzzy_organization_similarity_never_auto_merges():
result = resolve_entity_pair(
organization("left", name="Example Technology AB", website="example.se"),
organization("right", name="Example Technologies AB", website="https://www.example.se"),
)
assert result.score > 0.72
assert result.decision is ResolutionDecision.REVIEW
assert result.requires_human_review is True
def test_different_entity_types_are_distinct():
result = resolve_entity_pair(
organization("org"),
person("person"),
)
assert result.decision is ResolutionDecision.DISTINCT
def test_candidate_ranking_prefers_exact_then_review_and_is_stable():
query = organization("query", registration_number="5561234567", website="example.se")
candidates = [
organization("weak", name="Completely Different Company", registration_country="NO", city="Oslo"),
organization("review", name="Example Technologies AB", website="example.se"),
organization("exact", registration_number="556123-4567"),
]
ranked = rank_resolution_candidates(query, candidates)
assert [result.right_id for result in ranked] == ["exact", "review", "weak"]
assert ranked[0].decision is ResolutionDecision.EXACT_LINK
assert ranked[1].decision is ResolutionDecision.REVIEW
@@ -0,0 +1,70 @@
"""The engine must not accept anonymous traffic when INTERNAL_TOKEN is set.
Background (2026-09-15): lib/engine.ts on the edge has always SENT
`X-Internal-Token`, but the engine never verified it — a deployed engine would
have accepted anyone who could reach the port. The gate is fail-closed:
* INTERNAL_TOKEN set -> every route except /health requires the EXACT
token; wrong/missing = 401.
* INTERNAL_TOKEN unset -> gate inert (local dev); production compose always
sets it.
`/health` stays public on purpose: it is the liveness probe that
`lib/health-checks.ts` calls from the edge, and it leaks nothing but booleans.
The token is read at module import (the same value the running process serves
with), so each test reloads the module with the env it wants — and the
teardown reloads it one more time with the env CLEARED so later test files in
the same session never inherit a baked-in token.
"""
from __future__ import annotations
import importlib
import os
import pytest
from fastapi.testclient import TestClient
@pytest.fixture()
def engine(monkeypatch):
monkeypatch.setenv("INTERNAL_TOKEN", "s3cret")
import orchestrator.main as main
importlib.reload(main)
yield TestClient(main.app)
os.environ.pop("INTERNAL_TOKEN", None)
importlib.reload(main)
@pytest.fixture()
def engine_no_token(monkeypatch):
monkeypatch.delenv("INTERNAL_TOKEN", raising=False)
import orchestrator.main as main
importlib.reload(main)
yield TestClient(main.app)
os.environ.pop("INTERNAL_TOKEN", None)
importlib.reload(main)
def test_gate_off_when_internal_token_unset(engine_no_token):
assert engine_no_token.get("/health").status_code == 200
assert engine_no_token.get("/sources").status_code == 200
def test_health_stays_public_but_sources_require_token(engine):
# liveness probe is public by design
assert engine.get("/health").status_code == 200
# anonymous call to a data route -> 401 (was 200 before 2026-09-15)
r = engine.get("/sources")
assert r.status_code == 401
assert r.json()["error"]["code"] == "unauthorized"
def test_wrong_token_is_401_and_correct_token_passes(engine):
wrong = engine.get("/estimates?markets=SE", headers={"X-Internal-Token": "nope"})
assert wrong.status_code == 401
right = engine.get("/sources", headers={"X-Internal-Token": "s3cret"})
assert right.status_code == 200
+53
View File
@@ -0,0 +1,53 @@
"""
Honest documentation of two of the seven requested failure-test categories
that are NOT implemented as real fault-injection tests in this pass, and
why — matching this repo's established convention of stating a gap in code
(BEFORE_STATE.md, docs/P0_DATASET_QUALITY_FLOW.md) rather than silently
dropping it or faking coverage. These are `pytest.skip` markers, not
disguised passes, so they show up in the test report as explicitly
unaddressed rather than vanishing from view.
* CDC-interruption: this repo has NO change-data-capture pipeline
anywhere — no Debezium/WAL-slot consumer, no CDC producer, no
replication-slot code, confirmed by a full-repo search
(`grep -rn "debezium\\|wal_level\\|replication.slot\\|cdc" services/ src/`
finds nothing on this topic). A "CDC-interruption" fault-injection
test needs a CDC stream to interrupt; fabricating one to have
something to test would be building fictional infrastructure and
testing the fiction, not this codebase — the exact failure mode this
project's CLAUDE.md and BEFORE_STATE.md explicitly warn against
("never fabricate").
* True backfill idempotency (dedup against a delivery store): the
pipeline has no persistence layer at all (see workers/pipeline.py —
every run_job() call recomputes from scratch, nothing is written to a
database). "Backfill doesn't create duplicate deliveries" requires a
delivery store to check duplicates against, which doesn't exist.
test_pipeline_fault_injection.py::TestBackfillReplay covers the
narrower, real property that DOES hold today (replaying an identical
order config is compute-idempotent — byte-identical output, no drift)
and documents this exact distinction inline.
"""
import pytest
@pytest.mark.skip(
reason=(
"No CDC pipeline exists anywhere in this repo (verified by full-repo "
"search) — nothing to interrupt without inventing fictional "
"infrastructure. See this file's module docstring."
)
)
def test_cdc_interruption_not_implementable_against_real_code():
pass
@pytest.mark.skip(
reason=(
"No delivery-store persistence layer exists to dedupe a backfill "
"against — the compute-idempotency property that DOES exist is "
"covered for real in test_pipeline_fault_injection.py::"
"TestBackfillReplay. See this file's module docstring."
)
)
def test_true_backfill_idempotency_not_implementable_against_real_code():
pass
@@ -0,0 +1,112 @@
"""
P014: services/api/orchestrator/main.py had ZERO test coverage before this
pass, and `POST /orders/{oid}/run` had no idempotency protection at all --
calling it twice for the same order re-ran the full compliant sourcing
pipeline a second time, silently overwriting `_JOBS[oid]` with a second,
independently-produced delivery. This is the actual "duplicate delivery"
gap P014's recon flagged NOT MET (nothing downstream of order creation was
idempotent). These tests exercise the real ASGI app end to end (httpx
ASGITransport, no mocked HTTP layer) and prove: a sequential retry returns
the cached job without re-running the pipeline, a TRUE CONCURRENT race
(two requests in flight at once) is also closed by the per-order asyncio
lock, and an unknown order still 404s exactly as before.
"""
from __future__ import annotations
import asyncio
import httpx
import pytest
from orchestrator.main import app
def _fake_job_result(calls: list[str], order_id: str) -> dict:
calls.append(order_id)
return {
"stage": "qa",
"pct": 100,
"state": "done",
"metrics": {"rows": 1, "dropped_below_threshold": 0, "per_market": {"NO": 1}, "avg_confidence": 0.95},
"records": [{"market": "NO", "name": "Test AS", "confidence": 0.95}],
}
@pytest.mark.asyncio
async def test_sequential_retry_returns_cached_job_without_rerunning_pipeline(monkeypatch):
calls: list[str] = []
async def fake_run_job(order_id: str, config: dict) -> dict:
return _fake_job_result(calls, order_id)
monkeypatch.setattr("orchestrator.main.run_job", fake_run_job)
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
created = await client.post("/orders", json={"flow": "custom", "config": {"markets": ["NO"]}})
oid = created.json()["order_id"]
r1 = await client.post(f"/orders/{oid}/run")
r2 = await client.post(f"/orders/{oid}/run")
r3 = await client.post(f"/orders/{oid}/run")
assert r1.status_code == 200
assert r1.json() == r2.json() == r3.json()
assert calls == [oid] # run_job invoked exactly once across three /run calls
@pytest.mark.asyncio
async def test_true_concurrent_race_still_invokes_run_job_exactly_once(monkeypatch):
calls: list[str] = []
async def fake_run_job(order_id: str, config: dict) -> dict:
# Widen the race window: both requests reach this await before
# either has written to _JOBS, which is exactly the race a bare
# `if oid in _JOBS` check (no lock) would lose.
await asyncio.sleep(0.05)
return _fake_job_result(calls, order_id)
monkeypatch.setattr("orchestrator.main.run_job", fake_run_job)
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
created = await client.post("/orders", json={"flow": "custom", "config": {"markets": ["NO"]}})
oid = created.json()["order_id"]
r1, r2 = await asyncio.gather(
client.post(f"/orders/{oid}/run"),
client.post(f"/orders/{oid}/run"),
)
assert r1.status_code == 200 and r2.status_code == 200
assert r1.json() == r2.json()
assert calls == [oid] # THE regression this test guards: exactly one real pipeline run
@pytest.mark.asyncio
async def test_run_on_unknown_order_still_404s():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
res = await client.post("/orders/does-not-exist/run")
assert res.status_code == 404
@pytest.mark.asyncio
async def test_different_orders_each_get_their_own_real_run(monkeypatch):
calls: list[str] = []
async def fake_run_job(order_id: str, config: dict) -> dict:
return _fake_job_result(calls, order_id)
monkeypatch.setattr("orchestrator.main.run_job", fake_run_job)
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
o1 = (await client.post("/orders", json={"flow": "custom", "config": {"markets": ["NO"]}})).json()["order_id"]
o2 = (await client.post("/orders", json={"flow": "custom", "config": {"markets": ["GB"]}})).json()["order_id"]
await client.post(f"/orders/{o1}/run")
await client.post(f"/orders/{o2}/run")
# Idempotency is per-order, not global -- two distinct orders both really run.
assert sorted(calls) == sorted([o1, o2])
@@ -0,0 +1,162 @@
"""
Fault-injection tests for workers/pipeline.py's run_job — the REAL order
pipeline (not a mock of it). BEFORE_STATE.md §4 found schema-evolution,
CDC-interruption, backfill, and restart entirely untested. This file closes
what can be closed against code that actually exists, and says explicitly
why the rest can't be, instead of fabricating a harness for infrastructure
this repo doesn't have.
All external HTTP is mocked with respx (never hits real registries) so this
suite is deterministic and offline.
"""
from __future__ import annotations
import httpx
import pytest
import respx
from workers.pipeline import run_job
BRREG_URL = "https://data.brreg.no/enhetsregisteret/api/enheter/923609016"
PRH_URL = "https://avoindata.prh.fi/opendata-ytj-api/v3/companies?businessId=2077474-0"
VALID_BRREG_BODY = {
"navn": "Volvo Personvagnar Norge AS",
"konkurs": False,
"forretningsadresse": {"adresse": ["Storgata 1"], "poststed": "OSLO"},
}
class TestRestartMidFetch:
"""A worker crash/restart mid-job is not literally simulate-able (no
checkpointing exists to resume from — the pipeline is a single async
function with no persisted intermediate state). What this DOES test,
honestly: a connector raising mid-job (network reset, upstream 5xx,
connection drop — the kind of fault a real restart would also surface
as) never crashes the whole order; the job completes and delivers
whatever it validly could."""
@pytest.mark.asyncio
@respx.mock
async def test_a_connector_exception_does_not_crash_the_order(self):
respx.get(BRREG_URL).mock(side_effect=httpx.ConnectError("connection reset"))
respx.get(PRH_URL).mock(return_value=httpx.Response(200, json={
"companies": [{"names": [{"name": "Suomi Oy"}], "status": "active"}],
}))
result = await run_job(
"order_restart_1",
{"markets": ["NO", "FI"], "confidence": 50, "seeds": {"NO": ["923609016"], "FI": ["2077474-0"]}},
)
assert result["state"] == "done"
# NO failed entirely (connector raised); FI still delivered.
assert result["metrics"]["per_market"]["NO"] == 0
assert result["metrics"]["per_market"]["FI"] == 1
assert len(result["records"]) == 1
assert result["records"][0]["market"] == "FI"
@pytest.mark.asyncio
@respx.mock
async def test_every_connector_failing_delivers_zero_rows_not_a_crash(self):
respx.get(BRREG_URL).mock(side_effect=httpx.ConnectError("down"))
respx.get(PRH_URL).mock(side_effect=httpx.ConnectError("down"))
result = await run_job(
"order_restart_2",
{"markets": ["NO", "FI"], "confidence": 50, "seeds": {"NO": ["923609016"], "FI": ["2077474-0"]}},
)
assert result["state"] == "done"
assert result["records"] == []
assert result["metrics"]["rows"] == 0
class TestSchemaEvolution:
"""Upstream registries adding/removing/renaming fields without notice is
a real risk (BEFORE_STATE.md flagged this as wholly untested). Verified
against the actual HTTP-parsing boundary in sources/connectors.py, via
respx-mocked responses shaped like plausible upstream drift — not a
fabricated schema-registry harness (this repo has no schema
versioning/CDC system to test against; see test_known_gaps.py)."""
@pytest.mark.asyncio
@respx.mock
async def test_upstream_adding_unexpected_new_fields_does_not_break_parsing(self):
drifted_body = {
**VALID_BRREG_BODY,
# Simulated schema drift: brreg adds fields this connector never asked for.
"stiftelsesdato": "2020-01-01",
"naeringskode1": {"kode": "45.11", "beskrivelse": "Handel"},
"nested_new_thing": {"a": {"b": [1, 2, 3]}},
}
respx.get(BRREG_URL).mock(return_value=httpx.Response(200, json=drifted_body))
result = await run_job(
"order_schema_1",
{"markets": ["NO"], "confidence": 50, "seeds": {"NO": ["923609016"]}},
)
assert result["state"] == "done"
assert len(result["records"]) == 1
assert result["records"][0]["name"] == "Volvo Personvagnar Norge AS"
@pytest.mark.asyncio
@respx.mock
async def test_upstream_removing_an_expected_field_degrades_honestly_not_a_crash(self):
# Real drift case: upstream drops "navn" (renamed/moved). The
# connector must not crash, and must not fabricate a name — the
# record is simply not produced (pipeline's existing `if res and
# res.name` gate), which is the correct "level 0 / not available"
# behavior, not a bug to work around.
stripped_body = {k: v for k, v in VALID_BRREG_BODY.items() if k != "navn"}
respx.get(BRREG_URL).mock(return_value=httpx.Response(200, json=stripped_body))
result = await run_job(
"order_schema_2",
{"markets": ["NO"], "confidence": 50, "seeds": {"NO": ["923609016"]}},
)
assert result["state"] == "done"
assert result["records"] == [] # honestly nothing delivered, not a fabricated name
@pytest.mark.asyncio
@respx.mock
async def test_upstream_returning_a_wholly_different_shape_does_not_crash(self):
# Worst case: upstream returns something structurally alien (e.g. a
# maintenance-page JSON blob instead of a company record).
respx.get(BRREG_URL).mock(return_value=httpx.Response(200, json={"error": "maintenance", "retry_after": 60}))
result = await run_job(
"order_schema_3",
{"markets": ["NO"], "confidence": 50, "seeds": {"NO": ["923609016"]}},
)
assert result["state"] == "done"
assert result["records"] == []
class TestBackfillReplay:
"""This pipeline has NO persistence layer (BEFORE_STATE.md — every
run_job call recomputes from scratch; there is no delivery store to
dedupe a backfill against). A true "backfill doesn't create duplicate
deliveries" test would need that store and is NOT fabricated here. What
IS real and testable: replaying the identical order config (the exact
scenario a backfill re-run performs) is idempotent AT THE COMPUTE LEVEL
— same input, byte-identical output — so a backfill re-run at least
doesn't silently drift or become order-dependent across replays."""
@pytest.mark.asyncio
@respx.mock
async def test_replaying_the_same_order_config_yields_byte_identical_delivery(self):
respx.get(BRREG_URL).mock(return_value=httpx.Response(200, json=VALID_BRREG_BODY))
config = {"markets": ["NO"], "confidence": 50, "seeds": {"NO": ["923609016"]}}
first = await run_job("order_backfill", config)
second = await run_job("order_backfill", config)
# Strip the per-run artifact_ref/timestamps (legitimately differ —
# every replay IS a new delivery event) before comparing the
# substantive content.
def strip_run_identity(result):
recs = []
for r in result["records"]:
rec = {k: v for k, v in r.items()}
rec["provenance"] = [
{k: v for k, v in p.items() if k not in ("retrieved_at", "artifact_ref")} for p in rec["provenance"]
]
recs.append(rec)
return recs
assert strip_run_identity(first) == strip_run_identity(second)
assert first["metrics"]["rows"] == second["metrics"]["rows"] == 1
@@ -0,0 +1,114 @@
"""
P014: integration proof that a source signaling a block (HTTP 401/403/429/451)
during a real run_job() call (a) never crashes or fabricates a result, (b) is
recorded on the process-wide adaptive_router so the engine backs off that
source, and (c) the pipeline still delivers from the next compliant source in
the plan -- exactly the "source-racing several authorized sources" behavior
the siax-0pt skill documents, now with an honest memory of blocks instead of
silently re-trying a rate-limited source with none.
Uses the real default_router (module-level singleton pipeline.py actually
uses), cleared before and after every test in this file so this suite never
leaks state into -- or picks up state from -- any other test module that
imports workers.pipeline.
"""
from __future__ import annotations
import httpx
import pytest
import respx
from workers.adaptive_router import default_router
from workers.pipeline import run_job
COMPANIES_HOUSE_URL = "https://api.company-information.service.gov.uk/company/00000006"
GLEIF_URL = "https://api.gleif.org/api/v1/lei-records/00000006"
@pytest.fixture(autouse=True)
def _clean_router():
default_router.clear()
yield
default_router.clear()
class TestSourceBlockedDuringARealRun:
@pytest.mark.asyncio
@respx.mock
async def test_a_429_from_one_source_is_recorded_as_blocked_and_the_run_still_delivers_from_the_next_source(
self, monkeypatch
):
monkeypatch.setenv("COMPANIES_HOUSE_API_KEY", "test-key")
respx.get(COMPANIES_HOUSE_URL).mock(return_value=httpx.Response(429, json={"error": "rate limited"}))
respx.get(GLEIF_URL).mock(
return_value=httpx.Response(
200,
json={"data": {"attributes": {"entity": {"legalName": {"name": "Fallback Ltd"}, "status": "ACTIVE", "legalAddress": {}}}}},
)
)
assert default_router.is_blocked("GB", "companies_house") is False # sanity: clean slate
result = await run_job("order_block_1", {"markets": ["GB"], "confidence": 50, "seeds": {"GB": ["00000006"]}})
assert result["state"] == "done"
assert result["metrics"]["rows"] == 1
assert result["records"][0]["name"] == "Fallback Ltd"
assert result["records"][0]["source"] == "gleif" # companies_house was blocked, gleif answered
# THE regression this test guards: the block was actually recorded,
# not silently discarded the way a bare `except Exception: res = None`
# would (that's still the fallback for genuine errors, but a block is
# now distinguishable from one).
assert default_router.is_blocked("GB", "companies_house") is True
@pytest.mark.asyncio
@respx.mock
async def test_a_blocked_source_is_excluded_from_the_plan_on_the_very_next_key_in_the_same_run(self, monkeypatch):
monkeypatch.setenv("COMPANIES_HOUSE_API_KEY", "test-key")
gb_second_url = "https://api.company-information.service.gov.uk/company/11111111"
gleif_second_url = "https://api.gleif.org/api/v1/lei-records/11111111"
companies_house_calls = respx.get(COMPANIES_HOUSE_URL).mock(return_value=httpx.Response(429, json={}))
# No mock registered for gb_second_url at all -- if the pipeline tried
# companies_house AGAIN for the second key after it was just blocked,
# respx would raise on the unmocked request and this test would fail
# with a connection error, not a clean assertion. That absence IS the
# assertion: the plan excluded the just-blocked source.
respx.get(GLEIF_URL).mock(
return_value=httpx.Response(200, json={"data": {"attributes": {"entity": {"legalName": {"name": "First"}, "legalAddress": {}}}}})
)
respx.get(gleif_second_url).mock(
return_value=httpx.Response(200, json={"data": {"attributes": {"entity": {"legalName": {"name": "Second"}, "legalAddress": {}}}}})
)
result = await run_job(
"order_block_2",
{"markets": ["GB"], "confidence": 50, "seeds": {"GB": ["00000006", "11111111"]}},
)
assert result["state"] == "done"
assert result["metrics"]["rows"] == 2
names = {r["name"] for r in result["records"]}
assert names == {"First", "Second"}
# companies_house was hit exactly once (for the first key, where it
# got blocked) -- never retried for the second key in this run.
assert companies_house_calls.call_count == 1
@pytest.mark.asyncio
@respx.mock
async def test_a_plain_5xx_is_not_treated_as_a_block(self, monkeypatch):
# A genuine server error is a different signal from a compliance
# block -- it should NOT be recorded via record_blocked (that would
# incorrectly suppress a source that's just having a bad moment, not
# one that told the engine to stop).
monkeypatch.setenv("COMPANIES_HOUSE_API_KEY", "test-key")
respx.get(COMPANIES_HOUSE_URL).mock(return_value=httpx.Response(500, json={}))
respx.get(GLEIF_URL).mock(
return_value=httpx.Response(200, json={"data": {"attributes": {"entity": {"legalName": {"name": "X"}, "legalAddress": {}}}}})
)
result = await run_job("order_block_3", {"markets": ["GB"], "confidence": 50, "seeds": {"GB": ["00000006"]}})
assert result["state"] == "done"
assert default_router.is_blocked("GB", "companies_house") is False
+164
View File
@@ -0,0 +1,164 @@
"""
Tests for workers/quality_bridge.py (the Python half of the P010 TS/Python
bridge) and its wiring into workers/pipeline.run_job. Verifies the
fail-open contract end to end: disabled, not configured, timeout,
non-2xx, malformed body, and success — and, critically, that `delivered`
rows from run_job are IDENTICAL regardless of which of those the bridge
call resolves to (the bridge is advisory, never a second gate).
"""
from __future__ import annotations
import httpx
import pytest
import respx
from workers.pipeline import run_job
from workers.quality_bridge import run_quality_bridge
BRIDGE_URL = "http://edge.local/api/0pt/quality/bridge-run"
BRREG_URL = "https://data.brreg.no/enhetsregisteret/api/enheter/923609016"
VALID_BRREG_BODY = {
"navn": "Volvo Personvagnar Norge AS",
"konkurs": False,
"forretningsadresse": {"adresse": ["Storgata 1"]},
}
@pytest.fixture(autouse=True)
def _clean_env(monkeypatch):
monkeypatch.delenv("OPT_QUALITY_BRIDGE_ENABLED", raising=False)
monkeypatch.delenv("OPT_QUALITY_BRIDGE_URL", raising=False)
monkeypatch.delenv("EDGE_URL", raising=False)
monkeypatch.delenv("INTERNAL_TOKEN", raising=False)
class TestBridgeDirectly:
@pytest.mark.asyncio
async def test_disabled_by_default_makes_zero_network_calls(self, monkeypatch):
# No respx mock registered at all — if this made an HTTP call it would raise.
result = await run_quality_bridge(tenant_id="t_a", project_id="p_1", dataset_id="ds_1", rows=[])
assert result.status == "disabled"
assert result.score is None
@pytest.mark.asyncio
async def test_enabled_but_no_url_configured(self, monkeypatch):
monkeypatch.setenv("OPT_QUALITY_BRIDGE_ENABLED", "true")
result = await run_quality_bridge(tenant_id="t_a", project_id="p_1", dataset_id="ds_1", rows=[])
assert result.status == "not_configured"
@pytest.mark.asyncio
@respx.mock
async def test_successful_run_is_parsed(self, monkeypatch):
monkeypatch.setenv("OPT_QUALITY_BRIDGE_ENABLED", "true")
monkeypatch.setenv("OPT_QUALITY_BRIDGE_URL", "http://edge.local")
respx.post(BRIDGE_URL).mock(return_value=httpx.Response(201, json={
"run": {"run_id": "dqrun_1", "status": "succeeded", "score": 100},
"issues": [],
}))
result = await run_quality_bridge(
tenant_id="t_a", project_id="p_1", dataset_id="ds_1", rows=[{"name": "X", "confidence": 0.9}]
)
assert result.status == "ok"
assert result.score == 100
assert result.run_id == "dqrun_1"
assert result.issue_count == 0
@pytest.mark.asyncio
@respx.mock
async def test_timeout_fails_open(self, monkeypatch):
monkeypatch.setenv("OPT_QUALITY_BRIDGE_ENABLED", "true")
monkeypatch.setenv("OPT_QUALITY_BRIDGE_URL", "http://edge.local")
respx.post(BRIDGE_URL).mock(side_effect=httpx.TimeoutException("timed out"))
result = await run_quality_bridge(tenant_id="t_a", project_id="p_1", dataset_id="ds_1", rows=[])
assert result.status == "unavailable"
assert result.detail == "timeout"
@pytest.mark.asyncio
@respx.mock
async def test_non_2xx_fails_open(self, monkeypatch):
monkeypatch.setenv("OPT_QUALITY_BRIDGE_ENABLED", "true")
monkeypatch.setenv("OPT_QUALITY_BRIDGE_URL", "http://edge.local")
respx.post(BRIDGE_URL).mock(return_value=httpx.Response(500, json={"error": "boom"}))
result = await run_quality_bridge(tenant_id="t_a", project_id="p_1", dataset_id="ds_1", rows=[])
assert result.status == "unavailable"
assert "500" in result.detail
@pytest.mark.asyncio
@respx.mock
async def test_malformed_body_fails_open_not_raises(self, monkeypatch):
monkeypatch.setenv("OPT_QUALITY_BRIDGE_ENABLED", "true")
monkeypatch.setenv("OPT_QUALITY_BRIDGE_URL", "http://edge.local")
respx.post(BRIDGE_URL).mock(return_value=httpx.Response(201, content=b"not json"))
result = await run_quality_bridge(tenant_id="t_a", project_id="p_1", dataset_id="ds_1", rows=[])
assert result.status == "unavailable"
@pytest.mark.asyncio
@respx.mock
async def test_connection_refused_fails_open(self, monkeypatch):
monkeypatch.setenv("OPT_QUALITY_BRIDGE_ENABLED", "true")
monkeypatch.setenv("OPT_QUALITY_BRIDGE_URL", "http://edge.local")
respx.post(BRIDGE_URL).mock(side_effect=httpx.ConnectError("refused"))
result = await run_quality_bridge(tenant_id="t_a", project_id="p_1", dataset_id="ds_1", rows=[])
assert result.status == "unavailable"
class TestBridgeWiredIntoThePipeline:
"""The part that matters most: whatever the bridge does, `delivered`
(the rows the customer actually receives) must not change."""
@pytest.mark.asyncio
@respx.mock
async def test_missing_tenant_id_skips_the_bridge_honestly(self):
respx.get(BRREG_URL).mock(return_value=httpx.Response(200, json=VALID_BRREG_BODY))
result = await run_job("order_notenant", {"markets": ["NO"], "confidence": 50, "seeds": {"NO": ["923609016"]}})
assert result["metrics"]["quality_bridge"]["status"] == "not_configured"
assert len(result["records"]) == 1 # delivery unaffected
@pytest.mark.asyncio
@respx.mock
async def test_bridge_disabled_delivers_identically_to_bridge_enabled_and_failing(self, monkeypatch):
respx.get(BRREG_URL).mock(return_value=httpx.Response(200, json=VALID_BRREG_BODY))
config = {
"markets": ["NO"], "confidence": 50, "seeds": {"NO": ["923609016"]},
"tenant_id": "t_bridge_pipeline", "project_id": "p_1",
}
monkeypatch.delenv("OPT_QUALITY_BRIDGE_ENABLED", raising=False)
disabled_result = await run_job("order_bridge_off", config)
monkeypatch.setenv("OPT_QUALITY_BRIDGE_ENABLED", "true")
monkeypatch.setenv("OPT_QUALITY_BRIDGE_URL", "http://edge.local")
respx.post(BRIDGE_URL).mock(side_effect=httpx.ConnectError("edge unreachable"))
failing_result = await run_job("order_bridge_fail", config)
assert disabled_result["metrics"]["rows"] == failing_result["metrics"]["rows"] == 1
assert [r["name"] for r in disabled_result["records"]] == [r["name"] for r in failing_result["records"]]
assert disabled_result["metrics"]["quality_bridge"]["status"] == "disabled"
assert failing_result["metrics"]["quality_bridge"]["status"] == "unavailable"
@pytest.mark.asyncio
@respx.mock
async def test_bridge_success_stamps_quality_provenance_without_dropping_or_adding_rows(self, monkeypatch):
respx.get(BRREG_URL).mock(return_value=httpx.Response(200, json=VALID_BRREG_BODY))
monkeypatch.setenv("OPT_QUALITY_BRIDGE_ENABLED", "true")
monkeypatch.setenv("OPT_QUALITY_BRIDGE_URL", "http://edge.local")
respx.post(BRIDGE_URL).mock(return_value=httpx.Response(201, json={
"run": {"run_id": "dqrun_9", "status": "succeeded", "score": 100},
"issues": [],
}))
result = await run_job(
"order_bridge_ok",
{
"markets": ["NO"], "confidence": 50, "seeds": {"NO": ["923609016"]},
"tenant_id": "t_bridge_ok", "project_id": "p_1",
},
)
assert result["metrics"]["rows"] == 1
assert result["metrics"]["quality_bridge"]["status"] == "ok"
assert result["metrics"]["quality_bridge"]["score"] == 100
for p in result["records"][0]["provenance"]:
assert p["quality"] == {
"score": 100, "run_id": "dqrun_9", "run_status": "succeeded", "checked_by": "0pt-quality-bridge",
}
assert p["artifact_ref"] == "0pt:pipeline_delivery:order_bridge_ok"
@@ -0,0 +1,166 @@
"""Regression tests for the Python adapter to canonical TypeScript ER.
The removed Python scorer is deliberately not tested because it no longer
exists. These tests pin the load-bearing adapter semantics instead:
canonical match edges merge; review/non-match edges do not; hard negative
identity evidence constrains the whole cluster; bridge failure leaves records
unmerged.
"""
from __future__ import annotations
import copy
import httpx
import pytest
import respx
from workers.resolve import _apply_matches, resolve
def _prov(field_name: str, source_id: str, confidence: float) -> dict:
return {
"field_name": field_name,
"source_id": source_id,
"confidence": confidence,
"entity_resolution": None,
}
def _rec(name: str, source: str, confidence: float = 0.9) -> dict:
return {
"market": "SE",
"name": name,
"status": "active",
"lei": None,
"org_nr": None,
"source": source,
"confidence": confidence,
"provenance": [_prov("name", source, confidence)],
}
def _pair(a: str, b: str, status: str = "match", decided_by: str = "score", score: float = 0.97) -> dict:
return {
"candidate_id": f"c_{a}_{b}",
"record_a": a,
"record_b": b,
"score": score,
"status": status,
"decided_by": decided_by,
}
def test_apply_matches_is_deterministic_and_uses_canonical_edges_only():
records = [_rec("Acme AB", "source-a", 0.91), _rec("ACME Aktiebolag", "source-b", 0.96)]
assert len(_apply_matches(copy.deepcopy(records), [])) == 2
@pytest.mark.asyncio
@respx.mock
async def test_canonical_match_merges_and_stamps_provenance(monkeypatch):
monkeypatch.setenv("OPT_ER_BRIDGE_URL", "https://edge.example.test")
monkeypatch.setenv("INTERNAL_TOKEN", "test-internal-token")
records = [_rec("Acme AB", "source-a", 0.91), _rec("Acme AB", "source-b", 0.96)]
route = respx.post("https://edge.example.test/api/0pt/internal/er/candidates")
def responder(request: httpx.Request) -> httpx.Response:
body = __import__("json").loads(request.content)
assert request.headers["X-Internal-Token"] == "test-internal-token"
assert body["tenant_id"] == "tenant-a"
assert body["blocking_fields"] == ["market", "block_initial"]
a, b = body["records"][0]["record_id"], body["records"][1]["record_id"]
# Endast hard-rule-beslut (decided_by != score/None) far skapa en
# canonical identity-lank - consumenten ignorerar medvetet score/"match".
return httpx.Response(
200,
json={"pairs": [_pair(a, b, "match", "0pt.company.stable-identifiers.v3", 0.99)], "review_queue": []},
)
route.side_effect = responder
result = await resolve(records, tenant_id="tenant-a", project_id="project-a")
assert len(result) == 1
assert result[0]["agreed_sources"] == 2
assert result[0]["confidence"] == pytest.approx(0.99)
assert set(result[0]["merged_from"]) <= {"source-a", "source-b"}
for provenance in result[0]["provenance"]:
er = provenance["entity_resolution"]
assert er["method"] == "canonical_ts_entity_resolution"
assert set(er["merged_sources"]) == {"source-a", "source-b"}
@pytest.mark.asyncio
@respx.mock
async def test_pending_review_never_auto_merges(monkeypatch):
monkeypatch.setenv("OPT_ER_BRIDGE_URL", "https://edge.example.test")
monkeypatch.setenv("INTERNAL_TOKEN", "test-internal-token")
records = [_rec("Acme AB", "source-a"), _rec("Acme Group AB", "source-b")]
def responder(request: httpx.Request) -> httpx.Response:
body = __import__("json").loads(request.content)
a, b = body["records"][0]["record_id"], body["records"][1]["record_id"]
pair = _pair(a, b, "pending_review")
return httpx.Response(200, json={"pairs": [pair], "review_queue": [pair]})
respx.post("https://edge.example.test/api/0pt/internal/er/candidates").side_effect = responder
result = await resolve(records, tenant_id="tenant-a", project_id="project-a")
assert len(result) == 2
assert all(not r.get("merged_from") for r in result)
@pytest.mark.asyncio
@respx.mock
async def test_hard_non_match_blocks_transitive_cluster_merge(monkeypatch):
"""A-B and B-C matches may never imply A=C when canonical hard evidence says A!=C."""
monkeypatch.setenv("OPT_ER_BRIDGE_URL", "https://edge.example.test")
monkeypatch.setenv("INTERNAL_TOKEN", "test-internal-token")
records = [
_rec("Acme AB", "source-a", 0.95),
_rec("Acme AB", "source-b", 0.94),
_rec("Acme AB", "source-c", 0.93),
]
def responder(request: httpx.Request) -> httpx.Response:
body = __import__("json").loads(request.content)
a, b, c = [item["record_id"] for item in body["records"]]
return httpx.Response(
200,
json={
"pairs": [
_pair(a, b, "match", "0pt.company.stable-identifiers.v3", 0.98),
_pair(b, c, "match", "0pt.company.stable-identifiers.v3", 0.97),
_pair(a, c, "non_match", "0pt.company.stable-identifiers.v2", 0.0),
],
"review_queue": [],
},
)
respx.post("https://edge.example.test/api/0pt/internal/er/candidates").side_effect = responder
result = await resolve(records, tenant_id="tenant-a", project_id="project-a")
assert len(result) == 2
assert max(r.get("agreed_sources", 1) for r in result) == 2
assert not any(set(r.get("merged_from", [])) >= {"source-b", "source-c"} for r in result)
@pytest.mark.asyncio
@respx.mock
async def test_bridge_outage_fails_closed_to_unmerged_records(monkeypatch):
monkeypatch.setenv("OPT_ER_BRIDGE_URL", "https://edge.example.test")
monkeypatch.setenv("INTERNAL_TOKEN", "test-internal-token")
records = [_rec("Acme AB", "source-a"), _rec("Acme AB", "source-b")]
respx.post("https://edge.example.test/api/0pt/internal/er/candidates").mock(side_effect=httpx.ConnectError("offline"))
result = await resolve(records, tenant_id="tenant-a", project_id="project-a")
assert len(result) == 2
assert all(not r.get("merged_from") for r in result)
@pytest.mark.asyncio
async def test_missing_internal_configuration_makes_zero_network_calls(monkeypatch):
monkeypatch.delenv("OPT_ER_BRIDGE_URL", raising=False)
monkeypatch.delenv("EDGE_URL", raising=False)
monkeypatch.delenv("INTERNAL_TOKEN", raising=False)
records = [_rec("Acme AB", "source-a"), _rec("Acme AB", "source-b")]
result = await resolve(records, tenant_id="tenant-a", project_id="project-a")
assert len(result) == 2
@@ -0,0 +1,53 @@
"""A failed or malformed source must never become a verified empty result."""
import httpx
import pytest
import respx
from fastapi.testclient import TestClient
from orchestrator import main
from sources.connectors import opensanctions_screen, rdw_vehicle
@pytest.mark.asyncio
@pytest.mark.parametrize("status", [403, 429, 500])
async def test_source_http_failure_raises(status):
with respx.mock:
respx.get("https://api.opensanctions.org/search/default").respond(status)
respx.get("https://opendata.rdw.nl/resource/m9d7-ebf2.json").respond(status)
with pytest.raises(httpx.HTTPStatusError):
await opensanctions_screen("example")
with pytest.raises(httpx.HTTPStatusError):
await rdw_vehicle("AB123")
@pytest.mark.asyncio
async def test_malformed_and_valid_empty_are_distinct():
with respx.mock:
screen = respx.get("https://api.opensanctions.org/search/default").respond(200, json={})
vehicle = respx.get("https://opendata.rdw.nl/resource/m9d7-ebf2.json").respond(200, json={})
with pytest.raises(ValueError):
await opensanctions_screen("example")
with pytest.raises(ValueError):
await rdw_vehicle("AB123")
screen.respond(200, json={"results": []})
vehicle.respond(200, json=[])
assert (await opensanctions_screen("example"))["matches"] == []
assert await rdw_vehicle("AB123") is None
def test_routes_return_503_on_source_failure_and_mark_verified_empty(monkeypatch):
async def failed(*args):
raise RuntimeError("fixture failure")
async def empty_screen(*args):
return {"source": "opensanctions", "matches": []}
async def empty_vehicle(*args):
return None
monkeypatch.setattr(main, "_INTERNAL_TOKEN", "")
monkeypatch.setattr(main, "opensanctions_screen", failed)
monkeypatch.setattr(main, "rdw_vehicle", failed)
client = TestClient(main.app)
assert client.get('/screen?q=example').status_code == 503
assert client.get('/vehicles/AB123').status_code == 503
monkeypatch.setattr(main, "opensanctions_screen", empty_screen)
monkeypatch.setattr(main, "rdw_vehicle", empty_vehicle)
assert client.get('/screen?q=example').json() == {"source": "opensanctions", "source_status": "ok", "matches": []}
assert client.get('/vehicles/AB123').json() == {"vehicle": None, "source_status": "ok"}