catastrogps 2.2.0__tar.gz → 2.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. {catastrogps-2.2.0 → catastrogps-2.3.0}/CHANGELOG.md +5 -0
  2. {catastrogps-2.2.0 → catastrogps-2.3.0}/PKG-INFO +12 -3
  3. {catastrogps-2.2.0 → catastrogps-2.3.0}/README.md +11 -2
  4. {catastrogps-2.2.0 → catastrogps-2.3.0}/catastrogps/__init__.py +9 -0
  5. catastrogps-2.3.0/catastrogps/_version.py +1 -0
  6. {catastrogps-2.2.0 → catastrogps-2.3.0}/catastrogps/client.py +3 -0
  7. {catastrogps-2.2.0 → catastrogps-2.3.0}/catastrogps/errors.py +12 -0
  8. catastrogps-2.3.0/catastrogps/monitoring.py +110 -0
  9. {catastrogps-2.2.0 → catastrogps-2.3.0}/catastrogps/parcels.py +30 -0
  10. catastrogps-2.3.0/tests/test_startup.py +165 -0
  11. catastrogps-2.2.0/catastrogps/_version.py +0 -1
  12. {catastrogps-2.2.0 → catastrogps-2.3.0}/.gitignore +0 -0
  13. {catastrogps-2.2.0 → catastrogps-2.3.0}/LICENSE +0 -0
  14. {catastrogps-2.2.0 → catastrogps-2.3.0}/catastrogps/export.py +0 -0
  15. {catastrogps-2.2.0 → catastrogps-2.3.0}/catastrogps/fincas.py +0 -0
  16. {catastrogps-2.2.0 → catastrogps-2.3.0}/catastrogps/locations.py +0 -0
  17. {catastrogps-2.2.0 → catastrogps-2.3.0}/catastrogps/py.typed +0 -0
  18. {catastrogps-2.2.0 → catastrogps-2.3.0}/pyproject.toml +0 -0
  19. {catastrogps-2.2.0 → catastrogps-2.3.0}/tests/__init__.py +0 -0
  20. {catastrogps-2.2.0 → catastrogps-2.3.0}/tests/test_analysis.py +0 -0
  21. {catastrogps-2.2.0 → catastrogps-2.3.0}/tests/test_client.py +0 -0
  22. {catastrogps-2.2.0 → catastrogps-2.3.0}/tests/test_fincas.py +0 -0
  23. {catastrogps-2.2.0 → catastrogps-2.3.0}/tests/test_sigpac.py +0 -0
  24. {catastrogps-2.2.0 → catastrogps-2.3.0}/tests/test_subparcels_and_locations.py +0 -0
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.3.0 (2026-12-01)
4
+
5
+ - Startup plan endpoints: `parcels.notices(ref)`, `notices.search(...)` / `notices.iter_pages(...)`, `parcels.changes(ref, since=)`, report layers `parcels.risks|water|soil|protections|services(ref)` and `parcels.layer(ref, name)`, and batch jobs `batch.submit(references, layers=, country=)`, `batch.get(id)`, `batch.wait(id)`, `batch.csv(id)`.
6
+ - New errors: `PlanRequiredError` (`403 KEY_PLAN_001`, a `ForbiddenError`) and `PlanLimitError` (`429 KEY_LAYER_001`, `429 BAT_015`); neither is retried.
7
+
3
8
  ## 2.2.0 (2026-10-23)
4
9
 
5
10
  - `parcels.sigpac(ref, country=, lang=)`: `GET /v1/parcels/{ref}/sigpac`, every SIGPAC enclosure of a Spanish parcel (ES, PV, NA) with land use, irrigation, slope, altitude, CAP eligibility and region, incidents and outline. 1 unit, 0 when empty; `SIG_001` raises `ServiceUnavailableError`, retried and not charged.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: catastrogps
3
- Version: 2.2.0
3
+ Version: 2.3.0
4
4
  Summary: Official Python client for the Catastro GPS API: parcels from 29 European countries (including the Basque Country and Navarre foral cadastres) by reference, coordinates or address; building units, terrain, ground motion, solar and more
5
5
  Project-URL: Homepage, https://www.parcelgps.com/developers
