device_reservation_test.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // device_reservation_test.go — a client with a fixed address of its own takes
  2. // no lease, so the name pinned in /etc/config/dhcp is the only one there is.
  3. // End to end through the server: agent payload → polledFromAgent →
  4. // buildDevices, which is where an earlier attempt broke (the reservation map
  5. // was declared and read but never filled, so every such client stayed a MAC).
  6. package adapters
  7. import (
  8. "testing"
  9. "github.com/gnacho/netpulse/agent/probe"
  10. )
  11. func TestBuildDevicesNamesFromReservation(t *testing.T) {
  12. cfg := RouterConfig{ID: "gateway", Host: "192.0.2.1", Name: "openwrt", IsGateway: true, AgentOnly: true}
  13. l := NewLive(nil, nil, []RouterConfig{cfg}, nil)
  14. payload := &probe.Payload{
  15. Router: "gateway", Ts: 1, Version: "2.28.24",
  16. Data: probe.PayloadData{
  17. // Wired, seen only in the bridge FDB: no lease anywhere.
  18. FDB: &probe.FDBData{MACs: map[string]string{"02:00:00:00:00:01": "lan2"}},
  19. DHCP: &probe.DHCPData{
  20. Reservations: []probe.DhcpReservation{
  21. {MAC: "02:00:00:00:00:01", Name: "printer", IP: "192.0.2.10"},
  22. },
  23. },
  24. },
  25. }
  26. devices := l.buildDevices(map[string]*routerPolled{"gateway": l.polledFromAgent(cfg, payload)}, "")
  27. var found bool
  28. for _, d := range devices {
  29. if d.MAC != "02:00:00:00:00:01" {
  30. continue
  31. }
  32. found = true
  33. if d.Name != "printer" {
  34. t.Errorf("name = %q, want printer (from the reservation)", d.Name)
  35. }
  36. if d.IP != "192.0.2.10" {
  37. t.Errorf("ip = %q, want the reserved address", d.IP)
  38. }
  39. }
  40. if !found {
  41. t.Fatalf("the wired client never made it into the device list (%d devices)", len(devices))
  42. }
  43. }
  44. func TestBuildDevicesLeaseHostnameWinsOverReservation(t *testing.T) {
  45. cfg := RouterConfig{ID: "gateway", Host: "192.0.2.1", Name: "openwrt", IsGateway: true, AgentOnly: true}
  46. l := NewLive(nil, nil, []RouterConfig{cfg}, nil)
  47. payload := &probe.Payload{
  48. Router: "gateway", Ts: 1, Version: "2.28.24",
  49. Data: probe.PayloadData{
  50. FDB: &probe.FDBData{MACs: map[string]string{"02:00:00:00:00:02": "lan2"}},
  51. DHCP: &probe.DHCPData{
  52. Leases: []probe.DhcpLease{{MAC: "02:00:00:00:00:02", IP: "192.0.2.30", Hostname: "laptop"}},
  53. Reservations: []probe.DhcpReservation{
  54. {MAC: "02:00:00:00:00:02", Name: "old-name", IP: "192.0.2.99"},
  55. },
  56. },
  57. },
  58. }
  59. devices := l.buildDevices(map[string]*routerPolled{"gateway": l.polledFromAgent(cfg, payload)}, "")
  60. for _, d := range devices {
  61. if d.MAC == "02:00:00:00:00:02" && (d.Name != "laptop" || d.IP != "192.0.2.30") {
  62. t.Fatalf("the lease must win: %+v", d)
  63. }
  64. }
  65. }