|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# BSD 3-Clause License |
| 4 | +# |
| 5 | +# Copyright (c) 2019, Elasticsearch BV |
| 6 | +# All rights reserved. |
| 7 | +# |
| 8 | +# Redistribution and use in source and binary forms, with or without |
| 9 | +# modification, are permitted provided that the following conditions are met: |
| 10 | +# |
| 11 | +# * Redistributions of source code must retain the above copyright notice, this |
| 12 | +# list of conditions and the following disclaimer. |
| 13 | +# |
| 14 | +# * Redistributions in binary form must reproduce the above copyright notice, |
| 15 | +# this list of conditions and the following disclaimer in the documentation |
| 16 | +# and/or other materials provided with the distribution. |
| 17 | +# |
| 18 | +# * Neither the name of the copyright holder nor the names of its |
| 19 | +# contributors may be used to endorse or promote products derived from |
| 20 | +# this software without specific prior written permission. |
| 21 | +# |
| 22 | +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 23 | +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 24 | +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
| 25 | +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE |
| 26 | +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| 27 | +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| 28 | +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| 29 | +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
| 30 | +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 31 | +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 32 | + |
| 33 | +import os |
| 34 | +from typing import cast |
| 35 | + |
| 36 | +import pytest |
| 37 | + |
| 38 | +from elasticapm import get_client |
| 39 | +from elasticapm.conf.constants import SPAN, TRANSACTION |
| 40 | +from elasticapm.instrumentation.packages.psycopg import PGCursorProxy |
| 41 | +from elasticapm.utils import default_ports |
| 42 | +from tests.fixtures import TempStoreClient |
| 43 | + |
| 44 | +psycopg = pytest.importorskip("psycopg") |
| 45 | + |
| 46 | +pytestmark = pytest.mark.psycopg |
| 47 | + |
| 48 | +has_postgres_configured = "POSTGRES_DB" in os.environ |
| 49 | + |
| 50 | + |
| 51 | +def connect_kwargs(): |
| 52 | + return { |
| 53 | + "dbname": os.environ.get("POSTGRES_DB", "elasticapm_test"), |
| 54 | + "user": os.environ.get("POSTGRES_USER", "postgres"), |
| 55 | + "password": os.environ.get("POSTGRES_PASSWORD", "postgres"), |
| 56 | + "host": os.environ.get("POSTGRES_HOST", None), |
| 57 | + "port": os.environ.get("POSTGRES_PORT", None), |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | +@pytest.fixture(scope="function") |
| 62 | +def postgres_connection(request): |
| 63 | + conn = psycopg.connect(**connect_kwargs()) |
| 64 | + cursor = conn.cursor() |
| 65 | + cursor.execute( |
| 66 | + "CREATE TABLE test(id int, name VARCHAR(5) NOT NULL);" |
| 67 | + "INSERT INTO test VALUES (1, 'one'), (2, 'two'), (3, 'three');" |
| 68 | + ) |
| 69 | + |
| 70 | + yield conn |
| 71 | + |
| 72 | + # cleanup |
| 73 | + cursor.execute("ROLLBACK") |
| 74 | + |
| 75 | + |
| 76 | +@pytest.mark.integrationtest |
| 77 | +@pytest.mark.skipif(not has_postgres_configured, reason="PostgresSQL not configured") |
| 78 | +def test_destination(instrument, postgres_connection, elasticapm_client): |
| 79 | + elasticapm_client.begin_transaction("test") |
| 80 | + cursor = postgres_connection.cursor() |
| 81 | + cursor.execute("SELECT 1") |
| 82 | + elasticapm_client.end_transaction("test") |
| 83 | + transaction = elasticapm_client.events[TRANSACTION][0] |
| 84 | + span = elasticapm_client.spans_for_transaction(transaction)[0] |
| 85 | + assert span["context"]["destination"] == { |
| 86 | + "address": os.environ.get("POSTGRES_HOST", None), |
| 87 | + "port": default_ports["postgresql"], |
| 88 | + "service": {"name": "", "resource": "postgresql/elasticapm_test", "type": ""}, |
| 89 | + } |
| 90 | + |
| 91 | + |
| 92 | +@pytest.mark.integrationtest |
| 93 | +@pytest.mark.skipif(not has_postgres_configured, reason="PostgresSQL not configured") |
| 94 | +def test_psycopg_tracing_outside_of_elasticapm_transaction(instrument, postgres_connection, elasticapm_client): |
| 95 | + cursor = postgres_connection.cursor() |
| 96 | + # check that the cursor is a proxy, even though we're not in an elasticapm |
| 97 | + # transaction |
| 98 | + assert isinstance(cursor, PGCursorProxy) |
| 99 | + cursor.execute("SELECT 1") |
| 100 | + transactions = elasticapm_client.events[TRANSACTION] |
| 101 | + assert not transactions |
| 102 | + |
| 103 | + |
| 104 | +@pytest.mark.integrationtest |
| 105 | +@pytest.mark.skipif(not has_postgres_configured, reason="PostgresSQL not configured") |
| 106 | +def test_psycopg_select_LIKE(instrument, postgres_connection, elasticapm_client): |
| 107 | + """ |
| 108 | + Check that we pass queries with %-notation but without parameters |
| 109 | + properly to the dbapi backend |
| 110 | + """ |
| 111 | + cursor = postgres_connection.cursor() |
| 112 | + query = "SELECT * FROM test WHERE name LIKE 't%'" |
| 113 | + |
| 114 | + try: |
| 115 | + elasticapm_client.begin_transaction("web.django") |
| 116 | + cursor.execute(query) |
| 117 | + cursor.fetchall() |
| 118 | + elasticapm_client.end_transaction(None, "test-transaction") |
| 119 | + finally: |
| 120 | + # make sure we've cleared out the spans for the other tests. |
| 121 | + transactions = elasticapm_client.events[TRANSACTION] |
| 122 | + spans = elasticapm_client.spans_for_transaction(transactions[0]) |
| 123 | + span = spans[0] |
| 124 | + assert span["name"] == "SELECT FROM test" |
| 125 | + assert span["type"] == "db" |
| 126 | + assert span["subtype"] == "postgresql" |
| 127 | + assert span["action"] == "query" |
| 128 | + assert "db" in span["context"] |
| 129 | + assert span["context"]["db"]["instance"] == "elasticapm_test" |
| 130 | + assert span["context"]["db"]["type"] == "sql" |
| 131 | + assert span["context"]["db"]["statement"] == query |
| 132 | + assert span["context"]["service"]["target"]["type"] == "postgresql" |
| 133 | + assert span["context"]["service"]["target"]["name"] == "elasticapm_test" |
| 134 | + |
| 135 | + |
| 136 | +@pytest.mark.integrationtest |
| 137 | +@pytest.mark.skipif(not has_postgres_configured, reason="PostgresSQL not configured") |
| 138 | +def test_psycopg_composable_query_works(instrument, postgres_connection, elasticapm_client): |
| 139 | + """ |
| 140 | + Check that we parse queries that are psycopg.sql.Composable correctly |
| 141 | + """ |
| 142 | + from psycopg import sql |
| 143 | + |
| 144 | + cursor = postgres_connection.cursor() |
| 145 | + query = sql.SQL("SELECT * FROM {table} WHERE {row} LIKE 't%' ORDER BY {row} DESC").format( |
| 146 | + table=sql.Identifier("test"), row=sql.Identifier("name") |
| 147 | + ) |
| 148 | + baked_query = query.as_string(cursor.__wrapped__) |
| 149 | + result = None |
| 150 | + try: |
| 151 | + elasticapm_client.begin_transaction("web.django") |
| 152 | + cursor.execute(query) |
| 153 | + result = cursor.fetchall() |
| 154 | + elasticapm_client.end_transaction(None, "test-transaction") |
| 155 | + finally: |
| 156 | + # make sure we've cleared out the spans for the other tests. |
| 157 | + assert [(2, "two"), (3, "three")] == result |
| 158 | + transactions = elasticapm_client.events[TRANSACTION] |
| 159 | + spans = elasticapm_client.spans_for_transaction(transactions[0]) |
| 160 | + span = spans[0] |
| 161 | + assert span["name"] == "SELECT FROM test" |
| 162 | + assert "db" in span["context"] |
| 163 | + assert span["context"]["db"]["instance"] == "elasticapm_test" |
| 164 | + assert span["context"]["db"]["type"] == "sql" |
| 165 | + assert span["context"]["db"]["statement"] == baked_query |
| 166 | + |
| 167 | + |
| 168 | +@pytest.mark.integrationtest |
| 169 | +@pytest.mark.skipif(not has_postgres_configured, reason="PostgresSQL not configured") |
| 170 | +def test_psycopg_binary_query_works(instrument, postgres_connection, elasticapm_client): |
| 171 | + """ |
| 172 | + Check that we pass queries with %-notation but without parameters |
| 173 | + properly to the dbapi backend |
| 174 | + """ |
| 175 | + cursor = postgres_connection.cursor() |
| 176 | + query = b"SELECT * FROM test WHERE name LIKE 't%'" |
| 177 | + |
| 178 | + baked_query = query.decode() |
| 179 | + try: |
| 180 | + elasticapm_client.begin_transaction("web.django") |
| 181 | + cursor.execute(query) |
| 182 | + result = cursor.fetchall() |
| 183 | + elasticapm_client.end_transaction(None, "test-transaction") |
| 184 | + finally: |
| 185 | + # make sure we've cleared out the spans for the other tests. |
| 186 | + assert [(2, "two"), (3, "three")] == result |
| 187 | + transactions = elasticapm_client.events[TRANSACTION] |
| 188 | + spans = elasticapm_client.spans_for_transaction(transactions[0]) |
| 189 | + span = spans[0] |
| 190 | + assert span["name"] == "SELECT FROM test" |
| 191 | + assert "db" in span["context"] |
| 192 | + assert span["context"]["db"]["instance"] == "elasticapm_test" |
| 193 | + assert span["context"]["db"]["type"] == "sql" |
| 194 | + assert span["context"]["db"]["statement"] == baked_query |
| 195 | + |
| 196 | + |
| 197 | +@pytest.mark.integrationtest |
| 198 | +@pytest.mark.skipif(not has_postgres_configured, reason="PostgresSQL not configured") |
| 199 | +def test_psycopg_context_manager(instrument, elasticapm_client): |
| 200 | + elasticapm_client.begin_transaction("test") |
| 201 | + with psycopg.connect(**connect_kwargs()) as conn: |
| 202 | + with conn.cursor() as curs: |
| 203 | + curs.execute("SELECT 1;") |
| 204 | + curs.fetchall() |
| 205 | + elasticapm_client.end_transaction("test", "OK") |
| 206 | + transactions = elasticapm_client.events[TRANSACTION] |
| 207 | + spans = elasticapm_client.spans_for_transaction(transactions[0]) |
| 208 | + assert len(spans) == 2 |
| 209 | + assert spans[0]["subtype"] == "postgresql" |
| 210 | + assert spans[0]["action"] == "connect" |
| 211 | + assert spans[0]["context"]["service"]["target"]["type"] == "postgresql" |
| 212 | + assert spans[0]["context"]["service"]["target"]["name"] == "elasticapm_test" |
| 213 | + |
| 214 | + assert spans[1]["subtype"] == "postgresql" |
| 215 | + assert spans[1]["action"] == "query" |
| 216 | + |
| 217 | + |
| 218 | +@pytest.mark.integrationtest |
| 219 | +@pytest.mark.skipif(not has_postgres_configured, reason="PostgresSQL not configured") |
| 220 | +def test_psycopg_rows_affected(instrument, postgres_connection, elasticapm_client): |
| 221 | + cursor = postgres_connection.cursor() |
| 222 | + try: |
| 223 | + elasticapm_client.begin_transaction("web.django") |
| 224 | + cursor.execute("INSERT INTO test VALUES (4, 'four')") |
| 225 | + cursor.execute("SELECT * FROM test") |
| 226 | + cursor.execute("UPDATE test SET name = 'five' WHERE id = 4") |
| 227 | + cursor.execute("DELETE FROM test WHERE id = 4") |
| 228 | + elasticapm_client.end_transaction(None, "test-transaction") |
| 229 | + finally: |
| 230 | + transactions = elasticapm_client.events[TRANSACTION] |
| 231 | + spans = elasticapm_client.spans_for_transaction(transactions[0]) |
| 232 | + |
| 233 | + assert spans[0]["name"] == "INSERT INTO test" |
| 234 | + assert spans[0]["context"]["db"]["rows_affected"] == 1 |
| 235 | + |
| 236 | + assert spans[1]["name"] == "SELECT FROM test" |
| 237 | + assert "rows_affected" not in spans[1]["context"]["db"] |
| 238 | + |
| 239 | + assert spans[2]["name"] == "UPDATE test" |
| 240 | + assert spans[2]["context"]["db"]["rows_affected"] == 1 |
| 241 | + |
| 242 | + assert spans[3]["name"] == "DELETE FROM test" |
| 243 | + assert spans[3]["context"]["db"]["rows_affected"] == 1 |
| 244 | + |
| 245 | + |
| 246 | +@pytest.mark.integrationtest |
| 247 | +def test_psycopg_connection(instrument, elasticapm_transaction, postgres_connection): |
| 248 | + # elastciapm_client.events is only available on `TempStoreClient`, this keeps the type checkers happy |
| 249 | + elasticapm_client = cast(TempStoreClient, get_client()) |
| 250 | + elasticapm_client.end_transaction("test", "success") |
| 251 | + span = elasticapm_client.events[SPAN][0] |
| 252 | + host = os.environ.get("POSTGRES_HOST", "localhost") |
| 253 | + assert span["name"] == f"psycopg.connect {host}:5432" |
| 254 | + assert span["action"] == "connect" |
0 commit comments