]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
test: allow to trace libpq to STDERR, rename option to --pq-trace
authorDenis Laxalde <denis.laxalde@dalibo.com>
Thu, 15 Sep 2022 10:24:43 +0000 (12:24 +0200)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Fri, 16 Sep 2022 22:44:07 +0000 (23:44 +0100)
By using STDERR, we get the trace directly in pytest output for failing
tests. Though this requires care when used in combination with
--capture=sys because this would make sys.stderr an in-memory file.

When STDERR is used, we don't insert the header since the test case
identifier will be interleaved already.

tests/fix_db.py

index 11b6c2520b162d11a299ceaa4cac7d95566d10b2..a81f6f83770cc1ded95b6f8f42f4e1fc88d74fef 100644 (file)
@@ -1,4 +1,6 @@
+import io
 import os
+import sys
 import pytest
 import logging
 from contextlib import contextmanager
@@ -26,10 +28,10 @@ def pytest_addoption(parser):
         ),
     )
     parser.addoption(
-        "--pq-tracefile",
-        metavar="TRACEFILE",
+        "--pq-trace",
+        metavar="{TRACEFILE,STDERR}",
         default=None,
-        help="Generate a libpq trace to TRACEFILE.",
+        help="Generate a libpq trace to TRACEFILE or STDERR.",
     )
 
 
@@ -106,11 +108,22 @@ def tracefile(request):
     """Open and yield a file for libpq client/server communication traces if
     --pq-tracefile option is set.
     """
-    tracefile = request.config.getoption("--pq-tracefile")
+    tracefile = request.config.getoption("--pq-trace")
     if not tracefile:
         yield None
         return
 
+    if tracefile.lower() == "stderr":
+        try:
+            sys.stderr.fileno()
+        except io.UnsupportedOperation:
+            raise pytest.UsageError(
+                "cannot use stderr for --pq-trace (in-memory file?)"
+            ) from None
+
+        yield sys.stderr
+        return
+
     with open(tracefile, "w") as f:
         yield f
 
@@ -124,9 +137,10 @@ def maybe_trace(pgconn, tracefile, function):
         yield None
         return
 
-    title = f" {function.__module__}::{function.__qualname__} ".center(80, "=")
-    tracefile.write(title + "\n")
-    tracefile.flush()
+    if tracefile != sys.stderr:
+        title = f" {function.__module__}::{function.__qualname__} ".center(80, "=")
+        tracefile.write(title + "\n")
+        tracefile.flush()
 
     pgconn.trace(tracefile.fileno())
     try: