|
| 1 | +from unittest.mock import MagicMock, patch |
| 2 | + |
| 3 | +import grpc |
| 4 | + |
| 5 | +from durabletask.worker import TaskHubGrpcWorker |
| 6 | + |
| 7 | + |
| 8 | +# Helper to create a running worker with a mocked runLoop |
| 9 | +def _make_running_worker(): |
| 10 | + worker = TaskHubGrpcWorker() |
| 11 | + worker._is_running = True |
| 12 | + worker._runLoop = MagicMock() |
| 13 | + worker._runLoop.is_alive.return_value = False |
| 14 | + return worker |
| 15 | + |
| 16 | + |
| 17 | +def test_stop_with_grpc_future(): |
| 18 | + worker = _make_running_worker() |
| 19 | + mock_future = MagicMock(spec=grpc.Future) |
| 20 | + worker._response_stream = mock_future |
| 21 | + worker.stop() |
| 22 | + mock_future.cancel.assert_called_once() |
| 23 | + |
| 24 | + |
| 25 | +def test_stop_with_generator_call(): |
| 26 | + worker = _make_running_worker() |
| 27 | + mock_call = MagicMock() |
| 28 | + mock_stream = MagicMock() |
| 29 | + mock_stream.call = mock_call |
| 30 | + worker._response_stream = mock_stream |
| 31 | + worker.stop() |
| 32 | + mock_call.cancel.assert_called_once() |
| 33 | + |
| 34 | + |
| 35 | +def test_stop_with_unknown_stream_type(caplog): |
| 36 | + worker = _make_running_worker() |
| 37 | + # Not a grpc.Future, no 'call' attribute |
| 38 | + worker._response_stream = object() |
| 39 | + with caplog.at_level("WARNING"): |
| 40 | + worker.stop() |
| 41 | + assert any("Unknown response stream type" in m for m in caplog.text.splitlines()) |
| 42 | + |
| 43 | + |
| 44 | +def test_stop_with_none_stream(): |
| 45 | + worker = _make_running_worker() |
| 46 | + worker._response_stream = None |
| 47 | + # Should not raise |
| 48 | + worker.stop() |
| 49 | + |
| 50 | + |
| 51 | +def test_stop_when_not_running(): |
| 52 | + worker = TaskHubGrpcWorker() |
| 53 | + worker._is_running = False |
| 54 | + # Should return immediately, not set _shutdown |
| 55 | + with patch.object(worker._shutdown, "set") as shutdown_set: |
| 56 | + worker.stop() |
| 57 | + shutdown_set.assert_not_called() |
0 commit comments