forked from zaihui/go-hutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interceptor_test.go
66 lines (57 loc) · 1.39 KB
/
interceptor_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
package hutils
import (
"bytes"
"io"
"os"
"strings"
"testing"
grpc_testing "github.com/grpc-ecosystem/go-grpc-middleware/testing"
pb_testproto "github.com/grpc-ecosystem/go-grpc-middleware/testing/testproto"
"github.com/stretchr/testify/suite"
"google.golang.org/grpc"
)
var (
goodPing = &pb_testproto.PingRequest{Value: "goodPing", SleepTimeMs: 999}
)
type LogTestSuite struct {
*grpc_testing.InterceptorTestSuite
reader, writer *os.File
}
func TestLogTestSuite(t *testing.T) {
r, w, _ := os.Pipe()
// 替换原有os.Stdout
os.Stdout = w
logger := &Logger{}
sugarLog := logger.Init(LoggerOpt{EnableStdout: true}).Sugar()
s := &LogTestSuite{
InterceptorTestSuite: &grpc_testing.InterceptorTestSuite{
ServerOpts: []grpc.ServerOption{
grpc.UnaryInterceptor(NewUnaryServerAccessLogInterceptor(sugarLog, nil)),
},
},
}
s.reader = r
s.writer = w
suite.Run(t, s)
}
func (s *LogTestSuite) TestNewUnaryServerAccessLogInterceptor() {
_, err := s.Client.Ping(s.SimpleCtx(), goodPing)
s.NoError(err)
var buf bytes.Buffer
output := make(chan string, 1)
go func() {
io.Copy(&buf, s.reader)
output <- buf.String()
s.reader.Close()
}()
s.writer.Close()
o := strings.Split(<-output, "\n")
// 输出空行
s.Len(o, 1)
s.Equal(o[0], "")
}
func (s *LogTestSuite) TestMarshalJSON() {
buf, err := MarshalJSON(goodPing)
s.Nil(err)
s.True(strings.Contains(string(buf), "goodPing"))
}