Hacker News new | past | comments | ask | show | jobs | submit login
FreezeGun: easy mocking of Python datetimes (stevepulec.com)
88 points by spulec on Dec 11, 2012 | hide | past | favorite | 16 comments



Rubyists desiring similar functionality should check out either of the following libs. As far as I can tell they differ only in their pun selection.

https://github.com/travisjeffery/timecop

https://github.com/bebanjo/delorean

In the ruby community, disliking someone's choice of science fiction reference is grounds for a rewrite.


So I need to write one called "tardis"?


>In the ruby community, disliking someone's choice of science fiction reference is grounds for a rewrite.

Hmm, perhaps I should check Ruby out after all...


It's great. We got unicorns and Series As for everyone!


nice project. I usually avoid this by making my APIs accept a datetime objects and make the client code create the datetime object.

Pure functions make tests simple.


That's what I've been doing, but not because I believe it to be a better way, but because I'm to lazy to implement my own FreezeGun. I don't think the production code should contain unnecessary complexity that is only used for testing.


Quick question: why did you need to write FreezeGun?

I've always used Mock http://www.voidspace.org.uk/python/mock/ to patch datetimes and I've never had any problems.

You can patch pretty much anything with Mock.


What about those of us who prefer the simpler time module (which works mostly in epoch time)? It would be a simple change to extend FreezeGun to cover that module in a similar way, surely?


Cool, but unfortunately it breaks if the code your testing does from datetime import datetime :(

https://gist.github.com/4261936


Hey Timothy, thanks for the response. You are correct. I'll add a warning to the library and work on a solution. Unfortunately, I think it will need to involve ctypes.


Have you tried patching the now() method onto datetime.datetime instead of replacing the whole class? If that doesn't work, you could replace datetime first:

    import freezegun; freezegun.monkey_patch()
    from datetime import datetime
After that, freeze_time would just set a flag on your datetime class.


Sadly, it's not possible. datetime is a C class, so it is immutable.


Correct. I've gone with his latter solution for now and added a warning about import order. I'm not very happy with this solution through and will be spending some time with ctypes in the next few days to come up with something better.


I don't really have much experience in datetimes I guess. What is this really good for? Can someone provide some use cases where this library might be helpful?

Thanks


Mainly for testing


How well does this handle aware (non-naive) datetimes?




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: