Package: time-machine
Travel through time in your tests.A quick example:importdatetimeasdtfromzoneinfoimportZoneInfoimporttime_machinehill_valley_tz=ZoneInfo("America/Los_Angeles")@time_machine.travel(dt.datetime(1985,10,26,1,24,tzinfo=hill_valley_tz))deftest_delorean():assertdt.date.today().isoformat()=="1985-10-26"For a bit of background, seethe introductory blog postandthe benchmark blog post.InstallationUsepip:python-mpipinstalltime-machinePython 3.8 to 3.12 supported.
Only CPython is supported at this time because time-machine directly hooks into the C-level API.Testing a Django project?Check out my bookSpeed Up Your Django Testswhich covers loads of ways to write faster, more accurate tests.
I created time-machine whilst writing the book.UsageIf you’re coming from freezegun or libfaketime, see also the below section on migrating.travel(destination, *, tick=True)travel()is a class that allows time travel, to the datetime specified bydestination.
It does so by mocking all functions from Python’s standard library that return the current date or datetime.
It can be used independently, as a function decorator, or as a context manager.destinationspecifies the datetime to move to.
It may be:Adatetime.datetime.
If it is naive, it will be assumed to have the UTC timezone.
If it hastzinfoset to azoneinfo.ZoneInfoinstance, the current timezone will also be mocked.Adatetime.date.
This will be converted to a UTC datetime with the time 00:00:00.Adatetime.timedelta.
This will be interpreted relative to the current time.
If already within atravel()block, theshift()method is easier to use (documented below).Afloatorintspecifying aUnix timestampA string, which will be parsed withdateutil.parseand converted to a timestamp.
If the result is naive, it will be assumed to be local time.Additionally, you can provide some more complex types:A generator, in which casenext()will be called on it, with the result treated as above.A callable, in which case it will be called with no parameters, with the result treated as above.tickdefines whether time continues to “tick” after travelling, or is frozen.
IfTrue, the default, successive calls to mocked functions return values increasing by the elapsed real timesince the first call.So after starting travel to0.0(the UNIX epoch), the first call to any datetime function will return its representation of1970-01-0100:00:00.000000exactly.
The following calls “tick,” so if a call was made exactly half a second later, it would return1970-01-0100:00:00.500000.Mocked FunctionsAll datetime functions in the standard library are mocked to move to the destination current datetime:datetime.datetime.now()datetime.datetime.utcnow()time.clock_gettime()(only forCLOCK_REALTIME)time.clock_gettime_ns()(only forCLOCK_REALTIME)time.gmtime()time.localtime()time.monotonic()(not a real monotonic clock, returnstime.time())time.monotonic_ns()(not a real monotonic clock, returnstime.time_ns())time.strftime()time.time()time.time_ns()The mocking is done at the C layer, replacing the function pointers for these built-ins.
Therefore, it automatically affects everywhere those functions have been imported, unlike use ofunittest.mock.patch().Usage withstart()/stop()To use independently, create an instance, usestart()to move to the destination time, andstop()to move back.
For example:importdatetimeasdtimporttime_machinetraveller=time_machine.travel(dt.datetime(1985,10,26))traveller.start()# It's the past!assertdt.date.today()==dt.date(1985,10,26)traveller.stop()# We've gone back to the future!assertdt.date.today()>dt.date(2020,4,29)travel()instances are nestable, but you’ll need to be careful when manually managing to call theirstop()methods in the correct order, even when exceptions occur.
It’s recommended to use the decorator or context manager forms instead, to take advantage of Python features to do this.Function DecoratorWhen used as a function decorator, time is mocked during the wrapped function’s duration:importtimeimporttime_machine@time_machine.travel("1970-01-01 00:00 +0000")deftest_in_the_deep_past():assert0.0<time.time()<1.0You can also decorate asynchronous functions (coroutines):importtimeimporttime_machine@time_machine.travel("1970-01-01 00:00 +0000")asyncdeftest_in_the_deep_past():assert0.0<time.time()<1.0Beware: time is aglobalstate -see below.Context ManagerWhen used as a context manager, time is mocked during thewithblock:importtimeimporttime_machinedeftest_in_the_deep_past():withtime_machine.travel(0.0):assert0.0<time.time()<1.0Class DecoratorOnlyunittest.TestCasesubclasses are supported.
When applied as a class decorator to such classes, time is mocked from the start ofsetUpClass()to the end oftearDownClass():importtimeimporttime_machineimportunittest@time_machine.travel(0.0)classDeepPastTests(TestCase):deftest_in_the_deep_past(self):assert0.0<time.time()<1.0Note this is different tounittest.mock.patch()'s behaviour, which is to mock only during the test methods.
For pytest-style test classes, see the patterndocumented below.Timezone mockingIf thedestinationpassed totime_machine.travel()orCoordinates.move_to()has itstzinfoset to azoneinfo.ZoneInfoinstance, the current timezone will be mocked.
This will be done by callingtime.tzset(), so it is only available on Unix.
Thezoneinfomodule is new in Python 3.8 - on older Python versions use thebackports.zoneinfopackage, by the originalzoneinfoauthor.time.tzset()changes thetimemodule’stimezone constantsand features that rely on those, such astime.localtime().
It won’t affect other concepts of “the current timezone”, such as Django’s (which can be changed with itstimezone.override()).Here’s a worked example changing the current timezone:importdatetimeasdtimporttimefromzoneinfoimportZoneInfoimporttime_machinehill_valley_tz=ZoneInfo("America/Los_Angeles")@time_machine.travel(dt.datetime(2015,10,21,16,29,tzinfo=hill_valley_tz))deftest_hoverboard_era():asserttime.tzname==("PST","PDT")now=dt.datetime.now()assert(now.hour,now.minute)==(16,29)CoordinatesThestart()method and entry of the context manager both return aCoordinatesobject that corresponds to the given “trip” in time.
This has a couple methods that can be used to travel to other times.move_to(destination, tick=None)move_to()moves the current time to a new destination.destinationmay be any of the types supported bytravel.tickmay be set to a boolean, to change thetickflag oftravel.For example:importdatetimeasdtimporttimeimporttime_machinewithtime_machine.travel(0,tick=False)astraveller:asserttime.time()==0traveller.move_to(234)asserttime.time()==234shift(delta)shift()takes one argument,delta, which moves the current time by the given offset.deltamay be atimedeltaor a number of seconds, which will be added to destination.
It may be negative, in which case time will move to an earlier point.For example:importdatetimeasdtimporttimeimporttime_machinewithtime_machine.travel(0,tick=False)astraveller:asserttime.time()==0traveller.shift(dt.timedelta(seconds=100))asserttime.time()==100traveller.shift(-dt.timedelta(seconds=10))asserttime.time()==90pytest plugintime-machine also works as a pytest plugin.
It provides a function-scoped fixture calledtime_machinewith methodsmove_to()andshift(), which have the same signature as their equivalents inCoordinates.
This can be used to mock your test at different points in time and will automatically be un-mock when the test is torn down.For example:importdatetimeasdtdeftest_delorean(time_machine):time_machine.move_to(dt.datetime(1985,10,26))assertdt.date.today().isoformat()=="1985-10-26"time_machine.move_to(dt.datetime(2015,10,21))assertdt.date.today().isoformat()=="2015-10-21"time_machine.shift(dt.timedelta(days=1))assertdt.date.today().isoformat()=="2015-10-22"If you are using pytest test classes, you can apply the fixture to all test methods in a class by adding an autouse fixture:importtimeimportpytestclassTestSomething:@pytest.fixture(autouse=True)defset_time(self,time_machine):time_machine.move_to(1000.0)deftest_one(self):assertint(time.time())==1000.0deftest_two(self,time_machine):assertint(time.time())==1000.0time_machine.move_to(2000.0)assertint(time.time())==2000.0escape_hatchTheescape_hatchobject provides functions to bypass time-machine.
These allow you to call the real datetime functions, without any mocking.
It also provides a way to check if time-machine is currently time travelling.These capabilities are useful in rare circumstances.
For example, if you need to authenticate with an external service during time travel, you may need the real value ofdatetime.now().The functions are:escape_hatch.is_travelling()->bool- returnsTrueiftime_machine.travel()is active,Falseotherwise.escape_hatch.datetime.datetime.now()- wraps the realdatetime.datetime.now().escape_hatch.datetime.datetime.utcnow()- wraps the realdatetime.datetime.utcnow().escape_hatch.time.clock_gettime()- wraps the realtime.clock_gettime().escape_hatch.time.clock_gettime_ns()- wraps the realtime.clock_gettime_ns().escape_hatch.time.gmtime()- wraps the realtime.gmtime().escape_hatch.time.localtime()- wraps the realtime.localtime().escape_hatch.time.strftime()- wraps the realtime.strftime().escape_hatch.time.time()- wraps the realtime.time().escape_hatch.time.time_ns()- wraps the realtime.time_ns().For example:importtime_machinewithtime_machine.travel(...):iftime_machine.escape_hatch.is_travelling():print("We need to go back to the future!")real_now=time_machine.escape_hatch.datetime.datetime.now()external_authenticate(now=real_now)CaveatsTime is a global state.
Any concurrent threads or asynchronous functions are also be affected.
Some aren’t ready for time to move so rapidly or backwards, and may crash or produce unexpected results.Also beware that other processes are not affected.
For example, if you use SQL datetime functions on a database server, they will return the real time.ComparisonThere are some prior libraries that try to achieve the same thing.
They have their own strengths and weaknesses.
Here’s a quick comparison.unittest.mockThe standard library’sunittest.mockcan be used to target imports ofdatetimeandtimeto change the returned value for current time.
Unfortunately, this is fragile as it only affects the import location the mock targets.
Therefore, if you have several modules in a call tree requesting the date/time, you need several mocks.
This is a general problem with unittest.mock - seeWhy Your Mock Doesn’t Work.It’s also impossible to mock certain references, such as function default arguments:defupdate_books(_now=time.time):# set as default argument so faster lookupforbookinbooks:...Although such references are rare, they are occasionally used to optimize highly repeated loops.freezegunSteve Pulec’sfreezegunlibrary is a popular solution.
It provides a clear API which was much of the inspiration for time-machine.The main drawback is its slow implementation.
It essentially does a find-and-replace mock of all the places that thedatetimeandtimemodules have been imported.
This gets around the problems with using unittest.mock, but it means the time it takes to do the mocking is proportional to the number of loaded modules.
In large projects, this can take several seconds, an impractical overhead for an individual test.It’s also not a perfect search, since it searches only module-level imports.
Such imports are definitely the most common way projects use date and time functions, but they’re not the only way.
freezegun won’t find functions that have been “hidden” inside arbitrary objects, such as class-level attributes.It also can’t affect C extensions that call the standard library functions, including (I believe) Cython-ized Python code.python-libfaketimeSimon Weber’spython-libfaketimewraps thelibfaketimelibrary.
libfaketime replaces all the C-level system calls for the current time with its own wrappers.
It’s therefore a “perfect” mock for the current process, affecting every single point the current time might be fetched, and performs much faster than freezegun.Unfortunately python-libfaketime comes with the limitations ofLD_PRELOAD.
This is a mechanism to replace system libraries for a program as it loads (explanation).
This causes two issues in particular when you use python-libfaketime.First,LD_PRELOADis only available on Unix platforms, which prevents you from using it on Windows.Second, you have to help manageLD_PRELOAD.
You either use python-libfaketime’sreexec_if_needed()function, which restarts (re-execs) your test process while loading, or manually manage theLD_PRELOADenvironment variable.
Neither is ideal.
Re-execing breaks anything that might wrap your test process, such as profilers, debuggers, and IDE test runners.
Manually managing the environment variable is a bit of overhead, and must be done for each environment you run your tests in, including each developer’s machine.time-machinetime-machine is intended to combine the advantages of freezegun and libfaketime.
It works withoutLD_PRELOADbut still mocks the standard library functions everywhere they may be referenced.
Its weak point is that other libraries using date/time system calls won’t be mocked.
Thankfully this is rare.
It’s also possible such python libraries can be added to the set mocked by time-machine.One drawback is that it only works with CPython, so can’t be used with other Python interpreters like PyPy.
However it may possible to extend it to support other interpreters through different mocking mechanisms.Migrating from libfaketime or freezegunfreezegun has a useful API, and python-libfaketime copies some of it, with a different function name.
time-machine also copies some of freezegun’s API, intravel()'sdestination, andtickarguments, and theshift()method.
There are a few differences:time-machine’stickargument defaults toTrue, because code tends to make the (reasonable) assumption that time progresses whilst running, and should normally be tested as such.
Testing with time frozen can make it easy to write complete assertions, but it’s quite artificial.
Write assertions against time ranges, rather than against exact values.freezegun interprets dates and naive datetimes in the local time zone (including those parsed from strings withdateutil).
This means tests can pass when run in one time zone and fail in another.
time-machine instead interprets dates and naive datetimes in UTC so they are fixed points in time.
Provide time zones where required.freezegun’stick()method has been implemented asshift(), to avoid confusion with thetickargument.
It also requires an explicit delta rather than defaulting to 1 second.freezegun’stz_offsetargument is not supported, since it only partially mocks the current time zone.
Time zones are more complicated than a single offset from UTC, and freezegun only uses the offset intime.localtime().
Instead, time-machine will mock the current time zone if you give it adatetimewith aZoneInfotimezone.Some features aren’t supported like theauto_tick_secondsargument.
These may be added in a future release.If you are only fairly simple function calls, you should be able to migrate by replacing calls tofreezegun.freeze_time()andlibfaketime.fake_time()withtime_machine.travel().