【问题标题】:Mocking Hashicorp vault in Go在 Go 中模拟 Hashicorp 保险库
【发布时间】:2020-01-06 08:01:11
【问题描述】:

有没有一种简单的方法可以在 go 测试中模拟 Hashicorp 保险库?

我在 Go 中创建了一个访问 Vault 的服务,并希望为其创建适当的测试。

我没有找到我喜欢的简单解决方案(比如 python 中的 moto)。 我还尝试在 docker 中以开发模式使用保管库(采用系统测试路线),但我无法通过 API 写入它。 想法?

【问题讨论】:

  • 在单元测试中,你不会模拟你不拥有的类型/服务(相反 - 你模拟你自己的服务/存储库,提供对这些 3rd 方资源的访问)。在功能/集成测试中,您也不会模拟它们,而是针对它们进行测试。

标签: go integration-testing hashicorp-vault


【解决方案1】:

有没有一种简单的方法可以在 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 中解释了理性。

【讨论】:

  • 哇,这太棒了,正是我需要的。
【解决方案2】:

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

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

请参阅下面的接口示例。

https://gobyexample.com/interfaces

如果你分享一些示例代码,也许我们可以更具体一点,并给你一些代码示例。

【讨论】:

    【解决方案3】:

    需要注意的一个超级重要的事情:

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

    关注这个问题,我花了 4 天时间调试这个

    https://github.com/hashicorp/vault/issues/8440

    【讨论】:

      猜你喜欢
      • 2023-03-02
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 2022-08-08
      • 1970-01-01
      • 2023-02-03
      相关资源
      最近更新 更多