Skip to content
Draft
Show file tree
Hide file tree
Changes from 9 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
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
Copy Markdown
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
11 changes: 11 additions & 0 deletions stapi-pydantic/tests/test_datetime_interval.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from stapi_pydantic import DatetimeInterval


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

Choose a reason for hiding this comment

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

Looks like your code would support this, but I would also explicitly test the case of ../.., which I believe should also be valid.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'll add.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added. Also, added unit test for end before start.

_ = DatetimeInterval.__metadata__[1].func(dt1)
_ = DatetimeInterval.__metadata__[1].func(dt2)
_ = DatetimeInterval.__metadata__[1].func(dt3)