From 75c89c3edf14cbae630db10f2b1e8d9bf9834e48 Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Tue, 21 Nov 2023 09:49:24 +0100 Subject: [PATCH] test: fix test failing to connect if env vars are cleaned Add `dsn_env` fixture returning the `dsn` merged with the values in the PG* env vars. This way the env can be cleaned but a working connection string is still available. --- tests/fix_db.py | 18 ++++++++++++++++++ tests/test_module.py | 4 ++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/tests/fix_db.py b/tests/fix_db.py index 890e4ed5a..9abeda79e 100644 --- a/tests/fix_db.py +++ b/tests/fix_db.py @@ -9,6 +9,7 @@ from typing import Optional import psycopg from psycopg import pq from psycopg import sql +from psycopg.conninfo import conninfo_to_dict, make_conninfo from psycopg._compat import cache from psycopg.pq._debug import PGconnDebug @@ -104,6 +105,23 @@ def dsn(session_dsn, request): return session_dsn +@pytest.fixture +def dsn_env(dsn): + """Return a dsn including the connection parameters set in PG* env vars. + + Provide a working conninfo even in tests that modify the env vars. + """ + args = conninfo_to_dict(dsn) + for opt in pq.Conninfo.get_defaults(): + if not (opt.envvar and opt.envvar.decode() in os.environ): + continue + if opt.keyword.decode() in args: + continue + args[opt.keyword.decode()] = os.environ[opt.envvar.decode()] + + return make_conninfo(**args) + + @pytest.fixture(scope="session") def tracefile(request): """Open and yield a file for libpq client/server communication traces if diff --git a/tests/test_module.py b/tests/test_module.py index b039ee6ac..2e31c6fea 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -15,7 +15,7 @@ from ._test_connection import drop_default_args_from_conninfo ((), {"user": "foo", "dbname": None}, "user=foo"), ], ) -def test_connect(monkeypatch, dsn, args, kwargs, want, setpgenv): +def test_connect(monkeypatch, dsn_env, args, kwargs, want, setpgenv): # Check the main args passing from psycopg.connect to the conn generator # Details of the params manipulation are in test_conninfo. import psycopg.connection @@ -27,7 +27,7 @@ def test_connect(monkeypatch, dsn, args, kwargs, want, setpgenv): def mock_connect(conninfo): nonlocal got_conninfo got_conninfo = conninfo - return orig_connect(dsn) + return orig_connect(dsn_env) setpgenv({}) monkeypatch.setattr(psycopg.generators, "connect", mock_connect) -- 2.39.5