go4.org@v0.0.0-20230225012048-214862532bf5/types/types_test.go (about) 1 /* 2 Copyright 2013 Google Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package types 18 19 import ( 20 "encoding/json" 21 "strings" 22 "testing" 23 "time" 24 ) 25 26 func TestTime3339(t *testing.T) { 27 tm := time.Unix(123, 456) 28 t3 := Time3339(tm) 29 type O struct { 30 SomeTime Time3339 `json:"someTime"` 31 } 32 o := &O{SomeTime: t3} 33 got, err := json.Marshal(o) 34 if err != nil { 35 t.Fatal(err) 36 } 37 goodEnc := "{\"someTime\":\"1970-01-01T00:02:03.000000456Z\"}" 38 if string(got) != goodEnc { 39 t.Errorf("Encoding wrong.\n Got: %q\nWant: %q", got, goodEnc) 40 } 41 ogot := &O{} 42 err = json.Unmarshal([]byte(goodEnc), ogot) 43 if err != nil { 44 t.Fatal(err) 45 } 46 if !tm.Equal(ogot.SomeTime.Time()) { 47 t.Errorf("Unmarshal got time %v; want %v", ogot.SomeTime.Time(), tm) 48 } 49 } 50 51 func TestTime3339_Marshal(t *testing.T) { 52 tests := []struct { 53 in time.Time 54 want string 55 }{ 56 {time.Time{}, "null"}, 57 {time.Unix(1, 0), `"1970-01-01T00:00:01Z"`}, 58 } 59 for i, tt := range tests { 60 got, err := Time3339(tt.in).MarshalJSON() 61 if err != nil { 62 t.Errorf("%d. marshal(%v) got error: %v", i, tt.in, err) 63 continue 64 } 65 if string(got) != tt.want { 66 t.Errorf("%d. marshal(%v) = %q; want %q", i, tt.in, got, tt.want) 67 } 68 } 69 } 70 71 func TestTime3339_empty(t *testing.T) { 72 tests := []struct { 73 enc string 74 z bool 75 }{ 76 {enc: "null", z: true}, 77 {enc: `""`, z: true}, 78 {enc: "0000-00-00T00:00:00Z", z: true}, 79 {enc: "0001-01-01T00:00:00Z", z: true}, 80 {enc: "1970-01-01T00:00:00Z", z: true}, 81 {enc: "2001-02-03T04:05:06Z", z: false}, 82 {enc: "2001-02-03T04:05:06+06:00", z: false}, 83 {enc: "2001-02-03T04:05:06-06:00", z: false}, 84 {enc: "2001-02-03T04:05:06.123456789Z", z: false}, 85 {enc: "2001-02-03T04:05:06.123456789+06:00", z: false}, 86 {enc: "2001-02-03T04:05:06.123456789-06:00", z: false}, 87 } 88 for _, tt := range tests { 89 var tm Time3339 90 enc := tt.enc 91 if strings.Contains(enc, "T") { 92 enc = "\"" + enc + "\"" 93 } 94 err := json.Unmarshal([]byte(enc), &tm) 95 if err != nil { 96 t.Errorf("unmarshal %q = %v", enc, err) 97 } 98 if tm.IsAnyZero() != tt.z { 99 t.Errorf("unmarshal %q = %v (%d), %v; zero=%v; want %v", tt.enc, tm.Time(), tm.Time().Unix(), err, 100 !tt.z, tt.z) 101 } 102 } 103 }