aboutsummaryrefslogtreecommitdiffstats
path: root/internal/trace/trace_test.go
blob: 6f8f14094d8a7474c5c4c7a31abf10afd17ff8ea (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package trace

import (
	"bytes"
	"io"
	"log"
	"testing"
)

func TestMain(m *testing.M) {
	defer SetLogger(newLogger())
	if code := m.Run(); code != 0 {
		panic(code)
	}
}

func setUpTest(t testing.TB, buf *bytes.Buffer) {
	t.Cleanup(func() {
		if buf != nil {
			buf.Reset()
		}
		SetTarget(0)
	})
	w := io.Discard
	if buf != nil {
		w = buf
	}
	SetLogger(log.New(w, "", 0))
}

func TestEmpty(t *testing.T) {
	var buf bytes.Buffer
	setUpTest(t, &buf)
	General.Print("test")
	if buf.String() != "" {
		t.Error("expected empty string")
	}
}

func TestOneTarget(t *testing.T) {
	var buf bytes.Buffer
	setUpTest(t, &buf)
	SetTarget(General)
	General.Print("test")
	if buf.String() != "test\n" {
		t.Error("expected 'test'")
	}
}

func TestMultipleTargets(t *testing.T) {
	var buf bytes.Buffer
	setUpTest(t, &buf)
	SetTarget(General | Packet)
	General.Print("a")
	Packet.Print("b")
	if buf.String() != "a\nb\n" {
		t.Error("expected 'a\nb\n'")
	}
}

func TestPrintf(t *testing.T) {
	var buf bytes.Buffer
	setUpTest(t, &buf)
	SetTarget(General)
	General.Printf("a %d", 1)
	if buf.String() != "a 1\n" {
		t.Error("expected 'a 1\n'")
	}
}

func TestDisabledMultipleTargets(t *testing.T) {
	var buf bytes.Buffer
	setUpTest(t, &buf)
	SetTarget(General)
	General.Print("a")
	Packet.Print("b")
	if buf.String() != "a\n" {
		t.Error("expected 'a\n'")
	}
}

func BenchmarkDisabledTarget(b *testing.B) {
	setUpTest(b, nil)
	for i := 0; i < b.N; i++ {
		General.Print("test")
	}
}

func BenchmarkEnabledTarget(b *testing.B) {
	setUpTest(b, nil)
	SetTarget(General)
	for i := 0; i < b.N; i++ {
		General.Print("test")
	}
}