Skip to content
Merged
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
48 changes: 29 additions & 19 deletions src/pydanja/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,30 @@
]

ResourceType = TypeVar("ResourceType")
ModelType = TypeVar("ModelType", bound=BaseModel)


def _validate_ignoring_included(data: Any, handler: ModelWrapValidatorHandler[ModelType]) -> ModelType:
"""
Validate a resource container while bypassing validation for `included`.
"""
data_copy = deepcopy(data)
included = None

# dict payloads (e.g. DANJAResource(...))
if isinstance(data_copy, dict):
included = data_copy.pop("included", None)
# model payloads (e.g. DANJAResource.model_validate(existing_model))
elif hasattr(data_copy, "included"):
included = getattr(data_copy, "included")
delattr(data_copy, "included")

validated = handler(data_copy)

if included is not None:
setattr(validated, "included", included)

return validated


class DANJALink(BaseModel):
Expand Down Expand Up @@ -105,7 +129,7 @@ def resolve_resource_name(cls, resource) -> str:

@classmethod
def resolve_resource_id(cls, resource) -> Optional[str]:
for field_name, field in resource.model_fields.items():
for field_name, field in resource.__class__.model_fields.items():
if (
hasattr(field, "primary_key") and isinstance(field.primary_key, bool) and field.primary_key
): # Latest SQLMode
Expand Down Expand Up @@ -170,7 +194,7 @@ def include_from_basemodels(self, includes: list[Any]) -> None:
self.included = []
for include in includes:
# Convert these to resource types
self.included.append(DANJASingleResource(**include)) # ty: ignore
self.included.append(DANJASingleResource(**include))

@model_validator(mode="wrap")
@classmethod
Expand All @@ -181,14 +205,7 @@ def ignore_included(cls, data: Any, handler: ModelWrapValidatorHandler[Self]) ->
resource type as the top level data block. So in the meantime, we exclude `included` resources
from the validation process.
"""
data_copy = deepcopy(data)

# Exclude included resource types
if hasattr(data_copy, "included"):
delattr(data_copy, "included")

handler(data_copy)
return data
return _validate_ignoring_included(data, handler)


class DANJAResourceList(BaseModel, ResourceResolver, Generic[ResourceType]):
Expand Down Expand Up @@ -246,7 +263,7 @@ def include_from_basemodels(self, includes: list[Any]) -> None:
self.included = []
for include in includes:
# Convert these to resource types
self.included.append(DANJASingleResource(**include)) # ty: ignore
self.included.append(DANJASingleResource(**include))

@model_validator(mode="wrap")
@classmethod
Expand All @@ -257,11 +274,4 @@ def ignore_included(cls, data: Any, handler: ModelWrapValidatorHandler[Self]) ->
resource type as the top level data block. So in the meantime, we exclude `included` resources
from the validation process.
"""
data_copy = deepcopy(data)

# Exclude included resource types
if hasattr(data_copy, "included"):
delattr(data_copy, "included")

handler(data_copy)
return data
return _validate_ignoring_included(data, handler)
56 changes: 56 additions & 0 deletions tests/test_resource_creation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import pytest
import json
import warnings
from typing import Optional
from pathlib import Path
from src.pydanja import DANJAResource, DANJAResourceList
Expand Down Expand Up @@ -137,3 +138,58 @@ def test_it_creates_a_container_list_from_base_model_without_id(resource):

# Check resource data
assert(len(new_resources.resources) == len(basemodel_instances))


def test_it_does_not_warn_for_single_resource_with_included():
payload = {
"data": {
"id": "1",
"type": "fixturetesttype",
"attributes": {"id": 1, "name": "Stuff!", "description": "This is desc!"},
},
"included": [
{
"id": "200",
"type": "other",
"attributes": {"name": "Included model"},
}
],
}

with warnings.catch_warnings(record=True) as warning_records:
warnings.simplefilter("always")
resource = DANJAResource[FixtureTestType](**payload)

assert resource.included == payload["included"]
assert not any("Returning anything other than `self`" in str(w.message) for w in warning_records)


def test_it_does_not_warn_for_resource_list_with_included():
payload = {
"data": [
{
"id": "1",
"type": "fixturetesttype",
"attributes": {"id": 1, "name": "Stuff!", "description": "This is desc!"},
},
{
"id": "2",
"type": "fixturetesttype",
"attributes": {"id": 2, "name": "More Stuff!", "description": "This is more desc!"},
},
],
"included": [
{
"id": "200",
"type": "other",
"attributes": {"name": "Included model"},
}
],
}

with warnings.catch_warnings(record=True) as warning_records:
warnings.simplefilter("always")
resource_list = DANJAResourceList[FixtureTestType](**payload)

assert resource_list.included == payload["included"]
assert not any("Returning anything other than `self`" in str(w.message) for w in warning_records)