Skip to content

Instantly share code, notes, and snippets.

@zepatrik
Created November 24, 2021 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zepatrik/8616cc59843fd8f4ad88a3fe1e7078b3 to your computer and use it in GitHub Desktop.
Save zepatrik/8616cc59843fd8f4ad88a3fe1e7078b3 to your computer and use it in GitHub Desktop.
Run Ory Keto Server in your Go test suit
package testhelpers
import (
"context"
"fmt"
"net/http"
"os"
"testing"
"time"
"github.com/pkg/errors"
"github.com/ory/keto/cmd"
"github.com/ory/x/cmdx"
"github.com/ory/x/configx"
"github.com/phayes/freeport"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
)
func NewKetoServer(t testing.TB) {
dsn := "sqlite://file::memory:?_fk=true&cache=shared"
ketoFile := "stub/keto.yaml"
if _, err := os.Stat(ketoFile); errors.Is(err, os.ErrNotExist) || errors.Is(err, &os.PathError{}) {
t.Logf("WARN: ./stub/keto.yaml does not exist, creating an empty temporary keto.yaml file")
ketoFile = t.TempDir() + "/keto.yaml"
f, err := os.Create(ketoFile)
require.NoError(t, err)
_, err = f.Write([]byte("{}"))
require.NoError(t, err)
}
ports, err := freeport.GetFreePorts(2)
require.NoError(t, err)
readPort, writePort := ports[0], ports[1]
ctx := configx.ContextWithConfigOptions(context.Background(),
configx.WithValue("dsn", dsn),
configx.WithValue("log.level", "trace"),
configx.WithValue("config", []string{ketoFile}),
configx.WithValue("serve.read.port", readPort),
configx.WithValue("serve.write.port", writePort),
configx.WithValue("namespaces", []interface{}{
map[string]interface{}{
"name": "my-namespace",
"id": 0,
},
}),
)
ctx = context.WithValue(ctx, "dsn", dsn)
ctx, cancel := context.WithCancel(ctx)
t.Cleanup(cancel)
executor := &cmdx.CommandExecuter{New: func() *cobra.Command {
return cmd.NewRootCmd()
}, Ctx: ctx}
go func() {
t.Log("Starting server...")
_ = executor.ExecNoErr(t, "serve", "--config", ketoFile)
}()
readHost := fmt.Sprintf("127.0.0.1:%d", readPort)
writeHost := fmt.Sprintf("127.0.0.1:%d", writePort)
startedAt := time.Now()
for {
_, err := http.Get(fmt.Sprintf("http://%s", readHost))
if err == nil {
break
}
time.Sleep(50 * time.Millisecond)
if time.Now().Sub(startedAt).Seconds() > 5 {
t.Fatalf("Unable to reach server.")
}
}
t.Logf("Server is alive at read (%s) write (%s)", readHost, writeHost)
require.NotEmpty(t, t, readHost)
require.NotEmpty(t, t, writeHost)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment