Skip to content

Instantly share code, notes, and snippets.

@nownabe
Created April 7, 2022 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nownabe/62749be8cf8a645c7960171fae945035 to your computer and use it in GitHub Desktop.
Save nownabe/62749be8cf8a645c7960171fae945035 to your computer and use it in GitHub Desktop.
Firestore Emulator test
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"cloud.google.com/go/firestore"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
project1 = "project-1"
project2 = "project-2"
doc1 = "collection1/doc1"
doc2 = "collection2/doc2"
)
func main() {
os.Setenv("FIRESTORE_EMULATOR_HOST", "localhost:8937")
flushFirestoreEmulator(project1)
flushFirestoreEmulator(project2)
ctx := context.Background()
client1, err := firestore.NewClient(ctx, project1)
if err != nil {
panic(err)
}
client2, err := firestore.NewClient(ctx, project2)
if err != nil {
panic(err)
}
if _, err := client1.Doc(doc1).Create(ctx, map[string]interface{}{
"key1": "content1",
}); err != nil {
panic(err)
}
if _, err := client2.Doc(doc2).Create(ctx, map[string]interface{}{
"key2": "content2",
}); err != nil {
panic(err)
}
testDoc(ctx, client1, doc1, project1)
testDoc(ctx, client1, doc2, project1)
testDoc(ctx, client2, doc1, project2)
testDoc(ctx, client2, doc2, project2)
flushFirestoreEmulator(project1)
testDoc(ctx, client1, doc1, project1)
testDoc(ctx, client2, doc2, project2)
flushFirestoreEmulator(project2)
testDoc(ctx, client1, doc1, project1)
testDoc(ctx, client2, doc2, project2)
}
func testDoc(ctx context.Context, client *firestore.Client, path, prefix string) {
snap, err := client.Doc(path).Get(ctx)
if status.Code(err) == codes.NotFound {
fmt.Printf("%s - %s: Not Found\n", prefix, path)
} else if err != nil {
panic(err)
} else {
fmt.Printf("%s - %s: %+v\n", prefix, path, snap.Data())
}
}
func flushFirestoreEmulator(project string) {
fmt.Printf("======== Flush %s ========\n", project)
url := "http://localhost:8937/emulator/v1/projects/" + project + "/databases/(default)/documents"
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
panic(err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
if resp.StatusCode == 200 {
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
defer resp.Body.Close()
panic(body)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment