在打包项目中使用Firestore模拟器进行单元测试



我试图模拟一个firestore本地客户端在我的Go项目中运行我的单元集成测试,但是我已经打包了这个项目,以便firestore在一个单独的包中初始化并在其他包中使用。

所以我有点困惑,我应该在哪里定义本地firestore客户端和TestMain(m *testing.M)函数。下面是我的文件结构的基本思想:

main.go
main_test.go (This could also need firestore local connection)
pkg
|____datastore (where firestore clients are defined)
|___datastore.go
|___testing.go (I intended to have my TestMain(m *testing.M) function to run the emulator)
|___ .....
|____pkg2
|___myfile.go (go file that I use the firestore client to deal with firestore db)
|___myfile_test.go ( tests I am going to write that I need to use the local emulator)
|___ .....

所以我想知道如何实现这种测试。等待救援。此外,我得到了firestore模拟器的想法使用这个链接

我也遇到过同样的问题。因为go没有在所有测试之前运行的测试函数,所以没有好的方法在运行之前设置模拟器。

从我所看到的有两个选项:(我希望听到更多的建议)。

  1. 从这里使用emulators:exec scriptpath命令:https://firebase.google.com/docs/emulator-suite/install_and_configure。这将运行模拟器,然后运行脚本,在本例中是go测试。

  2. 编写一个实用程序函数来初始化firebase模拟器。然后,在每个包中,使用TestMain函数设置firebase环境。这将使您能够单独运行每个测试,但在运行整个测试套件时失败。最后一个问题的解决方案是删除go套件的并行处理,类似于:go test ./... -v -race -p 1

  3. 从外部运行模拟器,在测试之外,然后运行测试。这种方法的缺点是,您必须确保在启动测试套件之前手动运行模拟器。您还必须在每次测试后进行清理,这可能会变得很烦人。

我采用了第二种解决方案,但您必须确保模拟器尚未运行,并在每次包测试后终止它。

所以像这样:

shutdownCmd := exec.Command("bash", "-c", fmt.Sprintf("lsof -i tcp:%d | grep LISTEN | awk '{print $2}' | xargs kill -9", firestorePort))

然后你需要运行模拟器:

cmd := exec.Command("firebase", "emulators:start", "--only", "firestore")

您必须侦听模拟器的标准输出并解析它以检查何时:

  1. 模拟器准备就绪
  2. 模拟器无法启动
  3. 模拟器停止

然后,在模拟器启动后,您可以运行

result = m.Run()

这将运行当前包的测试套件。

最后,在对包进行测试之后,您必须向模拟器发送一个关闭信号(SIGINT):

syscall.Kill(cmd.Process.Pid, syscall.SIGINT)

我考虑过将解决方案开源发布,但没有足够的时间把它做得很好。如果你想让我与你分享完整的解决方案,请随时联系我

最新更新