22# Copyright (c) Microsoft Corporation.
33# Licensed under the MIT License.
44# ------------------------------------
5- from datetime import datetime
5+ from datetime import datetime , timedelta
66import sys
77import threading
8+ import time
89
910import pytest
1011from azure .core .tracing .common import with_current_context
@@ -85,7 +86,9 @@ def test_eventhubs_client_tracing(self, config, tracing_helper):
8586
8687 with tracing_helper .tracer .start_as_current_span (name = "root" ):
8788
88- current_date = datetime .now ()
89+ # Use a starting position slightly in the past to defend against any
90+ # clock skew between the test machine and the Event Hubs service.
91+ current_date = datetime .now () - timedelta (seconds = 30 )
8992
9093 with producer_client :
9194
@@ -120,8 +123,12 @@ def test_eventhubs_client_tracing(self, config, tracing_helper):
120123
121124 tracing_helper .exporter .clear ()
122125
126+ # Signal used to stop the consumer once we have received the batch.
127+ received = threading .Event ()
128+
123129 def on_event_batch (partition_context , event_batch ):
124- pass
130+ if event_batch :
131+ received .set ()
125132
126133 # Receive batch of events.
127134 worker = threading .Thread (
@@ -131,9 +138,20 @@ def on_event_batch(partition_context, event_batch):
131138 )
132139 worker .daemon = True
133140 worker .start ()
134- worker .join (timeout = 3 )
135141
142+ try :
143+ # Wait up to 60s for the consumer to connect and dispatch the batch.
144+ assert received .wait (timeout = 60 ), "Did not receive event batch within timeout"
145+ finally :
146+ consumer_client .close ()
147+ worker .join (timeout = 30 )
148+
149+ # Poll briefly for spans to be exported after the receive completes.
150+ deadline = time .monotonic () + 10
136151 receive_spans = tracing_helper .exporter .get_finished_spans ()
152+ while len (receive_spans ) < 2 and time .monotonic () < deadline :
153+ time .sleep (0.1 )
154+ receive_spans = tracing_helper .exporter .get_finished_spans ()
137155
138156 # We expect 2 spans to have finished: 1 receive span and 1 process span.
139157 assert len (receive_spans ) == 2
0 commit comments