psycopg.git / summary / log / commit / refs

commit    8a44473e3f75c1bfdd26052b68b1ead49b2e4ebe
Author:   Denis Laxalde <denis.laxalde@dalibo.com>
Commit:   Daniele Varrazzo <daniele.varrazzo@gmail.com>
Date:     Thu Sep 15 10:24:43 2022 +0000

    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.


tests/fix_db.py | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/tests/fix_db.py b/tests/fix_db.py index 11b6c252..a81f6f83 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: [parent: d41d8fc6a097]