jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML
https://jcristharif.com/msgspec/
BSD 3-Clause "New" or "Revised" License
2.01k stars 59 forks source link

Support freezegun fake types #678

Open nhairs opened 2 months ago

nhairs commented 2 months ago

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