time-machine icon indicating copy to clipboard operation
time-machine copied to clipboard

Add shift to TimeMachineFixture

Open henribru opened this issue 2 years ago • 1 comments

Description

It would be convenient if TimeMachineFixture supported shift in addition to move_to. You can work around the lack of this by doing time_machine.coordinates.shift(...), but it's slightly more verbose and requires you to have already called move_to. It also doesn't interact great with a typechecker since it will think time_machine.coordinates could still be None even if you've called move_to.

Would a contribution for this feature be accepted?

Edit: It would also simplify migration from pytest-freezegun since there you have both move_to and tick

henribru avatar May 04 '22 13:05 henribru

Yes sure!

adamchainz avatar May 04 '22 14:05 adamchainz

I was thinking through what this api would be. In the case one has already called move_to, it seems clear that time_machine.shift is simply an alias to time_machine.coordinates.shift.

There are other cases where a test doesn't care about the actual time, simply that some time has elapsed. In this case a user might call time_machine.shift without first calling move_to, my expectation is that this would create a new traveler starting at the current (real) time, then apply the shift. Creating a traveller without an explicit start point appears to be new functionality to time-machine. One very real case where this would be helpful is when Django data migrations create db records with a created timestamp, then a test needs to perform some action after those are created.

@adamchainz what are your thoughts on this logic? And if you think it makes sense at all, is the fixture the right place for it? From a quick look at the code, I am not sure where else to put it, unless the travel class made the destination optional.

AgDude avatar Nov 02 '22 13:11 AgDude

I see similar functionality has been proposed in #38. That seems like a good way to address my concern about putting entirely new functionality into the fixture, since the fixture could simply use a zero delta to initialize the traveller.

AgDude avatar Nov 02 '22 13:11 AgDude

@AgDude adding timedelta() support would be neat. Would you like to make a PR?

adamchainz avatar Nov 02 '22 19:11 adamchainz

I created PR #312 to add shift() method to the pytest fixture.

It just addresses the easy part of this request: when move_to() has been used before. The use case discussed by @AgDude , where move_to() is not called first, the implementation just raises a RunTimeError at the moment.

soxofaan avatar Dec 16 '22 11:12 soxofaan

Isn't this done?

llucax avatar Dec 29 '23 13:12 llucax

Yup, thanks for noting.

adamchainz avatar Dec 29 '23 22:12 adamchainz