1// Copyright 2017 Google LLC 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// http://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 15package firestore 16 17import ( 18 "context" 19 "testing" 20 21 "github.com/golang/protobuf/proto" 22 pb "google.golang.org/genproto/googleapis/firestore/v1" 23) 24 25func TestDoc(t *testing.T) { 26 coll := testClient.Collection("C") 27 got := coll.Doc("d") 28 want := &DocumentRef{ 29 Parent: coll, 30 ID: "d", 31 Path: "projects/projectID/databases/(default)/documents/C/d", 32 shortPath: "C/d", 33 } 34 if !testEqual(got, want) { 35 t.Errorf("got %+v, want %+v", got, want) 36 } 37} 38 39func TestNewDoc(t *testing.T) { 40 c := &Client{} 41 coll := c.Collection("C") 42 got := coll.NewDoc() 43 if got.Parent != coll { 44 t.Errorf("NewDoc got %v, want %v", got.Parent, coll) 45 } 46 if len(got.ID) != 20 { 47 t.Errorf("got %d-char ID, wanted 20", len(got.ID)) 48 } 49 50 got2 := coll.NewDoc() 51 if got.ID == got2.ID { 52 t.Error("got same ID") 53 } 54} 55 56func TestAdd(t *testing.T) { 57 ctx := context.Background() 58 c, srv, cleanup := newMock(t) 59 defer cleanup() 60 61 wantReq := commitRequestForSet() 62 w := wantReq.Writes[0] 63 w.CurrentDocument = &pb.Precondition{ 64 ConditionType: &pb.Precondition_Exists{false}, 65 } 66 srv.addRPCAdjust(wantReq, commitResponseForSet, func(gotReq proto.Message) { 67 // We can't know the doc ID before Add is called, so we take it from 68 // the request. 69 w.Operation.(*pb.Write_Update).Update.Name = gotReq.(*pb.CommitRequest).Writes[0].Operation.(*pb.Write_Update).Update.Name 70 }) 71 _, wr, err := c.Collection("C").Add(ctx, testData) 72 if err != nil { 73 t.Fatal(err) 74 } 75 if !testEqual(wr, writeResultForSet) { 76 t.Errorf("got %v, want %v", wr, writeResultForSet) 77 } 78} 79 80func TestNilErrors(t *testing.T) { 81 ctx := context.Background() 82 c, _, cleanup := newMock(t) 83 defer cleanup() 84 85 // Test that a nil CollectionRef results in a nil DocumentRef and errors 86 // where possible. 87 coll := c.Collection("a/b") // nil because "a/b" denotes a doc. 88 if coll != nil { 89 t.Fatal("collection not nil") 90 } 91 if got := coll.Doc("d"); got != nil { 92 t.Fatalf("got %v, want nil", got) 93 } 94 if got := coll.NewDoc(); got != nil { 95 t.Fatalf("got %v, want nil", got) 96 } 97 if _, _, err := coll.Add(ctx, testData); err != errNilDocRef { 98 t.Fatalf("got <%v>, want <%v>", err, errNilDocRef) 99 } 100} 101