Skip to content
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
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ dependencies = [
dev = [
"pytest>=8.1.1",
"mypy>=1.15.0",
"pytest>=8.3.5",
"ruff>=0.11.2",
"pymarkdownlnt>=0.9.25",
"pre-commit>=4.2.0",
Expand Down
5 changes: 5 additions & 0 deletions stapi-pydantic/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,8 @@ include = ["src/stapi_pydantic"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[dependency-groups]
dev = [
"pytest>=8.1.1",
]
27 changes: 16 additions & 11 deletions stapi-pydantic/src/stapi_pydantic/datetime_interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,37 @@
WrapSerializer,
)

_DatetimeTuple = tuple[datetime | None, datetime | None]

def validate_before(
value: str | tuple[datetime, datetime],
) -> tuple[datetime, datetime]:

def validate_before(value: str | _DatetimeTuple) -> _DatetimeTuple:
if isinstance(value, str):
start, end = value.split("/", 1)
return (datetime.fromisoformat(start), datetime.fromisoformat(end))
start_str, end_str = value.split("/", 1)
start = None if start_str == ".." else datetime.fromisoformat(start_str)
end = None if end_str == ".." else datetime.fromisoformat(end_str)
value = (start, end)
Copy link
Contributor

@philvarner philvarner Apr 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: one of the intervals has to closed, e.g., ../.. and / are not allowed. The code from stac-server (that I believe to be correct) is:

if (datetime) {
    const datetimeUpperCase = datetime.toUpperCase()
    const [start, end, ...rest] = datetimeUpperCase.split('/')
    if (rest.length) {
      throw new ValidationError(
        'datetime value is invalid, too many forward slashes for an interval'
      )
    } else if ((!start && !end)
        || (start === '..' && end === '..')
        || (!start && end === '..')
        || (start === '..' && !end)
    ) {
      throw new ValidationError(
        'datetime value is invalid, at least one end of the interval must be closed'
      )
    } else {
      const startDateTime = (start && start !== '..') ? rfc3339ToDateTime(start) : undefined
      const endDateTime = (end && end !== '..') ? rfc3339ToDateTime(end) : undefined
      validateStartAndEndDatetimes(startDateTime, endDateTime)
    }
    return datetimeUpperCase
  }

return value


def validate_after(value: tuple[datetime, datetime]) -> tuple[datetime, datetime]:
if value[1] < value[0]:
def validate_after(value: _DatetimeTuple) -> _DatetimeTuple:
# None/date & date/None are always valid
if value[1] and value[0] and value[1] < value[0]:
raise ValueError("end before start")
return value


def serialize(
value: tuple[datetime, datetime],
serializer: Callable[[tuple[datetime, datetime]], tuple[str, str]],
value: _DatetimeTuple,
serializer: Callable[[_DatetimeTuple], tuple[str, str]],
) -> str:
del serializer # unused
return f"{value[0].isoformat()}/{value[1].isoformat()}"
start = value[0].isoformat() if value[0] else ".."
end = value[1].isoformat() if value[1] else ".."
return f"{start}/{end}"


DatetimeInterval = Annotated[
tuple[AwareDatetime, AwareDatetime],
tuple[AwareDatetime | None, AwareDatetime | None],
BeforeValidator(validate_before),
AfterValidator(validate_after),
WrapSerializer(serialize, return_type=str),
Expand Down
21 changes: 21 additions & 0 deletions stapi-pydantic/tests/test_datetime_interval.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import pytest
from stapi_pydantic import DatetimeInterval


def test_valid_datetime_intervals() -> None:
"""Test the datetime interval validator."""
dt1 = DatetimeInterval.__metadata__[0].func("2025-04-01T00:00:00Z/2025-04-01T23:59:59Z")
_ = DatetimeInterval.__metadata__[1].func(dt1)
dt2 = DatetimeInterval.__metadata__[0].func("2025-04-01T00:00:00Z/..")
_ = DatetimeInterval.__metadata__[1].func(dt2)
dt3 = DatetimeInterval.__metadata__[0].func("../2025-04-01T23:59:59Z")
_ = DatetimeInterval.__metadata__[1].func(dt3)
dt4 = DatetimeInterval.__metadata__[0].func("../..")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: this should fail, per prior comment

_ = DatetimeInterval.__metadata__[1].func(dt4)


def test_invalid_datetime_intervals() -> None:
"""Test the datetime interval validator."""
with pytest.raises(ValueError, match="end before start"):
dt1 = DatetimeInterval.__metadata__[0].func("2025-04-01T00:00:00Z/2025-03-01T23:59:59Z")
_ = DatetimeInterval.__metadata__[1].func(dt1)
9 changes: 8 additions & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.