Parent directory

helpers_test.go

2754 bytes
 1package cmd
 2
 3import (
 4	"bytes"
 5	"context"
 6	"testing"
 7
 8	"github.com/charmbracelet/soft-serve/pkg/backend"
 9	"github.com/charmbracelet/soft-serve/pkg/config"
10	"github.com/charmbracelet/soft-serve/pkg/db"
11	"github.com/charmbracelet/soft-serve/pkg/db/migrate"
12	"github.com/charmbracelet/soft-serve/pkg/proto"
13	"github.com/charmbracelet/soft-serve/pkg/store"
14	"github.com/charmbracelet/soft-serve/pkg/store/database"
15	"github.com/matryer/is"
16	_ "modernc.org/sqlite"
17)
18
19// newAuthTestContext returns a context wired with a config and a real
20// migrated SQLite-backed backend, plus the backend itself so tests can set up
21// users and repositories.
22//
23// No user is attached to the returned context; use withUser to authenticate
24// as somebody.
25func newAuthTestContext(t *testing.T) (context.Context, *backend.Backend) {
26	t.Helper()
27	is := is.New(t)
28	ctx := context.Background()
29
30	dp := t.TempDir()
31	cfg := config.DefaultConfig()
32	cfg.DataPath = dp
33	cfg.DB.Driver = "sqlite"
34	cfg.DB.DataSource = dp + "/test.db"
35
36	ctx = config.WithContext(ctx, cfg)
37	dbx, err := db.Open(ctx, cfg.DB.Driver, cfg.DB.DataSource)
38	is.NoErr(err)
39	t.Cleanup(func() { dbx.Close() }) //nolint:errcheck
40
41	is.NoErr(migrate.Migrate(ctx, dbx))
42	ctx = db.WithContext(ctx, dbx)
43	dbstore := database.New(ctx, dbx)
44	ctx = store.WithContext(ctx, dbstore)
45	be := backend.New(ctx, cfg, dbx, dbstore)
46	ctx = backend.WithContext(ctx, be)
47
48	return ctx, be
49}
50
51// withUser creates a user and returns a context authenticated as them.
52func withUser(t *testing.T, ctx context.Context, be *backend.Backend, username string, admin bool) context.Context {
53	t.Helper()
54	is := is.New(t)
55	user, err := be.CreateUser(ctx, username, proto.UserOptions{Admin: admin})
56	is.NoErr(err)
57	return proto.WithUserContext(ctx, user)
58}
59
60// runRepo runs a `repo` subcommand and returns only its error.
61func runRepo(t *testing.T, ctx context.Context, args ...string) error {
62	t.Helper()
63	_, _, err := runRepoOutput(t, ctx, args...)
64	return err
65}
66
67// runRepoOutput runs a `repo` subcommand and returns its stdout and stderr
68// alongside the error, so tests can assert that sensitive values were not
69// printed even when a command fails.
70func runRepoOutput(t *testing.T, ctx context.Context, args ...string) (stdout, stderr string, err error) {
71	t.Helper()
72	c := RepoCommand()
73	var outBuf, errBuf bytes.Buffer
74	c.SetOut(&outBuf)
75	c.SetErr(&errBuf)
76	c.SetArgs(args)
77	err = c.ExecuteContext(ctx)
78	return outBuf.String(), errBuf.String(), err
79}
80
81// runUser runs a `user` subcommand and returns only its error.
82func runUser(t *testing.T, ctx context.Context, args ...string) error {
83	t.Helper()
84	c := UserCommand()
85	var outBuf, errBuf bytes.Buffer
86	c.SetOut(&outBuf)
87	c.SetErr(&errBuf)
88	c.SetArgs(args)
89	return c.ExecuteContext(ctx)
90}