blob: 750ffe8ed132331979b7a1fc3e6c6231a14b4d7a [file] [log] [blame]
Serge Bazanskifb0fb6d2022-02-18 12:11:28 +01001package rpc
2
3import (
4 "context"
5 "fmt"
6 "strings"
7 "testing"
8
9 "source.monogon.dev/metropolis/pkg/logtree"
10)
11
12// TestSpanRecording exercises the span->logtree forwarding functionality by
13// adding an event to the span and expecting to find it as a log entry.
14func TestSpanRecording(t *testing.T) {
15 lt := logtree.New()
16 span := newLogtreeSpan(lt.MustLeveledFor("test"))
17 span.Printf("hello world")
18
19 r, err := lt.Read("test", logtree.WithBacklog(logtree.BacklogAllAvailable))
20 if err != nil {
21 t.Fatalf("logtree read failed: %v", err)
22 }
23 defer r.Close()
24 found := false
25 needle := fmt.Sprintf("Span %x: hello world", span.uid)
26 for _, e := range r.Backlog {
27 if e.DN != "test" {
28 continue
29 }
30 if e.Leveled == nil {
31 continue
32 }
33 if e.Leveled.MessagesJoined() != needle {
34 continue
35 }
36 if parts := strings.Split(e.Leveled.Location(), ":"); parts[0] != "trace_test.go" {
37 t.Errorf("Trace/log location is %s, wanted something in trace_test.go", e.Leveled.Location())
38 }
39 found = true
40 break
41 }
42 if !found {
43 t.Fatalf("did not find expected logline")
44 }
45}
46
47// TestSpanContext exercises a span context injection/extraction roundtrip.
48func TestSpanContext(t *testing.T) {
49 ctx := context.Background()
50
51 lt := logtree.New()
52 span := newLogtreeSpan(lt.MustLeveledFor("test"))
53 ctx = contextWithSpan(ctx, span)
54 span2 := Trace(ctx)
55 if !span2.IsRecording() {
56 t.Errorf("Expected span to be active")
57 }
58
59 v, ok := span2.(*logtreeSpan)
60 if !ok {
61 t.Fatalf("Retrieved span is not *logtreeSpan")
62 }
63 if v != span {
64 t.Fatalf("Retrieved span differs from injected span")
65 }
66}
67
68// TestSpanContextFallback exercises an empty span retrieved from a context with
69// no span set.
70func TestSpanContextFallback(t *testing.T) {
71 ctx := context.Background()
72 // We expect this to never panic, just to drop any event.
73 Trace(ctx).Printf("plonk")
74 if Trace(ctx).IsRecording() {
75 t.Errorf("Expected span to be inactive")
76 }
77}