Skip to content

Commit

Permalink
Extend asyncpg instrumentation in Elastic APM (elastic#939)
Browse files Browse the repository at this point in the history
Issue elastic#889 added instrumentation for asyncpg, though only `execute` and
`executemany` were instrumented. This extends the instrumentation to
include `fetch`, `fetchval` and `fetchrow` methods.
  • Loading branch information
stj authored and romulorosa committed Oct 15, 2020
1 parent 6bc7589 commit eb9f25b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
3 changes: 3 additions & 0 deletions elasticapm/instrumentation/packages/asyncio/asyncpg.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ class AsyncPGInstrumentation(AsyncAbstractInstrumentedModule):
instrument_list = [
("asyncpg.connection", "Connection.execute"),
("asyncpg.connection", "Connection.executemany"),
("asyncpg.connection", "Connection.fetch"),
("asyncpg.connection", "Connection.fetchval"),
("asyncpg.connection", "Connection.fetchrow"),
]

async def call(self, module, method, wrapped, instance, args, kwargs):
Expand Down
37 changes: 37 additions & 0 deletions tests/instrumentation/asyncio_tests/asyncpg_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,40 @@ async def test_executemany(instrument, connection, elasticapm_client):
assert span["action"] == "query"
assert span["sync"] == False
assert span["name"] == "INSERT INTO test"


def _assert_fetch(result):
assert len(result) == 3
assert all(isinstance(val, asyncpg.Record) for val in result)


def _assert_fetchval(result):
assert result == 1


def _assert_fetchrow(result):
assert isinstance(result, asyncpg.Record)
assert result["id"] == 1


@pytest.mark.usefixtures("instrument")
@pytest.mark.parametrize(
"method,verify", [("fetch", _assert_fetch), ("fetchval", _assert_fetchval), ("fetchrow", _assert_fetchrow)]
)
async def test_fetch_methods(connection, elasticapm_client, method, verify):
elasticapm_client.begin_transaction("test")
result = await getattr(connection, method)("SELECT id FROM test;")
elasticapm_client.end_transaction("test", "OK")

verify(result)

transaction = elasticapm_client.events[constants.TRANSACTION][0]
spans = elasticapm_client.spans_for_transaction(transaction)

assert len(spans) == 1
span = spans[0]
assert transaction["id"] == span["transaction_id"]
assert span["subtype"] == "postgres"
assert span["action"] == "query"
assert span["sync"] is False
assert span["name"] == "SELECT FROM test"

0 comments on commit eb9f25b

Please sign in to comment.