-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserviceId_test.go
79 lines (68 loc) · 2.26 KB
/
serviceId_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
package grpc
import (
"strings"
"testing"
"golang.org/x/net/context"
"google.golang.org/grpc/metadata"
"github.com/binchencoder/letsgo/ident"
vexpb "github.com/binchencoder/gateway-proto/data"
)
func TestServiceId(t *testing.T) {
// Test to add and get service ID to context without existing metadata.
serviceId := int(123)
ctx := WithServiceId(context.Background(), serviceId)
id, err := GetServiceId(ToIncomingCtx(ctx))
if err != nil {
t.Errorf("GetServiceId() failed, %v", err)
}
if id != serviceId {
t.Errorf("Get wrong service ID, expected = %d, actual = %d", serviceId, id)
}
// Test to have more than one service IDs due to MD join.
serviceId = int(789)
ctx = WithServiceId(ctx, serviceId)
id, err = GetServiceId(ToIncomingCtx(ctx))
if err != nil {
t.Errorf("GetServiceId() failed, %v", err)
}
if id != serviceId {
t.Errorf("Get wrong service ID, expected = %d, actual = %d", serviceId, id)
}
// Test to add and get service ID to context with existing metadata.
testMdKey := "testMdKey"
testMdVal := "testMdVal"
md := metadata.Pairs(testMdKey, testMdVal)
ctx = metadata.NewOutgoingContext(context.Background(), md)
serviceId = int(456)
ctx = WithServiceId(ctx, serviceId)
id, err = GetServiceId(ToIncomingCtx(ctx))
if err != nil {
t.Errorf("GetServiceId() failed, %v", err)
}
if id != serviceId {
t.Errorf("Got wrong service ID, expected = %d, actual = %d", serviceId, id)
}
// Keys in metadata are always lower-case.
val, err := getLastVal(ToIncomingCtx(ctx), strings.ToLower(testMdKey))
if err != nil {
t.Errorf("Failed to get %q from metadata, %v", testMdKey, err)
}
if val != testMdVal {
t.Errorf("Got wrong value for %s, expected = %s, actual = %s", testMdKey, testMdVal, val)
}
// Test to get service ID from context without metadata.
_, err = GetServiceId(ToIncomingCtx(context.Background()))
if err == nil {
t.Errorf("Expect error when context does NOT have metadata")
}
// Test to get service ID from metadata does not have service ID.
userDetails := &vexpb.UserDetails{
CompanyId: "companyId",
UserId: "userId",
}
ctx = ident.WithUserDetails(ctx, userDetails)
_, err = GetServiceId(ToIncomingCtx(context.Background()))
if err == nil {
t.Errorf("Expect error when context metadata does NOT have service ID")
}
}