Skip to content

Support subclasses of datetime, date, time #86

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

Merged
merged 4 commits into from
Jul 24, 2023
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
6 changes: 6 additions & 0 deletions graphene_pydantic/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,12 @@ def find_graphene_type(
return Enum.from_enum(type_)
elif issubclass(type_, str):
return String
elif issubclass(type_, datetime.datetime):
return DateTime
elif issubclass(type_, datetime.date):
return Date
elif issubclass(type_, datetime.time):
return Time
else:
raise ConversionError(
f"Don't know how to convert the Pydantic field {field!r} ({field.type_})"
Expand Down
13 changes: 13 additions & 0 deletions tests/test_converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ def test_default_values():
assert field.type == graphene.String
assert field.default_value == "hi"

class DatetimeSubclass(datetime.datetime):
pass

class TimeSubclass(datetime.time):
pass

class DateSubclass(datetime.date):
pass


@pytest.mark.parametrize(
"input, expected",
Expand All @@ -60,6 +69,10 @@ def test_default_values():
((datetime.date, datetime.date(2019, 1, 1)), graphene.Date),
((datetime.time, datetime.time(15, 29)), graphene.Time),
((datetime.datetime, datetime.datetime(2019, 1, 1, 1, 37)), graphene.DateTime),
# Tests support for datetime mocking libraries like Freezegun
((DatetimeSubclass, DatetimeSubclass(2019, 1, 1, 1, 37)), graphene.DateTime),
((DateSubclass, DateSubclass(2019, 1, 1)), graphene.Date),
((TimeSubclass, TimeSubclass(15, 29)), graphene.Time),
],
)
def test_builtin_scalars(input, expected):
Expand Down