...
1 package testutils
2
3 import (
4 "bytes"
5 "encoding/json"
6 "strconv"
7 "strings"
8 "testing"
9
10 . "github.com/sirupsen/logrus"
11
12 "github.com/stretchr/testify/require"
13 )
14
15 func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) {
16 var buffer bytes.Buffer
17 var fields Fields
18
19 logger := New()
20 logger.Out = &buffer
21 logger.Formatter = new(JSONFormatter)
22
23 log(logger)
24
25 err := json.Unmarshal(buffer.Bytes(), &fields)
26 require.Nil(t, err)
27
28 assertions(fields)
29 }
30
31 func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) {
32 var buffer bytes.Buffer
33
34 logger := New()
35 logger.Out = &buffer
36 logger.Formatter = &TextFormatter{
37 DisableColors: true,
38 }
39
40 log(logger)
41
42 fields := make(map[string]string)
43 for _, kv := range strings.Split(buffer.String(), " ") {
44 if !strings.Contains(kv, "=") {
45 continue
46 }
47 kvArr := strings.Split(kv, "=")
48 key := strings.TrimSpace(kvArr[0])
49 val := kvArr[1]
50 if kvArr[1][0] == '"' {
51 var err error
52 val, err = strconv.Unquote(val)
53 require.NoError(t, err)
54 }
55 fields[key] = val
56 }
57 assertions(fields)
58 }
59
View as plain text