packagefirestoreimport("context""fmt""github.com/testcontainers/testcontainers-go/wait""github.com/testcontainers/testcontainers-go")// firestoreContainer represents the firestore container type used in the moduletypefirestoreContainerstruct{testcontainers.ContainerURIstring}// startContainer creates an instance of the firestore container typefuncstartContainer(ctxcontext.Context)(*firestoreContainer,error){req:=testcontainers.ContainerRequest{Image:"gcr.io/google.com/cloudsdktool/cloud-sdk:367.0.0-emulators",ExposedPorts:[]string{"8080/tcp"},WaitingFor:wait.ForLog("running"),Cmd:[]string{"/bin/sh","-c","gcloud beta emulators firestore start --host-port 0.0.0.0:8080",},}container,err:=testcontainers.GenericContainer(ctx,testcontainers.GenericContainerRequest{ContainerRequest:req,Started:true,})iferr!=nil{returnnil,err}mappedPort,err:=container.MappedPort(ctx,"8080")iferr!=nil{returnnil,err}hostIP,err:=container.Host(ctx)iferr!=nil{returnnil,err}uri:=fmt.Sprintf("%s:%s",hostIP,mappedPort.Port())return&firestoreContainer{Container:container,URI:uri},nil}
packagefirestoreimport("cloud.google.com/go/firestore""context""google.golang.org/api/option""google.golang.org/grpc""google.golang.org/grpc/credentials/insecure""testing")typePersonstruct{Firstnamestring`json:"firstname"`Lastnamestring`json:"lastname"`}typeemulatorCredsstruct{}func(ecemulatorCreds)GetRequestMetadata(ctxcontext.Context,uri...string)(map[string]string,error){returnmap[string]string{"authorization":"Bearer owner"},nil}func(ecemulatorCreds)RequireTransportSecurity()bool{returnfalse}funcTestFirestore(t*testing.T){ctx:=context.Background()container,err:=startContainer(ctx)iferr!=nil{t.Fatal(err)}// Clean up the container after the test is completet.Cleanup(func(){iferr:=container.Terminate(ctx);err!=nil{t.Fatalf("failed to terminate container: %s",err)}})conn,err:=grpc.Dial(container.URI,grpc.WithTransportCredentials(insecure.NewCredentials()),grpc.WithPerRPCCredentials(emulatorCreds{}))iferr!=nil{t.Fatal(err)}options:=[]option.ClientOption{option.WithGRPCConn(conn)}client,err:=firestore.NewClient(ctx,"test-project",options...)iferr!=nil{t.Fatal(err)}deferclient.Close()users:=client.Collection("users")docRef:=users.Doc("alovelace")data:=Person{Firstname:"Ada",Lastname:"Lovelace",}_,err=docRef.Create(ctx,data)iferr!=nil{t.Fatal(err)}// perform assertionsdocsnap,err:=docRef.Get(ctx)iferr!=nil{t.Fatal(err)}varsavedPersoniferr:=docsnap.DataTo(&saved);err!=nil{t.Fatal(err)}ifsaved!=data{t.Fatalf("Expected value %s. Got %s.",data,saved)}}