1
18
19 package peer
20
21 import (
22 "context"
23 "fmt"
24 "testing"
25
26 "google.golang.org/grpc/credentials"
27 )
28
29
30 type testAuthInfo struct {
31 credentials.CommonAuthInfo
32 }
33
34 func (ta testAuthInfo) AuthType() string {
35 return fmt.Sprintf("testAuthInfo-%d", ta.SecurityLevel)
36 }
37
38 type addr struct {
39 ipAddress string
40 }
41
42 func (addr) Network() string { return "" }
43
44 func (a *addr) String() string { return a.ipAddress }
45
46 func TestPeerStringer(t *testing.T) {
47 testCases := []struct {
48 name string
49 peer *Peer
50 want string
51 }{
52 {
53 name: "+Addr-LocalAddr+ValidAuth",
54 peer: &Peer{Addr: &addr{"example.com:1234"}, AuthInfo: testAuthInfo{credentials.CommonAuthInfo{SecurityLevel: credentials.PrivacyAndIntegrity}}},
55 want: "Peer{Addr: 'example.com:1234', LocalAddr: <nil>, AuthInfo: 'testAuthInfo-3'}",
56 },
57 {
58 name: "+Addr+LocalAddr+ValidAuth",
59 peer: &Peer{Addr: &addr{"example.com:1234"}, LocalAddr: &addr{"example.com:1234"}, AuthInfo: testAuthInfo{credentials.CommonAuthInfo{SecurityLevel: credentials.PrivacyAndIntegrity}}},
60 want: "Peer{Addr: 'example.com:1234', LocalAddr: 'example.com:1234', AuthInfo: 'testAuthInfo-3'}",
61 },
62 {
63 name: "+Addr-LocalAddr+emptyAuth",
64 peer: &Peer{Addr: &addr{"1.2.3.4:1234"}, AuthInfo: testAuthInfo{credentials.CommonAuthInfo{}}},
65 want: "Peer{Addr: '1.2.3.4:1234', LocalAddr: <nil>, AuthInfo: 'testAuthInfo-0'}",
66 },
67 {
68 name: "-Addr-LocalAddr+emptyAuth",
69 peer: &Peer{AuthInfo: testAuthInfo{}},
70 want: "Peer{Addr: <nil>, LocalAddr: <nil>, AuthInfo: 'testAuthInfo-0'}",
71 },
72 {
73 name: "zeroedPeer",
74 peer: &Peer{},
75 want: "Peer{Addr: <nil>, LocalAddr: <nil>, AuthInfo: <nil>}",
76 },
77 {
78 name: "nilPeer",
79 peer: nil,
80 want: "Peer<nil>",
81 },
82 }
83 for _, tc := range testCases {
84 t.Run(tc.name, func(t *testing.T) {
85 ctx := NewContext(context.Background(), tc.peer)
86 p, ok := FromContext(ctx)
87 if !ok {
88 t.Fatalf("Unable to get peer from context")
89 }
90 if p.String() != tc.want {
91 t.Fatalf("Error using peer String(): expected %q, got %q", tc.want, p.String())
92 }
93 })
94 }
95 }
96
View as plain text