1package testscript
2
3import (
4 "context"
5 "flag"
6 "fmt"
7 "net"
8 "os"
9 "path/filepath"
10 "strings"
11 "sync"
12 "testing"
13 "time"
14
15 "github.com/charmbracelet/soft-serve/server"
16 "github.com/charmbracelet/soft-serve/server/config"
17 "github.com/charmbracelet/soft-serve/server/test"
18 "github.com/rogpeppe/go-internal/testscript"
19)
20
21var update = flag.Bool("update", false, "update script files")
22
23func TestScript(t *testing.T) {
24 flag.Parse()
25 var lock sync.Mutex
26
27 t.Setenv("SOFT_SERVE_TEST_NO_HOOKS", "1")
28
29 // we'll use this key to talk with soft serve, and since testscript changes
30 // the cwd, we need to get its full path here
31 key, err := filepath.Abs("./testdata/admin1")
32 if err != nil {
33 t.Fatal(err)
34 }
35
36 // git does not handle 0600, and on clone, will save the files with its
37 // default perm, 0644, which is too open for ssh.
38 for _, f := range []string{
39 "admin1",
40 "admin2",
41 "user1",
42 "user2",
43 } {
44 if err := os.Chmod(filepath.Join("./testdata/", f), 0o600); err != nil {
45 t.Fatal(err)
46 }
47 }
48
49 sshArgs := []string{
50 "-F", "/dev/null",
51 "-o", "StrictHostKeyChecking=no",
52 "-o", "UserKnownHostsFile=/dev/null",
53 "-o", "IdentityAgent=none",
54 "-o", "IdentitiesOnly=yes",
55 "-i", key,
56 }
57
58 check := func(ts *testscript.TestScript, err error, neg bool) {
59 if neg && err == nil {
60 ts.Fatalf("expected error, got nil")
61 }
62 if !neg {
63 ts.Check(err)
64 }
65 }
66
67 testscript.Run(t, testscript.Params{
68 Dir: "testdata/script",
69 UpdateScripts: *update,
70 Cmds: map[string]func(ts *testscript.TestScript, neg bool, args []string){
71 "soft": func(ts *testscript.TestScript, neg bool, args []string) {
72 // TODO: maybe use plain ssh client here?
73 args = append(
74 sshArgs,
75 append([]string{
76 "-p", ts.Getenv("SSH_PORT"),
77 "localhost",
78 "--",
79 }, args...)...,
80 )
81 check(ts, ts.Exec("ssh", args...), neg)
82 },
83 "git": func(ts *testscript.TestScript, _ bool, args []string) {
84 ts.Setenv(
85 "GIT_SSH_COMMAND",
86 strings.Join(append([]string{"ssh"}, sshArgs...), " "),
87 )
88 ts.Check(ts.Exec("git", args...))
89 },
90 "mkreadme": func(ts *testscript.TestScript, _ bool, args []string) {
91 if len(args) != 1 {
92 ts.Fatalf("must have exactly 1 arg, the filename, got %d", len(args))
93 }
94 ts.Check(os.WriteFile(ts.MkAbs(args[0]), []byte("# example\ntest project"), 0o644))
95 },
96 },
97 Setup: func(e *testscript.Env) error {
98 sshPort := test.RandomPort()
99 e.Setenv("SSH_PORT", fmt.Sprintf("%d", sshPort))
100 data := t.TempDir()
101 cfg := config.Config{
102 Name: "Test Soft Serve",
103 DataPath: data,
104 InitialAdminKeys: []string{
105 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJI/1tawpdPmzuJcTGTJ+QReqB6cRUdKj4iQIdJUFdrl",
106 },
107 SSH: config.SSHConfig{
108 ListenAddr: fmt.Sprintf("localhost:%d", sshPort),
109 PublicURL: fmt.Sprintf("ssh://localhost:%d", sshPort),
110 KeyPath: filepath.Join(data, "ssh", "soft_serve_host_ed25519"),
111 ClientKeyPath: filepath.Join(data, "ssh", "soft_serve_client_ed25519"),
112 },
113 Git: config.GitConfig{
114 ListenAddr: fmt.Sprintf("localhost:%d", test.RandomPort()),
115 IdleTimeout: 3,
116 MaxConnections: 32,
117 },
118 HTTP: config.HTTPConfig{
119 ListenAddr: fmt.Sprintf("localhost:%d", test.RandomPort()),
120 PublicURL: fmt.Sprintf("http://localhost:%d", test.RandomPort()),
121 },
122 Stats: config.StatsConfig{
123 ListenAddr: fmt.Sprintf("localhost:%d", test.RandomPort()),
124 },
125 Log: config.LogConfig{
126 Format: "text",
127 TimeFormat: time.DateTime,
128 },
129 }
130 ctx := config.WithContext(context.Background(), &cfg)
131
132 // prevent race condition in lipgloss...
133 // this will probably be autofixed when we start using the colors
134 // from the ssh session instead of the server.
135 // XXX: take another look at this soon
136 lock.Lock()
137 srv, err := server.NewServer(ctx)
138 if err != nil {
139 return err
140 }
141 lock.Unlock()
142
143 go func() {
144 if err := srv.Start(); err != nil {
145 e.T().Fatal(err)
146 }
147 }()
148
149 e.Defer(func() {
150 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
151 defer cancel()
152 if err := srv.Shutdown(ctx); err != nil {
153 e.T().Fatal(err)
154 }
155 })
156
157 // wait until the server is up
158 for {
159 conn, _ := net.DialTimeout(
160 "tcp",
161 net.JoinHostPort("localhost", fmt.Sprintf("%d", sshPort)),
162 time.Second,
163 )
164 if conn != nil {
165 conn.Close()
166 break
167 }
168 }
169
170 return nil
171 },
172 })
173}