...
1
16
17 package ktesting
18
19 import (
20 "fmt"
21 "regexp"
22 "strings"
23 "testing"
24 "time"
25
26 "github.com/stretchr/testify/assert"
27 )
28
29
30
31 type testcase struct {
32 cb func(TContext)
33 expectNoFail bool
34 expectError string
35 expectDuration time.Duration
36 expectLog string
37 }
38
39 func (tc testcase) run(t *testing.T) {
40 bufferT := &logBufferT{T: t}
41 tCtx := Init(bufferT)
42 var err error
43 tCtx, finalize := WithError(tCtx, &err)
44 start := time.Now()
45 func() {
46 defer finalize()
47 tc.cb(tCtx)
48 }()
49
50 log := bufferT.log.String()
51 t.Logf("Log output:\n%s\n", log)
52 if tc.expectLog != "" {
53 assert.Equal(t, tc.expectLog, normalize(log))
54 } else if log != "" {
55 t.Error("Expected no log output.")
56 }
57
58 duration := time.Since(start)
59 assert.InDelta(t, tc.expectDuration.Seconds(), duration.Seconds(), 0.1, fmt.Sprintf("callback invocation duration %s", duration))
60 assert.Equal(t, !tc.expectNoFail, tCtx.Failed(), "Failed()")
61 if tc.expectError == "" {
62 assert.NoError(t, err)
63 } else if assert.NotNil(t, err) {
64 t.Logf("Result:\n%s", err.Error())
65 assert.Equal(t, tc.expectError, normalize(err.Error()))
66 }
67 }
68
69
70 func normalize(msg string) string {
71
72 msg = regexp.MustCompile(`[[:digit:]]+\.[[:digit:]]+s`).ReplaceAllString(msg, "x.y s")
73
74 msg = regexp.MustCompile(`0x[[:xdigit:]]+`).ReplaceAllString(msg, "0xXXXX")
75
76 msg = regexp.MustCompile(`[EI][[:digit:]]{4} [[:digit:]]{2}:[[:digit:]]{2}:[[:digit:]]{2}\.[[:digit:]]{6}\]`).ReplaceAllString(msg, "<klog header>:")
77 return msg
78 }
79
80 type logBufferT struct {
81 *testing.T
82 log strings.Builder
83 }
84
85 func (l *logBufferT) Log(args ...any) {
86 l.log.WriteString(fmt.Sprintln(args...))
87 }
88
89 func (l *logBufferT) Logf(format string, args ...any) {
90 l.log.WriteString(fmt.Sprintf(format, args...))
91 l.log.WriteRune('\n')
92 }
93
View as plain text