1 package runtime_test
2
3 import (
4 "testing"
5
6 "github.com/golang/protobuf/proto"
7 "github.com/golang/protobuf/ptypes/duration"
8 "github.com/golang/protobuf/ptypes/timestamp"
9 "github.com/grpc-ecosystem/grpc-gateway/runtime"
10 )
11
12 func TestConvertTimestamp(t *testing.T) {
13 specs := []struct {
14 name string
15 input string
16 output *timestamp.Timestamp
17 wanterr bool
18 }{
19 {
20 name: "a valid RFC3339 timestamp",
21 input: `"2016-05-10T10:19:13.123Z"`,
22 output: ×tamp.Timestamp{
23 Seconds: 1462875553,
24 Nanos: 123000000,
25 },
26 wanterr: false,
27 },
28 {
29 name: "invalid timestamp",
30 input: `"05-10-2016T10:19:13.123Z"`,
31 output: nil,
32 wanterr: true,
33 },
34 {
35 name: "JSON number",
36 input: "123",
37 output: nil,
38 wanterr: true,
39 },
40 {
41 name: "JSON bool",
42 input: "true",
43 output: nil,
44 wanterr: true,
45 },
46 }
47
48 for _, spec := range specs {
49 t.Run(spec.name, func(t *testing.T) {
50 ts, err := runtime.Timestamp(spec.input)
51 switch {
52 case err != nil && !spec.wanterr:
53 t.Errorf("got unexpected error\n%#v", err)
54 case err == nil && spec.wanterr:
55 t.Errorf("did not error when expecte")
56 case !proto.Equal(ts, spec.output):
57 t.Errorf(
58 "when testing %s; got\n%#v\nexpected\n%#v",
59 spec.name,
60 ts,
61 spec.output,
62 )
63 }
64 })
65 }
66 }
67
68 func TestConvertDuration(t *testing.T) {
69 specs := []struct {
70 name string
71 input string
72 output *duration.Duration
73 wanterr bool
74 }{
75 {
76 name: "a valid duration",
77 input: `"123.456s"`,
78 output: &duration.Duration{
79 Seconds: 123,
80 Nanos: 456000000,
81 },
82 wanterr: false,
83 },
84 {
85 name: "invalid duration",
86 input: `"123years"`,
87 output: nil,
88 wanterr: true,
89 },
90 {
91 name: "JSON number",
92 input: "123",
93 output: nil,
94 wanterr: true,
95 },
96 {
97 name: "JSON bool",
98 input: "true",
99 output: nil,
100 wanterr: true,
101 },
102 }
103
104 for _, spec := range specs {
105 t.Run(spec.name, func(t *testing.T) {
106 ts, err := runtime.Duration(spec.input)
107 switch {
108 case err != nil && !spec.wanterr:
109 t.Errorf("got unexpected error\n%#v", err)
110 case err == nil && spec.wanterr:
111 t.Errorf("did not error when expecte")
112 case !proto.Equal(ts, spec.output):
113 t.Errorf(
114 "when testing %s; got\n%#v\nexpected\n%#v",
115 spec.name,
116 ts,
117 spec.output,
118 )
119 }
120 })
121 }
122 }
123
View as plain text