Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions pymysql/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,14 +603,18 @@ def kill(self, thread_id):
raise TypeError("thread_id must be an integer")
self.query(f"KILL {thread_id:d}")

def ping(self, reconnect=False):
def ping(self, reconnect=False, timeout=None):
"""
Check if the server is alive.

`reconnect` is deprecated. Create a new connection if you want to reconnect.

:param reconnect: If the connection is closed, reconnect.
:type reconnect: boolean
:param timeout: Timeout in seconds for this ping only. It overrides
`read_timeout` and `write_timeout` during the call. If None, the
connection's own timeouts are used.
:type timeout: float

:raise Error: If the connection is closed and reconnect=False.
"""
Expand All @@ -621,21 +625,28 @@ def ping(self, reconnect=False):
DeprecationWarning,
2,
)
if timeout is not None and timeout <= 0:
raise ValueError("timeout should be > 0")
if self._sock is None:
if reconnect:
self.connect()
reconnect = False
else:
raise err.Error("Already closed")
saved_timeouts = self._read_timeout, self._write_timeout
if timeout is not None:
self._read_timeout = self._write_timeout = timeout
Comment thread
ritojoao marked this conversation as resolved.
Resolved
try:
self._execute_command(COMMAND.COM_PING, "")
self._read_ok_packet()
except Exception:
if reconnect:
self.connect()
self.ping(False)
self.ping(False, timeout)
else:
raise
finally:
self._read_timeout, self._write_timeout = saved_timeouts

def set_charset(self, charset):
"""Deprecated. Use set_character_set() instead."""
Expand Down
67 changes: 67 additions & 0 deletions pymysql/tests/test_ping_timeout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""Tests for Connection.ping(timeout=...) that do not need a MySQL server."""

import socket
import struct
import time

import pytest

import pymysql


def _connection_with_socket(sock, **kwargs):
conn = pymysql.connect(defer_connect=True, **kwargs)
conn._sock = sock
conn._rfile = sock.makefile("rb")
conn._current_timeout = conn._read_timeout
return conn


def test_ping_timeout_on_silent_server():
client, server = socket.socketpair()
conn = _connection_with_socket(client)
try:
start = time.monotonic()
with pytest.raises(pymysql.OperationalError):
conn.ping(timeout=0.2)
assert time.monotonic() - start < 5
assert conn._sock is None
finally:
server.close()
client.close()


def test_ping_timeout_is_restored_and_ping_works():
client, server = socket.socketpair()
conn = _connection_with_socket(client, read_timeout=30, write_timeout=40)
try:
# OK packet with sequence id 1, sent in reply to COM_PING.
ok = b"\x00\x00\x00\x02\x00\x00\x00"
server.sendall(struct.pack("<I", len(ok))[:3] + b"\x01" + ok)
conn.ping(timeout=0.5)
assert conn._read_timeout == 30
assert conn._write_timeout == 40
assert server.recv(16) == b"\x01\x00\x00\x00\x0e"
finally:
server.close()
client.close()


def test_ping_timeout_must_be_positive():
client, server = socket.socketpair()
conn = _connection_with_socket(client)
try:
with pytest.raises(ValueError):
conn.ping(timeout=0)
finally:
server.close()
client.close()


def test_ping_timeout_is_checked_before_reconnect(monkeypatch):
conn = pymysql.connect(defer_connect=True)
calls = []
monkeypatch.setattr(conn, "connect", lambda *args: calls.append(args))
with pytest.warns(DeprecationWarning), pytest.raises(ValueError):
conn.ping(reconnect=True, timeout=0)
assert calls == []