test_chrono.py revision 12391:ceeca8b41e4b
1from pybind11_tests import chrono as m 2import datetime 3 4 5def test_chrono_system_clock(): 6 7 # Get the time from both c++ and datetime 8 date1 = m.test_chrono1() 9 date2 = datetime.datetime.today() 10 11 # The returned value should be a datetime 12 assert isinstance(date1, datetime.datetime) 13 14 # The numbers should vary by a very small amount (time it took to execute) 15 diff = abs(date1 - date2) 16 17 # There should never be a days/seconds difference 18 assert diff.days == 0 19 assert diff.seconds == 0 20 21 # We test that no more than about 0.5 seconds passes here 22 # This makes sure that the dates created are very close to the same 23 # but if the testing system is incredibly overloaded this should still pass 24 assert diff.microseconds < 500000 25 26 27def test_chrono_system_clock_roundtrip(): 28 date1 = datetime.datetime.today() 29 30 # Roundtrip the time 31 date2 = m.test_chrono2(date1) 32 33 # The returned value should be a datetime 34 assert isinstance(date2, datetime.datetime) 35 36 # They should be identical (no information lost on roundtrip) 37 diff = abs(date1 - date2) 38 assert diff.days == 0 39 assert diff.seconds == 0 40 assert diff.microseconds == 0 41 42 43def test_chrono_duration_roundtrip(): 44 45 # Get the difference between two times (a timedelta) 46 date1 = datetime.datetime.today() 47 date2 = datetime.datetime.today() 48 diff = date2 - date1 49 50 # Make sure this is a timedelta 51 assert isinstance(diff, datetime.timedelta) 52 53 cpp_diff = m.test_chrono3(diff) 54 55 assert cpp_diff.days == diff.days 56 assert cpp_diff.seconds == diff.seconds 57 assert cpp_diff.microseconds == diff.microseconds 58 59 60def test_chrono_duration_subtraction_equivalence(): 61 62 date1 = datetime.datetime.today() 63 date2 = datetime.datetime.today() 64 65 diff = date2 - date1 66 cpp_diff = m.test_chrono4(date2, date1) 67 68 assert cpp_diff.days == diff.days 69 assert cpp_diff.seconds == diff.seconds 70 assert cpp_diff.microseconds == diff.microseconds 71 72 73def test_chrono_steady_clock(): 74 time1 = m.test_chrono5() 75 assert isinstance(time1, datetime.timedelta) 76 77 78def test_chrono_steady_clock_roundtrip(): 79 time1 = datetime.timedelta(days=10, seconds=10, microseconds=100) 80 time2 = m.test_chrono6(time1) 81 82 assert isinstance(time2, datetime.timedelta) 83 84 # They should be identical (no information lost on roundtrip) 85 assert time1.days == time2.days 86 assert time1.seconds == time2.seconds 87 assert time1.microseconds == time2.microseconds 88 89 90def test_floating_point_duration(): 91 # Test using a floating point number in seconds 92 time = m.test_chrono7(35.525123) 93 94 assert isinstance(time, datetime.timedelta) 95 96 assert time.seconds == 35 97 assert 525122 <= time.microseconds <= 525123 98 99 diff = m.test_chrono_float_diff(43.789012, 1.123456) 100 assert diff.seconds == 42 101 assert 665556 <= diff.microseconds <= 665557 102