diff --git a/tests/contrib/asyncio/starlette_instrument_disabled_tests.py b/tests/contrib/asyncio/starlette_instrument_disabled_tests.py index 80bc1c6b6..d4c7db083 100644 --- a/tests/contrib/asyncio/starlette_instrument_disabled_tests.py +++ b/tests/contrib/asyncio/starlette_instrument_disabled_tests.py @@ -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"]) @@ -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): diff --git a/tests/instrumentation/asyncio_tests/redis_asyncio_tests.py b/tests/instrumentation/asyncio_tests/redis_asyncio_tests.py index b6fe35920..843b425ce 100644 --- a/tests/instrumentation/asyncio_tests/redis_asyncio_tests.py +++ b/tests/instrumentation/asyncio_tests/redis_asyncio_tests.py @@ -34,6 +34,7 @@ redis = pytest.importorskip("redis.asyncio") # isort:skip +import asyncio import os import pytest_asyncio @@ -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") @@ -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" diff --git a/tests/instrumentation/kafka_tests.py b/tests/instrumentation/kafka_tests.py index 253f9c6b9..60126385e 100644 --- a/tests/instrumentation/kafka_tests.py +++ b/tests/instrumentation/kafka_tests.py @@ -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] @@ -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() @@ -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):