]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
test: fix test failing to connect if env vars are cleaned 682/head
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 21 Nov 2023 08:49:24 +0000 (09:49 +0100)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 21 Nov 2023 09:12:01 +0000 (10:12 +0100)
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
tests/test_module.py

index 890e4ed5a167c050cb0b3a864253d2a6f235fc01..9abeda79e9b5c13d46a4a4dfe2e3c03c4cd2e98a 100644 (file)
@@ -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
index b039ee6ac292fa28876c0ad78e9721c402329c8f..2e31c6feadb0200845b73568e0f1f8194b639baf 100644 (file)
@@ -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)