packagedatastoreimport("context""fmt""github.com/testcontainers/testcontainers-go""github.com/testcontainers/testcontainers-go/wait")// datastoreContainer represents the datastore container type used in the moduletypedatastoreContainerstruct{testcontainers.ContainerURIstring}// startContainer creates an instance of the datastore container typefuncstartContainer(ctxcontext.Context)(*datastoreContainer,error){req:=testcontainers.ContainerRequest{Image:"gcr.io/google.com/cloudsdktool/cloud-sdk:367.0.0-emulators",ExposedPorts:[]string{"8081/tcp"},WaitingFor:wait.ForHTTP("/").WithPort("8081/tcp"),Cmd:[]string{"/bin/sh","-c","gcloud beta emulators datastore start --project test-project --host-port 0.0.0.0:8081",},}container,err:=testcontainers.GenericContainer(ctx,testcontainers.GenericContainerRequest{ContainerRequest:req,Started:true,})iferr!=nil{returnnil,err}mappedPort,err:=container.MappedPort(ctx,"8081")iferr!=nil{returnnil,err}hostIP,err:=container.Host(ctx)iferr!=nil{returnnil,err}uri:=fmt.Sprintf("%s:%s",hostIP,mappedPort.Port())return&datastoreContainer{Container:container,URI:uri},nil}
packagedatastoreimport("cloud.google.com/go/datastore""context""google.golang.org/api/option""google.golang.org/grpc""google.golang.org/grpc/credentials/insecure""testing")typeTaskstruct{Descriptionstring}funcTestDatastore(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)}})options:=[]option.ClientOption{option.WithEndpoint(container.URI),option.WithoutAuthentication(),option.WithGRPCDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())),}dsClient,err:=datastore.NewClient(ctx,"test-project",options...)iferr!=nil{t.Fatal(err)}deferdsClient.Close()k:=datastore.NameKey("Task","sample",nil)data:=Task{Description:"my description",}_,err=dsClient.Put(ctx,k,&data)iferr!=nil{t.Fatal(err)}saved:=Task{}err=dsClient.Get(ctx,k,&saved)iferr!=nil{t.Fatal(err)}// perform assertionsifsaved!=data{t.Fatalf("Expected value %s. Got %s.",data,saved)}}