Skip to content

Commit 4301c4b

Browse files
Tests: harden test_emcy_consumer_wait (#532)
* Tests: harden test_emcy_consumer_wait Wait a little bit longer before dispatching the EMCY packet, and start the one-shot timer just before invoking the wait() call. * Better resource management
1 parent 83594ac commit 4301c4b

File tree

1 file changed

+24
-15
lines changed

1 file changed

+24
-15
lines changed

test/test_emcy.py

+24-15
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import logging
22
import threading
33
import unittest
4+
from contextlib import contextmanager
45

56
import can
67
import canopen
@@ -72,7 +73,7 @@ def test_emcy_consumer_reset(self):
7273
self.assertEqual(len(self.emcy.active), 0)
7374

7475
def test_emcy_consumer_wait(self):
75-
PAUSE = TIMEOUT / 4
76+
PAUSE = TIMEOUT / 2
7677

7778
def push_err():
7879
self.emcy.on_emcy(0x81, b'\x01\x20\x01\x01\x02\x03\x04\x05', 100)
@@ -84,34 +85,42 @@ def check_err(err):
8485
data=bytes([1, 2, 3, 4, 5]), ts=100,
8586
)
8687

88+
@contextmanager
89+
def timer(func):
90+
t = threading.Timer(PAUSE, func)
91+
try:
92+
yield t
93+
finally:
94+
t.join(TIMEOUT)
95+
8796
# Check unfiltered wait, on timeout.
8897
self.assertIsNone(self.emcy.wait(timeout=TIMEOUT))
8998

9099
# Check unfiltered wait, on success.
91-
timer = threading.Timer(PAUSE, push_err)
92-
timer.start()
93-
with self.assertLogs(level=logging.INFO):
94-
err = self.emcy.wait(timeout=TIMEOUT)
100+
with timer(push_err) as t:
101+
with self.assertLogs(level=logging.INFO):
102+
t.start()
103+
err = self.emcy.wait(timeout=TIMEOUT)
95104
check_err(err)
96105

97106
# Check filtered wait, on success.
98-
timer = threading.Timer(PAUSE, push_err)
99-
timer.start()
100-
with self.assertLogs(level=logging.INFO):
101-
err = self.emcy.wait(0x2001, TIMEOUT)
107+
with timer(push_err) as t:
108+
with self.assertLogs(level=logging.INFO):
109+
t.start()
110+
err = self.emcy.wait(0x2001, TIMEOUT)
102111
check_err(err)
103112

104113
# Check filtered wait, on timeout.
105-
timer = threading.Timer(PAUSE, push_err)
106-
timer.start()
107-
self.assertIsNone(self.emcy.wait(0x9000, TIMEOUT))
114+
with timer(push_err) as t:
115+
t.start()
116+
self.assertIsNone(self.emcy.wait(0x9000, TIMEOUT))
108117

109118
def push_reset():
110119
self.emcy.on_emcy(0x81, b'\x00\x00\x00\x00\x00\x00\x00\x00', 100)
111120

112-
timer = threading.Timer(PAUSE, push_reset)
113-
timer.start()
114-
self.assertIsNone(self.emcy.wait(0x9000, TIMEOUT))
121+
with timer(push_reset) as t:
122+
t.start()
123+
self.assertIsNone(self.emcy.wait(0x9000, TIMEOUT))
115124

116125

117126
class TestEmcyError(unittest.TestCase):

0 commit comments

Comments
 (0)