Files
nmon/internal/app/lifecycle_test.go
Vibe Coder 3a6afdda08
Some checks failed
ci / lint (push) Successful in 1m19s
ci / openapi (push) Successful in 28s
ci / postgres (push) Successful in 3m32s
ci / test (push) Failing after 8m34s
Fix two integration test failures seen in CI
TestRunReturnsStartError expected a start with no TLS flags to fail;
since the first-install wizard that start succeeds (install mode with
a self-signed certificate) and Run blocked until the 10 min timeout.
Use --tls-cert without --tls-key, which is always refused.

TestICMPStateMachine could advance the fake clock twice in one step on
a slow runner, firing an extra probe ([1 1 1 0 0 1 1]). Advance once,
only after the ICMP loop has re-armed its timer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017TuKgyKve2XLFtrrXWMi2w
2026-10-25 21:30:41 +00:00

318 lines
8.9 KiB
Go

package app
import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"github.com/v10networks/nmon/internal/clock"
"github.com/v10networks/nmon/internal/config"
"github.com/v10networks/nmon/internal/store"
"github.com/v10networks/nmon/internal/testutil"
)
// fakeMetricStore answers the one thing the supervisor asks of an external
// store, /health, and accepts any write.
func fakeMetricStore(t *testing.T) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/health" {
_, _ = w.Write([]byte("OK"))
return
}
w.WriteHeader(http.StatusNoContent)
}))
t.Cleanup(srv.Close)
return srv
}
// flagsFor returns flags that start a full server on loopback with external metric stores.
func flagsFor(t *testing.T, vm string) config.Flags {
t.Helper()
return config.Flags{
DataDir: filepath.Join(t.TempDir(), "data"),
SecretKeyFile: filepath.Join(t.TempDir(), "secret.key"),
Listen: "127.0.0.1:0",
InsecureHTTP: true,
VMHotURL: vm,
VMLongURL: vm,
}
}
func stopApp(t *testing.T, a *App) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := a.Stop(ctx); err != nil {
t.Errorf("stop: %v", err)
}
}
func TestStartServesAPIAndStopsCleanly(t *testing.T) {
vm := fakeMetricStore(t)
f := flagsFor(t, vm.URL)
f.TrapListen = "127.0.0.1:0"
a, err := Start(context.Background(), f)
if err != nil {
t.Fatal(err)
}
addr := a.Addr()
resp, err := http.Get("http://" + addr + "/openapi.json")
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("GET /openapi.json = %d", resp.StatusCode)
}
if a.HotURL() != vm.URL {
t.Errorf("HotURL = %q, want the external store %q", a.HotURL(), vm.URL)
}
if _, err := os.Stat(f.SecretKeyFile); err != nil {
t.Errorf("first run did not generate the key: %v", err)
}
stopApp(t, a)
stopApp(t, a) // idempotent
if c, err := net.DialTimeout("tcp", addr, time.Second); err == nil {
_ = c.Close()
t.Error("API still accepts connections after Stop")
}
}
func TestStartWithTrapReceiverDisabled(t *testing.T) {
vm := fakeMetricStore(t)
a, err := Start(context.Background(), flagsFor(t, vm.URL))
if err != nil {
t.Fatal(err)
}
defer stopApp(t, a)
if a.traps != nil {
t.Error("an empty --trap-listen must leave the receiver off")
}
}
func TestStartTwiceReusesKeyAndInventory(t *testing.T) {
vm := fakeMetricStore(t)
f := flagsFor(t, vm.URL)
a, err := Start(context.Background(), f)
if err != nil {
t.Fatal(err)
}
stopApp(t, a)
key, _ := os.ReadFile(f.SecretKeyFile)
b, err := Start(context.Background(), f)
if err != nil {
t.Fatalf("second start over the same data dir: %v", err)
}
defer stopApp(t, b)
if again, _ := os.ReadFile(f.SecretKeyFile); !bytes.Equal(key, again) {
t.Error("the key changed between runs")
}
}
func TestStartFailureStopsWhatCameUp(t *testing.T) {
vm := fakeMetricStore(t)
busy, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = busy.Close() }()
f := flagsFor(t, vm.URL)
f.Listen = busy.Addr().String()
a, err := Start(context.Background(), f)
if err == nil || !strings.Contains(err.Error(), "listen") {
if a != nil {
stopApp(t, a)
}
t.Fatalf("error %v, want a listen failure", err)
}
// Start unwound the inventory and metric stores it had brought up, so a second start over the same data dir works.
f.Listen = "127.0.0.1:0"
b, err := Start(context.Background(), f)
if err != nil {
t.Fatalf("restart after a failed start: %v", err)
}
stopApp(t, b)
}
func TestStartRefusesUnusableConfiguration(t *testing.T) {
vm := fakeMetricStore(t)
for name, tc := range map[string]struct {
mut func(*config.Flags)
want string
}{
"postgres needs a dsn": {func(f *config.Flags) { f.DBDriver = "postgres" }, "--db-dsn is required"},
"invalid config.yaml": {func(f *config.Flags) {
if err := os.MkdirAll(f.DataDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(config.File(f.DataDir), []byte("retention:\n hot: 1h\n"), 0o600); err != nil {
t.Fatal(err)
}
}, "retention.hot"},
"unreadable key": {func(f *config.Flags) {
if err := os.WriteFile(f.SecretKeyFile, []byte("not a key"), 0o600); err != nil {
t.Fatal(err)
}
}, "secret key"},
} {
t.Run(name, func(t *testing.T) {
f := flagsFor(t, vm.URL)
tc.mut(&f)
a, err := Start(context.Background(), f)
if err == nil {
stopApp(t, a)
t.Fatal("started")
}
if !strings.Contains(err.Error(), tc.want) {
t.Fatalf("error %q, want it to mention %q", err, tc.want)
}
})
}
}
func TestResolveSettingsAppliesDefaults(t *testing.T) {
dir := t.TempDir()
s, err := resolveSettings(config.Flags{DataDir: dir, InsecureHTTP: true})
if err != nil {
t.Fatal(err)
}
if s.Listen != DefaultListen || s.keyFile != DefaultSecretKeyFile || s.MaxInflight <= 0 {
t.Errorf("defaults not applied: %+v", s)
}
if s.driver != "sqlite" || s.dsn != config.InventoryDB(dir) {
t.Errorf("driver %q dsn %q", s.driver, s.dsn)
}
if !reflect.DeepEqual(s.cfg, config.Default()) {
t.Errorf("config %+v", s.cfg)
}
}
func TestRunStopsWhenContextEnds(t *testing.T) {
vm := fakeMetricStore(t)
f := flagsFor(t, vm.URL)
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
f.Listen = l.Addr().String()
_ = l.Close() // Run binds it again; Run has no ready signal, so the test polls the port
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan error, 1)
go func() { done <- Run(ctx, f) }()
deadline := time.Now().Add(20 * time.Second)
for {
if c, err := net.Dial("tcp", f.Listen); err == nil {
_ = c.Close()
break
}
if time.Now().After(deadline) {
t.Fatal("Run never started listening")
}
time.Sleep(20 * time.Millisecond)
}
cancel()
select {
case err := <-done:
if err != nil {
t.Fatalf("Run: %v", err)
}
case <-time.After(20 * time.Second):
t.Fatal("Run did not return after its context ended")
}
}
func TestRunReturnsStartError(t *testing.T) {
// No TLS flags is no longer an error (install mode serves a self-signed certificate), so use a flag combination
// that is always refused.
f := config.Flags{DataDir: t.TempDir(), TLSCert: "cert.pem"}
if err := Run(context.Background(), f); err == nil {
t.Fatal("expected the --tls-cert without --tls-key refusal")
}
}
func TestStopRunsStepsInReverseStartOrderAndJoinsErrors(t *testing.T) {
a := &App{log: testLogger()}
var order []string
for _, n := range []string{"inventory", "metric stores", "poller", "http"} {
a.onStop(n, func(context.Context) error {
order = append(order, n)
if n == "poller" {
return errors.New("boom")
}
return nil
})
}
err := a.Stop(context.Background())
if got := strings.Join(order, ","); got != "http,poller,metric stores,inventory" {
t.Errorf("order %s", got)
}
if err == nil || !strings.Contains(err.Error(), "stop poller: boom") {
t.Errorf("error %v", err)
}
if len(order) != 4 {
t.Errorf("a failing step must not skip the later ones: %v", order)
}
}
func TestStopAfterNothingStartedIsSafe(t *testing.T) {
if err := (&App{log: testLogger()}).Stop(context.Background()); err != nil {
t.Fatal(err)
}
}
func TestLogTrapsDownExplainsPermissionDenied(t *testing.T) {
var buf bytes.Buffer
a := &App{log: slog.New(slog.NewTextHandler(&buf, nil))}
a.logTrapsDown(":162", fmt.Errorf("listen: %w", os.ErrPermission))
if !strings.Contains(buf.String(), "CAP_NET_BIND_SERVICE") {
t.Errorf("no capability hint: %s", buf.String())
}
buf.Reset()
a.logTrapsDown(":162", errors.New("address in use"))
if strings.Contains(buf.String(), "CAP_NET_BIND_SERVICE") || !strings.Contains(buf.String(), "address in use") {
t.Errorf("unexpected: %s", buf.String())
}
}
func TestDiscoverableListsOnlyEnabledNetworkDevicesWithCredentials(t *testing.T) {
ctx := context.Background()
st := testutil.OpenStore(t, clock.Real())
cred := &store.SNMPCredential{Name: "c", Version: "v2c", Community: "public"}
if err := st.CreateCredential(ctx, cred); err != nil {
t.Fatal(err)
}
add := func(d *store.Device) *store.Device {
t.Helper()
if err := st.CreateDevice(ctx, d); err != nil {
t.Fatal(err)
}
return d
}
live := add(&store.Device{Name: "live", Kind: store.KindNetwork, SNMPCredentialID: &cred.ID, Enabled: true, Profile: "generic"})
add(&store.Device{Name: "disabled", Kind: store.KindNetwork, SNMPCredentialID: &cred.ID, Enabled: false, Profile: "generic"})
add(&store.Device{Name: "nocred", Kind: store.KindNetwork, Enabled: true, Profile: "generic"})
add(&store.Device{Name: "check", Kind: store.KindCheckOnly, Enabled: true, Profile: "generic"})
a := &App{st: st, log: testLogger()}
ids, err := a.discoverable(ctx)
if err != nil {
t.Fatal(err)
}
if len(ids) != 1 || ids[0] != live.ID {
t.Fatalf("discoverable = %v, want only %d", ids, live.ID)
}
}