portolan-python 0.1.8__tar.gz → 0.1.9__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. portolan_python-0.1.9/.github/workflows/ci.yml +45 -0
  2. {portolan_python-0.1.8 → portolan_python-0.1.9}/.gitignore +4 -0
  3. portolan_python-0.1.9/Makefile +40 -0
  4. {portolan_python-0.1.8 → portolan_python-0.1.9}/PKG-INFO +17 -1
  5. {portolan_python-0.1.8 → portolan_python-0.1.9}/README.md +16 -0
  6. portolan_python-0.1.9/docs/conformance.md +49 -0
  7. {portolan_python-0.1.8 → portolan_python-0.1.9}/docs/distribution.md +4 -4
  8. {portolan_python-0.1.8 → portolan_python-0.1.9}/docs/examples.md +2 -2
  9. {portolan_python-0.1.8 → portolan_python-0.1.9}/pyproject.toml +1 -1
  10. {portolan_python-0.1.8 → portolan_python-0.1.9}/src/portolan/__init__.py +13 -1
  11. {portolan_python-0.1.8 → portolan_python-0.1.9}/src/portolan/catalog.py +88 -59
  12. portolan_python-0.1.9/tests/conformance_adapter.py +147 -0
  13. {portolan_python-0.1.8 → portolan_python-0.1.9}/tests/test_catalog_api.py +170 -1
  14. portolan_python-0.1.9/tests/test_conformance_adapter.py +59 -0
  15. {portolan_python-0.1.8 → portolan_python-0.1.9}/uv.lock +1 -1
  16. portolan_python-0.1.8/.coverage +0 -0
  17. portolan_python-0.1.8/Makefile +0 -29
  18. {portolan_python-0.1.8 → portolan_python-0.1.9}/.github/workflows/release.yml +0 -0
  19. {portolan_python-0.1.8 → portolan_python-0.1.9}/docs/development.md +0 -0
  20. {portolan_python-0.1.8 → portolan_python-0.1.9}/docs/scope.md +0 -0
  21. {portolan_python-0.1.8 → portolan_python-0.1.9}/src/portolan/py.typed +0 -0
  22. {portolan_python-0.1.8 → portolan_python-0.1.9}/src/portolan/registry.py +0 -0
  23. {portolan_python-0.1.8 → portolan_python-0.1.9}/src/portolan/validation.py +0 -0
  24. {portolan_python-0.1.8 → portolan_python-0.1.9}/tests/test_registry_api.py +0 -0
@@ -0,0 +1,45 @@
1
+ name: CI
2
+
3
+ on:
4
+ pull_request:
5
+ push:
6
+ branches: [main]
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v6
13
+
14
+ - uses: actions/setup-python@v6
15
+ with:
16
+ python-version: "3.12"
17
+
18
+ - name: Install SDK and development tools
19
+ run: python -m pip install --upgrade ".[dev]"
20
+
21
+ - name: Run SDK checks
22
+ run: |
23
+ pytest
24
+ mypy src tests
25
+ ruff check .
26
+
27
+ - name: Check out pinned conformance suite
28
+ uses: actions/checkout@v6
29
+ with:
30
+ repository: geoverse-dev/portolan-conformance
31
+ ref: v0.1.1
32
+ path: portolan-conformance
33
+
34
+ - name: Install conformance suite
35
+ run: python -m pip install ./portolan-conformance
36
+
37
+ - name: Run SDK Read Profile v1
38
+ run: make check-conformance ADAPTER_PYTHON=python CONFORMANCE=portolan-conformance
39
+
40
+ - name: Upload conformance report
41
+ if: always()
42
+ uses: actions/upload-artifact@v7
43
+ with:
44
+ name: read-profile-report
45
+ path: read-profile-report.json
@@ -4,3 +4,7 @@
4
4
  .venv/
5
5
  __pycache__/
6
6
  *.py[cod]
