6 ms·
FreezeGun: easy mocking of Python datetimes
- ericmoritz 14y agonice 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.
- new_test 14y agoThat'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.
- JonnieCache 14y agoRubyists 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/travisjeffery/timecop https://github.com/bebanjo/delorean https://github.com/bebanjo/delorean In the ruby community, disliking someone's choice of science fiction reference is grounds for a rewrite.
- TimothyFitz 14y agoCool, but unfortunately it breaks if the code your testing does from datetime import datetime :( https://gist.github.com/4261936 https://gist.github.com/4261936
- spulec 14y agoHey 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.
- subleq 14y agoHave 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.
- madjar 14y agoSadly, it's not possible. datetime is a C class, so it is immutable.
- spulec 14y agoCorrect. 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.
- davepeck 14y agoHow well does this handle aware (non-naive) datetimes?
- manish_gill 14y agoI 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
- chewxy 14y agoMainly for testing
- marcofucci 14y agoQuick question: why did you need to write FreezeGun? I've always used Mock http://www.voidspace.org.uk/python/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.
- marcofucci 14y agoQuick question: why did you need to write FreezeGun? I've always used Mock http://www.voidspace.org.uk/python/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.
- ekimekim 14y agoWhat 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?