| 1 |
"""Tests for heartbeat thread""" |
| 2 |
|
| 3 |
# Copyright (c) IPython Development Team. |
| 4 |
# Distributed under the terms of the Modified BSD License. |
| 5 |
|
| 6 |
import errno |
| 7 |
from typing import no_type_check |
| 8 |
from unittest.mock import patch |
| 9 |
|
| 10 |
import pytest |
| 11 |
import zmq |
| 12 |
|
| 13 |
from ipykernel.heartbeat import Heartbeat |
| 14 |
|
| 15 |
|
| 16 |
def test_port_bind_failure_raises(): |
| 17 |
heart = Heartbeat(None) |
| 18 |
with patch.object(heart, "_try_bind_socket") as mock_try_bind: |
| 19 |
mock_try_bind.side_effect = zmq.ZMQError(-100, "fails for unknown error types") |
| 20 |
with pytest.raises(zmq.ZMQError): |
| 21 |
heart._bind_socket() |
| 22 |
assert mock_try_bind.call_count == 1 |
| 23 |
|
| 24 |
|
| 25 |
def test_port_bind_success(): |
| 26 |
heart = Heartbeat(None) |
| 27 |
with patch.object(heart, "_try_bind_socket") as mock_try_bind: |
| 28 |
heart._bind_socket() |
| 29 |
assert mock_try_bind.call_count == 1 |
| 30 |
|
| 31 |
|
| 32 |
@no_type_check |
| 33 |
def test_port_bind_failure_recovery(): |
| 34 |
try: |
| 35 |
errno.WSAEADDRINUSE |
| 36 |
except AttributeError: |
| 37 |
# Fake windows address in-use code |
| 38 |
errno.WSAEADDRINUSE = 12345 |
| 39 |
|
| 40 |
try: |
| 41 |
heart = Heartbeat(None) |
| 42 |
with patch.object(heart, "_try_bind_socket") as mock_try_bind: |
| 43 |
mock_try_bind.side_effect = [ |
| 44 |
zmq.ZMQError(errno.EADDRINUSE, "fails for non-bind unix"), |
| 45 |
zmq.ZMQError(errno.WSAEADDRINUSE, "fails for non-bind windows"), |
| 46 |
] + [0] * 100 |
| 47 |
# Shouldn't raise anything as retries will kick in |
| 48 |
heart._bind_socket() |
| 49 |
finally: |
| 50 |
# Cleanup fake assignment |
| 51 |
if errno.WSAEADDRINUSE == 12345: |
| 52 |
del errno.WSAEADDRINUSE |
| 53 |
|
| 54 |
|
| 55 |
def test_port_bind_failure_gives_up_retries(): |
| 56 |
heart = Heartbeat(None) |
| 57 |
with patch.object(heart, "_try_bind_socket") as mock_try_bind: |
| 58 |
mock_try_bind.side_effect = zmq.ZMQError(errno.EADDRINUSE, "fails for non-bind") |
| 59 |
with pytest.raises(zmq.ZMQError): |
| 60 |
heart._bind_socket() |
| 61 |
assert mock_try_bind.call_count == 100 |