登录
首页 >  Golang >  Go问答

在 Go 中模拟 Hashicorp 金库

来源:stackoverflow

时间:2024-04-27 22:00:34 262浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《在 Go 中模拟 Hashicorp 金库》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

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

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

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


解决方案


更新:此答案已过时。根据vault github上的this issue

“不幸的是,[这个]答案已经有好几年了。以前它是“尽力而为”的支持,但团队去年决定不再支持将 vault、api 或 sdk 作为模块导入到 go 中。对于给您带来的不便,我们深表歉意。”

--

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

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

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

请参阅下面的接口示例。

https://gobyexample.com/interfaces

如果您分享一些示例代码,也许我们可以更具体一点,并为您提供一些代码示例。

今天关于《在 Go 中模拟 Hashicorp 金库》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>