From dece0c3cd23128ff562f89aa7c678f92ec4ff384 Mon Sep 17 00:00:00 2001 From: Yuvraj Lamba Date: Tue, 24 Nov 2026 16:35:40 +0530 Subject: [PATCH 1/2] fix(stream): implement RFC 6455 WebSocket ping/pong heartbeats and TCP keepalive (#1841) Long running streaming commands (such as exec, attach, and port-forward) frequently fail with WebSocketConnectionClosedException or silent socket drops when passing through idle proxies, firewalls, and load balancers due to lack of heartbeats. Furthermore, kube-apiserver ping frames were unhandled. This patch: - Adds a background heartbeat daemon thread in WSClient that periodically sends RFC 6455 Ping frames at ping_interval (defaults to 30s when configuration.keep_alive is True, or configured via ws_ping_interval). - Handles incoming ABNF.OPCODE_PING frames in WSClient and PortForward, automatically responding with ABNF.OPCODE_PONG containing the received payload. - Records _last_pong_time upon receiving ABNF.OPCODE_PONG frames and supports ws_ping_timeout for dead-connection detection. - Applies TCP keepalive socket options (tcp_keepalive_socket_options) and custom configuration.socket_options in create_websocket. - Adds ping_interval and ping_timeout support to stream() and websocket_call(). - Adds comprehensive unit test coverage in WSClientPingPongTest. Signed-off-by: Yuvraj Lamba --- kubernetes/stream/stream.py | 4 + kubernetes/stream/ws_client.py | 101 +++++++++++++-- kubernetes/stream/ws_client_test.py | 182 ++++++++++++++++++++++++++++ 3 files changed, 275 insertions(+), 12 deletions(-) diff --git a/kubernetes/stream/stream.py b/kubernetes/stream/stream.py index 6ca5f14e4b..262122e922 100644 --- a/kubernetes/stream/stream.py +++ b/kubernetes/stream/stream.py @@ -28,6 +28,8 @@ def _websocket_request(websocket_request, force_kwargs, api_method, *args, **kwa preload_content = kwargs.pop('_preload_content', True) kwargs['_preload_content'] = False binary = kwargs.pop('binary', False) + ping_interval = kwargs.pop('ping_interval', None) + ping_timeout = kwargs.pop('ping_timeout', None) previous_call_api = api_client.call_api # Legacy-compatible generated methods preserve _preload_content=False @@ -51,6 +53,8 @@ def call_api( _request_timeout=_request_timeout, _preload_content=preload_content, binary=binary, + ping_interval=ping_interval, + ping_timeout=ping_timeout, ) return SimpleNamespace( response=response, diff --git a/kubernetes/stream/ws_client.py b/kubernetes/stream/ws_client.py index eeac7aba73..f246a2d9bf 100644 --- a/kubernetes/stream/ws_client.py +++ b/kubernetes/stream/ws_client.py @@ -29,6 +29,7 @@ import yaml from requests.utils import should_bypass_proxies +from kubernetes.utils.keepalive import tcp_keepalive_socket_options STDIN_CHANNEL = 0 STDOUT_CHANNEL = 1 @@ -50,7 +51,7 @@ def getvalue(self): class WSClient: def __init__(self, configuration, url, headers, capture_all, binary=False, - _request_timeout=None): + _request_timeout=None, ping_interval=None, ping_timeout=None): """A websocket client with support for channels. Exec command uses different channels for different streams. for @@ -81,6 +82,48 @@ def __init__(self, configuration, url, headers, capture_all, binary=False, self._connected = True self._returncode = None + self._ping_interval = ping_interval + if self._ping_interval is None and configuration: + interval = getattr(configuration, 'ws_ping_interval', None) + if isinstance(interval, (int, float)): + self._ping_interval = interval + if self._ping_interval is None and configuration and getattr(configuration, 'keep_alive', False) is True: + self._ping_interval = 30 + + self._ping_timeout = ping_timeout + if self._ping_timeout is None and configuration: + timeout = getattr(configuration, 'ws_ping_timeout', None) + if isinstance(timeout, (int, float)): + self._ping_timeout = timeout + + self._last_ping_time = None + self._last_pong_time = None + self._ping_stop_event = threading.Event() + self._ping_thread = None + + if isinstance(self._ping_interval, (int, float)) and self._ping_interval > 0: + self._ping_thread = threading.Thread( + name="Kubernetes WSClient ping worker", + target=self._send_ping_worker + ) + self._ping_thread.daemon = True + self._ping_thread.start() + + def _send_ping_worker(self): + while not self._ping_stop_event.wait(timeout=self._ping_interval): + if not self.is_open() or not self.sock: + break + if (self._ping_timeout and self._last_ping_time and + (self._last_pong_time is None or self._last_pong_time < self._last_ping_time)): + if time.time() - self._last_ping_time > self._ping_timeout: + self.close() + break + try: + self.sock.ping() + self._last_ping_time = time.time() + except Exception: + break + def peek_channel(self, channel, timeout=0): """Peek a channel and return part of the input, empty string otherwise.""" @@ -260,7 +303,16 @@ def update(self, timeout=0): op_code, frame = self.sock.recv_data_frame(True) if op_code == ABNF.OPCODE_CLOSE: self._connected = False + if hasattr(self, '_ping_stop_event') and self._ping_stop_event: + self._ping_stop_event.set() return + elif op_code == ABNF.OPCODE_PING: + try: + self.sock.pong(frame.data) + except Exception: + pass + elif op_code == ABNF.OPCODE_PONG: + self._last_pong_time = time.time() elif op_code == ABNF.OPCODE_BINARY or op_code == ABNF.OPCODE_TEXT: data = frame.data if len(data) > 0: @@ -301,16 +353,20 @@ def update(self, timeout=0): def run_forever(self, timeout=None): """Wait till connection is closed or timeout reached. Buffer any input received during this time.""" - if timeout: - if isinstance(timeout, tuple) and len(timeout) == 2: - timeout = timeout[1] + try: if timeout: - start = time.time() - while self.is_open() and time.time() - start < timeout: - self.update(timeout=(timeout - time.time() + start)) - return - while self.is_open(): - self.update(timeout=None) + if isinstance(timeout, tuple) and len(timeout) == 2: + timeout = timeout[1] + if timeout: + start = time.time() + while self.is_open() and time.time() - start < timeout: + self.update(timeout=(timeout - time.time() + start)) + return + while self.is_open(): + self.update(timeout=None) + finally: + if hasattr(self, '_ping_stop_event') and self._ping_stop_event: + self._ping_stop_event.set() @property def returncode(self): """ @@ -334,6 +390,8 @@ def close(self, **kwargs): close websocket connection. """ self._connected = False + if hasattr(self, '_ping_stop_event') and self._ping_stop_event: + self._ping_stop_event.set() if self.sock: self.sock.close(**kwargs) @@ -502,7 +560,12 @@ def _proxy(self): "Unexpected port number in initial channel frame: %s" % port_number ) channel_initialized[channel] = True - elif opcode not in (ABNF.OPCODE_PING, ABNF.OPCODE_PONG, ABNF.OPCODE_CLOSE): + elif opcode == ABNF.OPCODE_PING: + try: + self.websocket.pong(frame.data) + except Exception: + pass + elif opcode not in (ABNF.OPCODE_PONG, ABNF.OPCODE_CLOSE): raise RuntimeError("Unexpected websocket opcode: %s" % opcode) if not (isinstance(self.websocket.sock, ssl.SSLSocket) and self.websocket.sock.pending()): pending = False @@ -618,6 +681,17 @@ def create_websocket(configuration, url, headers=None, _request_timeout=None): websocket.connect(url, **connect_opt) if _request_timeout is not None: websocket.settimeout(read_timeout) + if hasattr(websocket, 'sock') and websocket.sock: + try: + socket_options = getattr(configuration, 'socket_options', None) + if isinstance(socket_options, (list, tuple)): + for opt in socket_options: + websocket.sock.setsockopt(*opt) + elif getattr(configuration, 'keep_alive', False) is True: + for opt in tcp_keepalive_socket_options(): + websocket.sock.setsockopt(*opt) + except (OSError, socket.error, AttributeError): + pass return websocket def websocket_proxycare(connect_opt, configuration, url, headers): @@ -657,9 +731,12 @@ def websocket_call(configuration, _method, url, **kwargs): _preload_content = kwargs.get("_preload_content", True) capture_all = kwargs.get("capture_all", True) binary = kwargs.get('binary', False) + ping_interval = kwargs.get('ping_interval') + ping_timeout = kwargs.get('ping_timeout') try: client = WSClient(configuration, url, headers, capture_all, binary=binary, - _request_timeout=_request_timeout) + _request_timeout=_request_timeout, + ping_interval=ping_interval, ping_timeout=ping_timeout) if not _preload_content: return client client.run_forever(timeout=_request_timeout) diff --git a/kubernetes/stream/ws_client_test.py b/kubernetes/stream/ws_client_test.py index afbe1b0685..421cdcf7ba 100644 --- a/kubernetes/stream/ws_client_test.py +++ b/kubernetes/stream/ws_client_test.py @@ -27,6 +27,7 @@ import socket import ssl import threading +import time import pytest from kubernetes import stream, client, config import websocket @@ -868,5 +869,186 @@ def test_no_context_when_verify_ssl_is_off(self): self.assertEqual(sslopt['cert_reqs'], ssl.CERT_NONE) +class WSClientPingPongTest(unittest.TestCase): + def setUp(self): + self.config_mock = MagicMock() + self.config_mock.assert_hostname = False + self.config_mock.api_key = {} + self.config_mock.proxy = None + self.config_mock.ssl_ca_cert = None + self.config_mock.cert_file = None + self.config_mock.key_file = None + self.config_mock.verify_ssl = True + self.config_mock.keep_alive = False + self.config_mock.ws_ping_interval = None + self.config_mock.ws_ping_timeout = None + + def _make_client(self, mock_ws, **kwargs): + with patch.object(ws_client_module, 'create_websocket') as mock_create: + mock_create.return_value = mock_ws + return WSClient(self.config_mock, "wss://test", headers=None, + capture_all=True, **kwargs) + + def test_ping_worker_sends_ping(self): + """Verify background thread sends ping frames at ping_interval.""" + mock_ws = MagicMock() + mock_ws.subprotocol = V5_CHANNEL_PROTOCOL + mock_ws.connected = True + client = self._make_client(mock_ws, ping_interval=0.01) + try: + time.sleep(0.05) + self.assertTrue(mock_ws.ping.called) + self.assertIsNotNone(client._last_ping_time) + finally: + client.close() + client._ping_thread.join(timeout=1) + self.assertFalse(client._ping_thread.is_alive()) + + def test_update_responds_to_ping_with_pong(self): + """Verify receiving a PING frame automatically responds with a PONG frame.""" + server_sock, client_sock = socket.socketpair() + try: + ws = websocket.WebSocket() + ws.sock = client_sock + ws.connected = True + client = self._make_client(ws) + + ping_payload = b'heartbeat-test' + ping_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_PING, 0, ping_payload).format() + close_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_CLOSE, 0, b'\x03\xe8').format() + server_sock.sendall(ping_frame + close_frame) + + with patch.object(ws, 'pong', wraps=ws.pong) as mock_pong: + client.update(timeout=2) + mock_pong.assert_called_with(ping_payload) + finally: + server_sock.close() + client_sock.close() + client.close() + + def test_update_records_last_pong_time(self): + """Verify receiving a PONG frame updates _last_pong_time.""" + server_sock, client_sock = socket.socketpair() + try: + ws = websocket.WebSocket() + ws.sock = client_sock + ws.connected = True + client = self._make_client(ws) + + pong_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_PONG, 0, b'').format() + close_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_CLOSE, 0, b'\x03\xe8').format() + server_sock.sendall(pong_frame + close_frame) + + t0 = time.time() + client.update(timeout=2) + self.assertIsNotNone(client._last_pong_time) + self.assertGreaterEqual(client._last_pong_time, t0 - 1.0) + finally: + server_sock.close() + client_sock.close() + client.close() + + def test_keep_alive_config_defaults_ping_interval_to_30(self): + """Verify keep_alive=True sets default ping_interval=30s.""" + self.config_mock.keep_alive = True + mock_ws = MagicMock() + mock_ws.connected = True + client = self._make_client(mock_ws) + try: + self.assertEqual(client._ping_interval, 30) + finally: + client.close() + + def test_ws_ping_interval_config_override(self): + """Verify ws_ping_interval overrides default keep_alive interval.""" + self.config_mock.keep_alive = True + self.config_mock.ws_ping_interval = 45 + mock_ws = MagicMock() + mock_ws.connected = True + client = self._make_client(mock_ws) + try: + self.assertEqual(client._ping_interval, 45) + finally: + client.close() + + def test_create_websocket_applies_keepalive_socket_options(self): + """Verify create_websocket applies TCP keepalive socket options when keep_alive=True.""" + config = Configuration() + config.keep_alive = True + with patch.object(ws_client_module, 'WebSocket', autospec=True) as mock_ws_cls: + mock_ws = mock_ws_cls.return_value + mock_sock = MagicMock() + mock_ws.sock = mock_sock + ws_client_module.create_websocket(config, "ws://example.com") + mock_sock.setsockopt.assert_any_call(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + + def test_create_websocket_applies_custom_socket_options(self): + """Verify create_websocket applies custom socket_options if configured.""" + config = Configuration() + custom_opts = [(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)] + config.socket_options = custom_opts + with patch.object(ws_client_module, 'WebSocket', autospec=True) as mock_ws_cls: + mock_ws = mock_ws_cls.return_value + mock_sock = MagicMock() + mock_ws.sock = mock_sock + ws_client_module.create_websocket(config, "ws://example.com") + mock_sock.setsockopt.assert_called_with(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + + def test_stream_request_forwards_ping_parameters(self): + """Verify stream._websocket_request forwards ping_interval and ping_timeout.""" + config = Configuration() + api_client = MagicMock() + api_client.configuration = config + + class DummyApi: + def __init__(self, client): + self.api_client = client + def sample_call(self, *args, **kwargs): + return self.api_client.call_api('GET', 'https://example.com') + + dummy = DummyApi(api_client) + + received_kwargs = {} + def mock_ws_request(conf, method, url, **kwargs): + received_kwargs.update(kwargs) + return ws_client_module.WSResponse("ok", 200) + + from kubernetes.stream.stream import _websocket_request + + _websocket_request(mock_ws_request, None, dummy.sample_call, ping_interval=25, ping_timeout=15) + self.assertEqual(received_kwargs.get('ping_interval'), 25) + self.assertEqual(received_kwargs.get('ping_timeout'), 15) + + def test_portforward_proxy_handles_ping_frame(self): + """Verify PortForward._proxy handles incoming PING frame and responds with PONG.""" + server_sock, client_sock = socket.socketpair() + try: + ws = websocket.WebSocket() + ws.sock = client_sock + ws.connected = True + + ping_payload = b'pf-ping' + ping_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_PING, 0, ping_payload).format() + close_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_CLOSE, 0, b'\x03\xe8').format() + server_sock.sendall(ping_frame + close_frame) + + with patch.object(ws, 'pong', wraps=ws.pong) as mock_pong: + pf = ws_client_module.PortForward(ws, [8080]) + try: + time.sleep(0.1) + mock_pong.assert_called_with(ping_payload) + finally: + pf.close() + finally: + server_sock.close() + client_sock.close() + + if __name__ == '__main__': unittest.main() From e9301190acfc1bad767e96c8919532d2253eb60e Mon Sep 17 00:00:00 2001 From: Yuvraj Lamba Date: Thu, 26 Nov 2026 23:16:00 +0530 Subject: [PATCH 2/2] fix(stream): address review feedback on ping/pong and keepalive Signed-off-by: Yuvraj Lamba --- kubernetes/stream/stream.py | 16 ++++--- kubernetes/stream/ws_client.py | 44 +++---------------- kubernetes/stream/ws_client_test.py | 66 ++++++++++++++--------------- 3 files changed, 48 insertions(+), 78 deletions(-) diff --git a/kubernetes/stream/stream.py b/kubernetes/stream/stream.py index 262122e922..eddcb4188c 100644 --- a/kubernetes/stream/stream.py +++ b/kubernetes/stream/stream.py @@ -29,7 +29,6 @@ def _websocket_request(websocket_request, force_kwargs, api_method, *args, **kwa kwargs['_preload_content'] = False binary = kwargs.pop('binary', False) ping_interval = kwargs.pop('ping_interval', None) - ping_timeout = kwargs.pop('ping_timeout', None) previous_call_api = api_client.call_api # Legacy-compatible generated methods preserve _preload_content=False @@ -43,18 +42,21 @@ def call_api( post_params=None, _request_timeout=None, ): - response = websocket_request( - configuration, - method, - url, + req_kwargs = dict( headers=header_params, body=body, post_params=post_params, _request_timeout=_request_timeout, _preload_content=preload_content, binary=binary, - ping_interval=ping_interval, - ping_timeout=ping_timeout, + ) + if ping_interval is not None: + req_kwargs['ping_interval'] = ping_interval + response = websocket_request( + configuration, + method, + url, + **req_kwargs, ) return SimpleNamespace( response=response, diff --git a/kubernetes/stream/ws_client.py b/kubernetes/stream/ws_client.py index f246a2d9bf..d9ea147d65 100644 --- a/kubernetes/stream/ws_client.py +++ b/kubernetes/stream/ws_client.py @@ -51,7 +51,7 @@ def getvalue(self): class WSClient: def __init__(self, configuration, url, headers, capture_all, binary=False, - _request_timeout=None, ping_interval=None, ping_timeout=None): + _request_timeout=None, ping_interval=None): """A websocket client with support for channels. Exec command uses different channels for different streams. for @@ -83,25 +83,12 @@ def __init__(self, configuration, url, headers, capture_all, binary=False, self._returncode = None self._ping_interval = ping_interval - if self._ping_interval is None and configuration: - interval = getattr(configuration, 'ws_ping_interval', None) - if isinstance(interval, (int, float)): - self._ping_interval = interval - if self._ping_interval is None and configuration and getattr(configuration, 'keep_alive', False) is True: - self._ping_interval = 30 - - self._ping_timeout = ping_timeout - if self._ping_timeout is None and configuration: - timeout = getattr(configuration, 'ws_ping_timeout', None) - if isinstance(timeout, (int, float)): - self._ping_timeout = timeout - - self._last_ping_time = None - self._last_pong_time = None self._ping_stop_event = threading.Event() self._ping_thread = None - if isinstance(self._ping_interval, (int, float)) and self._ping_interval > 0: + if (not isinstance(self._ping_interval, bool) + and isinstance(self._ping_interval, (int, float)) + and self._ping_interval > 0): self._ping_thread = threading.Thread( name="Kubernetes WSClient ping worker", target=self._send_ping_worker @@ -113,14 +100,8 @@ def _send_ping_worker(self): while not self._ping_stop_event.wait(timeout=self._ping_interval): if not self.is_open() or not self.sock: break - if (self._ping_timeout and self._last_ping_time and - (self._last_pong_time is None or self._last_pong_time < self._last_ping_time)): - if time.time() - self._last_ping_time > self._ping_timeout: - self.close() - break try: self.sock.ping() - self._last_ping_time = time.time() except Exception: break @@ -306,13 +287,6 @@ def update(self, timeout=0): if hasattr(self, '_ping_stop_event') and self._ping_stop_event: self._ping_stop_event.set() return - elif op_code == ABNF.OPCODE_PING: - try: - self.sock.pong(frame.data) - except Exception: - pass - elif op_code == ABNF.OPCODE_PONG: - self._last_pong_time = time.time() elif op_code == ABNF.OPCODE_BINARY or op_code == ABNF.OPCODE_TEXT: data = frame.data if len(data) > 0: @@ -560,12 +534,7 @@ def _proxy(self): "Unexpected port number in initial channel frame: %s" % port_number ) channel_initialized[channel] = True - elif opcode == ABNF.OPCODE_PING: - try: - self.websocket.pong(frame.data) - except Exception: - pass - elif opcode not in (ABNF.OPCODE_PONG, ABNF.OPCODE_CLOSE): + elif opcode not in (ABNF.OPCODE_PING, ABNF.OPCODE_PONG, ABNF.OPCODE_CLOSE): raise RuntimeError("Unexpected websocket opcode: %s" % opcode) if not (isinstance(self.websocket.sock, ssl.SSLSocket) and self.websocket.sock.pending()): pending = False @@ -732,11 +701,10 @@ def websocket_call(configuration, _method, url, **kwargs): capture_all = kwargs.get("capture_all", True) binary = kwargs.get('binary', False) ping_interval = kwargs.get('ping_interval') - ping_timeout = kwargs.get('ping_timeout') try: client = WSClient(configuration, url, headers, capture_all, binary=binary, _request_timeout=_request_timeout, - ping_interval=ping_interval, ping_timeout=ping_timeout) + ping_interval=ping_interval) if not _preload_content: return client client.run_forever(timeout=_request_timeout) diff --git a/kubernetes/stream/ws_client_test.py b/kubernetes/stream/ws_client_test.py index 421cdcf7ba..9a313babe4 100644 --- a/kubernetes/stream/ws_client_test.py +++ b/kubernetes/stream/ws_client_test.py @@ -880,8 +880,7 @@ def setUp(self): self.config_mock.key_file = None self.config_mock.verify_ssl = True self.config_mock.keep_alive = False - self.config_mock.ws_ping_interval = None - self.config_mock.ws_ping_timeout = None + self.config_mock.socket_options = None def _make_client(self, mock_ws, **kwargs): with patch.object(ws_client_module, 'create_websocket') as mock_create: @@ -898,14 +897,24 @@ def test_ping_worker_sends_ping(self): try: time.sleep(0.05) self.assertTrue(mock_ws.ping.called) - self.assertIsNotNone(client._last_ping_time) finally: client.close() client._ping_thread.join(timeout=1) self.assertFalse(client._ping_thread.is_alive()) - def test_update_responds_to_ping_with_pong(self): - """Verify receiving a PING frame automatically responds with a PONG frame.""" + def test_ping_opt_in_and_invalid_intervals(self): + """Verify app-level pings stay opt-in and skip non-positive or bool values.""" + mock_ws = MagicMock() + mock_ws.connected = True + for interval in (None, 0, -5, True): + client = self._make_client(mock_ws, ping_interval=interval) + try: + self.assertIsNone(client._ping_thread) + finally: + client.close() + + def test_update_responds_to_ping_with_single_pong(self): + """Verify receiving a PING frame responds with exactly one PONG frame.""" server_sock, client_sock = socket.socketpair() try: ws = websocket.WebSocket() @@ -922,14 +931,14 @@ def test_update_responds_to_ping_with_pong(self): with patch.object(ws, 'pong', wraps=ws.pong) as mock_pong: client.update(timeout=2) - mock_pong.assert_called_with(ping_payload) + mock_pong.assert_called_once_with(ping_payload) finally: server_sock.close() client_sock.close() client.close() - def test_update_records_last_pong_time(self): - """Verify receiving a PONG frame updates _last_pong_time.""" + def test_update_handles_pong_frame_without_error(self): + """Verify receiving a PONG frame is tolerated cleanly in update().""" server_sock, client_sock = socket.socketpair() try: ws = websocket.WebSocket() @@ -943,35 +952,22 @@ def test_update_records_last_pong_time(self): 1, 0, 0, 0, websocket.ABNF.OPCODE_CLOSE, 0, b'\x03\xe8').format() server_sock.sendall(pong_frame + close_frame) - t0 = time.time() client.update(timeout=2) - self.assertIsNotNone(client._last_pong_time) - self.assertGreaterEqual(client._last_pong_time, t0 - 1.0) + self.assertFalse(client.is_open()) finally: server_sock.close() client_sock.close() client.close() - def test_keep_alive_config_defaults_ping_interval_to_30(self): - """Verify keep_alive=True sets default ping_interval=30s.""" - self.config_mock.keep_alive = True - mock_ws = MagicMock() - mock_ws.connected = True - client = self._make_client(mock_ws) - try: - self.assertEqual(client._ping_interval, 30) - finally: - client.close() - - def test_ws_ping_interval_config_override(self): - """Verify ws_ping_interval overrides default keep_alive interval.""" + def test_keep_alive_config_does_not_start_ping_thread(self): + """Verify keep_alive=True only configures TCP keepalive, not app-level pings.""" self.config_mock.keep_alive = True - self.config_mock.ws_ping_interval = 45 mock_ws = MagicMock() mock_ws.connected = True client = self._make_client(mock_ws) try: - self.assertEqual(client._ping_interval, 45) + self.assertIsNone(client._ping_interval) + self.assertIsNone(client._ping_thread) finally: client.close() @@ -998,8 +994,8 @@ def test_create_websocket_applies_custom_socket_options(self): ws_client_module.create_websocket(config, "ws://example.com") mock_sock.setsockopt.assert_called_with(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - def test_stream_request_forwards_ping_parameters(self): - """Verify stream._websocket_request forwards ping_interval and ping_timeout.""" + def test_stream_request_forwards_ping_interval(self): + """Verify stream._websocket_request forwards ping_interval only when provided.""" config = Configuration() api_client = MagicMock() api_client.configuration = config @@ -1014,17 +1010,21 @@ def sample_call(self, *args, **kwargs): received_kwargs = {} def mock_ws_request(conf, method, url, **kwargs): + received_kwargs.clear() received_kwargs.update(kwargs) return ws_client_module.WSResponse("ok", 200) from kubernetes.stream.stream import _websocket_request - _websocket_request(mock_ws_request, None, dummy.sample_call, ping_interval=25, ping_timeout=15) + _websocket_request(mock_ws_request, None, dummy.sample_call, ping_interval=25) self.assertEqual(received_kwargs.get('ping_interval'), 25) - self.assertEqual(received_kwargs.get('ping_timeout'), 15) + self.assertNotIn('ping_timeout', received_kwargs) + + _websocket_request(mock_ws_request, None, dummy.sample_call) + self.assertNotIn('ping_interval', received_kwargs) - def test_portforward_proxy_handles_ping_frame(self): - """Verify PortForward._proxy handles incoming PING frame and responds with PONG.""" + def test_portforward_proxy_handles_ping_frame_with_single_pong(self): + """Verify PortForward._proxy handles incoming PING frame with a single PONG.""" server_sock, client_sock = socket.socketpair() try: ws = websocket.WebSocket() @@ -1042,7 +1042,7 @@ def test_portforward_proxy_handles_ping_frame(self): pf = ws_client_module.PortForward(ws, [8080]) try: time.sleep(0.1) - mock_pong.assert_called_with(ping_payload) + mock_pong.assert_called_once_with(ping_payload) finally: pf.close() finally: