如何将Google Cloud Firestore本地模拟器用于python和进行测试

时间:2019-02-25 14:07:07

标签: python google-cloud-platform google-cloud-firestore

我试图找出如何将firestore本地仿真器用于python和进行测试。但是我找不到操作文档。

有人可以帮我吗?

3 个答案:

答案 0 :(得分:2)

欢迎来到SO:)

Cloud Firestore Emulator(目前)的主要目的似乎是测试安全规则,如here所述。 This section指出:“当前唯一支持模拟器的SDK是Node.js SDK。”

令人困惑的是,还有these个针对Google Cloud Client库的Ruby文档。 python中似乎还没有提供相同的功能。

Here是作为Google Cloud SDK的一部分运行模拟器的说明。


考虑在数据存储区模式下使用 Cloud Firestore ,该工具具有更好的工具(可能只有更多时间才能成熟)。您可以在Running the Datastore mode Emulator页面上找到有关运行其模拟器的说明。

使用Choosing between Native Mode and Datastore Mode页来确定您要采取的方向。如果您认为需要其他“本机模式”功能,则可能最容易直接连接到云中的真实Firestore实例。

答案 1 :(得分:2)

到目前为止,只需设置这两个环境变量,就可以将 firebase_admin 的任何 SDK 连接到 Firebase 模拟器。我已经在 Python SDK 上亲自测试过,它的效果非常好。

export FIRESTORE_EMULATOR_HOST="localhost:8080"
export GCLOUD_PROJECT="any-valid-name"

Documentation Link

答案 2 :(得分:1)

使用firebase_admin python模块,遵循Cloud Firestore Docs中记录的标准设置

这将涉及使用initialize_app上下文调用credentials,然后使用firestore.client()创建传统的Firestore客户端

例如:

from firebase_admin import credentials, firestore, initialize_app

firebase_credentials_file_path = ...
cred = credentials.Certificate(firebase_credentials_file_path)
initialize_app(cred)
db = firestore.client()

下一步,您需要安装并运行Firestore Emulator,它将在localhost:8080上托管本地Firestore实例。

npx firebase setup:emulators:firestore
npx firebase --token $FIREBASE_TOKEN emulators:start --only firestore --project $PROJECT_KEY

最后,在已实例化的firestore.client实例中注入重定向,以使用不安全的GRPC通道与本地仿真器主机/端口进行交互:

import grpc
from google.cloud.firestore_v1.gapic import firestore_client
from google.cloud.firestore_v1.gapic.transports import firestore_grpc_transport

channel = grpc.insecure_channel("localhost:8080")
transport = firestore_grpc_transport.FirestoreGrpcTransport(channel=channel)
db._firestore_api_internal = firestore_client.FirestoreClient(transport=transport)

现在,您的db对象将与本地模拟器进行交互,而不会出现任何问题。

John Carterfiguring this out on the gcloud internal api的致谢