File: common_test.go

package info (click to toggle)
golang-github-lestrrat-go-pdebug 0.0~git20180220.0.569c974-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 108 kB
  • sloc: makefile: 2
file content (112 lines) | stat: -rw-r--r-- 2,306 bytes parent folder | download
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package pdebug

import (
	"bytes"
	"errors"
	"io"
	"regexp"
	"testing"

	"github.com/stretchr/testify/assert"
)

func setw(ctx *pdctx, w io.Writer) func() {
	oldw := ctx.Writer
	ctx.Writer = w
	return func() { ctx.Writer = oldw }
}

func TestPrintf(t *testing.T) {
	buf := &bytes.Buffer{}
	wg := setw(DefaultCtx, buf)
	defer wg()

	Printf("Hello, World!")

	if Enabled && Trace {
		re := regexp.MustCompile(`\|DEBUG\| \d+\.\d+ Hello, World!\n`)
		if !assert.True(t, re.MatchString(buf.String()), "Simple Printf works") {
			return
		}
	} else {
		if !assert.Equal(t, "", buf.String(), "Simple Printf should be suppressed") {
			return
		}
	}
}

func TestMarker(t *testing.T) {
	buf := &bytes.Buffer{}
	wg := setw(DefaultCtx, buf)
	defer wg()

	f2 := func() (err error) {
		g := Marker("f2").BindError(&err)
		defer g.End()
		Printf("Hello, World!")
		return errors.New("dummy error")
	}

	f1 := func() {
		g := Marker("f1")
		defer g.End()
		f2()
	}

	f1()

	if Enabled && Trace {
		re := regexp.MustCompile(`\|DEBUG\| \d+\.\d+ START f1\n\|DEBUG\| \d+\.\d+   START f2\n\|DEBUG\| \d+\.\d+     Hello, World!\n\|DEBUG\| \d+\.\d+   END f2 \(`)
		if !assert.True(t, re.MatchString(buf.String()), "Markers should work") {
			t.Logf("Expected '%v'", re)
			t.Logf("Actual   '%v'", buf.String())
			return
		}
	} else {
		if !assert.Equal(t, "", buf.String(), "Markers should work") {
			return
		}
	}
}

func TestLegacyMarker(t *testing.T) {
	buf := &bytes.Buffer{}
	wg := setw(DefaultCtx, buf)
	defer wg()

	f2 := func() (err error) {
		g := IPrintf("START f2")
		defer func() {
			if err == nil {
				g.IRelease("END f2")
			} else {
				g.IRelease("END f2: %s", err)
			}
		}()
		Printf("Hello, World!")
		return errors.New("dummy error")
	}

	f1 := func() {
		g := IPrintf("START f1")
		defer g.IRelease("END f1")
		f2()
	}

	f1()

	if Enabled && Trace {
		re := regexp.MustCompile(`\|DEBUG\| \d+\.\d+ START f1\n\|DEBUG\| \d+\.\d+   START f2\n\|DEBUG\| \d+\.\d+     Hello, World!\n\|DEBUG\| \d+\.\d+   END f2`)
		if !assert.True(t, re.MatchString(buf.String()), "Markers should work") {
			t.Logf("Expected '%v'", re)
			t.Logf("Actual   '%v'", buf.String())
			return
		}

		// TODO: check for error and timestamp
	} else {
		if !assert.Equal(t, "", buf.String(), "Markers should work") {
			return
		}
	}
}