Skip to content

Commit dbc2c16

Browse files
committed
fix func logger and add test
1 parent c00c620 commit dbc2c16

File tree

2 files changed

+56
-5
lines changed

2 files changed

+56
-5
lines changed

api/agent/func_logger.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -111,18 +111,20 @@ func (li *lineWriter) Write(ogb []byte) (int, error) {
111111

112112
var n int
113113
for {
114-
// read the line and advance buffer past it
115-
l, err := li.b.ReadBytes('\n')
116-
if err != nil {
117-
break // no more newlines in buffer (see ReadBytes contract)
114+
b := li.b.Bytes()
115+
i := bytes.IndexByte(b, '\n')
116+
if i < 0 {
117+
break // no more newlines in buffer
118118
}
119119

120-
// write in the line
120+
// write in this line and advance buffer past it
121+
l := b[:i+1]
121122
ns, err := li.w.Write(l)
122123
n += ns
123124
if err != nil {
124125
return n, err
125126
}
127+
li.b.Next(len(l))
126128
}
127129

128130
// technically we wrote all the bytes, so make things appear normal

api/agent/func_logger_test.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package agent
2+
3+
import (
4+
"bytes"
5+
"fmt"
6+
"testing"
7+
)
8+
9+
type testSliceWriter struct {
10+
b [][]byte
11+
}
12+
13+
func (tsw *testSliceWriter) Write(p []byte) (n int, err error) {
14+
l := make([]byte, len(p))
15+
copy(l, p)
16+
tsw.b = append(tsw.b, l)
17+
return len(p), nil
18+
}
19+
20+
func TestLineWriter(t *testing.T) {
21+
var tsw testSliceWriter
22+
lw := newLineWriter(&nopCloser{&tsw})
23+
24+
lineCount := 7
25+
lw.Write([]byte("0 line\n1 line\n2 line\n\n4 line"))
26+
lw.Write([]byte("+more\n5 line\n"))
27+
lw.Write([]byte("6 line"))
28+
29+
lw.Close()
30+
31+
if len(tsw.b) != lineCount {
32+
t.Errorf("Expected %v individual rows; got %v", lineCount, len(tsw.b))
33+
}
34+
35+
for x := 0; x < len(tsw.b); x++ {
36+
l := fmt.Sprintf("%v line\n", x)
37+
if x == 3 {
38+
if len(tsw.b[x]) != 1 {
39+
t.Errorf("Expected slice with only newline; got %v", tsw.b[x])
40+
}
41+
continue
42+
} else if x == 4 {
43+
l = "4 line+more\n"
44+
}
45+
if !bytes.Equal(tsw.b[x], []byte(l)) {
46+
t.Errorf("Expected slice %s equal to %s", []byte(l), tsw.b[x])
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)