Skip to content

Commit b5a4e29

Browse files
committed
fix(fastapi-instrumentation): fix tests
1 parent 34ed916 commit b5a4e29

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,11 @@ def _instrument(self, **kwargs):
392392
fastapi.FastAPI = _InstrumentedFastAPI
393393

394394
def _uninstrument(self, **kwargs):
395-
for instance in _InstrumentedFastAPI._instrumented_fastapi_apps:
395+
# Create a copy of the set to avoid RuntimeError during iteration
396+
instances_to_uninstrument = list(
397+
_InstrumentedFastAPI._instrumented_fastapi_apps
398+
)
399+
for instance in instances_to_uninstrument:
396400
self.uninstrument_app(instance)
397401
_InstrumentedFastAPI._instrumented_fastapi_apps.clear()
398402
fastapi.FastAPI = self._original_fastapi

instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_memory_leak.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,20 @@
2222
_InstrumentedFastAPI,
2323
)
2424

25+
# Check if sys.getrefcount is available (not available in PyPy)
26+
HAS_GETREFCOUNT = hasattr(sys, "getrefcount")
27+
2528

2629
class TestFastAPIMemoryLeak(unittest.TestCase):
2730
"""Test for memory leak in FastAPIInstrumentor.uninstrument_app()"""
2831

2932
def test_refcount_after_uninstrument(self):
3033
"""Test that refcount is restored after uninstrument_app()"""
34+
if not HAS_GETREFCOUNT:
35+
self.skipTest(
36+
"sys.getrefcount not available in this Python implementation"
37+
)
38+
3139
app = fastapi.FastAPI()
3240

3341
# Instrument the app
@@ -54,6 +62,11 @@ def test_refcount_after_uninstrument(self):
5462

5563
def test_multiple_instrument_uninstrument_cycles(self):
5664
"""Test that multiple instrument/uninstrument cycles don't leak memory"""
65+
if not HAS_GETREFCOUNT:
66+
self.skipTest(
67+
"sys.getrefcount not available in this Python implementation"
68+
)
69+
5770
app = fastapi.FastAPI()
5871

5972
initial_refcount = sys.getrefcount(app)
@@ -83,6 +96,11 @@ def test_multiple_instrument_uninstrument_cycles(self):
8396

8497
def test_multiple_apps_instrument_uninstrument(self):
8598
"""Test that multiple apps can be instrumented and uninstrumented without leaks"""
99+
if not HAS_GETREFCOUNT:
100+
self.skipTest(
101+
"sys.getrefcount not available in this Python implementation"
102+
)
103+
86104
apps = [fastapi.FastAPI() for _ in range(3)]
87105
initial_refcounts = [sys.getrefcount(app) for app in apps]
88106

0 commit comments

Comments
 (0)