-
-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathtest_time_machine.py
More file actions
1463 lines (1087 loc) · 41.5 KB
/
test_time_machine.py
File metadata and controls
1463 lines (1087 loc) · 41.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import datetime as dt
import os
import subprocess
import sys
import time
import typing
import uuid
from contextlib import contextmanager
from importlib.util import module_from_spec, spec_from_file_location
from textwrap import dedent
from unittest import SkipTest, TestCase, mock
from zoneinfo import ZoneInfo
import freezegun
import pytest
from dateutil import tz
import time_machine
NANOSECONDS_PER_SECOND = time_machine.NANOSECONDS_PER_SECOND
EPOCH_DATETIME = dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc)
EPOCH = EPOCH_DATETIME.timestamp()
EPOCH_PLUS_ONE_YEAR_DATETIME = dt.datetime(1971, 1, 1, tzinfo=dt.timezone.utc)
EPOCH_PLUS_ONE_YEAR = EPOCH_PLUS_ONE_YEAR_DATETIME.timestamp()
LIBRARY_EPOCH_DATETIME = dt.datetime(2020, 4, 29) # The day this library was made
LIBRARY_EPOCH = LIBRARY_EPOCH_DATETIME.timestamp()
py_have_clock_gettime = pytest.mark.skipif(
not hasattr(time, "clock_gettime"), reason="Doesn't have clock_gettime"
)
def sleep_one_cycle(clock: int) -> None:
time.sleep(time.clock_getres(clock))
@contextmanager
def change_local_timezone(local_tz: str | None) -> typing.Iterator[None]:
orig_tz = os.environ["TZ"]
if local_tz:
os.environ["TZ"] = local_tz
else:
del os.environ["TZ"]
time.tzset()
try:
yield
finally:
os.environ["TZ"] = orig_tz
time.tzset()
@pytest.mark.skipif(
not hasattr(time, "CLOCK_REALTIME"), reason="No time.CLOCK_REALTIME"
)
def test_import_without_clock_realtime():
orig = time.CLOCK_REALTIME
del time.CLOCK_REALTIME
try:
# Recipe for importing from path as documented in importlib
spec = spec_from_file_location(
f"{__name__}.time_machine_without_clock_realtime", time_machine.__file__
)
assert spec is not None
module = module_from_spec(spec)
# typeshed says exec_module does not always exist:
spec.loader.exec_module(module) # type: ignore[union-attr]
finally:
time.CLOCK_REALTIME = orig # type: ignore[misc]
# No assertions - testing for coverage only
# datetime module
def test_datetime_now_no_args():
with time_machine.travel(EPOCH):
now = dt.datetime.now()
assert now.year == 1970
assert now.month == 1
assert now.day == 1
# Not asserting on hour/minute because local timezone could shift it
assert now.second == 0
assert now.microsecond == 0
assert dt.datetime.now() >= LIBRARY_EPOCH_DATETIME
def test_datetime_now_no_args_no_tick():
with time_machine.travel(EPOCH, tick=False):
now = dt.datetime.now()
assert now.microsecond == 0
assert dt.datetime.now() >= LIBRARY_EPOCH_DATETIME
def test_datetime_now_arg():
with time_machine.travel(EPOCH):
now = dt.datetime.now(tz=dt.timezone.utc)
assert now.year == 1970
assert now.month == 1
assert now.day == 1
assert dt.datetime.now(dt.timezone.utc) >= LIBRARY_EPOCH_DATETIME.replace(
tzinfo=dt.timezone.utc
)
def test_datetime_utcnow():
with time_machine.travel(EPOCH):
now = dt.datetime.utcnow()
assert now.year == 1970
assert now.month == 1
assert now.day == 1
assert now.hour == 0
assert now.minute == 0
assert now.second == 0
assert now.microsecond == 0
assert now.tzinfo is None
assert dt.datetime.utcnow() >= LIBRARY_EPOCH_DATETIME
def test_datetime_utcnow_no_tick():
with time_machine.travel(EPOCH, tick=False):
now = dt.datetime.utcnow()
assert now.microsecond == 0
def test_date_today():
with time_machine.travel(EPOCH):
today = dt.date.today()
assert today.year == 1970
assert today.month == 1
assert today.day == 1
assert dt.datetime.today() >= LIBRARY_EPOCH_DATETIME
# time module
@py_have_clock_gettime
def test_time_clock_gettime_realtime():
with time_machine.travel(EPOCH + 180.0):
now = time.clock_gettime(time.CLOCK_REALTIME)
assert isinstance(now, float)
assert now == EPOCH + 180.0
now = time.clock_gettime(time.CLOCK_REALTIME)
assert isinstance(now, float)
assert now >= LIBRARY_EPOCH
@py_have_clock_gettime
def test_time_clock_gettime_monotonic_unaffected():
start = time.clock_gettime(time.CLOCK_MONOTONIC)
sleep_one_cycle(time.CLOCK_MONOTONIC)
with time_machine.travel(EPOCH + 180.0):
frozen = time.clock_gettime(time.CLOCK_MONOTONIC)
sleep_one_cycle(time.CLOCK_MONOTONIC)
assert isinstance(frozen, float)
assert frozen > start
now = time.clock_gettime(time.CLOCK_MONOTONIC)
assert isinstance(now, float)
assert now > frozen
@py_have_clock_gettime
def test_time_clock_gettime_ns_realtime():
with time_machine.travel(EPOCH + 190.0):
first = time.clock_gettime_ns(time.CLOCK_REALTIME)
sleep_one_cycle(time.CLOCK_REALTIME)
assert isinstance(first, int)
assert first == int((EPOCH + 190.0) * NANOSECONDS_PER_SECOND)
second = time.clock_gettime_ns(time.CLOCK_REALTIME)
assert first < second < int((EPOCH + 191.0) * NANOSECONDS_PER_SECOND)
now = time.clock_gettime_ns(time.CLOCK_REALTIME)
assert isinstance(now, int)
assert now >= int(LIBRARY_EPOCH * NANOSECONDS_PER_SECOND)
@py_have_clock_gettime
def test_time_clock_gettime_ns_monotonic_unaffected():
start = time.clock_gettime_ns(time.CLOCK_MONOTONIC)
sleep_one_cycle(time.CLOCK_MONOTONIC)
with time_machine.travel(EPOCH + 190.0):
frozen = time.clock_gettime_ns(time.CLOCK_MONOTONIC)
sleep_one_cycle(time.CLOCK_MONOTONIC)
assert isinstance(frozen, int)
assert frozen > start
now = time.clock_gettime_ns(time.CLOCK_MONOTONIC)
assert isinstance(now, int)
assert now > frozen
def test_time_gmtime_no_args():
with time_machine.travel(EPOCH):
local_time = time.gmtime()
assert local_time.tm_year == 1970
assert local_time.tm_mon == 1
assert local_time.tm_mday == 1
now_time = time.gmtime()
assert now_time.tm_year >= 2020
def test_time_gmtime_no_args_no_tick():
with time_machine.travel(EPOCH, tick=False):
local_time = time.gmtime()
assert local_time.tm_sec == 0
def test_time_gmtime_arg():
with time_machine.travel(EPOCH):
local_time = time.gmtime(EPOCH_PLUS_ONE_YEAR)
assert local_time.tm_year == 1971
assert local_time.tm_mon == 1
assert local_time.tm_mday == 1
def test_time_localtime():
with time_machine.travel(EPOCH):
local_time = time.localtime()
assert local_time.tm_year == 1970
assert local_time.tm_mon == 1
assert local_time.tm_mday == 1
now_time = time.localtime()
assert now_time.tm_year >= 2020
def test_time_localtime_no_tick():
with time_machine.travel(EPOCH, tick=False):
local_time = time.localtime()
assert local_time.tm_sec == 0
def test_time_localtime_arg():
with time_machine.travel(EPOCH):
local_time = time.localtime(EPOCH_PLUS_ONE_YEAR)
assert local_time.tm_year == 1971
assert local_time.tm_mon == 1
assert local_time.tm_mday == 1
def test_time_strftime_format():
with time_machine.travel(EPOCH):
assert time.strftime("%Y-%m-%d") == "1970-01-01"
assert int(time.strftime("%Y")) >= 2020
def test_time_strftime_format_no_tick():
with time_machine.travel(EPOCH, tick=False):
assert time.strftime("%S") == "00"
def test_time_strftime_format_t():
with time_machine.travel(EPOCH):
assert (
time.strftime("%Y-%m-%d", time.localtime(EPOCH_PLUS_ONE_YEAR))
== "1971-01-01"
)
def test_time_time():
with time_machine.travel(EPOCH):
first = time.time()
sleep_one_cycle(time.CLOCK_MONOTONIC)
assert isinstance(first, float)
assert first == EPOCH
second = time.time()
assert first < second < EPOCH + 1.0
now = time.time()
assert isinstance(now, float)
assert now >= LIBRARY_EPOCH
windows_epoch_in_posix = -11_644_445_222
@mock.patch.object(
time_machine,
"SYSTEM_EPOCH_TIMESTAMP_NS",
(windows_epoch_in_posix * NANOSECONDS_PER_SECOND),
)
def test_time_time_windows():
with time_machine.travel(EPOCH):
first = time.time()
sleep_one_cycle(time.CLOCK_MONOTONIC)
assert isinstance(first, float)
assert first == windows_epoch_in_posix
second = time.time()
assert isinstance(second, float)
assert windows_epoch_in_posix < second < windows_epoch_in_posix + 1.0
def test_time_time_no_tick():
with time_machine.travel(EPOCH, tick=False):
assert time.time() == EPOCH
def test_time_time_ns():
with time_machine.travel(EPOCH + 150.0):
first = time.time_ns()
sleep_one_cycle(time.CLOCK_MONOTONIC)
assert isinstance(first, int)
assert first == int((EPOCH + 150.0) * NANOSECONDS_PER_SECOND)
second = time.time_ns()
assert first < second < int((EPOCH + 151.0) * NANOSECONDS_PER_SECOND)
now = time.time_ns()
assert isinstance(now, int)
assert now >= int(LIBRARY_EPOCH * NANOSECONDS_PER_SECOND)
def test_time_time_ns_no_tick():
with time_machine.travel(EPOCH, tick=False):
assert time.time_ns() == int(EPOCH * NANOSECONDS_PER_SECOND)
# all supported forms
def test_nestable():
with time_machine.travel(EPOCH + 55.0):
assert time.time() == EPOCH + 55.0
with time_machine.travel(EPOCH + 50.0):
assert time.time() == EPOCH + 50.0
def test_unsupported_type():
with pytest.raises(TypeError) as excinfo, time_machine.travel([]): # type: ignore[arg-type]
pass # pragma: no cover
assert excinfo.value.args == ("Unsupported destination []",)
def test_exceptions_dont_break_it():
with pytest.raises(ValueError), time_machine.travel(0.0):
raise ValueError("Hi")
# Unreachable code analysis doesn’t work with raises being caught by
# context manager
with time_machine.travel(0.0):
pass
@time_machine.travel(EPOCH_DATETIME + dt.timedelta(seconds=70))
def test_destination_datetime():
assert time.time() == EPOCH + 70.0
@time_machine.travel(EPOCH_DATETIME.replace(tzinfo=tz.gettz("America/Chicago")))
def test_destination_datetime_tzinfo_non_zoneinfo():
assert time.time() == EPOCH + 21600.0
def test_destination_datetime_tzinfo_zoneinfo():
orig_timezone = time.timezone
orig_altzone = time.altzone
orig_tzname = time.tzname
orig_daylight = time.daylight
dest = LIBRARY_EPOCH_DATETIME.replace(tzinfo=ZoneInfo("Africa/Addis_Ababa"))
with time_machine.travel(dest):
assert time.timezone == -3 * 3600
assert time.altzone == -3 * 3600
assert time.tzname == ("EAT", "EAT")
assert time.daylight == 0
assert time.localtime() == time.struct_time(
(
2020,
4,
29,
0,
0,
0,
2,
120,
0,
)
)
assert time.timezone == orig_timezone
assert time.altzone == orig_altzone
assert time.tzname == orig_tzname
assert time.daylight == orig_daylight
def test_destination_datetime_tzinfo_zoneinfo_nested():
orig_tzname = time.tzname
dest = LIBRARY_EPOCH_DATETIME.replace(tzinfo=ZoneInfo("Africa/Addis_Ababa"))
with time_machine.travel(dest):
assert time.tzname == ("EAT", "EAT")
dest2 = LIBRARY_EPOCH_DATETIME.replace(tzinfo=ZoneInfo("Pacific/Auckland"))
with time_machine.travel(dest2):
assert time.tzname == ("NZST", "NZDT")
assert time.tzname == ("EAT", "EAT")
assert time.tzname == orig_tzname
def test_destination_datetime_tzinfo_zoneinfo_no_orig_tz():
with change_local_timezone(None):
orig_tzname = time.tzname
dest = LIBRARY_EPOCH_DATETIME.replace(tzinfo=ZoneInfo("Africa/Addis_Ababa"))
with time_machine.travel(dest):
assert time.tzname == ("EAT", "EAT")
assert time.tzname == orig_tzname
def test_destination_datetime_tzinfo_zoneinfo_utc_no_orig_tz():
with change_local_timezone(None):
orig_tzname = time.tzname
dest = LIBRARY_EPOCH_DATETIME.replace(tzinfo=ZoneInfo("UTC"))
with time_machine.travel(dest):
assert time.tzname == ("UTC", "UTC")
assert time.tzname == orig_tzname
def test_destination_datetime_tzinfo_datetime_timezone_utc_no_orig_tz():
with change_local_timezone(None):
orig_tzname = time.tzname
dest = LIBRARY_EPOCH_DATETIME.replace(tzinfo=dt.timezone.utc)
with time_machine.travel(dest):
assert time.tzname == ("UTC", "UTC")
assert time.tzname == orig_tzname
@pytest.mark.skipif(
sys.version_info < (3, 11), reason="datetime.UTC was introduced in Python 3.11"
)
def test_destination_datetime_tzinfo_datetime_utc_no_orig_tz():
with change_local_timezone(None):
orig_tzname = time.tzname
dest = LIBRARY_EPOCH_DATETIME.replace(tzinfo=dt.UTC)
with time_machine.travel(dest):
assert time.tzname == ("UTC", "UTC")
assert time.tzname == orig_tzname
def test_destination_datetime_tzinfo_zoneinfo_windows():
orig_timezone = time.timezone
pretend_windows_no_tzset = mock.patch.object(time_machine, "tzset", new=None)
mock_have_tzset_false = mock.patch.object(time_machine, "HAVE_TZSET", new=False)
dest = LIBRARY_EPOCH_DATETIME.replace(tzinfo=ZoneInfo("Africa/Addis_Ababa"))
with pretend_windows_no_tzset, mock_have_tzset_false, time_machine.travel(dest):
assert time.timezone == orig_timezone
@time_machine.travel(int(EPOCH + 77))
def test_destination_int():
assert time.time() == int(EPOCH + 77)
@time_machine.travel(EPOCH_DATETIME.replace(tzinfo=None) + dt.timedelta(seconds=120))
def test_destination_datetime_naive():
assert time.time() == EPOCH + 120.0
@time_machine.travel(EPOCH_DATETIME.date())
def test_destination_date():
assert time.time() == EPOCH
def test_destination_timedelta():
now = time.time()
with time_machine.travel(dt.timedelta(seconds=3600)):
assert now + 3600 <= time.time() <= now + 3601
def test_destination_timedelta_first_travel_in_process():
# Would previously segfault
subprocess.run(
[
sys.executable,
"-c",
dedent(
"""
from datetime import timedelta
import time_machine
with time_machine.travel(timedelta()):
pass
"""
),
],
check=True,
)
def test_destination_timedelta_negative():
now = time.time()
with time_machine.travel(dt.timedelta(seconds=-3600)):
assert now - 3600 <= time.time() <= now - 3599
def test_destination_timedelta_nested():
with time_machine.travel(EPOCH), time_machine.travel(dt.timedelta(seconds=10)):
assert time.time() == EPOCH + 10.0
def test_destination_string_no_dateutil_unparsable():
with (
mock.patch.object(time_machine, "HAVE_DATEUTIL", new=False),
pytest.raises(ValueError) as excinfo,
time_machine.travel("the future"),
):
pass # pragma: no cover
assert excinfo.value.args == ("Invalid isoformat string: 'the future'",)
@pytest.mark.parametrize(
("string", "expected_time"),
[
("1970-01-01 00:00:00", EPOCH),
("1970-01-01 00:01:01", EPOCH + 61.0),
("1970-01-01", EPOCH),
],
)
def test_destination_string_no_dateutil(string, expected_time):
with (
mock.patch.object(time_machine, "HAVE_DATEUTIL", new=False),
time_machine.travel(string),
):
assert time.time() == expected_time
@pytest.mark.skipif(
sys.version_info < (3, 11),
reason="datetime.fromisoformat extended formats added in 3.11",
)
@pytest.mark.parametrize(
("string", "expected_time"),
[
("19700101T000102", EPOCH + 62.0),
("1970-01-01T00:00:05+01:00", EPOCH - 3600.0 + 5),
],
)
def test_destination_string_no_dateutil_extended_formats(string, expected_time):
with (
mock.patch.object(time_machine, "HAVE_DATEUTIL", new=False),
time_machine.travel(string),
):
assert time.time() == expected_time
def test_destination_string_unparsable_dateutil():
with (
pytest.raises(ValueError) as excinfo,
time_machine.travel("the future"),
):
pass # pragma: no cover
assert excinfo.value.args == ("Unknown string format: %s", "the future")
@pytest.mark.parametrize(
("string", "expected_time"),
[
("1st January 1970 00:03:03", EPOCH + 183.0),
("1st Jan 1970", EPOCH),
],
)
def test_destination_string_dateutil(string, expected_time):
with time_machine.travel(string):
assert time.time() == expected_time
@pytest.mark.parametrize(
["local_tz", "expected_offset"],
[
("UTC", 0),
("Europe/Amsterdam", -3600),
("US/Eastern", 5 * 3600),
],
)
@pytest.mark.parametrize("destination", ["1970-01-01 00:00", "1970-01-01"])
def test_destination_string_naive(local_tz, expected_offset, destination):
# MIXED mode (default) - strings are interpreted as local time
with change_local_timezone(local_tz), time_machine.travel(destination):
assert time.time() == EPOCH + expected_offset
@time_machine.travel(lambda: EPOCH + 140.0)
def test_destination_callable_lambda_float():
assert time.time() == EPOCH + 140.0
@time_machine.travel(lambda: "1970-01-01 00:02 +0000")
def test_destination_callable_lambda_string():
assert time.time() == EPOCH + 120.0
@time_machine.travel(EPOCH + 13.0 for _ in range(1)) # pragma: no branch
def test_destination_generator():
assert time.time() == EPOCH + 13.0
def test_traveller_object():
traveller = time_machine.travel(EPOCH + 10.0)
assert time.time() >= LIBRARY_EPOCH
try:
traveller.start()
assert time.time() == EPOCH + 10.0
finally:
traveller.stop()
assert time.time() >= LIBRARY_EPOCH
@time_machine.travel(EPOCH + 15.0)
def test_function_decorator():
assert time.time() == EPOCH + 15.0
def test_coroutine_decorator():
recorded_time = None
@time_machine.travel(EPOCH + 140.0)
async def record_time() -> None:
nonlocal recorded_time
recorded_time = time.time()
asyncio.run(record_time())
assert recorded_time == EPOCH + 140.0
def test_async_context_manager():
recorded_time = None
async def record_time() -> None:
nonlocal recorded_time
async with time_machine.travel(EPOCH + 150.0):
recorded_time = time.time()
asyncio.run(record_time())
assert recorded_time == EPOCH + 150.0
def test_async_context_manager_stops_properly():
recorded_times = []
async def record_times() -> None:
recorded_times.append(time.time())
async with time_machine.travel(EPOCH + 160.0):
recorded_times.append(time.time())
recorded_times.append(time.time())
asyncio.run(record_times())
assert recorded_times[0] >= LIBRARY_EPOCH
assert recorded_times[1] == EPOCH + 160.0
assert recorded_times[2] >= LIBRARY_EPOCH
def test_async_context_manager_traveller():
recorded_time = None
shifted_time = None
async def test_traveller() -> None:
nonlocal recorded_time, shifted_time
async with time_machine.travel(EPOCH + 170.0, tick=False) as traveller:
recorded_time = time.time()
traveller.shift(10.0)
shifted_time = time.time()
asyncio.run(test_traveller())
assert recorded_time == EPOCH + 170.0
assert shifted_time == EPOCH + 180.0
def test_class_decorator_fails_non_testcase():
with pytest.raises(TypeError) as excinfo:
@time_machine.travel(EPOCH)
class Something:
pass
assert excinfo.value.args == ("Can only decorate unittest.TestCase subclasses.",)
@time_machine.travel(EPOCH)
class ClassDecoratorInheritanceBase(TestCase):
prop: bool
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.setUpTestData()
@classmethod
def setUpTestData(cls) -> None:
cls.prop = True
class ClassDecoratorInheritanceTests(ClassDecoratorInheritanceBase):
@classmethod
def setUpTestData(cls) -> None:
super().setUpTestData()
cls.prop = False
def test_ineheritance_correctly_rebound(self):
assert self.prop is False
class TestMethodDecorator:
@time_machine.travel(EPOCH + 95.0)
def test_method_decorator(self):
assert time.time() == EPOCH + 95.0
class UnitTestMethodTests(TestCase):
@time_machine.travel(EPOCH + 25.0)
def test_method_decorator(self):
assert time.time() == EPOCH + 25.0
@time_machine.travel(EPOCH + 95.0)
class UnitTestClassTests(TestCase):
def test_class_decorator(self):
sleep_one_cycle(time.CLOCK_MONOTONIC)
assert EPOCH + 95.0 < time.time() < EPOCH + 96.0
@time_machine.travel(EPOCH + 25.0)
def test_stacked_method_decorator(self):
assert time.time() == EPOCH + 25.0
@time_machine.travel(EPOCH + 95.0)
class UnitTestClassCustomSetUpClassTests(TestCase):
custom_setupclass_ran: bool
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.custom_setupclass_ran = True
def test_class_decorator(self):
sleep_one_cycle(time.CLOCK_MONOTONIC)
assert EPOCH + 95.0 < time.time() < EPOCH + 96.0
assert self.custom_setupclass_ran
@time_machine.travel(EPOCH + 110.0)
class UnitTestClassSetUpClassSkipTests(TestCase):
@classmethod
def setUpClass(cls):
raise SkipTest("Not today")
# Other tests would fail if the travel() wasn't stopped
def test_thats_always_skipped(self): # pragma: no cover
pass
# shift() tests
def test_shift_with_timedelta():
with time_machine.travel(EPOCH, tick=False) as traveller:
traveller.shift(dt.timedelta(days=1))
assert time.time() == EPOCH + (3600.0 * 24)
def test_shift_integer_delta():
with time_machine.travel(EPOCH, tick=False) as traveller:
traveller.shift(10)
assert time.time() == EPOCH + 10
def test_shift_negative_delta():
with time_machine.travel(EPOCH, tick=False) as traveller:
traveller.shift(-10)
assert time.time() == EPOCH - 10
def test_shift_wrong_delta():
with (
time_machine.travel(EPOCH, tick=False) as traveller,
pytest.raises(TypeError) as excinfo,
):
traveller.shift(delta="1.1") # type: ignore[arg-type]
assert excinfo.value.args == ("Unsupported type for delta argument: '1.1'",)
def test_shift_when_tick():
with time_machine.travel(EPOCH, tick=True) as traveller:
traveller.shift(10.0)
assert EPOCH + 10.0 <= time.time() < EPOCH + 20.0
# move_to() tests
def test_move_to_datetime():
with time_machine.travel(EPOCH) as traveller:
assert time.time() == EPOCH
traveller.move_to(EPOCH_PLUS_ONE_YEAR_DATETIME)
first = time.time()
sleep_one_cycle(time.CLOCK_MONOTONIC)
assert first == EPOCH_PLUS_ONE_YEAR
second = time.time()
assert first < second < first + 1.0
def test_move_to_datetime_no_tick():
with time_machine.travel(EPOCH, tick=False) as traveller:
traveller.move_to(EPOCH_PLUS_ONE_YEAR_DATETIME)
assert time.time() == EPOCH_PLUS_ONE_YEAR
assert time.time() == EPOCH_PLUS_ONE_YEAR
def test_move_to_past_datetime():
with time_machine.travel(EPOCH_PLUS_ONE_YEAR) as traveller:
assert time.time() == EPOCH_PLUS_ONE_YEAR
traveller.move_to(EPOCH_DATETIME)
assert time.time() == EPOCH
def test_move_to_datetime_with_tzinfo_zoneinfo():
orig_timezone = time.timezone
orig_altzone = time.altzone
orig_tzname = time.tzname
orig_daylight = time.daylight
with time_machine.travel(EPOCH) as traveller:
assert time.time() == EPOCH
assert time.timezone == orig_timezone
assert time.altzone == orig_altzone
assert time.tzname == orig_tzname
assert time.daylight == orig_daylight
dest = EPOCH_PLUS_ONE_YEAR_DATETIME.replace(
tzinfo=ZoneInfo("Africa/Addis_Ababa")
)
traveller.move_to(dest)
assert time.timezone == -3 * 3600
assert time.altzone == -3 * 3600
assert time.tzname == ("EAT", "EAT")
assert time.daylight == 0
assert time.localtime() == time.struct_time(
(
1971,
1,
1,
0,
0,
0,
4,
1,
0,
)
)
assert time.timezone == orig_timezone
assert time.altzone == orig_altzone
assert time.tzname == orig_tzname
assert time.daylight == orig_daylight
def test_move_to_datetime_change_tick_on():
with time_machine.travel(EPOCH, tick=False) as traveller:
traveller.move_to(EPOCH_PLUS_ONE_YEAR_DATETIME, tick=True)
assert time.time() == EPOCH_PLUS_ONE_YEAR
sleep_one_cycle(time.CLOCK_MONOTONIC)
assert time.time() > EPOCH_PLUS_ONE_YEAR
def test_move_to_datetime_change_tick_off():
with time_machine.travel(EPOCH, tick=True) as traveller:
traveller.move_to(EPOCH_PLUS_ONE_YEAR_DATETIME, tick=False)
assert time.time() == EPOCH_PLUS_ONE_YEAR
assert time.time() == EPOCH_PLUS_ONE_YEAR
# uuid tests
def time_from_uuid1(value: uuid.UUID) -> dt.datetime:
return dt.datetime(1582, 10, 15) + dt.timedelta(microseconds=value.time // 10)
def time_from_uuid7(value: uuid.UUID) -> dt.datetime:
return dt.datetime.fromtimestamp((value.int >> 80) / 1000)
def test_uuid1():
"""
Test that the uuid.uuid1() methods generate values for the destination.
They are a known location in the stdlib that can make system calls to find
the current datetime.
"""
destination = dt.datetime(2017, 2, 6, 14, 8, 21)
with time_machine.travel(destination, tick=False):
assert time_from_uuid1(uuid.uuid1()) == destination
@pytest.mark.skipif(
sys.version_info < (3, 14),
reason="Only valid on Python 3.14+",
)
def test_uuid7_future() -> None:
"""
Test that we can go back in time after setting a future date.
Normally UUID7 would disallow this, since it keeps track of
the _last_timestamp_v7, but we override that now.
"""
if not hasattr(uuid, "uuid7"):
pytest.skip("uuid.uuid7 is not available")
destination_future = dt.datetime(2056, 2, 6, 14, 3, 21)
with time_machine.travel(destination_future, tick=False):
assert time_from_uuid7(uuid.uuid7()) == destination_future
destination_past = dt.datetime(1978, 7, 6, 23, 6, 31)
with time_machine.travel(destination_past, tick=False):
assert time_from_uuid7(uuid.uuid7()) == destination_past
# error handling tests
def test_c_extension_init_import_error():
code = dedent(
"""\
import sys
sys.modules["datetime"] = None
try:
import _time_machine
except ImportError as exc:
print(exc.args[0])
"""
)
result = subprocess.run(
[sys.executable, "-c", code],
check=True,
stdout=subprocess.PIPE,
text=True,
)
assert result.stdout == "import of datetime halted; None in sys.modules\n"
@pytest.mark.parametrize(
"func, args",
[
(dt.datetime.now, ()),
(dt.datetime.utcnow, ()),
(time.gmtime, ()),
(time.clock_gettime, (time.CLOCK_REALTIME,)),
(time.clock_gettime_ns, (time.CLOCK_REALTIME,)),
(time.localtime, ()),
(time.strftime, ("%Y-%m-%d",)),
(time.time, ()),
(time.time_ns, ()),
],
)
def test_time_machine_import_error(func, args):
with (
time_machine.travel(EPOCH),
mock.patch.dict(sys.modules, {"time_machine": None}),
pytest.raises(ModuleNotFoundError) as excinfo,
):
func(*args)
assert excinfo.value.args == ("import of time_machine halted; None in sys.modules",)
@pytest.mark.parametrize(
"func, args",
[
(dt.datetime.now, ()),
(dt.datetime.utcnow, ()),