Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def clean_instrumentation():
elasticapm.uninstrument()


@pytest.mark.usefixtures("event_loop")
@pytest.mark.parametrize("framework", ["starlette", "fastapi"])
@pytest.mark.parametrize("instrument", [False, True])
@pytest.mark.parametrize("kind", ["success", "handled", "unhandled", "stream"])
Expand Down Expand Up @@ -112,6 +113,7 @@ async def error_handler(request, exc):
assert response.content == b"ab"


@pytest.mark.usefixtures("event_loop")
@pytest.mark.parametrize("elasticapm_client", [{"instrument": False}, {"instrument": True}], indirect=True)
def test_library_instrumentation_respects_instrument_setting(elasticapm_client):
async def endpoint(request):
Expand Down
17 changes: 14 additions & 3 deletions tests/instrumentation/asyncio_tests/redis_asyncio_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@

redis = pytest.importorskip("redis.asyncio") # isort:skip

import asyncio
import os

import pytest_asyncio
Expand Down Expand Up @@ -145,14 +146,24 @@ async def test_redis_client(instrument, elasticapm_client, redis_async_conn):


@pytest.mark.integrationtest
async def test_publish_subscribe_async(instrument, elasticapm_client, redis_async_conn):
async def test_publish_subscribe_async(instrument, elasticapm_client, redis_async_conn, mocker):
elasticapm_client.begin_transaction("transaction.test")
pubsub = redis_async_conn.pubsub()
delay = 0.01
with capture_span("test_publish_subscribe", "test"):
# publish
await redis_async_conn.publish("mykey", "a")

# subscribe
# Freeze span timing so only the simulated delay contributes to SUBSCRIBE's duration.
clock = mocker.patch("elasticapm.traces._time_func", return_value=elasticapm.traces._time_func())
execute = pubsub._execute

async def delayed_execute(*args, **kwargs):
await asyncio.sleep(0)
clock.return_value += delay
return await execute(*args, **kwargs)

mocker.patch.object(pubsub, "_execute", new=delayed_execute)
await pubsub.subscribe("mykey")

elasticapm_client.end_transaction("MyView")
Expand Down Expand Up @@ -184,7 +195,7 @@ async def test_publish_subscribe_async(instrument, elasticapm_client, redis_asyn
"port": int(os.environ.get("REDIS_PORT", 6379)),
"service": {"name": "", "resource": "redis", "type": ""},
}
assert spans[1]["duration"] > 0.2 # sanity test to ensure we measure the actual call
assert spans[1]["duration"] == pytest.approx(delay * 1000) # span durations are in milliseconds

assert spans[2]["name"] == "test_publish_subscribe"
assert spans[2]["type"] == "test"
Expand Down
46 changes: 30 additions & 16 deletions tests/instrumentation/kafka_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@

kafka = pytest.importorskip("kafka")

from kafka import KafkaConsumer, KafkaProducer
from kafka import KafkaConsumer, KafkaProducer, TopicPartition
from kafka.admin import KafkaAdminClient, NewTopic

pytestmark = [pytest.mark.kafka]
Expand All @@ -57,15 +57,18 @@ def topics():
admin_client = KafkaAdminClient(bootstrap_servers=[f"{KAFKA_HOST}:9092"])
# Use unique topic names because Kafka topic deletion is asynchronous and fixed names can leak state between tests.
try:
admin_client.create_topics([NewTopic(name, num_partitions=1, replication_factor=1) for name in topics])
except Exception:
pass
yield topics
try:
admin_client.delete_topics(topics)
except Exception:
pass
admin_client.close()
response = admin_client.create_topics(
[NewTopic(name, num_partitions=1, replication_factor=1) for name in topics]
)
errors = [error for error in response.topic_errors if error[1]]
assert not errors, f"Failed to create Kafka test topics: {errors}"
yield topics
finally:
try:
admin_client.delete_topics(topics)
except Exception:
pass
admin_client.close()


@pytest.fixture()
Expand All @@ -83,12 +86,23 @@ def consumer(topics):
# Unique topics can be produced to before the consumer's initial offset is resolved.
auto_offset_reset="earliest",
)
consumer.subscribe(topics=topics)
deadline = time.time() + 5
while not consumer.assignment() and time.time() < deadline:
consumer.poll(timeout_ms=100)
yield consumer
consumer.close()
try:
consumer.subscribe(topics=topics)
expected_assignment = {TopicPartition(topic, 0) for topic in topics}
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
# Retry transient missing-topic metadata instead of waiting for the cached snapshot to expire.
consumer.topics()
consumer.poll(timeout_ms=100)
if consumer.assignment() == expected_assignment:
break
else:
pytest.fail(
f"Kafka consumer assignment timed out: expected {expected_assignment}, got {consumer.assignment()}"
)
yield consumer
finally:
consumer.close()


def test_kafka_produce(instrument, elasticapm_client, producer, topics):
Expand Down
Loading