package servercmd_test import ( "bytes" "errors" "io" "net/http" "path/filepath" "strings" "testing" servercmd "inbox/internal/servercmd" ) func TestRunValidatesWorkspaceDir(t *testing.T) { if err := servercmd.Run([]string{}, servercmd.RunnerDeps{}); err == nil || !strings.Contains(err.Error(), "--workspaces-dir is required") { t.Fatalf("Run missing dir error = %v", err) } missing := t.TempDir() + "/missing" if err := servercmd.Run([]string{"--workspaces-dir", missing}, servercmd.RunnerDeps{}); err == nil || !strings.Contains(err.Error(), "workspaces-dir does not exist") { t.Fatalf("Run invalid dir error = %v", err) } } func TestRunInitializesRuntimeBuildsMuxAndCallsServer(t *testing.T) { root := t.TempDir() sentinel := errors.New("stop server") var gotAddr string var gotConfig servercmd.Config var initConfig servercmd.Config var stderr bytes.Buffer err := servercmd.Run([]string{"--workspaces-dir", root, "--port", "4321"}, servercmd.RunnerDeps{ StdErr: stderrWriter{&stderr}, InitRuntime: func(cfg servercmd.Config) (io.Closer, error) { initConfig = cfg return nil, nil }, BuildMux: func(cfg servercmd.Config) http.Handler { gotConfig = cfg return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) }) }, ListenAndServe: func(addr string, handler http.Handler) error { gotAddr = addr return sentinel }, }) if !errors.Is(err, sentinel) { t.Fatalf("Run error = %v, want sentinel", err) } if gotAddr != ":4321" { t.Fatalf("listen addr = %q, want :4321", gotAddr) } if gotConfig.WorkspacesDir != root { t.Fatalf("build mux workspaces dir = %q, want %q", gotConfig.WorkspacesDir, root) } if gotConfig.Port != 4321 || gotConfig.Addr != ":4321" { t.Fatalf("unexpected build mux config = %#v", gotConfig) } if initConfig.ProjectRoot != filepath.Dir(root) { t.Fatalf("init runtime project root = %q, want %q", initConfig.ProjectRoot, filepath.Dir(root)) } if !strings.Contains(stderr.String(), "inbox API server listening on http://localhost:4321") { t.Fatalf("stderr = %q, want startup log", stderr.String()) } } type stderrWriter struct { buf *bytes.Buffer } func (w stderrWriter) Write(p []byte) (int, error) { if w.buf == nil { return len(p), nil } return w.buf.Write(p) }