InMemorySpanExporter
测试类完成后打开遥测未重置。这导致span_list = self.memory_exporter.get_finished_spans()
第二个测试类为空。
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from contextlib import contextmanager
import unittest
tracer = trace.get_tracer(__name__)
@contextmanager
def method(name):
with tracer.start_as_current_span(name) as span:
try:
yield span
except Exception as error:
span.record_exception(error)
raise
class OpenTelemetryBase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tracer_provider = TracerProvider()
cls.memory_exporter = InMemorySpanExporter()
cls.span_processor = SimpleSpanProcessor(cls.memory_exporter)
cls.tracer_provider.add_span_processor(cls.span_processor)
trace.set_tracer_provider(cls.tracer_provider)
def tearDown(self):
self.memory_exporter.clear()
class TestTracing(OpenTelemetryBase):
def test_method_1(self):
with self.assertRaises(Exception):
with method("TestTracing1") as span:
raise Exception("Failed trace 1")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
self.assertEqual(span_list[0].status.description, "Exception: Failed trace 1")
self.assertEqual(span_list[0].name, "TestTracing1")
class TestTracingB(OpenTelemetryBase):
def test_method_2(self):
with self.assertRaises(Exception):
with method("TestTracingB1") as span:
raise Exception("Failed traceB 1")
span_list = self.memory_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
self.assertEqual(span_list[0].status.description, "Exception: Failed traceB 1")
self.assertEqual(span_list[0].name, "TestTracingB1")
仅运行测试类 1 的命令:py.test tracing.py::TestTracing
:成功执行。
仅运行测试类 2 的命令py.test tracing.py::TestTracingB
::成功执行。
但是同时运行两个测试类的命令:py.test tracing.py
输出:tracing.py .F
第一次成功,第二次测试失败。
FAILED tracing.py::TestTracingB::test_method_2 - AssertionError: 0 != 1
即使我memory_exporter.clear()
在每次测试中都使用了 in tera down。
对于该setUpClass
方法,如果我将其更改为设置,则同一类中的多个测试将开始失败,只有第一个将通过其余测试将失败。