6
6
  Project-URL: Documentation, https://www.parcelgps.com/developers
@@ -44,7 +44,7 @@ Official Python client for the [Catastro GPS API](https://www.parcelgps.com/deve
44
44
  - Quota, prepaid balance and per-minute limit of every response, typed exceptions for every API code.
45
45
  - Two small dependencies (`httpx`, `typing_extensions`), typed, Python 3.9+.
46
46
 
47
- **Free tier: 250 calls a month, forever. Failed lookups are not charged.** Get a key at [parcelgps.com/developers](https://www.parcelgps.com/developers).
47
+ **Free tier: 25 calls a month, forever. Failed lookups are not charged.** Get a key at [parcelgps.com/developers](https://www.parcelgps.com/developers).
48
48
 
49
49
  ## Install
50
50
 
@@ -94,6 +94,11 @@ with CatastroGPS() as client:
94
94
  | `resolve(text, hint=)` | `GET /v1/resolve` | Free, no quota: which country and kind a text is |
95
95
  | `crop_catalog(lang=)` | `GET /v1/reference/crops` | Free, no quota: every `cropCode` with its name in the 10 languages |
96
96
  | `locations.provinces()`, `locations.municipalities(region)`, `locations.streets(region, municipality, name=)` | `GET /v1/locations/...` | Spain, common territory |
97
+ | `parcels.notices(ref, limit=)` | `GET /v1/parcels/{ref}/notices` | **Startup plan and above.** Official notices that cite the parcel, 19 countries |
98
+ | `notices.search(country=, municipality_code=, municipality=, kind=, date_from=, date_to=, has_parcels=, cursor=, limit=)`, `notices.iter_pages(...)` | `GET /v1/notices` | **Startup.** Search official notices; `iter_pages` follows `nextCursor` |
99
+ | `parcels.changes(ref, since=, country=)` | `GET /v1/parcels/{ref}/changes` | **Startup.** ES only (surface, use, outline); `monitored` says whether we keep snapshots |
100
+ | `parcels.risks`, `water`, `soil`, `protections`, `services` (or `parcels.layer(ref, name)`) | `GET /v1/parcels/{ref}/{layer}` | **Startup.** Level and one sentence per item; limited in different parcels per month (Startup 2,000, Growth 10,000); show `attribution` ("Source: Catastro GPS") |
101
+ | `batch.submit(references, layers=, country=)`, `batch.get(id)`, `batch.wait(id)`, `batch.csv(id)` | `POST /v1/batch`, `GET /v1/batch/{id}` | **Startup.** Up to 1,000 references; one unit per reference and layer, charged on acceptance; reading is free |
97
102
 
98
103
  ## Examples
99
104
 
@@ -214,6 +219,8 @@ except QuotaExceededError as error:
214
219
  | `PlaceNameError` (a `ValidationError`) | `422 CNV_PLACE_NAME`: a place name, with the geocoded `location` when found |
215
220
  | `ValidationError` | `400 VALIDATION_ERROR`, other `422` |
216
221
  | `AuthenticationError` / `ForbiddenError` | `401 KEY_AUTH_001..003`, `403` |
222
+ | `PlanRequiredError` (a `ForbiddenError`) | `403 KEY_PLAN_001`: the key's plan does not include the endpoint; not charged, not retried |
223
+ | `PlanLimitError` | `429 KEY_LAYER_001` (different parcels per month of report layers used up) or `429 BAT_015` (not enough units for the batch); not retried |
217
224
  | `NotFoundError` | `404 NOT_FOUND` |
218
225
  | `QuotaExceededError` | `429 KEY_AUTH_004` |
219
226
  | `RateLimitError` | `429 KEY_RATE_002`, `RATE_LIMIT_EXCEEDED`; `retry_after` |
@@ -258,11 +265,13 @@ Not covered: Hungary, Romania and the rest (`CoverageError`). Terrain and ground
258
265
 
259
266
  | Plan | Price | Calls / month | Prepaid overage per 1,000 |
260
267
  |------|-------|---------------|---------------------------|
261
- | Free | €0, forever | 250 | €10 |
268
+ | Free | €0, forever | 25 | €10 |
262
269
  | Developer | €19 / month | 5,000 | €5 |
263
270
  | Startup | €49 / month | 15,000 | €4 |
264
271
  | Growth | €99 / month | 50,000 | €2.50 |
265
272
 
273
+ Developer adds price data (`/market`, `/value-history`, price fields). Startup adds official notices, batch, cadastral changes and report layers. The full table is at https://parcelgps.com/developers#plans and in `x-plan-matrix` of the OpenAPI spec.
274
+
266
275
  Overage prices are net (VAT apart) and are charged from a prepaid balance you top up in the portal; with the balance at zero the API answers `429`, never debt.
267
276
 
268
277
  The same key works with the JavaScript SDK (`npm install catastrogps`), the Go SDK and the MCP server for AI agents ([`catastro-gps-mcp`](https://www.npmjs.com/package/catastro-gps-mcp)).
@@ -13,7 +13,7 @@ Official Python client for the [Catastro GPS API](https://www.parcelgps.com/deve
13
13
  - Quota, prepaid balance and per-minute limit of every response, typed exceptions for every API code.
14
14
  - Two small dependencies (`httpx`, `typing_extensions`), typed, Python 3.9+.
15
15
 
16
- **Free tier: 250 calls a month, forever. Failed lookups are not charged.** Get a key at [parcelgps.com/developers](https://www.parcelgps.com/developers).
16
+ **Free tier: 25 calls a month, forever. Failed lookups are not charged.** Get a key at [parcelgps.com/developers](https://www.parcelgps.com/developers).
17
17
 
18
18
  ## Install
19
19
 
@@ -63,6 +63,11 @@ with CatastroGPS() as client:
63
63
  | `resolve(text, hint=)` | `GET /v1/resolve` | Free, no quota: which country and kind a text is |
64
64
  | `crop_catalog(lang=)` | `GET /v1/reference/crops` | Free, no quota: every `cropCode` with its name in the 10 languages |
65
65
  | `locations.provinces()`, `locations.municipalities(region)`, `locations.streets(region, municipality, name=)` | `GET /v1/locations/...` | Spain, common territory |
66
+ | `parcels.notices(ref, limit=)` | `GET /v1/parcels/{ref}/notices` | **Startup plan and above.** Official notices that cite the parcel, 19 countries |
67
+ | `notices.search(country=, municipality_code=, municipality=, kind=, date_from=, date_to=, has_parcels=, cursor=, limit=)`, `notices.iter_pages(...)` | `GET /v1/notices` | **Startup.** Search official notices; `iter_pages` follows `nextCursor` |
68
+ | `parcels.changes(ref, since=, country=)` | `GET /v1/parcels/{ref}/changes` | **Startup.** ES only (surface, use, outline); `monitored` says whether we keep snapshots |
69
+ | `parcels.risks`, `water`, `soil`, `protections`, `services` (or `parcels.layer(ref, name)`) | `GET /v1/parcels/{ref}/{layer}` | **Startup.** Level and one sentence per item; limited in different parcels per month (Startup 2,000, Growth 10,000); show `attribution` ("Source: Catastro GPS") |
70
+ | `batch.submit(references, layers=, country=)`, `batch.get(id)`, `batch.wait(id)`, `batch.csv(id)` | `POST /v1/batch`, `GET /v1/batch/{id}` | **Startup.** Up to 1,000 references; one unit per reference and layer, charged on acceptance; reading is free |
66
71
 
67
72
  ## Examples
68
73
 
@@ -183,6 +188,8 @@ except QuotaExceededError as error:
183
188
  | `PlaceNameError` (a `ValidationError`) | `422 CNV_PLACE_NAME`: a place name, with the geocoded `location` when found |
184
189
  | `ValidationError` | `400 VALIDATION_ERROR`, other `422` |
185
190
  | `AuthenticationError` / `ForbiddenError` | `401 KEY_AUTH_001..003`, `403` |
191
+ | `PlanRequiredError` (a `ForbiddenError`) | `403 KEY_PLAN_001`: the key's plan does not include the endpoint; not charged, not retried |
192
+ | `PlanLimitError` | `429 KEY_LAYER_001` (different parcels per month of report layers used up) or `429 BAT_015` (not enough units for the batch); not retried |
186
193
  | `NotFoundError` | `404 NOT_FOUND` |
187
194
  | `QuotaExceededError` | `429 KEY_AUTH_004` |
188
195
  | `RateLimitError` | `429 KEY_RATE_002`, `RATE_LIMIT_EXCEEDED`; `retry_after` |
@@ -227,11 +234,13 @@ Not covered: Hungary, Romania and the rest (`CoverageError`). Terrain and ground
227
234
 
228
235
  | Plan | Price | Calls / month | Prepaid overage per 1,000 |
229
236
  |------|-------|---------------|---------------------------|
230
- | Free | €0, forever | 250 | €10 |
237
+ | Free | €0, forever | 25 | €10 |
231
238
  | Developer | €19 / month | 5,000 | €5 |
232
239
  | Startup | €49 / month | 15,000 | €4 |
233
240
  | Growth | €99 / month | 50,000 | €2.50 |
234
241
 
242
+ Developer adds price data (`/market`, `/value-history`, price fields). Startup adds official notices, batch, cadastral changes and report layers. The full table is at https://parcelgps.com/developers#plans and in `x-plan-matrix` of the OpenAPI spec.
243
+
235
244
  Overage prices are net (VAT apart) and are charged from a prepaid balance you top up in the portal; with the balance at zero the API answers `429`, never debt.
236
245
 
237
246
  The same key works with the JavaScript SDK (`npm install catastrogps`), the Go SDK and the MCP server for AI agents ([`catastro-gps-mcp`](https://www.npmjs.com/package/catastro-gps-mcp)).
@@ -9,6 +9,8 @@ from catastrogps.errors import (
9
9
  NetworkError,
10
10
  NotFoundError,
11
11
  PlaceNameError,
12
+ PlanLimitError,
13
+ PlanRequiredError,
12
14
  QuotaExceededError,
13
15
  RateLimitError,
14
16
  ServerError,
@@ -17,16 +19,23 @@ from catastrogps.errors import (
17
19
  ValidationError,
18
20
  )
19
21
  from catastrogps.export import EXPORT_FORMATS
22
+ from catastrogps.monitoring import BATCH_LAYERS, MAX_BATCH_REFERENCES
20
23
  from catastrogps.parcels import (
21
24
  ADDRESS_COUNTRY_CODES,
22
25
  COUNTRY_CODES,
23
26
  CROP_LANGUAGES,
24
27
  ENRICHMENT_COUNTRY_CODES,
28
+ REPORT_LAYERS,
25
29
  UNITS_COUNTRY_CODES,
26
30
  )
27
31
 
28
32
  __all__ = [
29
33
  "ADDRESS_COUNTRY_CODES",
34
+ "BATCH_LAYERS",
35
+ "MAX_BATCH_REFERENCES",
36
+ "REPORT_LAYERS",
37
+ "PlanLimitError",
38
+ "PlanRequiredError",
30
39
  "COUNTRY_CODES",
31
40
  "CROP_LANGUAGES",
32
41
  "DEFAULT_BASE_URL",
@@ -0,0 +1 @@
1
+ __version__ = "2.3.0"
@@ -21,6 +21,7 @@ from catastrogps.errors import (
21
21
  from catastrogps.export import ExportResource
22
22
  from catastrogps.fincas import FincasResource
23
23
  from catastrogps.locations import LocationsResource
24
+ from catastrogps.monitoring import BatchResource, NoticesResource
24
25
  from catastrogps.parcels import ParcelsResource, crop_language
25
26
 
26
27
  DEFAULT_BASE_URL = "https://api.parcelgps.com"
@@ -63,6 +64,8 @@ class CatastroGPS:
63
64
  self.export = ExportResource(self)
64
65
  self.fincas = FincasResource(self)
65
66
  self.locations = LocationsResource(self)
67
+ self.notices = NoticesResource(self)
68
+ self.batch = BatchResource(self)
66
69
 
67
70
  def search_address_candidates(
68
71
  self,
@@ -31,6 +31,14 @@ class ForbiddenError(CatastroGPSError):
31
31
  pass
32
32
 
33
33
 
34
+ class PlanRequiredError(ForbiddenError):
35
+ pass
36
+
37
+
38
+ class PlanLimitError(CatastroGPSError):
39
+ pass
40
+
41
+
34
42
  class NotFoundError(CatastroGPSError):
35
43
  pass
36
44
 
@@ -123,6 +131,10 @@ def error_from_response(
123
131
  return CoverageError(message, **kwargs)
124
132
  if code == "CNV_PLACE_NAME":
125
133
  return PlaceNameError(message, **kwargs)
134
+ if code == "KEY_PLAN_001":
135
+ return PlanRequiredError(message, **kwargs)
136
+ if code in ("KEY_LAYER_001", "BAT_015"):
137
+ return PlanLimitError(message, **kwargs)
126
138
  if code == "KEY_AUTH_004":
127
139
  return QuotaExceededError(message, quota=quota, **kwargs)
128
140
  if status == 429:
@@ -0,0 +1,110 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from collections.abc import Iterator
5
+ from typing import TYPE_CHECKING, Any
6
+ from urllib.parse import quote
7
+
8
+ from catastrogps.errors import CatastroGPSError
9
+
10
+ if TYPE_CHECKING:
11
+ from catastrogps.client import CatastroGPS
12
+
13
+ MAX_BATCH_REFERENCES = 1000
14
+ BATCH_LAYERS = ("parcel", "notices", "changes")
15
+ FINISHED_BATCH_STATUSES = ("completed", "partial_failure", "failed")
16
+ DEFAULT_WAIT_INTERVAL_SECONDS = 5.0
17
+ DEFAULT_WAIT_TIMEOUT_SECONDS = 1800.0
18
+
19
+
20
+ class NoticesResource:
21
+ def __init__(self, client: CatastroGPS) -> None:
22
+ self._client = client
23
+
24
+ def search(
25
+ self,
26
+ *,
27
+ country: str | None = None,
28
+ municipality_code: str | None = None,
29
+ municipality: str | None = None,
30
+ kind: str | None = None,
31
+ date_from: str | None = None,
32
+ date_to: str | None = None,
33
+ has_parcels: bool | None = None,
34
+ cursor: str | None = None,
35
+ limit: int | None = None,
36
+ ) -> dict[str, Any]:
37
+ query = {
38
+ "country": country,
39
+ "municipalityCode": municipality_code,
40
+ "municipality": municipality,
41
+ "kind": kind,
42
+ "from": date_from,
43
+ "to": date_to,
44
+ "hasParcels": None if has_parcels is None else str(has_parcels).lower(),
45
+ "cursor": cursor,
46
+ "limit": limit,
47
+ }
48
+ return self._client.request("GET", "/v1/notices", query=query)
49
+
50
+ def iter_pages(self, **filters: Any) -> Iterator[dict[str, Any]]:
51
+ cursor = filters.pop("cursor", None)
52
+ while True:
53
+ page = self.search(cursor=cursor, **filters)
54
+ yield page
55
+ cursor = page.get("nextCursor")
56
+ if not cursor:
57
+ return
58
+
59
+
60
+ class BatchResource:
61
+ def __init__(self, client: CatastroGPS) -> None:
62
+ self._client = client
63
+
64
+ def submit(
65
+ self, references: list[str], *, layers: list[str] | None = None, country: str | None = None
66
+ ) -> dict[str, Any]:
67
+ cleaned = [reference.strip() for reference in references if reference and reference.strip()]
68
+ if not cleaned:
69
+ raise CatastroGPSError("references must not be empty")
70
+ if len(cleaned) > MAX_BATCH_REFERENCES:
71
+ raise CatastroGPSError(f"a batch takes up to {MAX_BATCH_REFERENCES} references")
72
+ for layer in layers or []:
73
+ if layer not in BATCH_LAYERS:
74
+ raise CatastroGPSError(f"layers must be among {', '.join(BATCH_LAYERS)}")
75
+ body: dict[str, Any] = {"references": cleaned}
76
+ if layers:
77
+ body["layers"] = layers
78
+ if country:
79
+ body["country"] = country
80
+ return self._client.request("POST", "/v1/batch", body=body)
81
+
82
+ def get(self, batch_id: str) -> dict[str, Any]:
83
+ return self._client.request("GET", batch_path(batch_id))
84
+
85
+ def csv(self, batch_id: str) -> str:
86
+ content = self._client.request("GET", batch_path(batch_id), query={"format": "csv"}, raw=True)
87
+ return content.decode("utf-8")
88
+
89
+ def wait(
90
+ self,
91
+ batch_id: str,
92
+ *,
93
+ interval: float = DEFAULT_WAIT_INTERVAL_SECONDS,
94
+ timeout: float = DEFAULT_WAIT_TIMEOUT_SECONDS,
95
+ ) -> dict[str, Any]:
96
+ deadline = time.monotonic() + timeout
97
+ while True:
98
+ batch = self.get(batch_id)
99
+ if batch.get("status") in FINISHED_BATCH_STATUSES:
100
+ return batch
101
+ if time.monotonic() + interval > deadline:
102
+ raise CatastroGPSError(f"batch {batch_id} did not finish in time")
103
+ time.sleep(interval)
104
+
105
+
106
+ def batch_path(batch_id: str) -> str:
107
+ cleaned = (batch_id or "").strip()
108
+ if not cleaned:
109
+ raise CatastroGPSError("batch id must not be empty")
110
+ return f"/v1/batch/{quote(cleaned, safe='')}"
@@ -83,6 +83,8 @@ CROP_LANGUAGES = ("es", "ca", "en", "pt", "fr", "it", "de", "pl", "nl", "cs")
83
83
  MIN_COMPARE = 2
84
84
  MAX_COMPARE = 3
85
85
 
86
+ REPORT_LAYERS = ("risks", "water", "soil", "protections", "services")
87
+
86
88
 
87
89
  def parcel_path(reference: str, suffix: str = "") -> str:
88
90
  cleaned = (reference or "").strip()
@@ -167,6 +169,34 @@ class ParcelsResource:
167
169
  def value_history(self, reference: str, *, country: str | None = None) -> dict[str, Any]:
168
170
  return self._client.request("GET", parcel_path(reference, "/value-history"), query={"country": country})
169
171
 
172
+ def notices(self, reference: str, *, limit: int | None = None) -> dict[str, Any]:
173
+ return self._client.request("GET", parcel_path(reference, "/notices"), query={"limit": limit})
174
+
175
+ def changes(self, reference: str, *, since: str | None = None, country: str | None = None) -> dict[str, Any]:
176
+ return self._client.request(
177
+ "GET", parcel_path(reference, "/changes"), query={"since": since, "country": country}
178
+ )
179
+
180
+ def layer(self, reference: str, layer: str, *, country: str | None = None) -> dict[str, Any]:
181
+ if layer not in REPORT_LAYERS:
182
+ raise CatastroGPSError(f"layer must be one of {', '.join(REPORT_LAYERS)}")
183
+ return self._client.request("GET", parcel_path(reference, f"/{layer}"), query={"country": country})
184
+
185
+ def risks(self, reference: str, *, country: str | None = None) -> dict[str, Any]:
186
+ return self.layer(reference, "risks", country=country)
187
+
188
+ def water(self, reference: str, *, country: str | None = None) -> dict[str, Any]:
189
+ return self.layer(reference, "water", country=country)
190
+
191
+ def soil(self, reference: str, *, country: str | None = None) -> dict[str, Any]:
192
+ return self.layer(reference, "soil", country=country)
193
+
194
+ def protections(self, reference: str, *, country: str | None = None) -> dict[str, Any]:
195
+ return self.layer(reference, "protections", country=country)
196
+
197
+ def services(self, reference: str, *, country: str | None = None) -> dict[str, Any]:
198
+ return self.layer(reference, "services", country=country)
199
+
170
200
  def compare(self, parcels: list[tuple[str, str]] | list[dict[str, str]]) -> dict[str, Any]:
171
201
  items = [_compare_item(parcel) for parcel in parcels]
172
202
  if not MIN_COMPARE <= len(items) <= MAX_COMPARE:
@@ -0,0 +1,165 @@
1
+ import json
2
+
3
+ import httpx
4
+ import pytest
5
+
6
+ import catastrogps.client as client_module
7
+ import catastrogps.monitoring as monitoring_module
8
+ from catastrogps import (
9
+ MAX_BATCH_REFERENCES,
10
+ CatastroGPS,
11
+ CatastroGPSError,
12
+ ForbiddenError,
13
+ PlanLimitError,
14
+ PlanRequiredError,
15
+ )
16
+
17
+
18
+ class Recorder:
19
+ def __init__(self, *responses):
20
+ self.responses = list(responses)
21
+ self.requests = []
22
+
23
+ def __call__(self, request: httpx.Request) -> httpx.Response:
24
+ self.requests.append(request)
25
+ return self.responses.pop(0)
26
+
27
+
28
+ @pytest.fixture(autouse=True)
29
+ def no_sleep(monkeypatch):
30
+ monkeypatch.setattr(client_module.time, "sleep", lambda _seconds: None)
31
+ monkeypatch.setattr(monitoring_module.time, "sleep", lambda _seconds: None)
32
+
33
+
34
+ def make(*responses, max_retries=2):
35
+ recorder = Recorder(*responses)
36
+ http = httpx.Client(transport=httpx.MockTransport(recorder))
37
+ client = CatastroGPS(
38
+ "pk_test_000000000000", base_url="https://api.example.test", http_client=http, max_retries=max_retries
39
+ )
40
+ return client, recorder
41
+
42
+
43
+ def ok(data, status=200):
44
+ return httpx.Response(status, json={"success": True, "data": data})
45
+
46
+
47
+ NOTICE = {"id": "n1", "country": "ES", "source": "boe_es", "kind": "expropriation", "publishedAt": "2026-11-30",
48
+ "title": "Anuncio", "url": "https://www.boe.es/x", "municipalities": [], "municipalityCodes": []}
49
+ BATCH = {"id": "b1", "status": "pending", "layers": ["parcel"], "referenceCount": 2, "processed": 0, "succeeded": 0,
50
+ "failed": 0, "unitsCharged": 2, "createdAt": "2026-12-01T10:00:00Z", "results": []}
51
+
52
+
53
+ def test_parcel_notices_and_limit():
54
+ client, recorder = make(ok({"reference": "R1", "count": 1, "items": [NOTICE]}))
55
+ result = client.parcels.notices(" R1 ", limit=5)
56
+ assert result["items"][0]["kind"] == "expropriation"
57
+ request = recorder.requests[0]
58
+ assert request.url.path == "/v1/parcels/R1/notices"
59
+ assert request.url.params["limit"] == "5"
60
+
61
+
62
+ def test_notice_search_maps_filters_and_pages():
63
+ client, recorder = make(
64
+ ok({"count": 1, "items": [NOTICE], "nextCursor": "c2"}),
65
+ ok({"count": 1, "items": [NOTICE]}),
66
+ )
67
+ pages = list(client.notices.iter_pages(country="ES", kind="planning", date_from="2026-01-01",
68
+ date_to="2026-02-01", has_parcels=True, municipality_code="33024",
69
+ municipality="GIJON", limit=1))
70
+ assert len(pages) == 2
71
+ first = recorder.requests[0].url.params
72
+ assert first["from"] == "2026-01-01"
73
+ assert first["to"] == "2026-02-01"
74
+ assert first["hasParcels"] == "true"
75
+ assert first["municipalityCode"] == "33024"
76
+ assert "cursor" not in first
77
+ assert recorder.requests[1].url.params["cursor"] == "c2"
78
+
79
+
80
+ def test_notice_search_without_filters():
81
+ client, recorder = make(ok({"count": 0, "items": []}))
82
+ client.notices.search(has_parcels=False)
83
+ assert dict(recorder.requests[0].url.params) == {"hasParcels": "false"}
84
+
85
+
86
+ def test_changes_since():
87
+ client, recorder = make(ok({"reference": "R", "country": "ES", "monitored": False, "count": 0, "items": []}))
88
+ assert client.parcels.changes("R", since="2026-01-01", country="ES")["monitored"] is False
89
+ assert recorder.requests[0].url.path == "/v1/parcels/R/changes"
90
+ assert recorder.requests[0].url.params["since"] == "2026-01-01"
91
+
92
+
93
+ @pytest.mark.parametrize("layer", ["risks", "water", "soil", "protections", "services"])
94
+ def test_report_layers(layer):
95
+ client, recorder = make(ok({"reference": "R", "country": "ES", "layer": layer, "items": [],
96
+ "attribution": "Source: Catastro GPS"}))
97
+ assert getattr(client.parcels, layer)("R", country="ES")["attribution"] == "Source: Catastro GPS"
98
+ assert recorder.requests[0].url.path == f"/v1/parcels/R/{layer}"
99
+
100
+
101
+ def test_unknown_layer_is_refused_locally():
102
+ client, recorder = make()
103
+ with pytest.raises(CatastroGPSError, match="layer must be one of"):
104
+ client.parcels.layer("R", "market")
105
+ assert recorder.requests == []
106
+
107
+
108
+ def test_plan_errors_are_typed_and_not_retried():
109
+ client, recorder = make(httpx.Response(403, json={"success": False, "code": "KEY_PLAN_001", "message": "Startup"}))
110
+ with pytest.raises(PlanRequiredError) as raised:
111
+ client.parcels.risks("R")
112
+ assert isinstance(raised.value, ForbiddenError)
113
+ assert len(recorder.requests) == 1
114
+
115
+ client, recorder = make(httpx.Response(429, json={"success": False, "code": "KEY_LAYER_001", "message": "cap"},
116
+ headers={"Retry-After": "1"}))
117
+ with pytest.raises(PlanLimitError):
118
+ client.parcels.water("R")
119
+ assert len(recorder.requests) == 1
120
+
121
+
122
+ def test_batch_submit_trims_and_sends_layers():
123
+ client, recorder = make(ok(BATCH, 202), ok(BATCH, 202))
124
+ client.batch.submit([" A1 ", "", "B2"], layers=["parcel", "notices"], country="ES")
125
+ request = recorder.requests[0]
126
+ assert request.method == "POST"
127
+ assert json.loads(request.content) == {"references": ["A1", "B2"], "layers": ["parcel", "notices"], "country": "ES"}
128
+ client.batch.submit(["A1"])
129
+ assert json.loads(recorder.requests[1].content) == {"references": ["A1"]}
130
+
131
+
132
+ def test_batch_validation():
133
+ client, recorder = make()
134
+ with pytest.raises(CatastroGPSError, match="must not be empty"):
135
+ client.batch.submit([" "])
136
+ with pytest.raises(CatastroGPSError, match="up to 1000"):
137
+ client.batch.submit([f"R{i}" for i in range(MAX_BATCH_REFERENCES + 1)])
138
+ with pytest.raises(CatastroGPSError, match="layers must be among"):
139
+ client.batch.submit(["A"], layers=["market"])
140
+ with pytest.raises(CatastroGPSError, match="batch id"):
141
+ client.batch.get(" ")
142
+ assert recorder.requests == []
143
+
144
+
145
+ def test_batch_units_error():
146
+ client, _ = make(httpx.Response(429, json={"success": False, "code": "BAT_015", "message": "units"}))
147
+ with pytest.raises(PlanLimitError):
148
+ client.batch.submit(["A"])
149
+
150
+
151
+ def test_batch_get_csv_and_wait():
152
+ client, recorder = make(
153
+ ok({**BATCH, "status": "processing"}),
154
+ ok({**BATCH, "status": "completed"}),
155
+ httpx.Response(200, content=b"index,reference\n0,A1\n", headers={"Content-Type": "text/csv"}),
156
+ )
157
+ assert client.batch.wait("b1", interval=0.0, timeout=10)["status"] == "completed"
158
+ assert client.batch.csv("b1") == "index,reference\n0,A1\n"
159
+ assert recorder.requests[2].url.params["format"] == "csv"
160
+
161
+
162
+ def test_batch_wait_times_out():
163
+ client, _ = make(ok({**BATCH, "status": "processing"}))
164
+ with pytest.raises(CatastroGPSError, match="did not finish"):
165
+ client.batch.wait("b1", interval=5, timeout=1)
@@ -1 +0,0 @@
1
- __version__ = "2.2.0"
File without changes
File without changes
File without changes