|
1 | 1 | from unittest import TestCase |
2 | | -from datetime import datetime |
| 2 | +from datetime import datetime, timedelta, timezone |
3 | 3 |
|
4 | 4 | from electionguard.utils import to_ticks |
5 | 5 |
|
6 | 6 |
|
7 | 7 | class TestUtils(TestCase): |
8 | | - def test_conversion_to_ticks(self): |
| 8 | + def test_conversion_to_ticks_from_utc(self): |
9 | 9 | # Act |
10 | | - ticks = to_ticks(datetime.utcnow()) |
| 10 | + ticks = to_ticks(datetime.now(timezone.utc)) |
11 | 11 |
|
12 | 12 | self.assertIsNotNone(ticks) |
13 | 13 | self.assertGreater(ticks, 0) |
| 14 | + |
| 15 | + def test_conversion_to_ticks_from_local(self): |
| 16 | + # Act |
| 17 | + ticks = to_ticks(datetime.now()) |
| 18 | + |
| 19 | + self.assertIsNotNone(ticks) |
| 20 | + self.assertGreater(ticks, 0) |
| 21 | + |
| 22 | + def test_conversion_to_ticks_with_tz(self): |
| 23 | + # Arrange |
| 24 | + now = datetime.now() |
| 25 | + now_with_tz = (now).astimezone() |
| 26 | + now_utc_with_tz = now_with_tz.astimezone(timezone.utc) |
| 27 | + |
| 28 | + # Act |
| 29 | + ticks_now = to_ticks(now) |
| 30 | + ticks_local = to_ticks(now_with_tz) |
| 31 | + ticks_utc = to_ticks(now_utc_with_tz) |
| 32 | + |
| 33 | + # Assert |
| 34 | + self.assertIsNotNone(ticks_now) |
| 35 | + self.assertIsNotNone(ticks_local) |
| 36 | + self.assertIsNotNone(ticks_utc) |
| 37 | + |
| 38 | + # Ensure all three tick values are the same |
| 39 | + unique_ticks = set([ticks_now, ticks_local, ticks_utc]) |
| 40 | + self.assertEqual(1, len(unique_ticks)) |
| 41 | + self.assertTrue(ticks_now in unique_ticks) |
| 42 | + |
| 43 | + def test_conversion_to_ticks_produces_valid_epoch(self): |
| 44 | + # Arrange |
| 45 | + now = datetime.now() |
| 46 | + |
| 47 | + # Act |
| 48 | + ticks_now = to_ticks(now) |
| 49 | + now_from_ticks = datetime.fromtimestamp(ticks_now) |
| 50 | + |
| 51 | + # Assert |
| 52 | + # Values below seconds are dropped from the epoch |
| 53 | + self.assertEqual(now.replace(microsecond=0), now_from_ticks) |
0 commit comments