7
+ .coverage
8
+ .coverage.*
9
+ htmlcov/
10
+ read-profile-report.json
@@ -0,0 +1,40 @@
1
+ .PHONY: help setup test coverage lint typecheck check check-conformance build clean
2
+
3
+ UV ?= uv
4
+ ADAPTER_PYTHON ?= $(UV) run python
5
+ CONFORMANCE_REPOSITORY ?= https://github.com/geoverse-dev/portolan-conformance.git
6
+ CONFORMANCE_VERSION ?= v0.1.1
7
+ CONFORMANCE ?= uvx --from 'git+$(CONFORMANCE_REPOSITORY)@$(CONFORMANCE_VERSION)' portolan-conformance
8
+ CONFORMANCE_REPORT ?= read-profile-report.json
9
+
10
+ help:
11
+ @printf '%s\n' 'Targets: setup test coverage lint typecheck check check-conformance build clean'
12
+
13
+ setup:
14
+ $(UV) sync --extra dev
15
+
16
+ test:
17
+ $(UV) run --extra dev pytest
18
+
19
+ coverage:
20
+ $(UV) run --extra dev pytest --cov=portolan --cov-report=term-missing
21
+
22
+ lint:
23
+ $(UV) run --extra dev ruff check .
24
+
25
+ typecheck:
26
+ $(UV) run --extra dev mypy
27
+
28
+ check: lint typecheck test
29
+
30
+ check-conformance:
31
+ $(CONFORMANCE) run \
32
+ --profile read \
33
+ --adapter '$(ADAPTER_PYTHON) $(CURDIR)/tests/conformance_adapter.py' \
34
+ --report '$(CONFORMANCE_REPORT)'
35
+
36
+ build:
37
+ $(UV) build
38
+
39
+ clean:
40
+ rm -rf dist build *.egg-info .pytest_cache .ruff_cache .mypy_cache htmlcov
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: portolan-python
3
- Version: 0.1.8
3
+ Version: 0.1.9
4
4
  Summary: A lightweight Python implementation of the Portolan specification.
5
5
  Author: Portolan contributors
6
6
  License: Apache-2.0
@@ -220,5 +220,21 @@ The Portolan specification remains the source of truth.
220
220
  - [Examples](docs/examples.md) shows basic API usage.
221
221
  - [Development](docs/development.md) lists setup, test, and build commands.
222
222
  - [Distribution](docs/distribution.md) explains releases, `pip`, and PyPI publishing.
223
+ - [Conformance](docs/conformance.md) explains SDK conformance and catalog validation.
224
+
225
+ ## Conformance checks
226
+
227
+ Install the pinned `portolan-conformance` revision from the CI workflow.
228
+ Then run the SDK adapter against Read Profile v1:
229
+
230
+ ```bash
231
+ make check-conformance
232
+ ```
233
+
234
+ The target writes `read-profile-report.json` in the repository root.
235
+ It verifies SDK reading behavior only.
236
+ It does not validate full catalog conformance.
237
+
238
+ See [Conformance](docs/conformance.md) for the supported profile and Rashid integration.
223
239
 
224
240
  ---
@@ -206,5 +206,21 @@ The Portolan specification remains the source of truth.
206
206
  - [Examples](docs/examples.md) shows basic API usage.
207
207
  - [Development](docs/development.md) lists setup, test, and build commands.
208
208
  - [Distribution](docs/distribution.md) explains releases, `pip`, and PyPI publishing.
209
+ - [Conformance](docs/conformance.md) explains SDK conformance and catalog validation.
210
+
211
+ ## Conformance checks
212
+
213
+ Install the pinned `portolan-conformance` revision from the CI workflow.
214
+ Then run the SDK adapter against Read Profile v1:
215
+
216
+ ```bash
217
+ make check-conformance
218
+ ```
219
+
220
+ The target writes `read-profile-report.json` in the repository root.
221
+ It verifies SDK reading behavior only.
222
+ It does not validate full catalog conformance.
223
+
224
+ See [Conformance](docs/conformance.md) for the supported profile and Rashid integration.
209
225
 
210
226
  ---
