有没有一种简单的方法可以在 Go 测试中模拟 HashiCorp Vault?
不要。使用真实的东西! HashiCorp 为即时启动服务器提供了实用功能1。这使您的测试更加有用,并且通常可以作为开发人员如何设置本地开发服务器的可行指南。
这是一个非常基本的例子。测试框架非常灵活(这也使得它相当复杂)。有关更多选项,请参阅软件包文档,包括在 HA 模式下运行多个服务器。我发现 Vault 自己的测试用例在设置更复杂的场景时非常有用。
package main
import (
"net"
"testing"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/http"
"github.com/hashicorp/vault/vault"
)
func TestVaultStuff(t *testing.T) {
ln, client := createTestVault(t)
defer ln.Close()
// Pass the client to the code under test.
myFunction(client)
}
func createTestVault(t *testing.T) (net.Listener, *api.Client) {
t.Helper()
// Create an in-memory, unsealed core (the "backend", if you will).
core, keyShares, rootToken := vault.TestCoreUnsealed(t)
_ = keyShares
// Start an HTTP server for the core.
ln, addr := http.TestServer(t, core)
// Create a client that talks to the server, initially authenticating with
// the root token.
conf := api.DefaultConfig()
conf.Address = addr
client, err := api.NewClient(conf)
if err != nil {
t.Fatal(err)
}
client.SetToken(rootToken)
// Setup required secrets, policies, etc.
_, err = client.Logical().Write("secret/foo", map[string]interface{}{
"secret": "bar",
})
if err != nil {
t.Fatal(err)
}
return ln, client
}
1 他们为所有项目提供测试服务器,而不仅仅是 Vault。 Mitchell Hashimoto 在his talk on advanced testing 中解释了理性。