forked from airheartdev/duffel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoding_test.go
More file actions
102 lines (84 loc) · 2.47 KB
/
encoding_test.go
File metadata and controls
102 lines (84 loc) · 2.47 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Copyright 2021-present Airheart, Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package duffel
import (
"testing"
"time"
"github.com/segmentio/encoding/json"
"github.com/stretchr/testify/assert"
)
func Test_MarshallingDate(t *testing.T) {
a := assert.New(t)
testDate := Date(time.Date(2016, time.January, 1, 0, 0, 0, 0, time.UTC))
type test struct {
DepartureDate Date `json:"departure_date"`
}
testStruct := test{
DepartureDate: testDate,
}
payload, err := json.Marshal(testStruct)
a.NoError(err)
a.Equal(`{"departure_date":"2016-01-01"}`, string(payload))
var unmarshalled test
err = json.Unmarshal(payload, &unmarshalled)
a.NoError(err)
a.Equal(testDate, unmarshalled.DepartureDate)
}
func TestDateTime(t *testing.T) {
tz, _ := time.LoadLocation("Asia/Bangkok")
tests := []struct {
Input string
Expected time.Time
}{
{Input: "{\"date_time\": \"2022-02-22T12:01:00Z\"}", Expected: time.Date(2022, 2, 22, 12, 1, 0, 0, time.UTC)},
{Input: "{\"date_time\": \"2022-02-22T12:01:00+07:00\"}", Expected: time.Date(2022, 2, 22, 12, 1, 0, 0, tz)},
{Input: "{\"date_time\": \"2022-02-22T12:01:00\"}", Expected: time.Date(2022, 2, 22, 12, 1, 0, 0, time.UTC)},
}
type container struct {
DateTime DateTime `json:"date_time"`
}
for _, test := range tests {
d := new(container)
err := json.Unmarshal([]byte(test.Input), d)
if err != nil {
t.Fatal(err)
}
actual := time.Time(d.DateTime)
if actual.Unix() != test.Expected.Unix() {
t.Errorf("%s: expected %s, got %s", test.Input, test.Expected, actual)
}
}
}
func TestDistance(t *testing.T) {
testCases := []struct {
Name string
Distance string
Want Distance
}{
{Distance: "5567.72", Want: 5567.72},
{Distance: "1233.325455", Want: 1233.325455},
{Distance: "20.15", Want: 20.15},
{Distance: "\"20.15\"", Want: 20.15},
{Distance: "\"null\"", Want: 0},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
var distance Distance
if err := distance.UnmarshalJSON([]byte(tc.Distance)); err != nil {
t.Fatal(err)
}
if distance != Distance(tc.Want) {
t.Errorf("%s: expected %f, got: %f", tc.Distance, tc.Want, distance)
}
})
}
}
func TestJSONUnescape(t *testing.T) {
b := []byte("\"name\"")
a := json.Unescape(b)
assert.Equal(t, "name", string(a))
b = []byte(`"null"`)
a = json.Unescape(b)
assert.Equal(t, "null", string(a))
}