-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
92 lines (75 loc) · 1.96 KB
/
main_test.go
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
package main
import (
"bytes"
"fmt"
"io"
"os"
"strings"
"testing"
)
func TestHandleLogLine(t *testing.T) {
// First test line that will not be able to unmarshal
output := captureStdOutAndStdErr(func() {
handleLogLine("This will not unmarshal")
})
expectedError := "Log entry unmarshaling error: invalid character 'T' looking for beginning of value\n"
if output != expectedError {
t.Errorf("Incorrect output, got: %s, want: %s.", output, expectedError)
}
// Test line that will unmarshal. We are trimming newline when formming json
// Output adds newline to stdOut
expectedOutput := "This is some logged text\n"
output = captureStdOutAndStdErr(func() {
handleLogLine(fmt.Sprintf(`{"textPayload":"%s"}`, strings.TrimRight(expectedOutput, "\n")))
})
if output != expectedOutput {
t.Errorf("Incorrect output, got: %s, want: %s.", output, expectedOutput)
}
// Test empty line
output = captureStdOutAndStdErr(func() {
handleLogLine("")
})
if output != "" {
t.Error("Expected empty output")
}
}
func TestHandleLogLines(t *testing.T) {
lines := []string{
`{"textPayload":"firstLine"}`,
`{"textPayload":"secondLine"}`,
`Unable to marshal`,
}
output := captureStdOutAndStdErr(func() {
handleLogLines(lines)
})
if !strings.Contains(output, "firstLine") {
t.Errorf("Incorrect output, got: %s, want: %s.", output, "firstLine")
}
if !strings.Contains(output, "secondLine") {
t.Errorf("Incorrect output, got: %s, want: %s.", output, "secondLine")
}
if !strings.Contains(output, "Log entry unmarshaling error") {
t.Errorf("Incorrect output, got: %s, want: %s.", output, "Log entry unmarshaling error")
}
}
func captureStdOutAndStdErr(f func()) string {
r, w, err := os.Pipe()
if err != nil {
panic(err)
}
stdout := os.Stdout
os.Stdout = w
defer func() {
os.Stdout = stdout
}()
stderr := os.Stderr
os.Stderr = w
defer func() {
os.Stderr = stderr
}()
f()
w.Close()
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String()
}