Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CoverageJSON TypeAdapter to support generic loading of CoverageJSON #17

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.8', '3.9', '3.10', '3.11', '3.12']
python-version: ['3.9', '3.10', '3.11', '3.12']

steps:
- uses: actions/checkout@v4
Expand Down
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ pip install git+https://github.com/KNMI/covjson-pydantic.git

## Usage

### Generating CovJSON

```python
from datetime import datetime, timezone
from pydantic import AwareDatetime
Expand Down Expand Up @@ -104,6 +106,36 @@ Will print
}
```

### Validating CovJSON

There is a helper `TypeAdapter` called `CoverageJSON` that will validate any (supported) CoverageJSON input, and
return the corresponding model. These can be of the type `CoverageCollection`, `Coverage`, `Domain`, `TiledNdArray`
or `NdArray`.

```python
from covjson_pydantic.coverage import CoverageJSON
covjson = CoverageJSON.validate_json("""
{
"type": "NdArray",
"dataType": "float",
"axisNames": [
"t",
"y",
"x"
],
"shape": [
1,
1,
1
],
"values": [
27.1
]
}
""")
print(type(covjson))
```

## Contributing

Make an editable installation from within the repository root
Expand Down
24 changes: 24 additions & 0 deletions example.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from datetime import timezone

from covjson_pydantic.coverage import Coverage
from covjson_pydantic.coverage import CoverageJSON
from covjson_pydantic.domain import Axes
from covjson_pydantic.domain import Domain
from covjson_pydantic.domain import DomainType
Expand All @@ -22,3 +23,26 @@
)

print(c.model_dump_json(exclude_none=True, indent=4))

covjson = CoverageJSON.validate_json(
"""
{
"type": "NdArray",
"dataType": "float",
"axisNames": [
"t",
"y",
"x"
],
"shape": [
1,
1,
1
],
"values": [
27.1
]
}
"""
)
print(type(covjson))
18 changes: 15 additions & 3 deletions src/covjson_pydantic/coverage.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
from typing import Annotated
from typing import Dict
from typing import List
from typing import Literal
from typing import Optional
from typing import Union

from covjson_pydantic.domain import Domain
from covjson_pydantic.ndarray import NdArray
from covjson_pydantic.ndarray import TiledNdArray
from pydantic import AnyUrl
from pydantic import Field
from pydantic import TypeAdapter

from .base_models import CovJsonBaseModel
from .domain import Domain
from .domain import DomainType
from .ndarray import NdArray
from .ndarray import TiledNdArray
from .parameter import Parameter
from .parameter import ParameterGroup
from .reference_system import ReferenceSystemConnectionObject
Expand All @@ -32,3 +35,12 @@ class CoverageCollection(CovJsonBaseModel, extra="allow"):
parameters: Optional[Dict[str, Parameter]] = None
parameterGroups: Optional[List[ParameterGroup]] = None # noqa: N815
referencing: Optional[List[ReferenceSystemConnectionObject]] = None


# type: Union[CoverageCollection, Coverage, Domain, TiledNdArray, NdArray]
CoverageJSON = TypeAdapter(
Annotated[
Union[CoverageCollection, Coverage, Domain, TiledNdArray, NdArray],
Field(discriminator="type"),
]
)
10 changes: 10 additions & 0 deletions tests/test_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pytest
from covjson_pydantic.coverage import Coverage
from covjson_pydantic.coverage import CoverageCollection
from covjson_pydantic.coverage import CoverageJSON
from covjson_pydantic.domain import Axes
from covjson_pydantic.domain import Domain
from covjson_pydantic.ndarray import NdArray
Expand Down Expand Up @@ -76,3 +77,12 @@ def test_error_cases(file_name, object_type, error_message):

with pytest.raises(ValidationError, match=error_message):
object_type.model_validate_json(json_string)


def test_covjson_type_adapter():
file = Path(__file__).parent.resolve() / "test_data" / "coverage-json.json"
# Put JSON in default unindented format
with open(file, "r") as f:
o = CoverageJSON.validate_json(f.read())

assert isinstance(o, Coverage)
Loading