Files
gochat/backend/scripts/health_check_test.go
T
Rogeeandrogee 798ea43c2f HH-442: isolate runtime processes and harden shutdown (#90)
* HH-442: isolate runtime processes and harden shutdown

* HH-442: harden worker shutdown races

* HH-442: gate dependency shutdown on active handlers

---------

Co-authored-by: Rogee <rogee@ipao.vip>
2026-08-22 02:38:15 +08:00

77 lines
2.2 KiB
Go

package scripts
import (
"encoding/json"
"errors"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"testing"
"github.com/stretchr/testify/require"
)
func TestHealthCheckJSONExitCodes(t *testing.T) {
tests := []struct {
name string
status func(string) int
exitCode int
}{
{name: "healthy", status: func(string) int { return http.StatusOK }, exitCode: 0},
{name: "degraded", status: func(path string) int {
if path == "/metrics" {
return http.StatusServiceUnavailable
}
return http.StatusOK
}, exitCode: 1},
{name: "unhealthy", status: func(path string) int {
if path == "/live" || path == "/ready" {
return http.StatusServiceUnavailable
}
return http.StatusOK
}, exitCode: 2},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(test.status(r.URL.Path))
}))
defer server.Close()
output, exitCode := runHealthScript(t, server.URL, "--json", "--full")
require.Equal(t, test.exitCode, exitCode)
var payload map[string]any
require.NoError(t, json.Unmarshal(output, &payload), string(output))
})
}
}
func TestHealthCheckJSONInvalidInvocation(t *testing.T) {
command := exec.Command("./health_check.sh", "--json", "--timeout")
output, err := command.Output()
var exitErr *exec.ExitError
require.True(t, errors.As(err, &exitErr))
require.Equal(t, 2, exitErr.ExitCode())
require.JSONEq(t, `{"error":"--timeout requires a positive integer","checks":[],"summary":{"critical_failures":1,"degraded_failures":0}}`, string(output))
}
func runHealthScript(t *testing.T, rawURL string, args ...string) ([]byte, int) {
t.Helper()
parsed, err := url.Parse(rawURL)
require.NoError(t, err)
host, port, err := net.SplitHostPort(parsed.Host)
require.NoError(t, err)
command := exec.Command("./health_check.sh", args...)
command.Env = append(os.Environ(), "GOCHAT_HOST="+host, "GOCHAT_PORT="+port, "GOCHAT_METRICS_PORT="+port)
output, err := command.Output()
if err == nil {
return output, 0
}
var exitErr *exec.ExitError
require.True(t, errors.As(err, &exitErr), "health script failed to execute: %v", err)
return output, exitErr.ExitCode()
}