package main import ( "context" "io" "net/http" "os" "path/filepath" "strings" "testing" "time" "git.asio.asia/nixevol/NixMsg/internal/config" ) func TestServeHealthzAndListenAddr(t *testing.T) { t.Parallel() dataDir := t.TempDir() cfgPath := filepath.Join(dataDir, "config.yaml") cfgYAML := []byte("listen: \"127.0.0.1:0\"\ndata_dir: \"" + filepath.ToSlash(dataDir) + "\"\n") if err := os.WriteFile(cfgPath, cfgYAML, 0o644); err != nil { t.Fatal(err) } cfg, err := config.Load(cfgPath) if err != nil { t.Fatal(err) } 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(5 * 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) } 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(5 * time.Second): t.Fatal("serve did not stop") } }