|
| 1 | +/* |
| 2 | + * Copyright The OpenTelemetry Authors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package io.opentelemetry.contrib.noopapi; |
| 7 | + |
| 8 | +import static org.assertj.core.api.Assertions.assertThat; |
| 9 | + |
| 10 | +import io.opentelemetry.api.common.AttributeKey; |
| 11 | +import io.opentelemetry.api.common.Attributes; |
| 12 | +import io.opentelemetry.api.trace.Span; |
| 13 | +import io.opentelemetry.api.trace.SpanBuilder; |
| 14 | +import io.opentelemetry.api.trace.SpanContext; |
| 15 | +import io.opentelemetry.api.trace.SpanKind; |
| 16 | +import io.opentelemetry.api.trace.TraceFlags; |
| 17 | +import io.opentelemetry.api.trace.TraceState; |
| 18 | +import io.opentelemetry.context.Context; |
| 19 | +import io.opentelemetry.context.Scope; |
| 20 | +import java.util.concurrent.TimeUnit; |
| 21 | +import org.junit.jupiter.api.Test; |
| 22 | + |
| 23 | +class NoopOpenTelemetryTest { |
| 24 | + |
| 25 | + private static final SpanContext SPAN_CONTEXT = |
| 26 | + SpanContext.create( |
| 27 | + "00000000000000000000000000000061", |
| 28 | + "0000000000000061", |
| 29 | + TraceFlags.getDefault(), |
| 30 | + TraceState.getDefault()); |
| 31 | + |
| 32 | + @Test |
| 33 | + void contextNoOp() { |
| 34 | + // Context.root() is not a no-op Context, so the default context is never root. |
| 35 | + Context context = Context.current(); |
| 36 | + assertThat(context).isNotSameAs(Context.root()); |
| 37 | + // No allocations |
| 38 | + assertThat(context.with(Span.wrap(SPAN_CONTEXT))).isSameAs(context); |
| 39 | + assertThat(SPAN_CONTEXT.isValid()).isTrue(); |
| 40 | + try (Scope ignored = Context.current().with(Span.wrap(SPAN_CONTEXT)).makeCurrent()) { |
| 41 | + // No context mounted, so always an invalid span. |
| 42 | + assertThat(Span.fromContext(Context.current()).getSpanContext().isValid()).isFalse(); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + @Test |
| 47 | + void tracerNoOp() { |
| 48 | + SpanBuilder span1 = NoopOpenTelemetry.getInstance().getTracer("test").spanBuilder("test"); |
| 49 | + SpanBuilder span2 = NoopOpenTelemetry.getInstance().getTracer("test").spanBuilder("test"); |
| 50 | + // No allocations |
| 51 | + assertThat(span1).isSameAs(span2); |
| 52 | + |
| 53 | + // No crash |
| 54 | + span1.setParent(Context.current()); |
| 55 | + span1.setNoParent(); |
| 56 | + span1.addLink(SPAN_CONTEXT); |
| 57 | + span1.addLink(SPAN_CONTEXT, Attributes.empty()); |
| 58 | + span1.setAttribute("key", "value"); |
| 59 | + span1.setAttribute("key", 1L); |
| 60 | + span1.setAttribute("key", 1.0); |
| 61 | + span1.setAttribute("key", true); |
| 62 | + span1.setAttribute(AttributeKey.stringKey("key"), "value"); |
| 63 | + span1.setSpanKind(SpanKind.CLIENT); |
| 64 | + span1.setStartTimestamp(1, TimeUnit.DAYS); |
| 65 | + |
| 66 | + // No allocations |
| 67 | + assertThat(span1.startSpan()).isSameAs(Span.getInvalid()); |
| 68 | + } |
| 69 | +} |
0 commit comments