Пример #1
0
def test_connection_warn_close(dsn, recwarn):
    conn = Connection.connect(dsn)
    conn.close()
    del conn
    assert not recwarn

    conn = Connection.connect(dsn)
    del conn
    assert "IDLE" in str(recwarn.pop(ResourceWarning).message)

    conn = Connection.connect(dsn)
    conn.execute("select 1")
    del conn
    assert "INTRANS" in str(recwarn.pop(ResourceWarning).message)

    conn = Connection.connect(dsn)
    try:
        conn.execute("select wat")
    except Exception:
        pass
    del conn
    assert "INERROR" in str(recwarn.pop(ResourceWarning).message)

    with Connection.connect(dsn) as conn:
        pass
    del conn
    assert not recwarn
Пример #2
0
def test_row_factory(dsn):
    defaultconn = Connection.connect(dsn)
    assert defaultconn.row_factory is tuple_row  # type: ignore[comparison-overlap]
    defaultconn.close()

    conn = Connection.connect(dsn, row_factory=my_row_factory)
    assert conn.row_factory is my_row_factory  # type: ignore[comparison-overlap]

    cur = conn.execute("select 'a' as ve")
    assert cur.fetchone() == ["Ave"]

    with conn.cursor(row_factory=lambda c: set) as cur1:
        cur1.execute("select 1, 1, 2")
        assert cur1.fetchall() == [{1, 2}]

    with conn.cursor(row_factory=tuple_row) as cur2:
        cur2.execute("select 1, 1, 2")
        assert cur2.fetchall() == [(1, 1, 2)]

    # TODO: maybe fix something to get rid of 'type: ignore' below.
    conn.row_factory = tuple_row  # type: ignore[assignment]
    cur3 = conn.execute("select 'vale'")
    r = cur3.fetchone()
    assert r and r == ("vale",)  # type: ignore[comparison-overlap]
    conn.close()
Пример #3
0
def test_connect_str_subclass(dsn):
    class MyString(str):
        pass

    conn = Connection.connect(MyString(dsn))
    assert not conn.closed
    assert conn.pgconn.status == conn.ConnStatus.OK
Пример #4
0
def test_connect_timeout():
    s = socket.socket(socket.AF_INET)
    s.bind(("localhost", 0))
    port = s.getsockname()[1]
    s.listen(0)

    def closer():
        time.sleep(1.5)
        s.close()

    Thread(target=closer).start()

    t0 = time.time()
    with pytest.raises(psycopg.OperationalError, match="timeout expired"):
        Connection.connect(host="localhost", port=port, connect_timeout=1)
    elapsed = time.time() - t0
    assert elapsed == pytest.approx(1.0, abs=0.05)
Пример #5
0
def svcconn(dsn):
    """
    Return a session `Connection` connected to the ``--test-dsn`` database.
    """
    from psycopg import Connection

    conn = Connection.connect(dsn, autocommit=True)
    yield conn
    conn.close()
Пример #6
0
def conn(dsn, request):
    """Return a `Connection` connected to the ``--test-dsn`` database."""
    from psycopg import Connection

    conn = Connection.connect(dsn)
    msg = check_connection_version(conn.info.server_version, request.function)
    if msg:
        conn.close()
        pytest.skip(msg)
    yield conn
    conn.close()
Пример #7
0
def test_row_factory(dsn):
    conn = Connection.connect(dsn)
    assert conn.row_factory is tuple_row

    conn = Connection.connect(dsn, row_factory=my_row_factory)
    assert conn.row_factory is my_row_factory

    cur = conn.execute("select 'a' as ve")
    assert cur.fetchone() == ["Ave"]

    with conn.cursor(row_factory=lambda c: set) as cur:
        cur.execute("select 1, 1, 2")
        assert cur.fetchall() == [{1, 2}]

    with conn.cursor(row_factory=tuple_row) as cur:
        cur.execute("select 1, 1, 2")
        assert cur.fetchall() == [(1, 1, 2)]

    conn.row_factory = tuple_row
    cur = conn.execute("select 'vale'")
    assert cur.fetchone() == ("vale", )
Пример #8
0
def test_context_inerror_rollback_no_clobber(conn, dsn, caplog):
    caplog.set_level(logging.WARNING, logger="psycopg")

    with pytest.raises(ZeroDivisionError):
        with Connection.connect(dsn) as conn2:
            with conn2.transaction():
                conn2.execute("select 1")
                conn.execute(
                    "select pg_terminate_backend(%s::int)",
                    [conn2.pgconn.backend_pid],
                )
                1 / 0

    assert len(caplog.records) == 1
    rec = caplog.records[0]
    assert rec.levelno == logging.WARNING
    assert "in rollback" in rec.message
Пример #9
0
def test_context_active_rollback_no_clobber(conn, dsn, caplog):
    caplog.set_level(logging.WARNING, logger="psycopg")

    with pytest.raises(ZeroDivisionError):
        conn2 = Connection.connect(dsn)
        with conn2.transaction():
            with conn2.cursor() as cur:
                with cur.copy(
                    "copy (select generate_series(1, 10)) to stdout"
                ) as copy:
                    for row in copy.rows():
                        1 / 0

    assert len(caplog.records) == 1
    rec = caplog.records[0]
    assert rec.levelno == logging.WARNING
    assert "in rollback" in rec.message
    conn2.close()
Пример #10
0
def test_get_connection_params(dsn, kwargs, exp):
    params = Connection._get_connection_params(dsn, **kwargs)
    conninfo = make_conninfo(**params)
    assert conninfo_to_dict(conninfo) == exp[0]
    assert params.get("connect_timeout") == exp[1]
Пример #11
0
def test_connect_bad():
    with pytest.raises(psycopg.OperationalError):
        Connection.connect("dbname=nosuchdb")
Пример #12
0
def test_autocommit_connect(dsn):
    conn = Connection.connect(dsn, autocommit=True)
    assert conn.autocommit
Пример #13
0
def test_connect(dsn):
    conn = Connection.connect(dsn)
    assert not conn.closed
    assert conn.pgconn.status == conn.ConnStatus.OK
Пример #14
0
def test_connect_timeout(deaf_port):
    t0 = time.time()
    with pytest.raises(psycopg.OperationalError, match="timeout expired"):
        Connection.connect(host="localhost", port=deaf_port, connect_timeout=1)
    elapsed = time.time() - t0
    assert elapsed == pytest.approx(1.0, abs=0.05)