Files
2026-09-24 09:52:57 +01:00

87 lines
1.6 KiB
Go

package main
import (
"context"
"os"
"testing"
"time"
"git.i3omb.com/gronod/ha-n95-local-control/internal/config"
"git.i3omb.com/gronod/ha-n95-local-control/internal/httpx"
)
func withCleanEnv(t *testing.T, pairs ...string) {
t.Helper()
old := os.Environ()
t.Cleanup(func() {
os.Clearenv()
for _, e := range old {
if i := len("="); i > 0 {
// Split at first '='.
k, v, _ := splitEnv(e)
os.Setenv(k, v)
}
}
})
os.Clearenv()
for _, p := range pairs {
k, v, _ := splitEnv(p)
os.Setenv(k, v)
}
}
func splitEnv(e string) (string, string, bool) {
for i := 0; i < len(e); i++ {
if e[i] == '=' {
return e[:i], e[i+1:], true
}
}
return e, "", false
}
func TestHealthcheckSubcommandLive(t *testing.T) {
withCleanEnv(t,
"ADVERTISE_IP=192.0.2.10",
"MQTT_HOST=mqtt.example.invalid",
"HEALTH_PORT=18080",
)
cfg, err := config.Load(os.Environ())
if err != nil {
t.Fatalf("load config: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
_ = httpx.ServeHealth(ctx, cfg)
}()
defer func() {
cancel()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("server did not stop")
}
}()
time.Sleep(50 * time.Millisecond)
if got := healthcheck(); got != 0 {
t.Fatalf("healthcheck returned %d, want 0", got)
}
}
func TestHealthcheckSubcommandClosedPort(t *testing.T) {
withCleanEnv(t,
"ADVERTISE_IP=192.0.2.10",
"MQTT_HOST=mqtt.example.invalid",
"HEALTH_PORT=18080",
)
if got := healthcheck(); got != 1 {
t.Fatalf("healthcheck returned %d, want 1", got)
}
}