@@ -0,0 +1,49 @@
1
+ # Conformance
2
+
3
+ `portolan-python` implements SDK Read Profile v1.
4
+ The profile checks how the SDK reads and navigates Portolan metadata.
5
+
6
+ Run the profile with:
7
+
8
+ ```bash
9
+ make check-conformance
10
+ ```
11
+
12
+ The command downloads the pinned `portolan-conformance` release.
13
+ It runs the SDK adapter against 25 read behavior cases.
14
+ It writes `read-profile-report.json` in the repository root.
15
+
16
+ A passing report confirms the tested read behavior.
17
+ It does not confirm that a catalog conforms to the Portolan specification.
18
+
19
+ ## Validate a catalog
20
+
21
+ Use [`rashid`](https://github.com/portolan-sdi/rashid) for normative catalog validation.
22
+ Rashid checks metadata, structure, extensions, asset bytes, and hosting behavior.
23
+
24
+ Python applications can use both libraries for separate tasks:
25
+
26
+ ```python
27
+ from portolan import open_document
28
+ from rashid import validate
29
+
30
+ document = open_document("https://example.test/catalog.json")
31
+ report = validate("https://example.test/catalog.json")
32
+
33
+ if report.errors:
34
+ for finding in report.errors:
35
+ print(finding.message)
36
+ ```
37
+
38
+ `open_document()` reads the metadata through `portolan-python`.
39
+ `validate()` checks the catalog through Rashid.
40
+
41
+ ## Supported profiles
42
+
43
+ | Profile | Status | Purpose |
44
+ |---|---|---|
45
+ | SDK Read Profile v1 | Supported | Read and navigate STAC metadata consistently. |
46
+ | Metadata Validation Profile v1 | Not implemented | Test embedded SDK metadata validation. |
47
+
48
+ Python users can call Rashid directly, so `portolan-python` does not duplicate its normative rules.
49
+ Java provides embedded metadata validation because JVM applications cannot call Rashid as a native library.
@@ -8,8 +8,8 @@ preferred package index for published versions.
8
8
  Push a tag that matches the version in `pyproject.toml`:
9
9
 
10
10
  ```bash
11
- git tag v0.1.8
12
- git push origin v0.1.8
11
+ git tag v0.1.9
12
+ git push origin v0.1.9
13
13
  ```
14
14
 
15
15
  The release workflow runs the tests, builds both distributions, checks their
@@ -25,7 +25,7 @@ Install the wheel attached to a release:
25
25
 
26
26
  ```bash
27
27
  python -m pip install \
28
- https://github.com/jemacchi/portolan-python/releases/download/v0.1.8/portolan_python-0.1.8-py3-none-any.whl
28
+ https://github.com/geoverse-dev/portolan-python/releases/download/v0.1.9/portolan_python-0.1.9-py3-none-any.whl
29
29
  ```
30
30
 
31
31
  This path needs no package index account.
@@ -35,7 +35,7 @@ This path needs no package index account.
35
35
  Install a published version from PyPI with:
36
36
 
37
37
  ```bash
38
- python -m pip install portolan-python==0.1.8
38
+ python -m pip install portolan-python==0.1.9
39
39
  ```
40
40
 
41
41
  Omit the version constraint to install the latest published version.
@@ -10,14 +10,14 @@ GitHub:
10
10
 
11
11
  ```bash
12
12
  python -m pip install \
13
- https://github.com/jemacchi/portolan-python/releases/download/v0.1.8/portolan_python-0.1.8-py3-none-any.whl
13
+ https://github.com/geoverse-dev/portolan-python/releases/download/v0.1.9/portolan_python-0.1.9-py3-none-any.whl
14
14
  ```
15
15
 
16
16
  You can also install the source at a specific tag:
17
17
 
18
18
  ```bash
19
19
  python -m pip install \
20
- "portolan-python @ git+https://github.com/jemacchi/portolan-python.git@v0.1.8"
20
+ "portolan-python @ git+https://github.com/geoverse-dev/portolan-python.git@v0.1.9"
21
21
  ```
22
22
 
23
23
  ## List collections and assets
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "portolan-python"
3
- version = "0.1.8"
3
+ version = "0.1.9"
4
4
  description = "A lightweight Python implementation of the Portolan specification."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -2,7 +2,17 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from portolan.catalog import Asset, AssetFormat, Catalog, Collection, Item, Link, is_stac_metadata
5
+ from portolan.catalog import (
6
+ Asset,
7
+ AssetFormat,
8
+ Catalog,
9
+ Collection,
10
+ Item,
11
+ Link,
12
+ StacDocument,
13
+ is_stac_metadata,
14
+ open_document,
15
+ )
6
16
  from portolan.registry import (
7
17
  DEFAULT_REGISTRY_URL,
8
18
  RegistryCatalogEntry,
@@ -20,10 +30,12 @@ __all__ = [
20
30
  "Item",
21
31
  "Link",
22
32
  "RegistryCatalogEntry",
33
+ "StacDocument",
23
34
  "ValidationError",
24
35
  "ValidationResult",
25
36
  "Validator",
26
37
  "download_registry_catalog",
27
38
  "is_stac_metadata",
28
39
  "load_registry_entries",
40
+ "open_document",
29
41
  ]
@@ -6,7 +6,7 @@ import json
6
6
  from collections.abc import Iterator
7
7
  from dataclasses import dataclass
8
8
  from enum import Enum
9
- from pathlib import Path
9
+ from pathlib import Path, PureWindowsPath
10
10
  from typing import Any
11
11
  from urllib.parse import unquote, urljoin, urlparse
12
12
  from urllib.request import Request, urlopen
@@ -34,6 +34,12 @@ class Link:
34
34
  title: str | None
35
35
  raw: JsonObject
36
36
 
37
+ @property
38
+ def original_href(self) -> str:
39
+ """Return the HREF exactly as authored in the containing document."""
40
+ value = self.raw.get("href")
41
+ return value if isinstance(value, str) else ""
42
+
37
43
 
38
44
  @dataclass(frozen=True)
39
45
  class Asset:
@@ -47,6 +53,12 @@ class Asset:
47
53
  description: str | None
48
54
  raw: JsonObject
49
55
 
56
+ @property
57
+ def original_href(self) -> str:
58
+ """Return the HREF exactly as authored in the containing document."""
59
+ value = self.raw.get("href")
60
+ return value if isinstance(value, str) else ""
61
+
50
62
  @property
51
63
  def format(self) -> AssetFormat:
52
64
  """Return the known Portolan asset format, without reading the asset bytes."""
@@ -64,24 +76,44 @@ class Asset:
64
76
  return AssetFormat.UNKNOWN
65
77
 
66
78
 
67
- class Catalog:
68
- """A loaded Portolan catalog root."""
79
+ class StacDocument:
80
+ """Common read-only access to a loaded STAC metadata document."""
69
81
 
70
82
  def __init__(self, data: JsonObject, href: str) -> None:
71
83
  self._data = data
72
84
  self._href = href
73
85
 
74
- @classmethod
75
- def open(cls, source: str | Path) -> Catalog:
76
- """Open a local or remote Portolan catalog document."""
77
- href = _source_to_href(source)
78
- data = _read_json_href(href)
79
- return cls(data, href)
80
-
81
86
  @property
82
87
  def id(self) -> str:
83
88
  return str(self._data.get("id", ""))
84
89
 
90
+ @property
91
+ def type(self) -> str:
92
+ value = self._data.get("type")
93
+ return value if isinstance(value, str) else ""
94
+
95
+ @property
96
+ def title(self) -> str | None:
97
+ value = self._data.get("title")
98
+ return value if isinstance(value, str) else None
99
+
100
+ @property
101
+ def description(self) -> str | None:
102
+ value = self._data.get("description")
103
+ return value if isinstance(value, str) else None
104
+
105
+ @property
106
+ def stac_version(self) -> str | None:
107
+ value = self._data.get("stac_version")
108
+ return value if isinstance(value, str) else None
109
+
110
+ @property
111
+ def stac_extensions(self) -> tuple[str, ...]:
112
+ value = self._data.get("stac_extensions")
113
+ if not isinstance(value, list):
114
+ return ()
115
+ return tuple(extension for extension in value if isinstance(extension, str))
116
+
85
117
  @property
86
118
  def href(self) -> str:
87
119
  return self._href
@@ -93,6 +125,29 @@ class Catalog:
93
125
  def links(self) -> Iterator[Link]:
94
126
  yield from _links(self._data, self._href)
95
127
 
128
+ def assets(self) -> Iterator[Asset]:
129
+ """Yield metadata for assets without reading their bytes."""
130
+ yield from _assets(self._data, self._href)
131
+
132
+ def children(self) -> Iterator[Link]:
133
+ """Yield direct STAC child links without traversing their targets."""
134
+ yield from (link for link in self.links() if link.rel == "child")
135
+
136
+ def direct_item_links(self) -> Iterator[Link]:
137
+ """Yield direct STAC item links without traversing child catalogs."""
138
+ yield from (link for link in self.links() if link.rel == "item")
139
+
140
+
141
+ class Catalog(StacDocument):
142
+ """A loaded Portolan catalog root."""
143
+
144
+ @classmethod
145
+ def open(cls, source: str | Path) -> Catalog:
146
+ """Open a local or remote Portolan catalog document."""
147
+ href = _source_to_href(source)
148
+ data = _read_json_href(href)
149
+ return cls(data, href)
150
+
96
151
  def collections(self) -> Iterator[Collection]:
97
152
  """Yield child collections, including collections below child catalogs."""
98
153
  yield from _collections_from_catalog(self._data, self._href, set())
@@ -102,13 +157,9 @@ class Catalog:
102
157
  yield from _item_links_from_document(self._data, self._href, set())
103
158
 
104
159
 
105
- class Collection:
160
+ class Collection(StacDocument):
106
161
  """A loaded STAC Collection within a Portolan catalog."""
107
162
 
108
- def __init__(self, data: JsonObject, href: str) -> None:
109
- self._data = data
110
- self._href = href
111
-
112
163
  @classmethod
113
164
  def open(cls, source: str | Path) -> Collection:
114
165
  """Open a local or remote STAC Collection document."""
@@ -116,24 +167,6 @@ class Collection:
116
167
  data = _read_json_href(href)
117
168
  return cls(data, href)
118
169
 
119
- @property
120
- def id(self) -> str:
121
- return str(self._data.get("id", ""))
122
-
123
- @property
124
- def href(self) -> str:
125
- return self._href
126
-
127
- @property
128
- def data(self) -> JsonObject:
129
- return dict(self._data)
130
-
131
- def links(self) -> Iterator[Link]:
132
- yield from _links(self._data, self._href)
133
-
134
- def assets(self) -> Iterator[Asset]:
135
- yield from _assets(self._data, self._href)
136
-
137
170
  def items(self) -> Iterator[Item]:
138
171
  """Yield linked items from this collection."""
139
172
  for link in self.item_links():
@@ -151,13 +184,9 @@ class Collection:
151
184
  yield from _item_links_from_document(self._data, self._href, set())
152
185
 
153
186
 
154
- class Item:
187
+ class Item(StacDocument):
155
188
  """A loaded STAC Item."""
156
189
 
157
- def __init__(self, data: JsonObject, href: str) -> None:
158
- self._data = data
159
- self._href = href
160
-
161
190
  @classmethod
162
191
  def open(cls, source: str | Path) -> Item:
163
192
  """Open a local or remote STAC Item document."""
@@ -165,23 +194,18 @@ class Item:
165
194
  data = _read_json_href(href)
166
195
  return cls(data, href)
167
196
 
168
- @property
169
- def id(self) -> str:
170
- return str(self._data.get("id", ""))
171
-
172
- @property
173
- def href(self) -> str:
174
- return self._href
175
-
176
- @property
177
- def data(self) -> JsonObject:
178
- return dict(self._data)
179
-
180
- def links(self) -> Iterator[Link]:
181
- yield from _links(self._data, self._href)
182
-
183
- def assets(self) -> Iterator[Asset]:
184
- yield from _assets(self._data, self._href)
197
+ def open_document(source: str | Path) -> Catalog | Collection | Item:
198
+ """Open any supported STAC metadata document using its declared type."""
199
+ href = _source_to_href(source)
200
+ data = _read_json_href(href)
201
+ document_type = data.get("type")
202
+ if document_type == "Catalog":
203
+ return Catalog(data, href)
204
+ if document_type == "Collection":
205
+ return Collection(data, href)
206
+ if document_type == "Feature":
207
+ return Item(data, href)
208
+ raise ValueError(f"Unsupported STAC document type: {document_type!r}")
185
209
 
186
210
 
187
211
  def is_stac_metadata(source: str | Path) -> bool:
@@ -278,10 +302,15 @@ def _source_to_href(source: str | Path, *, default_document: str = "catalog.json
278
302
  if isinstance(source, Path):
279
303
  path = source
280
304
  else:
281
- parsed = urlparse(source)
282
- if parsed.scheme in {"http", "https", "file"}:
283
- return source
284
- path = Path(source)
305
+ if PureWindowsPath(source).is_absolute():
306
+ path = Path(source)
307
+ else:
308
+ parsed = urlparse(source)
309
+ if parsed.scheme in {"http", "https", "file"}:
310
+ return source
311
+ if parsed.scheme:
312
+ raise ValueError(f"Unsupported URI scheme: {parsed.scheme}")
313
+ path = Path(source)
285
314
  if path.is_dir():
286
315
  path = path / default_document
287
316
  return path.resolve().as_uri()
@@ -0,0 +1,147 @@
1
+ """Command-line adapter for the Portolan SDK Read Profile v1 test suite."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from json import JSONDecodeError
8
+ from typing import Any
9
+ from urllib.error import HTTPError, URLError
10
+
11
+ from portolan import Catalog, StacDocument, open_document
12
+
13
+ JsonObject = dict[str, Any]
14
+ OPERATIONS = frozenset(
15
+ {"document", "inspect", "children", "collections", "items", "assets", "links"}
16
+ )
17
+
18
+
19
+ def _entry(document: StacDocument) -> JsonObject:
20
+ return {"id": document.id, "uri": document.href}
21
+
22
+
23
+ def _linked_entries(document: StacDocument, relation: str) -> list[JsonObject]:
24
+ entries = []
25
+ for link in document.links():
26
+ if link.rel == relation:
27
+ entries.append(_entry(open_document(link.href)))
28
+ return sorted(entries, key=lambda entry: (entry["id"], entry["uri"]))
29
+
30
+
31
+ def _extra_fields(raw: JsonObject, known: set[str]) -> JsonObject:
32
+ return {key: value for key, value in raw.items() if key not in known}
33
+
34
+
35
+ def _operate(operation: str, uri: str) -> JsonObject:
36
+ document = open_document(uri)
37
+ if operation == "document":
38
+ return {"document": document.data}
39
+ if operation == "inspect":
40
+ return {
41
+ "type": document.type,
42
+ "id": document.id,
43
+ "title": document.title,
44
+ "description": document.description,
45
+ "stac_version": document.stac_version,
46
+ "stac_extensions": list(document.stac_extensions),
47
+ }
48
+ if operation == "children":
49
+ return {"entries": _linked_entries(document, "child")}
50
+ if operation == "collections":
51
+ if not isinstance(document, Catalog):
52
+ return {"entries": []}
53
+ entries = [_entry(collection) for collection in document.collections()]
54
+ return {"entries": sorted(entries, key=lambda entry: (entry["id"], entry["uri"]))}
55
+ if operation == "items":
56
+ return {"entries": _linked_entries(document, "item")}
57
+ if operation == "assets":
58
+ raw_assets = document.data.get("assets")
59
+ entries = []
60
+ if isinstance(raw_assets, dict):
61
+ assets_by_key = {asset.key: asset for asset in document.assets()}
62
+ for key, raw in raw_assets.items():
63
+ valid_asset = (
64
+ isinstance(key, str) and isinstance(raw, dict) and key in assets_by_key
65
+ )
66
+ if not valid_asset:
67
+ continue
68
+ asset = assets_by_key[key]
69
+ roles = raw.get("roles", [])
70
+ entries.append(
71
+ {
72
+ "key": key,
73
+ "href": asset.original_href,
74
+ "resolved_href": asset.href,
75
+ "type": raw.get("type") if isinstance(raw.get("type"), str) else None,
76
+ "roles": roles if isinstance(roles, list) else [],
77
+ "title": raw.get("title") if isinstance(raw.get("title"), str) else None,
78
+ "description": raw.get("description")
79
+ if isinstance(raw.get("description"), str)
80
+ else None,
81
+ "extra_fields": _extra_fields(
82
+ raw, {"href", "type", "roles", "title", "description"}
83
+ ),
84
+ }
85
+ )
86
+ return {"entries": sorted(entries, key=lambda entry: entry["key"])}
87
+ if operation == "links":
88
+ entries = []
89
+ for link in document.links():
90
+ entries.append(
91
+ {
92
+ "rel": link.rel,
93
+ "href": link.original_href,
94
+ "resolved_href": link.href,
95
+ "type": link.media_type,
96
+ "title": link.title,
97
+ "extra_fields": _extra_fields(link.raw, {"rel", "href", "type", "title"}),
98
+ }
99
+ )
100
+ return {"entries": sorted(entries, key=lambda entry: (entry["rel"], entry["href"]))}
101
+ raise ValueError("UNSUPPORTED_OPERATION")
102
+
103
+
104
+ def _request(value: object) -> JsonObject:
105
+ if not isinstance(value, dict):
106
+ raise ValueError("INVALID_REQUEST")
107
+ if value.get("protocol_version") != "1":
108
+ raise ValueError("UNSUPPORTED_PROTOCOL")
109
+ operation = value.get("operation")
110
+ uri = value.get("uri")
111
+ if not isinstance(operation, str) or not isinstance(uri, str) or not uri:
112
+ raise ValueError("INVALID_REQUEST")
113
+ if operation not in OPERATIONS:
114
+ raise ValueError("UNSUPPORTED_OPERATION")
115
+ return _operate(operation, uri)
116
+
117
+
118
+ def _error_code(error: Exception) -> str:
119
+ message = str(error)
120
+ if message in {"INVALID_REQUEST", "UNSUPPORTED_PROTOCOL", "UNSUPPORTED_OPERATION"}:
121
+ return message
122
+ if isinstance(error, FileNotFoundError) or isinstance(error, HTTPError) and error.code == 404:
123
+ return "NOT_FOUND"
124
+ if isinstance(error, JSONDecodeError):
125
+ return "INVALID_JSON"
126
+ if isinstance(error, (HTTPError, URLError, OSError)):
127
+ return "READ_ERROR"
128
+ if isinstance(error, ValueError) and message.startswith("Unsupported URI scheme"):
129
+ return "UNSUPPORTED_PROTOCOL"
130
+ return "READ_ERROR"
131
+
132
+
133
+ def main() -> int:
134
+ try:
135
+ try:
136
+ request = json.loads(sys.stdin.readline())
137
+ except JSONDecodeError as error:
138
+ raise ValueError("INVALID_REQUEST") from error
139
+ response: JsonObject = {"status": "ok", "result": _request(request)}
140
+ except Exception as error: # Adapter boundary translates SDK and transport errors.
141
+ response = {"status": "error", "error": {"code": _error_code(error)}}
142
+ print(json.dumps(response, ensure_ascii=False, separators=(",", ":")))
143
+ return 0
144
+
145
+
146
+ if __name__ == "__main__":
147
+ raise SystemExit(main())
@@ -8,7 +8,15 @@ from typing import Any
8
8
 
9
9
  import pytest
10
10
 
11
- from portolan import AssetFormat, Catalog, Collection, Item, Validator, is_stac_metadata
11
+ from portolan import (
12
+ AssetFormat,
13
+ Catalog,
14
+ Collection,
15
+ Item,
16
+ Validator,
17
+ is_stac_metadata,
18
+ open_document,
19
+ )
12
20
 
13
21
  pytestmark = pytest.mark.unit
14
22
 
@@ -193,6 +201,157 @@ def test_collection_item_links_preserve_written_href_and_resolve_against_owner()
193
201
  assert link.raw["href"] == "./items/road-a.json"
194
202
  assert link.href == "https://example.test/catalog/roads/items/road-a.json"
195
203
  assert link.media_type == "application/geo+json"
204
+ assert link.original_href == "./items/road-a.json"
205
+
206
+
207
+ def test_open_document_returns_the_matching_public_model(tmp_path: Path) -> None:
208
+ documents = [
209
+ ("catalog.json", {"type": "Catalog", "id": "root", "links": []}, Catalog),
210
+ ("collection.json", {"type": "Collection", "id": "roads", "links": []}, Collection),
211
+ ("item.json", {"type": "Feature", "id": "road", "links": []}, Item),
212
+ ]
213
+ for name, data, expected_type in documents:
214
+ path = tmp_path / name
215
+ _write_json(path, data)
216
+ assert isinstance(open_document(path.as_uri()), expected_type)
217
+
218
+
219
+ def test_document_metadata_and_direct_links_are_available(tmp_path: Path) -> None:
220
+ _write_json(
221
+ tmp_path / "catalog.json",
222
+ {
223
+ "type": "Catalog",
224
+ "id": "root",
225
+ "title": "Root",
226
+ "description": None,
227
+ "stac_version": "1.1.0",
228
+ "stac_extensions": ["https://example.test/ext.json"],
229
+ "links": [
230
+ {"rel": "child", "href": "./nested.json"},
231
+ {"rel": "item", "href": "./direct.json"},
232
+ ],
233
+ },
234
+ )
235
+ catalog = open_document(tmp_path / "catalog.json")
236
+ assert isinstance(catalog, Catalog)
237
+ assert catalog.type == "Catalog"
238
+ assert catalog.title == "Root"
239
+ assert catalog.description is None
240
+ assert catalog.stac_version == "1.1.0"
241
+ assert catalog.stac_extensions == ("https://example.test/ext.json",)
242
+ assert [link.original_href for link in catalog.children()] == ["./nested.json"]
243
+ assert [link.original_href for link in catalog.direct_item_links()] == ["./direct.json"]
244
+
245
+
246
+ def test_assets_expose_original_and_resolved_hrefs() -> None:
247
+ collection = Collection(
248
+ {
249
+ "type": "Collection",
250
+ "id": "roads",
251
+ "assets": {"data": {"href": "./data.parquet", "roles": ["data"]}},
252
+ },
253
+ "https://example.test/catalog/collection.json",
254
+ )
255
+ [asset] = list(collection.assets())
256
+ assert asset.original_href == "./data.parquet"
257
+ assert asset.href == "https://example.test/catalog/data.parquet"
258
+
259
+
260
+ def test_read_models_ignore_malformed_optional_metadata() -> None:
261
+ catalog = Catalog(
262
+ {
263
+ "type": 7,
264
+ "title": 7,
265
+ "description": [],
266
+ "stac_version": {},
267
+ "stac_extensions": "not-a-list",
268
+ "links": [
269
+ None,
270
+ {"rel": 7, "href": "ignored.json"},
271
+ {"rel": "child", "href": 7},
272
+ {"rel": "child", "href": "valid.json", "type": 7, "title": []},
273
+ ],
274
+ "assets": {
275
+ "not-an-object": 7,
276
+ "missing-href": {},
277
+ "fallback-type": {
278
+ "href": "data.bin",
279
+ "media_type": "application/octet-stream",
280
+ "roles": "data",
281
+ "title": 7,
282
+ "description": [],
283
+ },
284
+ },
285
+ },
286
+ "https://example.test/catalog.json",
287
+ )
288
+
289
+ assert catalog.type == ""
290
+ assert catalog.title is None
291
+ assert catalog.description is None
292
+ assert catalog.stac_version is None
293
+ assert catalog.stac_extensions == ()
294
+ [link] = list(catalog.links())
295
+ assert link.media_type is None
296
+ assert link.title is None
297
+ [asset] = list(catalog.assets())
298
+ assert asset.media_type == "application/octet-stream"
299
+ assert asset.roles == ()
300
+ assert asset.title is None
301
+ assert asset.description is None
302
+
303
+
304
+ def test_traversal_stops_at_catalog_cycles(tmp_path: Path) -> None:
305
+ _write_json(
306
+ tmp_path / "catalog.json",
307
+ {
308
+ "type": "Catalog",
309
+ "id": "root",
310
+ "links": [{"rel": "child", "href": "nested.json"}],
311
+ },
312
+ )
313
+ _write_json(
314
+ tmp_path / "nested.json",
315
+ {
316
+ "type": "Catalog",
317
+ "id": "nested",
318
+ "links": [
319
+ {"rel": "child", "href": "catalog.json"},
320
+ {"rel": "item", "href": "item.json"},
321
+ ],
322
+ },
323
+ )
324
+
325
+ catalog = Catalog.open(tmp_path)
326
+
327
+ assert list(catalog.collections()) == []
328
+ assert [link.original_href for link in catalog.item_links()] == ["item.json"]
329
+
330
+
331
+ def test_unknown_document_type_and_uri_scheme_are_rejected(tmp_path: Path) -> None:
332
+ unknown = tmp_path / "unknown.json"
333
+ _write_json(unknown, {"type": "Unknown", "id": "x"})
334
+
335
+ with pytest.raises(ValueError, match="Unsupported STAC document type"):
336
+ open_document(unknown)
337
+ with pytest.raises(ValueError, match="Unsupported URI scheme"):
338
+ Catalog.open("s3://bucket/catalog.json")
339
+
340
+
341
+ def test_validator_accepts_absent_optional_links_and_assets() -> None:
342
+ result = Validator.validate(
343
+ Catalog(
344
+ {
345
+ "type": "Catalog",
346
+ "stac_version": "1.1.0",
347
+ "id": "root",
348
+ "description": "Root",
349
+ },
350
+ "file:///catalog.json",
351
+ )
352
+ )
353
+
354
+ assert result.valid
196
355
 
197
356
 
198
357
  def test_catalog_open_accepts_directory_path(tmp_path: Path) -> None:
@@ -232,6 +391,16 @@ def test_catalog_open_accepts_string_and_file_uri_sources(tmp_path: Path) -> Non
232
391
  assert from_uri.id == "demo"
233
392
 
234
393
 
394
+ @pytest.mark.parametrize(
395
+ "source",
396
+ [r"C:\catalog\catalog.json", r"\\server\share\catalog.json"],
397
+ )
398
+ def test_windows_paths_are_treated_as_paths_instead_of_uri_schemes(source: str) -> None:
399
+ from portolan.catalog import _source_to_href
400
+
401
+ assert _source_to_href(source).startswith("file:")
402
+
403
+
235
404
  def test_collection_and_item_open_accept_directory_or_file_sources(tmp_path: Path) -> None:
236
405
  _write_json(
237
406
  tmp_path / "roads" / "collection.json",
@@ -0,0 +1,59 @@
1
+ """Tests for the development-only Read Profile adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import pytest
12
+
13
+ pytestmark = pytest.mark.unit
14
+
15
+
16
+ def _invoke(request: object) -> dict[str, Any]:
17
+ process = subprocess.run(
18
+ [sys.executable, str(Path(__file__).with_name("conformance_adapter.py"))],
19
+ input=json.dumps(request),
20
+ text=True,
21
+ capture_output=True,
22
+ check=False,
23
+ )
24
+ assert process.returncode == 0
25
+ assert process.stderr == ""
26
+ value = json.loads(process.stdout)
27
+ assert isinstance(value, dict)
28
+ return value
29
+
30
+
31
+ def test_adapter_delegates_document_reading_to_sdk(tmp_path: Path) -> None:
32
+ path = tmp_path / "catalog.json"
33
+ document: dict[str, Any] = {
34
+ "type": "Catalog",
35
+ "id": "á",
36
+ "links": [],
37
+ "unknown": None,
38
+ }
39
+ path.write_text(json.dumps(document), encoding="utf-8")
40
+
41
+ response = _invoke(
42
+ {"protocol_version": "1", "operation": "document", "uri": path.as_uri()}
43
+ )
44
+
45
+ assert response == {"status": "ok", "result": {"document": document}}
46
+
47
+
48
+ @pytest.mark.parametrize(
49
+ ("payload", "code"),
50
+ [
51
+ ({"protocol_version": "2", "operation": "inspect", "uri": "file:///x"},
52
+ "UNSUPPORTED_PROTOCOL"),
53
+ ({"protocol_version": "1", "operation": "unknown", "uri": "file:///x"},
54
+ "UNSUPPORTED_OPERATION"),
55
+ ({"protocol_version": "1", "operation": "inspect"}, "INVALID_REQUEST"),
56
+ ],
57
+ )
58
+ def test_adapter_returns_stable_domain_errors(payload: object, code: str) -> None:
59
+ assert _invoke(payload) == {"status": "error", "error": {"code": code}}
@@ -468,7 +468,7 @@ wheels = [
468
468
 
469
469
  [[package]]
470
470
  name = "portolan-python"
471
- version = "0.1.8"
471
+ version = "0.1.9"
472
472
  source = { editable = "." }
473
473
 
474
474
  [package.optional-dependencies]
Binary file
@@ -1,29 +0,0 @@
1
- .PHONY: help setup test coverage lint typecheck check build clean
2
-
3
- UV ?= uv
4
-
5
- help:
6
- @printf '%s\n' 'Targets: setup test coverage lint typecheck check build clean'
7
-
8
- setup:
9
- $(UV) sync --extra dev
10
-
11
- test:
12
- $(UV) run --extra dev pytest
13
-
14
- coverage:
15
- $(UV) run --extra dev pytest --cov=portolan --cov-report=term-missing
16
-
17
- lint:
18
- $(UV) run --extra dev ruff check .
19
-
20
- typecheck:
21
- $(UV) run --extra dev mypy
22
-
23
- check: lint typecheck test
24
-
25
- build:
26
- $(UV) build
27
-
28
- clean:
29
- rm -rf dist build *.egg-info .pytest_cache .ruff_cache .mypy_cache htmlcov