@@ -21,25 +21,37 @@ using opentelemetry::exporter::memory::InMemorySpanExporter;
21
21
using opentelemetry::trace::SpanContext;
22
22
23
23
/* *
24
- * A mock sampler that returns non-empty sampling results attributes.
24
+ * A mock sampler with ShouldSample returning:
25
+ * Decision::RECORD_AND_SAMPLE if trace_id is valid
26
+ * Decision::DROP otherwise.
25
27
*/
26
28
class MockSampler final : public Sampler
27
29
{
28
30
public:
29
31
SamplingResult ShouldSample (
30
32
const SpanContext & /* parent_context*/ ,
31
- trace_api::TraceId /* trace_id*/ ,
33
+ trace_api::TraceId trace_id,
32
34
nostd::string_view /* name*/ ,
33
35
trace_api::SpanKind /* span_kind*/ ,
34
36
const opentelemetry::common::KeyValueIterable & /* attributes*/ ,
35
37
const opentelemetry::trace::SpanContextKeyValueIterable & /* links*/ ) noexcept override
36
38
{
37
- // Return two pairs of attributes. These attributes should be added to the
38
- // span attributes
39
- return {Decision::RECORD_AND_SAMPLE,
40
- nostd::unique_ptr<const std::map<std::string, opentelemetry::common::AttributeValue>>(
41
- new const std::map<std::string, opentelemetry::common::AttributeValue>(
42
- {{" sampling_attr1" , 123 }, {" sampling_attr2" , " string" }}))};
39
+ // Sample only if valid trace_id ( This is to test Sampler get's valid trace id)
40
+ if (trace_id.IsValid ())
41
+ {
42
+ // Return two pairs of attributes. These attributes should be added to the
43
+ // span attributes
44
+ return {Decision::RECORD_AND_SAMPLE,
45
+ nostd::unique_ptr<const std::map<std::string, opentelemetry::common::AttributeValue>>(
46
+ new const std::map<std::string, opentelemetry::common::AttributeValue>(
47
+ {{" sampling_attr1" , 123 }, {" sampling_attr2" , " string" }}))};
48
+ }
49
+ else
50
+ {
51
+ // we should never reach here
52
+ assert (false );
53
+ return {Decision::DROP};
54
+ }
43
55
}
44
56
45
57
nostd::string_view GetDescription () const noexcept override { return " MockSampler" ; }
@@ -599,3 +611,15 @@ TEST(Tracer, ExpectParent)
599
611
EXPECT_EQ (spandata_first->GetSpanId (), spandata_second->GetParentSpanId ());
600
612
EXPECT_EQ (spandata_second->GetSpanId (), spandata_third->GetParentSpanId ());
601
613
}
614
+
615
+ TEST (Tracer, ValidTraceIdToSampler)
616
+ {
617
+ std::unique_ptr<InMemorySpanExporter> exporter (new InMemorySpanExporter ());
618
+ std::shared_ptr<InMemorySpanData> span_data = exporter->GetData ();
619
+ auto tracer = initTracer (std::move (exporter), new MockSampler ());
620
+
621
+ auto span = tracer->StartSpan (" span 1" );
622
+ // sampler was fed with valid trace_id, so span shouldn't be NoOp Span.
623
+ EXPECT_TRUE (span->IsRecording ());
624
+ EXPECT_TRUE (span->GetContext ().IsValid ());
625
+ }
0 commit comments