device_seen_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. package adapters
  2. import (
  3. "testing"
  4. "time"
  5. )
  6. // #954: first_seen se fija en el alta y no se toca después; last_seen
  7. // avanza en cada ciclo online. Los clientes offline no entran en la tabla.
  8. func TestDeviceSeenFirstStableLastAdvances(t *testing.T) {
  9. d := openLiveTestDB(t)
  10. l := &Live{db: d}
  11. devs := []Device{
  12. {MAC: "aa:bb:cc:dd:ee:ff", Online: true},
  13. {MAC: "11:22:33:44:55:66", Online: false},
  14. }
  15. l.noteDevicesSeen(devs, 1000)
  16. l.noteDevicesSeen(devs, 2000)
  17. out := []Device{
  18. {MAC: "AA:BB:CC:DD:EE:FF"}, // normalización: case-insensitive
  19. {MAC: "11:22:33:44:55:66"},
  20. }
  21. l.applyDeviceSeen(out)
  22. if out[0].FirstSeenMs != 1000 {
  23. t.Errorf("first_seen = %d; want 1000 (el alta no se reescribe)", out[0].FirstSeenMs)
  24. }
  25. if out[0].LastSeenMs != 2000 {
  26. t.Errorf("last_seen = %d; want 2000 (avanza cada ciclo online)", out[0].LastSeenMs)
  27. }
  28. if out[1].FirstSeenMs != 0 || out[1].LastSeenMs != 0 {
  29. t.Errorf("offline no debe tener fila: %+v", out[1])
  30. }
  31. }
  32. // #954: sin BD (demo/tests) ambos lados son no-op y los campos quedan a 0.
  33. func TestDeviceSeenNilDB(t *testing.T) {
  34. l := &Live{}
  35. devs := []Device{{MAC: "aa:bb:cc:dd:ee:ff", Online: true}}
  36. l.noteDevicesSeen(devs, 1000) // no panic
  37. l.applyDeviceSeen(devs)
  38. if devs[0].FirstSeenMs != 0 || devs[0].LastSeenMs != 0 {
  39. t.Errorf("con db nil no se rellena: %+v", devs[0])
  40. }
  41. }
  42. // #1145: los clientes del registro que ya no se ven en vivo salen como
  43. // offline (ghosts) conservando su último nombre y seen; los que siguen
  44. // vivos no se duplican.
  45. func TestGhostDevicesOfflineRetention(t *testing.T) {
  46. d := openLiveTestDB(t)
  47. l := &Live{db: d}
  48. l.noteDevicesSeen([]Device{
  49. {MAC: "aa:bb:cc:dd:ee:ff", Online: true, Hostname: "iphone-peter"},
  50. {MAC: "11:22:33:44:55:66", Online: true},
  51. }, 1000)
  52. // Solo uno sigue vivo: el otro sale como ghost con su nombre y seen.
  53. ghosts := l.ghostDevices([]Device{{MAC: "11:22:33:44:55:66", Online: true}})
  54. if len(ghosts) != 1 {
  55. t.Fatalf("ghosts = %d, want 1", len(ghosts))
  56. }
  57. g := ghosts[0]
  58. if g.MAC != "AA:BB:CC:DD:EE:FF" || g.Online {
  59. t.Fatalf("ghost = %+v, want offline AA:BB:CC:DD:EE:FF", g)
  60. }
  61. if g.Hostname != "iphone-peter" {
  62. t.Fatalf("hostname = %q, want iphone-peter", g.Hostname)
  63. }
  64. if g.FirstSeenMs != 1000 || g.LastSeenMs != 1000 {
  65. t.Fatalf("seen = %d/%d, want 1000/1000", g.FirstSeenMs, g.LastSeenMs)
  66. }
  67. // Los dos vivos: ningún ghost.
  68. if ghosts := l.ghostDevices([]Device{
  69. {MAC: "11:22:33:44:55:66", Online: true},
  70. {MAC: "AA:BB:CC:DD:EE:FF", Online: true},
  71. }); len(ghosts) != 0 {
  72. t.Fatalf("ghosts = %d, want 0", len(ghosts))
  73. }
  74. }
  75. // #1145: la caché gl-clients de GL.iNet emite MACs con guiones; el pase de
  76. // normalización dedupe con la versión de dos puntos y enriquece la entrada.
  77. func TestNormalizeDevicesDashedMAC(t *testing.T) {
  78. out := normalizeDevices([]Device{
  79. {MAC: "AA-BB-CC-DD-EE-FF", Online: false, Hostname: "watch"},
  80. {MAC: "aa:bb:cc:dd:ee:ff", Online: true, IP: "192.168.1.50"},
  81. })
  82. if len(out) != 1 {
  83. t.Fatalf("devices = %d, want 1 (dedup por MAC normalizada)", len(out))
  84. }
  85. if out[0].MAC != "AA:BB:CC:DD:EE:FF" || !out[0].Online {
  86. t.Fatalf("device = %+v, want online con MAC canonica", out[0])
  87. }
  88. if out[0].Hostname != "watch" || out[0].IP != "192.168.1.50" {
  89. t.Fatalf("merge = %+v, want hostname+IP combinados", out[0])
  90. }
  91. }
  92. // #1145: el nombre nuevo (lease) pisa al guardado solo si no es vacío.
  93. func TestNoteDevicesSeenKeepsLastName(t *testing.T) {
  94. d := openLiveTestDB(t)
  95. l := &Live{db: d}
  96. l.noteDevicesSeen([]Device{{MAC: "aa:bb:cc:dd:ee:ff", Online: true, Hostname: "iphone"}}, 1000)
  97. l.noteDevicesSeen([]Device{{MAC: "AA:BB:CC:DD:EE:FF", Online: true}}, 2000)
  98. ghosts := l.ghostDevices(nil)
  99. if len(ghosts) != 1 || ghosts[0].Hostname != "iphone" {
  100. t.Fatalf("ghosts = %+v, want 1 con hostname iphone", ghosts)
  101. }
  102. }
  103. // #1278: un cliente borrado a mano (lápida) no vuelve a alta aunque una
  104. // fuente lo siga reportando online, y no sale en la lista de fantasmas.
  105. // La re-alta manual (allowlist) quita la lápida.
  106. func TestDeletedClientTombstone(t *testing.T) {
  107. d := openLiveTestDB(t)
  108. l := &Live{db: d}
  109. mac := "12:77:BC:5A:5A:FA"
  110. if err := d.AddDeletedClient(mac); err != nil {
  111. t.Fatal(err)
  112. }
  113. devs := []Device{{MAC: mac, Online: true, Name: "iphone-viejo"}}
  114. l.noteDevicesSeen(devs, 1000)
  115. count := func() int {
  116. t.Helper()
  117. rows, err := d.Query("SELECT COUNT(*) FROM device_seen WHERE mac = ?", mac)
  118. if err != nil {
  119. t.Fatal(err)
  120. }
  121. defer rows.Close()
  122. if !rows.Next() {
  123. t.Fatal("sin fila de conteo")
  124. }
  125. var n int
  126. if err := rows.Scan(&n); err != nil {
  127. t.Fatal(err)
  128. }
  129. return n
  130. }
  131. if n := count(); n != 0 {
  132. t.Errorf("la MAC enterrada se dio de alta igual (%d filas)", n)
  133. }
  134. // Fantasmas: la MAC no sale aunque tenga registro previo.
  135. if _, err := d.Exec("INSERT INTO device_seen (mac, first_seen, last_seen) VALUES (?, 1, 2)", mac); err != nil {
  136. t.Fatal(err)
  137. }
  138. for _, g := range l.ghostDevices(nil) {
  139. if g.MAC == mac {
  140. t.Errorf("la MAC enterrada sale como fantasma: %+v", g)
  141. }
  142. }
  143. // Re-alta manual: la lápida se quita y vuelve a alta normal.
  144. if err := d.DeleteDeletedClient(mac); err != nil {
  145. t.Fatal(err)
  146. }
  147. l.noteDevicesSeen(devs, 3000)
  148. if n := count(); n != 1 {
  149. t.Errorf("tras quitar la lápida la MAC se da de alta (%d filas)", n)
  150. }
  151. }
  152. // #1292: la lápida filtra la LISTA FINAL - una estación stale del AP puede
  153. // re-emitir la MAC sin que pase por device_seen.
  154. func TestFilterTombstonedFinalList(t *testing.T) {
  155. d := openLiveTestDB(t)
  156. l := &Live{db: d}
  157. if err := d.AddDeletedClient("12:77:BC:5A:5A:FA"); err != nil {
  158. t.Fatal(err)
  159. }
  160. devs := l.filterTombstoned([]Device{
  161. {MAC: "12:77:BC:5A:5A:FA", Online: true},
  162. {MAC: "AA:BB:CC:DD:EE:FF", Online: true},
  163. })
  164. if len(devs) != 1 || devs[0].MAC != "AA:BB:CC:DD:EE:FF" {
  165. t.Errorf("filterTombstoned = %+v", devs)
  166. }
  167. }
  168. // #1307: el purge de MACs de flota (#1278) también debe cubrir los BSSID de
  169. // las radios (ap1-phy1-mac-addr...): los AP se ven a sí mismos como
  170. // estaciones y esas MACs reaparecen como clientes fantasma igual que la MAC
  171. // base y la de bridge.
  172. func TestPurgeFleetSeenIncludesRadioBSSIDs(t *testing.T) {
  173. d := openLiveTestDB(t)
  174. l := &Live{db: d, lastPolled: map[string]*routerPolled{
  175. "ap1": {brMac: "aa:aa:aa:aa:aa:01", radios: []Radio{
  176. {Name: "2.4 GHz", BSSID: "aa:aa:aa:aa:aa:02"},
  177. {Name: "5 GHz", BSSID: "AA-AA-AA-AA-AA-03"}, // guiones: normaliza
  178. {Name: "5 GHz", BSSID: ""}, // sin BSSID: no-op
  179. }},
  180. }}
  181. // El registro guarda MACs normalizadas (normSeenMAC en el alta): mayúsculas
  182. // y dos puntos.
  183. purged := []string{"AA:AA:AA:AA:AA:01", "AA:AA:AA:AA:AA:02", "AA:AA:AA:AA:AA:03"}
  184. kept := "BB:BB:BB:BB:BB:BB"
  185. for _, m := range append(append([]string{}, purged...), kept) {
  186. if _, err := d.Exec("INSERT INTO device_seen (mac, first_seen, last_seen) VALUES (?, 1, 2)", m); err != nil {
  187. t.Fatalf("seed %s: %v", m, err)
  188. }
  189. }
  190. l.purgeFleetSeen()
  191. for _, m := range purged {
  192. var n int
  193. if err := d.QueryRow("SELECT COUNT(*) FROM device_seen WHERE mac = ?", m).Scan(&n); err != nil || n != 0 {
  194. t.Errorf("mac %s debería estar purgada (n=%d, err=%v)", m, n, err)
  195. }
  196. }
  197. var n int
  198. if err := d.QueryRow("SELECT COUNT(*) FROM device_seen WHERE mac = ?", kept).Scan(&n); err != nil || n != 1 {
  199. t.Errorf("mac ajena %s no debe tocarse (n=%d, err=%v)", kept, n, err)
  200. }
  201. }
  202. // #1307: la fuente viva re-emite las MACs de flota cada ciclo; el purge del
  203. // registro no basta, la LISTA final debe filtrarlas igual que las lápidas.
  204. func TestFilterTombstonedAlsoFiltersFleetMACs(t *testing.T) {
  205. d := openLiveTestDB(t)
  206. l := &Live{db: d, lastPolled: map[string]*routerPolled{
  207. "ap1": {brMac: "aa:aa:aa:aa:aa:01", radios: []Radio{{Name: "2.4 GHz", BSSID: "aa:aa:aa:aa:aa:02"}}},
  208. }}
  209. devs := []Device{
  210. {MAC: "AA:AA:AA:AA:AA:01"}, // bridge
  211. {MAC: "aa:aa:aa:aa:aa:02"}, // BSSID radio (case-insensitive)
  212. {MAC: "cc:cc:cc:cc:cc:cc"}, // cliente real
  213. }
  214. out := l.filterTombstoned(devs)
  215. if len(out) != 1 || out[0].MAC != "cc:cc:cc:cc:cc:cc" {
  216. t.Fatalf("filterTombstoned = %+v, want solo el cliente real", out)
  217. }
  218. }
  219. // #1315: cuando el lease expira la fuente viva deja de dar nombre/IP (Name
  220. // vuelve a ser la MAC, IP vacía) pero el cliente sigue listado vía
  221. // estación/ARP. applyDeviceSeen debe restaurar el último conocido del
  222. // registro (#1145), como ya hacían los ghosts.
  223. func TestApplyDeviceSeenRestoresNameAndIP(t *testing.T) {
  224. d := openLiveTestDB(t)
  225. l := &Live{db: d}
  226. l.noteDevicesSeen([]Device{
  227. {MAC: "aa:bb:cc:dd:ee:ff", Online: true, Hostname: "iphone-peter", IP: "192.168.1.50"},
  228. }, 1000)
  229. // Mismo cliente en el ciclo vivo SIN nombre ni IP (lease expirado).
  230. out := []Device{{MAC: "AA:BB:CC:DD:EE:FF", Name: "AA:BB:CC:DD:EE:FF", Online: false}}
  231. l.applyDeviceSeen(out)
  232. if out[0].Name != "iphone-peter" {
  233. t.Errorf("Name = %q, want iphone-peter (retenido del registro)", out[0].Name)
  234. }
  235. if out[0].Hostname != "iphone-peter" {
  236. t.Errorf("Hostname = %q, want iphone-peter", out[0].Hostname)
  237. }
  238. if out[0].IP != "192.168.1.50" {
  239. t.Errorf("IP = %q, want 192.168.1.50", out[0].IP)
  240. }
  241. // Un nombre real (alias/override) NO se pisa con el del registro.
  242. aliased := []Device{{MAC: "AA:BB:CC:DD:EE:FF", Name: "telefono-ana", Online: false}}
  243. l.applyDeviceSeen(aliased)
  244. if aliased[0].Name != "telefono-ana" {
  245. t.Errorf("Name = %q, want telefono-ana (el alias manda)", aliased[0].Name)
  246. }
  247. }
  248. // #1315 (sub-bug a, MACs enlazadas): con alias -> canónico, al expirar el
  249. // lease el merge deja como nombre del canónico la MAC de una alias (la
  250. // clasificación/restore antigua solo reconocía la propia MAC). El nombre
  251. // vivo que es una MAC de cualquier interfaz (isMACLike) se restaura desde
  252. // el registro y el server nunca emite esa MAC como hostname.
  253. func TestApplyDeviceSeenRestoresLinkedAliasMACName(t *testing.T) {
  254. d := openLiveTestDB(t)
  255. l := &Live{db: d}
  256. l.noteDevicesSeen([]Device{
  257. {MAC: "cc:cc:cc:00:00:01", Online: true, Hostname: "galaxy-s9", Type: "movil"},
  258. }, 1000)
  259. // El canónico llega vivo con la MAC de una alias como nombre (merge de
  260. // #1151 cuando el primario no tiene hostname).
  261. out := []Device{{MAC: "CC:CC:CC:00:00:01", Name: "AA:AA:AA:00:00:02", Online: true, Type: "desconocido"}}
  262. l.applyDeviceSeen(out)
  263. if out[0].Name != "galaxy-s9" {
  264. t.Errorf("Name = %q, want galaxy-s9 (la MAC de la alias no es un nombre)", out[0].Name)
  265. }
  266. if out[0].Hostname != "galaxy-s9" {
  267. t.Errorf("Hostname = %q, want galaxy-s9", out[0].Hostname)
  268. }
  269. }
  270. // #1315 (sub-bug a): noteDevicesSeen nunca persiste una MAC como nombre. El
  271. // caso linked es el que contaminaba el registro: el nombre fusionado era la
  272. // MAC de una alias (distinta de la MAC del dispositivo) y el guard antiguo
  273. // (!= MAC propia, case-insensitive) la dejaba pasar.
  274. func TestNoteDevicesSeenSkipsMACLikeNames(t *testing.T) {
  275. d := openLiveTestDB(t)
  276. l := &Live{db: d}
  277. l.noteDevicesSeen([]Device{
  278. {MAC: "cc:cc:cc:00:00:01", Online: true, Name: "cc:cc:cc:00:00:01"}, // MAC propia
  279. {MAC: "dd:dd:dd:00:00:01", Online: true, Name: "AA:AA:AA:00:00:02"}, // MAC de otra interfaz (linked)
  280. {MAC: "ee:ee:ee:00:00:01", Online: true, Name: "EE-EE-EE-00-00-01"}, // MAC con guiones
  281. {MAC: "ff:ff:ff:00:00:01", Online: true, Name: "iphone-peter", Type: "movil"}, // nombre real
  282. }, 1000)
  283. ghosts := l.ghostDevices(nil)
  284. byMAC := map[string]Device{}
  285. for _, g := range ghosts {
  286. byMAC[g.MAC] = g
  287. }
  288. for _, mac := range []string{"CC:CC:CC:00:00:01", "DD:DD:DD:00:00:01", "EE:EE:EE:00:00:01"} {
  289. if g, ok := byMAC[mac]; !ok || g.Hostname != "" || g.Name != "" {
  290. t.Errorf("registro de %s = %+v, want sin nombre (una MAC no es nombre)", mac, g)
  291. }
  292. }
  293. if g, ok := byMAC["FF:FF:FF:00:00:01"]; !ok || g.Hostname != "iphone-peter" {
  294. t.Errorf("registro de FF:FF:FF:00:00:01 = %+v, want iphone-peter", g)
  295. }
  296. }
  297. // #1315 (sub-bug a): sanidad de BD vieja. Los ciclos anteriores al fix
  298. // pudieron persistir una MAC como nombre; al leer, seenByMac lo ignora y el
  299. // server deja de emitirla como hostname en vez de restaurarla.
  300. func TestApplyDeviceSeenIgnoresStoredMACName(t *testing.T) {
  301. d := openLiveTestDB(t)
  302. l := &Live{db: d}
  303. if _, err := d.Exec("INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES ('CC:CC:CC:00:00:01', 1, 2, 'AA-BB-CC-DD-EE-FF')"); err != nil {
  304. t.Fatal(err)
  305. }
  306. out := []Device{{MAC: "CC:CC:CC:00:00:01", Name: "CC:CC:CC:00:00:01", Online: false}}
  307. l.applyDeviceSeen(out)
  308. if out[0].Name != "CC:CC:CC:00:00:01" {
  309. t.Errorf("Name = %q, want la MAC viva conservada (el nombre MAC del registro no se restaura)", out[0].Name)
  310. }
  311. if out[0].Hostname != "" {
  312. t.Errorf("Hostname = %q, want vacío (nunca se emite una MAC como hostname)", out[0].Hostname)
  313. }
  314. }
  315. // #1315 (sub-bug b): stickiness del tipo. Se persiste el último tipo
  316. // INFERIDO (no override, no genérico) y, al expirar el lease, cuando la
  317. // clasificación viva cae en "desconocido" se conserva el retenido. Los
  318. // overrides manuales nunca se persisten ni se pisan.
  319. func TestApplyDeviceSeenStickyInferredType(t *testing.T) {
  320. d := openLiveTestDB(t)
  321. l := &Live{db: d}
  322. l.noteDevicesSeen([]Device{
  323. {MAC: "aa:bb:cc:dd:ee:ff", Online: true, Hostname: "galaxy-s9", Type: "movil"},
  324. {MAC: "11:22:33:44:55:66", Online: true, Hostname: "tv-salon", Type: "tv", TypeOverride: "tv"},
  325. {MAC: "77:77:77:77:77:77", Online: true, Hostname: "sin-tipo", Type: "desconocido"},
  326. }, 1000)
  327. // Lease expirado: nombre degradado, clasificación viva "desconocido".
  328. out := []Device{
  329. {MAC: "AA:BB:CC:DD:EE:FF", Name: "AA:BB:CC:DD:EE:FF", Online: true, Type: "desconocido"},
  330. {MAC: "11:22:33:44:55:66", Name: "11:22:33:44:55:66", Online: true, Type: "tv", TypeOverride: "tv"},
  331. }
  332. l.applyDeviceSeen(out)
  333. if out[0].Type != "movil" {
  334. t.Errorf("Type = %q, want movil (sticky del último inferido)", out[0].Type)
  335. }
  336. if out[1].Type != "tv" || out[1].TypeOverride != "tv" {
  337. t.Errorf("Type = %q/%q, want tv override intacto (nunca se pisa)", out[1].Type, out[1].TypeOverride)
  338. }
  339. // El override manual NO quedó persistido como inferido.
  340. var stored string
  341. if err := d.QueryRow("SELECT device_type FROM device_seen WHERE mac = '11:22:33:44:55:66'").Scan(&stored); err != nil {
  342. t.Fatal(err)
  343. }
  344. if stored != "" {
  345. t.Errorf("device_type persistido del override = %q, want vacío (solo se guarda lo inferido)", stored)
  346. }
  347. // El genérico tampoco se persiste.
  348. if err := d.QueryRow("SELECT device_type FROM device_seen WHERE mac = '77:77:77:77:77:77'").Scan(&stored); err != nil {
  349. t.Fatal(err)
  350. }
  351. if stored != "" {
  352. t.Errorf("device_type persistido del desconocido = %q, want vacío", stored)
  353. }
  354. // Inferencia viva no genérica: manda sobre el retenido.
  355. l.noteDevicesSeen([]Device{
  356. {MAC: "aa:bb:cc:dd:ee:ff", Online: true, Hostname: "nuevo-nombre-tv", Type: "tv"},
  357. }, 2000)
  358. out2 := []Device{{MAC: "AA:BB:CC:DD:EE:FF", Name: "AA:BB:CC:DD:EE:FF", Online: true, Type: "desconocido"}}
  359. l.applyDeviceSeen(out2)
  360. if out2[0].Type != "tv" {
  361. t.Errorf("Type = %q, want tv (la inferencia nueva pisa al retenido)", out2[0].Type)
  362. }
  363. }
  364. // #1315 (sub-bug b): los fantasmas también conservan el último tipo
  365. // inferido; sin esto el icono se perdía igual que en la lista viva.
  366. func TestGhostDevicesStickyType(t *testing.T) {
  367. d := openLiveTestDB(t)
  368. l := &Live{db: d}
  369. l.noteDevicesSeen([]Device{
  370. {MAC: "aa:bb:cc:dd:ee:ff", Online: true, Hostname: "roborock-s8", Type: "aspirador"},
  371. {MAC: "11:22:33:44:55:66", Online: true, Hostname: "sin-tipo"},
  372. }, 1000)
  373. ghosts := l.ghostDevices(nil)
  374. byMAC := map[string]Device{}
  375. for _, g := range ghosts {
  376. byMAC[g.MAC] = g
  377. }
  378. if g := byMAC["AA:BB:CC:DD:EE:FF"]; g.Type != "aspirador" {
  379. t.Errorf("ghost Type = %q, want aspirador (sticky)", g.Type)
  380. }
  381. if g := byMAC["11:22:33:44:55:66"]; g.Type != "desconocido" {
  382. t.Errorf("ghost Type = %q, want desconocido (nunca hubo inferencia)", g.Type)
  383. }
  384. }
  385. // "Nuevo" = alta del registro HOY y "esta semana" = alta en los últimos 7
  386. // días. Sin esto el live no marcaba NUNCA ninguno de los dos y el tile
  387. // "New (7 days)" se quedaba en 0 aunque la tabla de clientes de abajo listara
  388. // los descubiertos esa misma semana.
  389. func TestDeviceSeenNewFlagsFromSeenDay(t *testing.T) {
  390. d := openLiveTestDB(t)
  391. now := time.Date(2026, 3, 14, 12, 0, 0, 0, time.UTC)
  392. l := &Live{db: d, now: func() time.Time { return now }}
  393. hoy := now.Add(-6 * time.Hour).UnixMilli() // mismo día, antes del mediodía
  394. ayer := now.Add(-20 * time.Hour).UnixMilli() // ayer
  395. cuatro := now.Add(-4 * 24 * time.Hour).UnixMilli()
  396. ocho := now.Add(-8 * 24 * time.Hour).UnixMilli()
  397. l.noteDevicesSeen([]Device{
  398. {MAC: "aa:bb:cc:dd:ee:ff", Online: true},
  399. {MAC: "11:22:33:44:55:66", Online: true},
  400. }, hoy)
  401. l.noteDevicesSeen([]Device{{MAC: "22:33:44:55:66:77", Online: true}}, ayer)
  402. l.noteDevicesSeen([]Device{{MAC: "33:44:55:66:77:88", Online: true}}, cuatro)
  403. l.noteDevicesSeen([]Device{{MAC: "44:55:66:77:88:99", Online: true}}, ocho)
  404. out := []Device{
  405. {MAC: "AA:BB:CC:DD:EE:FF", Online: true},
  406. {MAC: "11:22:33:44:55:66", Online: true},
  407. {MAC: "22:33:44:55:66:77", Online: true},
  408. {MAC: "33:44:55:66:77:88", Online: true},
  409. {MAC: "44:55:66:77:88:99", Online: true},
  410. {MAC: "55:66:77:88:99:AA", Online: true}, // sin fila: nunca visto por este server
  411. }
  412. l.applyDeviceSeen(out)
  413. want := []struct{ isNew, isWeek bool }{
  414. {true, true}, // hoy
  415. {true, true}, // hoy
  416. {false, true}, // ayer
  417. {false, true}, // hace 4 días
  418. {false, false},
  419. {false, false}, // sin registro → la app pinta "—"
  420. }
  421. for i, w := range want {
  422. if out[i].IsNew != w.isNew || out[i].NewThisWeek != w.isWeek {
  423. t.Errorf("[%d] %s: isNew=%v newThisWeek=%v, want %v/%v",
  424. i, out[i].MAC, out[i].IsNew, out[i].NewThisWeek, w.isNew, w.isWeek)
  425. }
  426. }
  427. if got := countNewToday(out); got != 2 {
  428. t.Errorf("countNewToday = %d, want 2", got)
  429. }
  430. if out[5].FirstSeenMs != 0 {
  431. t.Errorf("sin fila no debe inventar first_seen: %d", out[5].FirstSeenMs)
  432. }
  433. // Los fantasmas (ya fuera de toda fuente viva) leen el mismo first_seen:
  434. // un alta de hoy que se fue sigue siendo un alta de hoy.
  435. ghosts := l.ghostDevices(nil)
  436. if len(ghosts) != 5 {
  437. t.Fatalf("ghosts = %d, want 5 (ninguno está en la lista que se pasa)", len(ghosts))
  438. }
  439. for _, g := range ghosts {
  440. isWeek := g.MAC != "44:55:66:77:88:99"
  441. isNew := g.MAC == "AA:BB:CC:DD:EE:FF" || g.MAC == "11:22:33:44:55:66"
  442. if g.IsNew != isNew || g.NewThisWeek != isWeek {
  443. t.Errorf("ghost %s: isNew=%v newThisWeek=%v, want %v/%v",
  444. g.MAC, g.IsNew, g.NewThisWeek, isNew, isWeek)
  445. }
  446. }
  447. }
  448. // Los dos cortes: "hoy" es el día local del server (como el pico de tráfico
  449. // diario), la semana es una ventana móvil de 7 × 24 h.
  450. func TestNewFlagsCutAtDayAndWeek(t *testing.T) {
  451. now := time.Date(2026, 3, 14, 0, 0, 0, 1, time.UTC)
  452. startOfDay := time.Date(2026, 3, 14, 0, 0, 0, 0, time.UTC).UnixMilli()
  453. if !(seenRow{first: startOfDay}).isNewToday(now) {
  454. t.Error("el primer ms del día es nuevo")
  455. }
  456. if (seenRow{first: startOfDay - 1}).isNewToday(now) {
  457. t.Error("último ms de ayer no es nuevo, por 1 ms que sea")
  458. }
  459. week := now.Add(-7 * 24 * time.Hour).UnixMilli()
  460. if !(seenRow{first: week}).isNewThisWeek(now) {
  461. t.Error("justo hace 7 días sigue siendo esta semana")
  462. }
  463. if (seenRow{first: week - 1}).isNewThisWeek(now) {
  464. t.Error("1 ms fuera de la ventana de 7 días no es de esta semana")
  465. }
  466. for name, s := range map[string]seenRow{"hoy": {first: startOfDay}, "sin fila": {first: 0}, "negativo": {first: -1}} {
  467. if s.isNewToday(now) != (s.first > 0) || s.isNewThisWeek(now) != (s.first > 0) {
  468. t.Errorf("%s: los dos flags deben negar un alta ausente", name)
  469. }
  470. }
  471. }