Skip to content

Commit cc0b3f3

Browse files
committed
Suggested restructuring from review.
* Independent test_epoch() method. * Reduce diff for constant test vector, remove unpacking. * Avoid use of internal constants (except the OFFSET one tested above) in dynamic unpacking test vector.
1 parent f9df77e commit cc0b3f3

1 file changed

Lines changed: 19 additions & 19 deletions

File tree

test/test_time.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import struct
12
import time
23
import unittest
34
from datetime import datetime
@@ -9,38 +10,37 @@
910

1011
class TestTime(unittest.TestCase):
1112

13+
def test_epoch(self):
14+
"""Verify that the epoch matches the standard definition."""
15+
epoch = datetime.strptime(
16+
"1984-01-01 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z"
17+
).timestamp()
18+
self.assertEqual(int(epoch), canopen.timestamp.OFFSET)
19+
1220
def test_time_producer(self):
1321
network = canopen.Network()
1422
network.NOTIFIER_SHUTDOWN_TIMEOUT = 0.0
1523
network.connect(interface="virtual", receive_own_messages=True)
1624
producer = canopen.timestamp.TimeProducer(network)
1725

18-
# Test that the epoch is correct
19-
epoch = datetime.strptime(
20-
"1984-01-01 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z"
21-
).timestamp()
22-
self.assertEqual(int(epoch), canopen.timestamp.OFFSET)
26+
# Provide a specific time to verify the proper encoding
27+
producer.transmit(1_927_999_438) # 2031-02-04T19:23:58+00:00
28+
msg = network.bus.recv(1)
29+
self.assertEqual(msg.arbitration_id, 0x100)
30+
self.assertEqual(msg.dlc, 6)
31+
self.assertEqual(msg.data, b"\xb0\xa4\x29\x04\x31\x43")
2332

33+
# Test again with the current time as implicit timestamp
2434
current = time.time()
2535
with patch("canopen.timestamp.time.time", return_value=current):
26-
current_in_epoch = current - epoch
27-
28-
# Test it looking up the current time
36+
current_from_epoch = current - canopen.timestamp.OFFSET
2937
producer.transmit()
3038
msg = network.bus.recv(1)
3139
self.assertEqual(msg.arbitration_id, 0x100)
3240
self.assertEqual(msg.dlc, 6)
33-
ms, days = canopen.timestamp.TIME_OF_DAY_STRUCT.unpack(msg.data)
34-
self.assertEqual(days, int(current_in_epoch) // canopen.timestamp.ONE_DAY)
35-
self.assertEqual(ms, int((current_in_epoch % canopen.timestamp.ONE_DAY) * 1000))
36-
37-
# Provide a specific time to verify the proper encoding
38-
faketime = 1_927_999_438 # 2031-02-04 19:23:58
39-
producer.transmit(faketime)
40-
msg = network.bus.recv(1)
41-
self.assertEqual(msg.arbitration_id, 0x100)
42-
self.assertEqual(msg.dlc, 6)
43-
self.assertEqual(msg.data, b"\xb0\xa4\x29\x04\x31\x43")
41+
ms, days = struct.unpack("<LH", msg.data)
42+
self.assertEqual(days, int(current_from_epoch) // 86400)
43+
self.assertEqual(ms, int(current_from_epoch % 86400 * 1000))
4444

4545
network.disconnect()
4646

0 commit comments

Comments
 (0)