From 3dab0c3e43b18be9013dd8ad9cfa2dac6cf22d9d Mon Sep 17 00:00:00 2001 From: Kevin Zheng Date: Fri, 10 May 2024 20:50:05 +0000 Subject: [PATCH] added opentelemetry sdk module cleanup to system test --- tests/system/test_system.py | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/tests/system/test_system.py b/tests/system/test_system.py index 207a9709c..aae3d0d92 100644 --- a/tests/system/test_system.py +++ b/tests/system/test_system.py @@ -19,6 +19,7 @@ import numbers import os import pytest +import sys import unittest import uuid @@ -40,9 +41,6 @@ from google.protobuf.struct_pb2 import Struct, Value, ListValue, NullValue -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider - from test_utils.retry import RetryErrors from test_utils.retry import RetryResult from test_utils.system import unique_resource_id @@ -119,6 +117,22 @@ def setUpModule(): Config.use_mtls == "always", reason="Skip the test case for mTLS testing" ) +def _cleanup_otel_sdk_modules(f): + """ + Decorator to delete all references to opentelemetry SDK modules after a + testcase is run. Test case should import opentelemetry SDK modules inside + the function. This is to test situations where the opentelemetry SDK + is not imported at all. + """ + def wrapped(*args, **kwargs): + f(*args, **kwargs) + + # Deleting from sys.modules should be good enough in this use case + for module_name in list(sys.modules.keys()): + if module_name.startswith('opentelemetry.sdk'): + sys.modules.pop(module_name) + + return wrapped class TestLogging(unittest.TestCase): JSON_PAYLOAD = { @@ -665,7 +679,12 @@ def test_log_root_handler(self): self.assertEqual(len(entries), 1) self.assertEqual(entries[0].payload, expected_payload) + @_cleanup_otel_sdk_modules def test_log_handler_otel_integration(self): + # Doing OTel imports here to not taint the other tests with OTel SDK imports + from opentelemetry import trace + from opentelemetry.sdk.trace import TracerProvider + LOG_MESSAGE = "This is a test of OpenTelemetry" LOGGER_NAME = "otel-integration" handler_name = self._logger_name(LOGGER_NAME)