为了账号安全,请及时绑定邮箱和手机立即绑定

在 Go 中模拟 Hashicorp 金库

在 Go 中模拟 Hashicorp 金库

Go
蝴蝶刀刀 2023-07-17 16:58:37
有没有一种简单的方法可以在 go 测试中模拟 Hashicorp 金库?我在 Go 中创建了一个访问 Vault 的服务,并希望为其创建适当的测试。我没有找到我喜欢的简单解决方案(比如 python 中的 moto )。我还尝试在 docker 中以开发模式使用保管库(采用系统测试路线),但我在通过 API 写入它时遇到问题。想法?
查看完整描述

3 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

更新:这个答案已经过时了。

“不幸的是,[这个]答案已经有好几年了。以前它是“尽力而为”的支持,但团队去年决定不再支持在 Go 中导入 Vault、API 或 SDK 作为模块。我带来不便敬请谅解。”

--

有没有一种简单的方法可以在 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。



查看完整回答
反对 回复 2023-07-17
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

需要注意的一件非常重要的事情:

TestCoreUnsealed不使用常规的 KV 后端,而是使用 aPassthroughBackend来本质上模拟 kv 行为。

查看完整回答
反对 回复 2023-07-17
?
婷婷同学_

TA贡献1844条经验 获得超8个赞

因为 Go 是一种静态类型语言,所以我们必须在编译时知道事物的类型。因此,要进行这种类型的独立测试,我们需要在代码中创建在测试方面具有逻辑意义的边界。

在 Go 中创建接口来定义这些边界,因此从这个意义上说,您希望在您和此第三方库之间创建一个接口,以便您可以用您可以控制的函数/方法/类型替换库函数/方法/类型的输入和输出并定义了条件,以便您可以测试代码对第三方的输出或条件的行为方式。

查看完整回答
反对 回复 2023-07-17
  • 3 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信