|
54 | 54 | has_postgres_configured = "POSTGRES_DB" in os.environ |
55 | 55 |
|
56 | 56 |
|
| 57 | +def connect_kwargs(): |
| 58 | + return { |
| 59 | + "database": os.environ.get("POSTGRES_DB", "elasticapm_test"), |
| 60 | + "user": os.environ.get("POSTGRES_USER", "postgres"), |
| 61 | + "host": os.environ.get("POSTGRES_HOST", None), |
| 62 | + "port": os.environ.get("POSTGRES_PORT", None), |
| 63 | + } |
| 64 | + |
| 65 | + |
57 | 66 | @pytest.yield_fixture(scope="function") |
58 | 67 | def postgres_connection(request): |
59 | | - conn = psycopg2.connect( |
60 | | - database=os.environ.get("POSTGRES_DB", "elasticapm_test"), |
61 | | - user=os.environ.get("POSTGRES_USER", "postgres"), |
62 | | - host=os.environ.get("POSTGRES_HOST", None), |
63 | | - port=os.environ.get("POSTGRES_PORT", None), |
64 | | - ) |
| 68 | + conn = psycopg2.connect(**connect_kwargs()) |
65 | 69 | cursor = conn.cursor() |
66 | 70 | cursor.execute( |
67 | 71 | "CREATE TABLE test(id int, name VARCHAR(5) NOT NULL);" |
@@ -376,3 +380,22 @@ def test_psycopg2_call_stored_procedure(instrument, postgres_connection, elastic |
376 | 380 | span = elasticapm_client.spans_for_transaction(transactions[0])[0] |
377 | 381 | assert span["name"] == "squareme()" |
378 | 382 | assert span["action"] == "exec" |
| 383 | + |
| 384 | + |
| 385 | +@pytest.mark.integrationtest |
| 386 | +@pytest.mark.skipif(not has_postgres_configured, reason="PostgresSQL not configured") |
| 387 | +def test_psycopg_context_manager(instrument, elasticapm_client): |
| 388 | + elasticapm_client.begin_transaction("test") |
| 389 | + with psycopg2.connect(**connect_kwargs()) as conn: |
| 390 | + with conn.cursor() as curs: |
| 391 | + curs.execute("SELECT 1;") |
| 392 | + curs.fetchall() |
| 393 | + elasticapm_client.end_transaction("test", "OK") |
| 394 | + transactions = elasticapm_client.events[TRANSACTION] |
| 395 | + spans = elasticapm_client.spans_for_transaction(transactions[0]) |
| 396 | + assert len(spans) == 2 |
| 397 | + assert spans[0]["subtype"] == "postgresql" |
| 398 | + assert spans[0]["action"] == "connect" |
| 399 | + |
| 400 | + assert spans[1]["subtype"] == "postgresql" |
| 401 | + assert spans[1]["action"] == "query" |
0 commit comments