package tui import ( "net" "net/netip" "slices" "strings" "testing" "time" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/x/ansi" "github.com/mattn/go-runewidth" "nscan/internal/oui" "nscan/internal/scanner" "nscan/internal/store" ) func testModel(t *testing.T) *model { t.Helper() st, err := store.Open(t.TempDir()) if err != nil { t.Fatal(err) } targets, _ := scanner.ParseRange("192.168.1.0/24") return newModel(Config{ Network: &scanner.Network{ Iface: &net.Interface{Name: "en0"}, LocalIP: netip.MustParseAddr("192.168.1.10"), Prefix: netip.MustParsePrefix("192.168.1.10/24"), Gateway: netip.MustParseAddr("192.168.1.1"), }, Range: "192.168.1.0/24", Targets: targets, Interval: time.Minute, Store: st, }) } func host(ip, mac string) scanner.Host { h := scanner.Host{IP: netip.MustParseAddr(ip), RTT: 2 * time.Millisecond, Via: "icmp"} if mac != "" { h.MAC, _ = net.ParseMAC(mac) } return h } func TestUpsertRekeysByMAC(t *testing.T) { m := testModel(t) m.upsert(host("192.168.1.20", "")) if m.devs["ip:192.168.1.20"] == nil { t.Fatal("ip-keyed row missing") } m.upsert(host("192.168.1.20", "aa:bb:cc:00:00:01")) if m.devs["ip:192.168.1.20"] != nil || m.devs["aa:bb:cc:00:00:01"] == nil || len(m.devs) != 1 { t.Fatalf("rows after MAC arrived: %v", keys(m)) } // A later ICMP-only result for the same IP lands on the MAC row. m.upsert(scanner.Host{IP: netip.MustParseAddr("192.168.1.20"), MDNSName: "nas"}) if len(m.devs) != 1 || m.devs["aa:bb:cc:00:00:01"].host.MDNSName != "nas" { t.Fatalf("rows: %v", keys(m)) } } func keys(m *model) []string { var ks []string for k := range m.devs { ks = append(ks, k) } return ks } func TestScanCycleAndViews(t *testing.T) { m := testModel(t) m.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) m.scanning, m.scanNo = true, 1 hosts := []scanner.Host{ host("192.168.1.1", "3c:a6:2f:00:00:01"), host("192.168.1.10", "f0:18:9b:00:00:02"), host("192.168.1.33", "b8:27:eb:00:00:03"), } hosts[0].Gateway = true hosts[1].Self = true hosts[2].MDNSName = "raspberrypi" hosts[2].Services = []scanner.Service{{Type: "_ssh._tcp", Instance: "raspberrypi", Port: 22}} for _, h := range hosts { m.Update(scanHostMsg{1, h}) } m.Update(scanDoneMsg{no: 1, hosts: hosts, dur: time.Second}) if len(m.list) != 3 { t.Fatalf("list has %d rows", len(m.list)) } // Second scan without the Pi: it goes offline and leaves the plain list. m.scanning, m.scanNo = true, 2 m.Update(scanDoneMsg{no: 2, hosts: hosts[:2], dur: time.Second}) if len(m.list) != 2 { t.Fatalf("list has %d rows after the Pi vanished", len(m.list)) } m.Update(key("c")) if len(m.list) != 3 { t.Fatalf("cumulative list has %d rows", len(m.list)) } press := func(keys ...string) { for _, k := range keys { m.Update(key(k)) } } for _, size := range [][2]int{{120, 30}, {80, 24}, {40, 12}, {200, 60}} { m.Update(tea.WindowSizeMsg{Width: size[0], Height: size[1]}) check := func(view string) { t.Helper() out := m.View() lines := strings.Split(out, "\n") for i, l := range lines { if w := ansi.StringWidth(l); w > size[0] { t.Errorf("%s at %dx%d: line %d is %d wide", view, size[0], size[1], i, w) } } if len(lines) > size[1] { t.Errorf("%s at %dx%d: %d lines", view, size[0], size[1], len(lines)) } } check("list") press("enter") check("detail") press("esc", "h") check("history") press("z") check("history daily") press("esc", "?") check("help") press("esc", "v") check("columns") press("esc") } // Rename via the input line. m.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) press("home", "n") for _, r := range "Router" { m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}}) } m.Update(tea.KeyMsg{Type: tea.KeyEnter}) sel := m.selected() if got := m.label(sel); !strings.HasPrefix(got, "Router") { t.Errorf("label after rename = %q", got) } if !strings.Contains(m.View(), "Router") { t.Error("renamed device not shown") } } func key(s string) tea.KeyMsg { switch s { case "enter": return tea.KeyMsg{Type: tea.KeyEnter} case "esc": return tea.KeyMsg{Type: tea.KeyEsc} case "home": return tea.KeyMsg{Type: tea.KeyHome} } return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} } func TestStoredDevicesGetVendor(t *testing.T) { m := testModel(t) m.cfg.Store.Update("da:a1:19:00:00:01", func(d *store.Device) { d.IP, d.MAC, d.Vendor = "192.168.1.50", "da:a1:19:00:00:01", "Private Adresse" }) m.setTargets(m.cfg.Range, m.cfg.Targets) if got := m.devs["da:a1:19:00:00:01"].host.Vendor; got != oui.Private { t.Errorf("vendor of stored device = %q, want %q", got, oui.Private) } m.Update(tea.WindowSizeMsg{Width: 140, Height: 30}) if !strings.Contains(m.View(), "Vendor database missing") { t.Error("no hint about the missing vendor database") } } func TestLayoutFollowsContent(t *testing.T) { m := testModel(t) gw := host("192.168.1.1", "3c:a6:2f:00:00:01") gw.Gateway = true pi := host("192.168.1.33", "b8:27:eb:00:00:03") pi.MDNSName = "raspberrypi" for _, typ := range []string{"_ssh._tcp", "_sftp-ssh._tcp", "_smb._tcp", "_http._tcp", "_workstation._tcp", "_rfb._tcp", "_afpovertcp._tcp", "_device-info._tcp"} { pi.Services = append(pi.Services, scanner.Service{Type: typ, Instance: "raspberrypi"}) } m.upsert(gw) m.upsert(pi) m.refresh() width := func(cols []column, widths []int, c column) int { return widths[slices.Index(cols, c)] } total := func(widths []int) int { n := rowPrefix + 2*(len(widths)-1) for _, w := range widths { n += w } return n } services := runewidth.StringWidth(serviceSummary(pi.Services)) // Wide enough: every column as wide as its content, the rest for services. m.Update(tea.WindowSizeMsg{Width: 200, Height: 30}) cols, widths := m.layout(time.Now()) if got := width(cols, widths, colName); got != len("raspberrypi") { t.Errorf("name column %d wide, want %d", got, len("raspberrypi")) } if got := width(cols, widths, colIP); got != len("192.168.1.33") { t.Errorf("IP column %d wide", got) } if got := width(cols, widths, colServices); got <= services { t.Errorf("services column %d wide, want more than its content (%d)", got, services) } if got := total(widths); got != 200 { t.Errorf("table %d wide, want 200", got) } // Too narrow: the long service list gives up width, the short name does not. m.Update(tea.WindowSizeMsg{Width: 100, Height: 30}) cols, widths = m.layout(time.Now()) if got := width(cols, widths, colName); got != len("raspberrypi") { t.Errorf("name column %d wide at 100 columns, want %d", got, len("raspberrypi")) } if got := width(cols, widths, colServices); got >= services || got < colMin[colServices] { t.Errorf("services column %d wide at 100 columns", got) } if got := total(widths); got != 100 { t.Errorf("table %d wide, want 100", got) } } func TestUpdateHintShown(t *testing.T) { m := testModel(t) m.cfg.Version, m.cfg.Update = "1.0.1", "1.0.2" m.Update(tea.WindowSizeMsg{Width: 120, Height: 40}) if got := ansi.Strip(m.View()); !strings.Contains(got, "nscan 1.0.1 → 1.0.2") { t.Errorf("title bar without the update: %q", strings.SplitN(got, "\n", 2)[0]) } m.Update(key("?")) if got := ansi.Strip(m.View()); !strings.Contains(got, "1.0.2 is available, run nscan update") { t.Error("help screen does not mention the update") } }