diff --git a/firestore/client.go b/firestore/client.go index 3049e2203117..1cad80581c7c 100644 --- a/firestore/client.go +++ b/firestore/client.go @@ -73,6 +73,7 @@ type Client struct { projectID string databaseID string // A client is tied to a single database. readSettings *readSettings // readSettings allows setting a snapshot time to read the database + UsesEmulator bool // a boolean that indicates if the client is using the emulator } // NewClient creates a new Firestore client that uses the given project. @@ -81,12 +82,14 @@ func NewClient(ctx context.Context, projectID string, opts ...option.ClientOptio return nil, errors.New("firestore: projectID was empty") } var o []option.ClientOption + var usesEmulator bool // If this environment variable is defined, configure the client to talk to the emulator. if addr := os.Getenv("FIRESTORE_EMULATOR_HOST"); addr != "" { conn, err := grpc.Dial(addr, grpc.WithInsecure(), grpc.WithPerRPCCredentials(emulatorCreds{})) if err != nil { return nil, fmt.Errorf("firestore: dialing address from env var FIRESTORE_EMULATOR_HOST: %s", err) } + usesEmulator = true o = []option.ClientOption{option.WithGRPCConn(conn)} projectID, _ = detect.ProjectID(ctx, projectID, "", opts...) if projectID == "" { @@ -111,6 +114,7 @@ func NewClient(ctx context.Context, projectID string, opts ...option.ClientOptio projectID: projectID, databaseID: DefaultDatabaseID, readSettings: &readSettings{}, + UsesEmulator: usesEmulator, } return c, nil } diff --git a/firestore/client_test.go b/firestore/client_test.go index f710aaea07bc..9909352a5865 100644 --- a/firestore/client_test.go +++ b/firestore/client_test.go @@ -16,6 +16,7 @@ package firestore import ( "context" + "os" "testing" "time" @@ -399,3 +400,19 @@ func TestClient_WithReadOptions(t *testing.T) { t.Fatal(err) } } + +func TestClient_UsesEmulator(t *testing.T) { + c, _, cleanup := newMock(t) + defer cleanup() + if c.UsesEmulator { + t.Error("got true, want false") + } + + os.Setenv("FIRESTORE_EMULATOR_HOST", "localhost:8080") + defer os.Unsetenv("FIRESTORE_EMULATOR_HOST") + c, _, cleanup = newMock(t) + defer cleanup() + if !c.UsesEmulator { + t.Error("got false, want true") + } +}