在Go中模拟Hashicorp保险库 [英] Mocking Hashicorp vault in Go
问题描述
在去测试中,有没有一种简单的方法可以模拟Hashicorp保险库?
Is there an easy way to mock Hashicorp vault in go tests ?
我在Go中创建了一个可访问保险柜的服务,并希望为其创建适当的测试.
I created a service in Go that accesses Vault, and would like to create proper testing for it.
我没有找到我喜欢的简单解决方案(例如python中的moto). 我还尝试在docker中以dev模式使用Vault(采用系统测试路线),但是我无法通过API写入文件. 想法?
I didn't find a simple solution I like (like moto in python). I also tried using a vault in dev mode in docker (take the system test route) but I have trouble writing to it via API. Ideas ?
推荐答案
在Go测试中,有没有一种简单的方法可以模拟HashiCorp Vault?
Is there an easy way to mock HashiCorp Vault in Go tests?
不要.使用真实的东西! HashiCorp提供有用的实用程序功能来动态启动服务器 1 .这使您的测试更加有用,并且经常可以作为开发人员如何设置本地开发服务器的可行指南.
Don't. Use the real thing! HashiCorp helpfully provides utility functions for starting a server on the fly1. This makes your tests much more useful, and can often serve as an actionable guide for developers on how to setup local development servers too.
这是一个非常基本的例子.测试框架非常灵活(这也使它变得相当复杂).请参阅软件包文档以获取更多选项,包括以HA模式运行多个服务器.在设置更复杂的方案时,我发现Vault自己的测试用例非常有用.
Here is a very basic example. The testing framework is very flexible (which also makes it fairly complicated). Refer to the package documentations for more options, including running multiple servers in HA mode. I found Vault's own test cases very useful when setting up more complicated scenarios.
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)在他对高级测试的讨论中解释了其合理性.
1 They provide test servers for all of their projects, not just Vault. Mitchell Hashimoto explained the rational in his talk on advanced testing.
这篇关于在Go中模拟Hashicorp保险库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!