Skip to content

Commit

Permalink
fix: honour the PGCONNECT_TIMEOUT env var
Browse files Browse the repository at this point in the history
  • Loading branch information
dvarrazzo committed Dec 13, 2023
1 parent 5d18a15 commit 57781bf
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
2 changes: 2 additions & 0 deletions docs/news.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ Psycopg 3.1.15 (unreleased)
:ticket:`#694`).
- Fix async connection to hosts resolving to multiple IP addresses (regression
in 3.1.13, :ticket:`#695`).
- Respect the :envvar:`PGCONNECT_TIMEOUT` environment variable to determine
the connection timeout.


Current release
Expand Down
4 changes: 3 additions & 1 deletion psycopg/psycopg/conninfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,9 @@ def timeout_from_conninfo(params: ConnDict) -> int:
# - at least 2 seconds.
#
# See connectDBComplete in fe-connect.c
value = params.get("connect_timeout", _DEFAULT_CONNECT_TIMEOUT)
value: str | int | None = _get_param(params, "connect_timeout")
if value is None:
value = _DEFAULT_CONNECT_TIMEOUT
try:
timeout = int(value)
except ValueError:
Expand Down
20 changes: 20 additions & 0 deletions tests/test_conninfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from psycopg import ProgrammingError
from psycopg.conninfo import make_conninfo, conninfo_to_dict, ConnectionInfo
from psycopg.conninfo import conninfo_attempts, conninfo_attempts_async
from psycopg.conninfo import timeout_from_conninfo, _DEFAULT_CONNECT_TIMEOUT
from psycopg._encodings import pg2pyenc

from .fix_crdb import crdb_encoding
Expand Down Expand Up @@ -530,6 +531,25 @@ async def test_conninfo_random_async(fake_resolve):
assert hostaddrs != sorted(hostaddrs)


@pytest.mark.parametrize(
"conninfo, want, env",
[
("", _DEFAULT_CONNECT_TIMEOUT, None),
("host=foo", _DEFAULT_CONNECT_TIMEOUT, None),
("connect_timeout=-1", _DEFAULT_CONNECT_TIMEOUT, None),
("connect_timeout=0", _DEFAULT_CONNECT_TIMEOUT, None),
("connect_timeout=1", 2, None),
("connect_timeout=10", 10, None),
("", 15, {"PGCONNECT_TIMEOUT": "15"}),
],
)
def test_timeout(setpgenv, conninfo, want, env):
setpgenv(env)
params = conninfo_to_dict(conninfo)
timeout = timeout_from_conninfo(params)
assert timeout == want


@pytest.fixture
async def fake_resolve(monkeypatch):
fake_hosts = {
Expand Down

0 comments on commit 57781bf

Please sign in to comment.