From: Denis Laxalde Date: Thu, 15 Sep 2022 10:24:43 +0000 (+0200) Subject: test: allow to trace libpq to STDERR, rename option to --pq-trace X-Git-Tag: 3.1.2~2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=8a44473e3f75c1bfdd26052b68b1ead49b2e4ebe;p=thirdparty%2Fpsycopg.git test: allow to trace libpq to STDERR, rename option to --pq-trace 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. --- diff --git a/tests/fix_db.py b/tests/fix_db.py index 11b6c2520..a81f6f837 100644 --- a/tests/fix_db.py +++ b/tests/fix_db.py @@ -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: