020 update city code resolving

This commit is contained in:
Раис Юсупалиев
2026-03-21 10:03:46 +03:00
parent c4175121a0
commit 163f379a65
14 changed files with 45939 additions and 271 deletions
@@ -11,9 +11,10 @@ from app.adapters.delivery_providers.cdek.client import (
CDEKProvider,
CDEKRequestError,
)
from app.cities import cities_map
from app import config as config_module
from app.config import AdapterConfig, Settings
from app.schemas.request import DeliveryEntity, DeliveryRequest
from app.schemas.request import DeliveryCalculationRequest, DeliveryEntity
class StubAuthClient:
@@ -62,28 +63,14 @@ class SequenceHTTPClient:
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> httpx.Response:
self.calls.append(
{
"method": "GET",
"url": url,
"json": None,
"data": None,
"params": params,
"headers": headers,
"timeout": timeout,
}
)
result = self._next_result()
if isinstance(result, Exception):
raise result
return result
raise AssertionError("CDEK city lookup API must not be called.")
class RecordingHTTPClient:
def __init__(self) -> None:
self.auth_timeouts: list[float | None] = []
self.city_lookup_timeouts: list[float | None] = []
self.tariff_timeouts: list[float | None] = []
self.tariff_payloads: list[dict[str, Any]] = []
async def get(
self,
@@ -93,16 +80,7 @@ class RecordingHTTPClient:
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> httpx.Response:
request = httpx.Request("GET", url, params=params)
self.city_lookup_timeouts.append(timeout)
assert headers == {"Authorization": "Bearer provider-token"}
city = params.get("name") if params else None
code_by_city = {"Moscow": 44, "Kazan": 424}
return httpx.Response(
200,
json={"code": code_by_city.get(city, 44), "full_name": city},
request=request,
)
raise AssertionError("CDEK city lookup API must not be called.")
async def post(
self,
@@ -125,6 +103,7 @@ class RecordingHTTPClient:
assert headers == {"Authorization": "Bearer provider-token"}
assert data is None
assert json is not None
self.tariff_payloads.append(json)
return httpx.Response(
200,
json={
@@ -149,33 +128,29 @@ class RecordingHTTPClient:
)
def _make_request(**overrides: object) -> DeliveryRequest:
def _make_request(**overrides: object) -> DeliveryCalculationRequest:
payload: dict[str, object] = {
"entity": DeliveryEntity.INDIVIDUAL,
"from_city": "Moscow",
"to_city": "Kazan",
"country_code": None,
"from_city": 1,
"to_city": 2,
"weight_kg": 1.2,
"length_cm": 20,
"width_cm": 10,
"height_cm": 5,
}
payload.update(overrides)
return DeliveryRequest(**payload)
return DeliveryCalculationRequest(**payload)
def _cdek_code(city_id: str) -> int:
city_entry = cities_map[city_id]
cdek_data = city_entry["cdek"]
assert isinstance(cdek_data, dict)
return int(cdek_data["code"])
def test_cdek_client_retries_timeout_and_applies_timeout_seconds() -> None:
request = _make_request()
city_lookup_moscow = httpx.Response(
200,
json={"code": 44, "full_name": "Moscow"},
request=httpx.Request("GET", "https://api.cdek.test/v2/location/suggest/cities"),
)
city_lookup_kazan = httpx.Response(
200,
json={"code": 424, "full_name": "Kazan"},
request=httpx.Request("GET", "https://api.cdek.test/v2/location/suggest/cities"),
)
first_error = httpx.ReadTimeout(
"read timeout",
request=httpx.Request("POST", "https://api.cdek.test/v2/calculator/tarifflist"),
@@ -185,9 +160,7 @@ def test_cdek_client_retries_timeout_and_applies_timeout_seconds() -> None:
json={"tariff_codes": [{"delivery_sum": 500}]},
request=httpx.Request("POST", "https://api.cdek.test/v2/calculator/tarifflist"),
)
http_client = SequenceHTTPClient(
[city_lookup_moscow, city_lookup_kazan, first_error, second_response]
)
http_client = SequenceHTTPClient([first_error, second_response])
sleep_calls: list[float] = []
async def fake_sleep(seconds: float) -> None:
@@ -206,37 +179,22 @@ def test_cdek_client_retries_timeout_and_applies_timeout_seconds() -> None:
result = asyncio.run(client.get_raw_price(request))
assert result == {"tariff_codes": [{"delivery_sum": 500}]}
assert len(http_client.calls) == 4
assert http_client.calls[0]["method"] == "GET"
assert http_client.calls[0]["params"] == {
"name": "Moscow",
}
assert http_client.calls[1]["method"] == "GET"
assert http_client.calls[2]["method"] == "POST"
assert http_client.calls[2]["json"]["from_location"] == {"code": 44}
assert http_client.calls[2]["json"]["to_location"] == {"code": 424}
assert http_client.calls[2]["timeout"] == 10.0
assert len(http_client.calls) == 2
assert http_client.calls[0]["method"] == "POST"
assert http_client.calls[0]["json"]["from_location"] == {"code": _cdek_code("1")}
assert http_client.calls[0]["json"]["to_location"] == {"code": _cdek_code("2")}
assert http_client.calls[0]["timeout"] == 10.0
assert sleep_calls == [0.5]
def test_cdek_client_passes_country_code_when_provided() -> None:
request = _make_request(country_code="KZ")
city_lookup_from = httpx.Response(
200,
json={"code": 88, "full_name": "Moscow"},
request=httpx.Request("GET", "https://api.cdek.test/v2/location/suggest/cities"),
)
city_lookup_to = httpx.Response(
200,
json={"code": 99, "full_name": "Kazan"},
request=httpx.Request("GET", "https://api.cdek.test/v2/location/suggest/cities"),
)
def test_cdek_client_builds_payload_from_cities_map_codes() -> None:
request = _make_request()
tariff_response = httpx.Response(
200,
json={"tariff_codes": [{"delivery_sum": 500}]},
request=httpx.Request("POST", "https://api.cdek.test/v2/calculator/tarifflist"),
)
http_client = SequenceHTTPClient([city_lookup_from, city_lookup_to, tariff_response])
http_client = SequenceHTTPClient([tariff_response])
client = CDEKClient(
http_client=http_client, # type: ignore[arg-type]
auth_client=StubAuthClient(), # type: ignore[arg-type]
@@ -246,30 +204,54 @@ def test_cdek_client_passes_country_code_when_provided() -> None:
asyncio.run(client.get_raw_price(request))
assert http_client.calls[0]["params"] == {
"name": "Moscow",
"country_code": "KZ",
}
assert http_client.calls[0]["json"]["from_location"] == {"code": _cdek_code("1")}
assert http_client.calls[0]["json"]["to_location"] == {"code": _cdek_code("2")}
assert http_client.calls[0]["json"]["packages"] == [
{"weight": 1200, "length": 20, "width": 10, "height": 5}
]
assert http_client.calls[0]["params"] is None
def test_cdek_client_raises_when_city_mapping_is_missing() -> None:
request = _make_request(from_city=999999)
http_client = SequenceHTTPClient([])
client = CDEKClient(
http_client=http_client, # type: ignore[arg-type]
auth_client=StubAuthClient(), # type: ignore[arg-type]
base_url="https://api.cdek.test/v2",
retry_attempts=0,
)
with pytest.raises(CDEKRequestError, match="city id 999999"):
asyncio.run(client.get_raw_price(request))
assert http_client.calls == []
def test_cdek_client_raises_when_cdek_code_is_not_configured() -> None:
request = _make_request(to_city=3)
http_client = SequenceHTTPClient([])
client = CDEKClient(
http_client=http_client, # type: ignore[arg-type]
auth_client=StubAuthClient(), # type: ignore[arg-type]
base_url="https://api.cdek.test/v2",
retry_attempts=0,
)
with pytest.raises(CDEKRequestError, match="city id 3"):
asyncio.run(client.get_raw_price(request))
assert http_client.calls == []
def test_cdek_client_raises_on_non_retriable_http_error() -> None:
request = _make_request()
city_lookup_moscow = httpx.Response(
200,
json={"code": 44, "full_name": "Moscow"},
request=httpx.Request("GET", "https://api.cdek.test/v2/location/suggest/cities"),
)
city_lookup_kazan = httpx.Response(
200,
json={"code": 424, "full_name": "Kazan"},
request=httpx.Request("GET", "https://api.cdek.test/v2/location/suggest/cities"),
)
bad_response = httpx.Response(
400,
json={"error": "bad request"},
request=httpx.Request("POST", "https://api.cdek.test/v2/calculator/tarifflist"),
)
http_client = SequenceHTTPClient([city_lookup_moscow, city_lookup_kazan, bad_response])
http_client = SequenceHTTPClient([bad_response])
client = CDEKClient(
http_client=http_client, # type: ignore[arg-type]
auth_client=StubAuthClient(), # type: ignore[arg-type]
@@ -280,26 +262,7 @@ def test_cdek_client_raises_on_non_retriable_http_error() -> None:
with pytest.raises(CDEKClientError):
asyncio.run(client.get_raw_price(request))
assert len(http_client.calls) == 3
def test_cdek_client_raises_when_city_code_not_found() -> None:
request = _make_request()
city_lookup_empty = httpx.Response(
200,
json=[],
request=httpx.Request("GET", "https://api.cdek.test/v2/location/suggest/cities"),
)
http_client = SequenceHTTPClient([city_lookup_empty])
client = CDEKClient(
http_client=http_client, # type: ignore[arg-type]
auth_client=StubAuthClient(), # type: ignore[arg-type]
base_url="https://api.cdek.test/v2",
retry_attempts=0,
)
with pytest.raises(CDEKRequestError, match="no matches"):
asyncio.run(client.get_raw_price(request))
assert len(http_client.calls) == 1
def test_provider_uses_adapter_yaml_config_for_timeout_and_cache_ttl(
@@ -353,8 +316,17 @@ observability:
assert provider.cache_ttl_seconds == 777
assert http_client.auth_timeouts == [7.5]
assert http_client.city_lookup_timeouts == [7.5, 7.5]
assert http_client.tariff_timeouts == [7.5]
assert http_client.tariff_payloads == [
{
"type": 2,
"from_location": {"code": _cdek_code("1")},
"to_location": {"code": _cdek_code("2")},
"packages": [
{"weight": 1200, "length": 20, "width": 10, "height": 5}
],
}
]
assert [price.provider for price in result] == ["cdek", "cdek"]
assert [price.service_name for price in result] == ["Express", "Economy"]
assert [price.price for price in result] == [Decimal("899.00"), Decimal("499.00")]
@@ -375,6 +347,5 @@ def test_provider_uses_default_adapter_timeout_and_cache_ttl() -> None:
assert provider.cache_ttl_seconds == 900
assert http_client.auth_timeouts == [10.0]
assert http_client.city_lookup_timeouts == [10.0, 10.0]
assert http_client.tariff_timeouts == [10.0]
assert len(result) == 2