|
22 | 22 | import json |
23 | 23 | import time |
24 | 24 | import pytest |
| 25 | +from unittest.mock import patch |
25 | 26 |
|
26 | 27 | thread_lock = threading.RLock() |
27 | 28 |
|
@@ -194,6 +195,33 @@ def on_stopped_leading(): |
194 | 195 |
|
195 | 196 | self.assert_history(leadership_history, ["get leadership", "start leading", "stop leading"]) |
196 | 197 |
|
| 198 | + def test_onstarted_leading_runs_in_daemon_thread(self): |
| 199 | + captured = {} |
| 200 | + real_thread = threading.Thread |
| 201 | + |
| 202 | + def record_thread(*args, **kwargs): |
| 203 | + thread = real_thread(*args, **kwargs) |
| 204 | + captured["daemon"] = thread.daemon |
| 205 | + return thread |
| 206 | + |
| 207 | + started = threading.Event() |
| 208 | + |
| 209 | + mock_lock = MockResourceLock("mock", "mock_namespace", "mock", thread_lock, |
| 210 | + lambda: None, lambda: None, lambda: None, None) |
| 211 | + mock_lock.renew_count_max = 1 |
| 212 | + |
| 213 | + config = electionconfig.Config(lock=mock_lock, lease_duration=2, |
| 214 | + renew_deadline=1.5, retry_period=1, |
| 215 | + onstarted_leading=started.set, |
| 216 | + onstopped_leading=lambda: None) |
| 217 | + |
| 218 | + with patch.object(leaderelection.threading, "Thread", new=record_thread): |
| 219 | + leaderelection.LeaderElection(config).run() |
| 220 | + |
| 221 | + self.assertTrue(started.wait(1), "onstarted_leading callback did not run") |
| 222 | + self.assertIn("daemon", captured) |
| 223 | + self.assertTrue(captured["daemon"]) |
| 224 | + |
197 | 225 | def assert_history(self, history, expected): |
198 | 226 | self.assertIsNotNone(expected) |
199 | 227 | self.assertIsNotNone(history) |
|
0 commit comments