isle/go/cmd/entrypoint/main_test.go

78 lines
1.7 KiB
Go

package main
import (
"bytes"
"context"
"isle/daemon"
"isle/daemon/jsonrpc2"
"isle/toolkit"
"net/http/httptest"
"reflect"
"testing"
"dev.mediocregopher.com/mediocre-go-lib.git/mlog"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v3"
)
type runHarness struct {
ctx context.Context
logger *mlog.Logger
stdout *bytes.Buffer
daemonRPC *daemon.MockRPC
daemonRPCServer *httptest.Server
}
func newRunHarness(t *testing.T) *runHarness {
t.Parallel()
var (
ctx = context.Background()
logger = toolkit.NewTestLogger(t)
stdout = new(bytes.Buffer)
daemonRPC = daemon.NewMockRPC(t)
daemonRPCHandler = jsonrpc2.NewHTTPHandler(daemon.NewRPCHandler(
logger.WithNamespace("rpc"), daemonRPC,
))
daemonRPCServer = httptest.NewServer(daemonRPCHandler)
)
t.Cleanup(daemonRPCServer.Close)
return &runHarness{ctx, logger, stdout, daemonRPC, daemonRPCServer}
}
func (h *runHarness) run(t *testing.T, args ...string) error {
httpClient := toolkit.NewHTTPClient(h.logger.WithNamespace("http"))
t.Cleanup(func() {
assert.NoError(t, httpClient.Close())
})
daemonRPCClient := daemon.RPCFromClient(
jsonrpc2.NewHTTPClient(httpClient, h.daemonRPCServer.URL),
)
return doRootCmd(h.ctx, h.logger, &subCmdCtxOpts{
args: args,
daemonRPC: daemonRPCClient,
stdout: h.stdout,
})
}
func (h *runHarness) runAssertStdout(
t *testing.T,
want any,
args ...string,
) {
var (
gotType = reflect.ValueOf(want)
got = reflect.New(gotType.Type())
)
h.stdout.Reset()
assert.NoError(t, h.run(t, args...))
assert.NoError(t, yaml.Unmarshal(h.stdout.Bytes(), got.Interface()))
assert.Equal(t, want, got.Elem().Interface())
}