Files
NixMsg/cmd/nixmsg/serve_test.go

135 lines
3.0 KiB
Go

package main
import (
"context"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.asio.asia/nixevol/NixMsg/internal/auth"
"git.asio.asia/nixevol/NixMsg/internal/config"
"git.asio.asia/nixevol/NixMsg/internal/store"
)
func writeTestConfig(t *testing.T, dataDir string) string {
t.Helper()
cfgPath := filepath.Join(dataDir, "config.yaml")
cfgYAML := []byte("listen: \"127.0.0.1:0\"\ndata_dir: \"" + filepath.ToSlash(dataDir) + "\"\nlog:\n level: error\n")
if err := os.WriteFile(cfgPath, cfgYAML, 0o644); err != nil {
t.Fatal(err)
}
return cfgPath
}
func initAdminForTest(t *testing.T, dataDir string) {
t.Helper()
db, err := store.Open(dataDir, "FULL")
if err != nil {
t.Fatal(err)
}
defer func() { _ = db.Close() }()
phc, err := auth.HashPassword("test-admin-password-xx")
if err != nil {
t.Fatal(err)
}
if err := store.SetAdminPasswordHash(context.Background(), db.Write, phc); err != nil {
t.Fatal(err)
}
}
func TestServeHealthzAndListenAddr(t *testing.T) {
t.Parallel()
dataDir := t.TempDir()
cfgPath := writeTestConfig(t, dataDir)
initAdminForTest(t, dataDir)
cfg, err := config.Load(cfgPath)
if err != nil {
t.Fatal(err)
}
if vErr := cfg.Validate(); vErr != nil {
t.Fatal(vErr)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
errCh := make(chan error, 1)
go func() {
errCh <- runServe(ctx, cfg)
}()
var addr string
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
b, readErr := os.ReadFile(filepath.Join(dataDir, "listen.addr"))
if readErr == nil {
addr = strings.TrimSpace(string(b))
if addr != "" {
break
}
}
time.Sleep(20 * time.Millisecond)
}
if addr == "" {
t.Fatal("listen.addr not written")
}
resp, err := http.Get("http://" + addr + "/healthz")
if err != nil {
t.Fatalf("healthz: %v", err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status=%d body=%s", resp.StatusCode, body)
}
if string(body) != "ok" {
t.Fatalf("unexpected body: %q", body)
}
ready, err := http.Get("http://" + addr + "/readyz")
if err != nil {
t.Fatalf("readyz: %v", err)
}
defer func() { _ = ready.Body.Close() }()
if ready.StatusCode != http.StatusOK {
t.Fatalf("readyz status=%d", ready.StatusCode)
}
if _, err := os.Stat(filepath.Join(dataDir, "nixmsg.db")); err != nil {
t.Fatalf("db missing: %v", err)
}
cancel()
select {
case err := <-errCh:
if err != nil {
t.Fatalf("serve exit: %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("serve did not stop")
}
}
func TestServeRejectsWithoutAdmin(t *testing.T) {
t.Parallel()
dataDir := t.TempDir()
cfgPath := writeTestConfig(t, dataDir)
cfg, err := config.Load(cfgPath)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err = runServe(ctx, cfg)
if err == nil || !strings.Contains(err.Error(), "admin password") {
t.Fatalf("want admin init error, got %v", err)
}
}