Skip to content

Commit

Permalink
epoch - docs & tests
Browse files Browse the repository at this point in the history
  • Loading branch information
commonism committed Nov 20, 2024
1 parent 6f0b765 commit e4becc9
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
33 changes: 33 additions & 0 deletions pydantic_extra_types/epoch.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,22 @@ def _f(cls, value: Any, serializer: Callable[[Any], Any]) -> Any: # pragma: no


class Number(_Base):
"""epoch.Number parses unix timestamp as float and converts it to datetime.
```py
from pydantic import BaseModel
from pydantic_extra_types import epoch
class LogEntry(BaseModel):
timestamp: epoch.Number
logentry = LogEntry(timestamp=1.1)
print(logentry)
#> timestamp=datetime.datetime(1970, 1, 1, 0, 0, 1, 100000, tzinfo=datetime.timezone.utc)
```
"""

TYPE = 'number'
SCHEMA = core_schema.float_schema()

Expand All @@ -53,6 +69,23 @@ def _f(cls, value: Any, serializer: Callable[[float], float]) -> float:


class Integer(_Base):
"""epoch.Integer parses unix timestamp as integer and converts it to datetime.
```
```py
from pydantic import BaseModel
from pydantic_extra_types import epoch
class LogEntry(BaseModel):
timestamp: epoch.Integer
logentry = LogEntry(timestamp=1)
print(logentry)
#> timestamp=datetime.datetime(1970, 1, 1, 0, 0, 1, tzinfo=datetime.timezone.utc)
```
"""

TYPE = 'integer'
SCHEMA = core_schema.int_schema()

Expand Down
35 changes: 35 additions & 0 deletions tests/test_json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from typing_extensions import Annotated

import pydantic_extra_types
from pydantic_extra_types import epoch
from pydantic_extra_types.color import Color
from pydantic_extra_types.coordinate import Coordinate, Latitude, Longitude
from pydantic_extra_types.country import CountryAlpha2, CountryAlpha3, CountryNumericCode, CountryShortName
Expand Down Expand Up @@ -464,6 +465,40 @@
],
},
),
(
epoch.Integer,
{
'title': 'Model',
'type': 'object',
'properties': {
'x': {
'title': 'X',
'type': 'integer',
'format': 'date-time',
},
},
'required': [
'x',
],
},
),
(
epoch.Number,
{
'title': 'Model',
'type': 'object',
'properties': {
'x': {
'title': 'X',
'type': 'number',
'format': 'date-time',
},
},
'required': [
'x',
],
},
),
],
)
def test_json_schema(cls, expected):
Expand Down

0 comments on commit e4becc9

Please sign in to comment.