Skip to content
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

Support freezegun fake types #678

Open
nhairs opened this issue May 5, 2024 · 1 comment
Open

Support freezegun fake types #678

nhairs opened this issue May 5, 2024 · 1 comment

Comments

@nhairs
Copy link

nhairs commented May 5, 2024

freezegun is a utility library commonly used in testing to control the time. In doing so it causes the datetime library to produce fake types.

Although these types correctly identify themselves as instances of their relevant type, msgspec does not identify them as such leading to errors.

Although it would be possible to use the default argument, this may not always be feasible for the calling library. It would be great if msgspec could natively support these.

>>> import datetime
>>> import freezegun.api
>>> isinstance(freezegun.api.FakeDate(2024,5,5), datetime.date)
True
>>> isinstance(freezegun.api.FakeDatetime(2024, 5, 5), datetime.datetime)
True
>>> import datetime
>>> import freezegun.api
>>> import msgspec.json
>>> encoder = msgspec.json.Encoder()
>>> now = datetime.datetime.now()
>>> encoder.encode(now)
b'"2024-05-05T15:18:26.690496"'
>>> encoder.encode(freezegun.api.datetime_to_fakedatetime(now))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Encoding objects of type FakeDatetime is unsupported
@gsakkis
Copy link

gsakkis commented Sep 6, 2024

Same issue with convert:

from dataclasses import dataclass
from datetime import datetime

import msgspec
from freezegun import freeze_time

@dataclass
class Token:
    exp: datetime


def test_datetime():
    exp = datetime(2022, 2, 3)
    token = msgspec.convert({"exp": exp}, Token, strict=False)
    assert token.exp == exp


@freeze_time("2022-02-03")
def test_fake_datetime():
    exp = datetime.now()
    token = msgspec.convert({"exp": exp}, Token, strict=False)
    assert token.exp == exp

Output:

test_msgspec.py::test_datetime PASSED
test_msgspec.py::test_fake_datetime FAILED

FAILED test_msgspec.py::test_fake_datetime - msgspec.ValidationError: Expected `datetime`, got `FakeDatetime` - at `$.exp`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants