github.com/cornelk/go-cloud@v0.17.1/docstore/gcpfirestore/codec_test.go (about) 1 // Copyright 2019 The Go Cloud Development Kit Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package gcpfirestore 16 17 import ( 18 "testing" 19 "time" 20 21 "github.com/cornelk/go-cloud/docstore" 22 "github.com/cornelk/go-cloud/docstore/drivertest" 23 "github.com/golang/protobuf/ptypes" 24 ts "github.com/golang/protobuf/ptypes/timestamp" 25 "github.com/google/go-cmp/cmp" 26 "google.golang.org/genproto/googleapis/type/latlng" 27 ) 28 29 // Test that special types round-trip. 30 // These aren't tested in the docstore-wide conformance tests. 31 func TestCodecSpecial(t *testing.T) { 32 const nameField = "Name" 33 34 type S struct { 35 Name string 36 T time.Time 37 TS, TSn *ts.Timestamp 38 LL, LLn *latlng.LatLng 39 } 40 tm := time.Date(2019, 3, 14, 0, 0, 0, 0, time.UTC) 41 ts, err := ptypes.TimestampProto(tm) 42 if err != nil { 43 t.Fatal(err) 44 } 45 in := &S{ 46 Name: "name", 47 T: tm, 48 TS: ts, 49 TSn: nil, 50 LL: &latlng.LatLng{Latitude: 3, Longitude: 4}, 51 LLn: nil, 52 } 53 var got S 54 55 enc, err := encodeDoc(drivertest.MustDocument(in), nameField) 56 if err != nil { 57 t.Fatal(err) 58 } 59 enc.Name = "collPath/" + in.Name 60 gotdoc := drivertest.MustDocument(&got) 61 // Test type-driven decoding (where the types of the struct fields are available). 62 if err := decodeDoc(enc, gotdoc, nameField, docstore.DefaultRevisionField); err != nil { 63 t.Fatal(err) 64 } 65 if diff := cmp.Diff(&got, in); diff != "" { 66 t.Error(diff) 67 } 68 69 // Test type-blind decoding. 70 gotmap := map[string]interface{}{} 71 gotmapdoc := drivertest.MustDocument(gotmap) 72 if err := decodeDoc(enc, gotmapdoc, nameField, docstore.DefaultRevisionField); err != nil { 73 t.Fatal(err) 74 } 75 wantmap := map[string]interface{}{ 76 "Name": "name", 77 "T": in.T, 78 "TS": in.T, // timestamps always decode as time.Time 79 "TSn": nil, 80 "LL": in.LL, 81 "LLn": nil, 82 } 83 if diff := cmp.Diff(gotmap, wantmap); diff != "" { 84 t.Error(diff) 85 } 86 }