Is there an easy way to mock HashiCorp Vault in Go tests?
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.
Here is a very basic example. The testing framework is very flexible (which also makes them 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 They provide test servers for all of their projects, not just Vault. Mitchell Hashimoto explained the rational in his talk on advanced testing.