aboutsummaryrefslogtreecommitdiffstats
path: root/internal/trace/trace_test.go
diff options
context:
space:
mode:
authorAyman Bagabas <ayman.bagabas@gmail.com>2023-11-08 18:40:06 -0500
committerAyman Bagabas <ayman.bagabas@gmail.com>2023-11-15 16:53:32 -0500
commita8e17350b8b1c97e252964c863fca0fac9ff5cec (patch)
treec02d6d5c15d0d9aff7241f4874ae58e6756024ad /internal/trace/trace_test.go
parenteb1b04dbe45f7c9e866eb52e8ccccf3885a06217 (diff)
downloadgo-git-a8e17350b8b1c97e252964c863fca0fac9ff5cec.tar.gz
internal: add trace package
This adds a generic tracing package to log messages to output if target is enabled.
Diffstat (limited to 'internal/trace/trace_test.go')
-rw-r--r--internal/trace/trace_test.go95
1 files changed, 95 insertions, 0 deletions
diff --git a/internal/trace/trace_test.go b/internal/trace/trace_test.go
new file mode 100644
index 0000000..6f8f140
--- /dev/null
+++ b/internal/trace/trace_test.go
@@ -0,0 +1,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")
+ }
+}