batch_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package nebula
  2. import (
  3. "net/netip"
  4. "testing"
  5. )
  6. func TestSendBatchBookkeeping(t *testing.T) {
  7. b := newSendBatch(4, 32)
  8. if b.Len() != 0 || b.Cap() != 4 {
  9. t.Fatalf("fresh batch: len=%d cap=%d", b.Len(), b.Cap())
  10. }
  11. ap := netip.MustParseAddrPort("10.0.0.1:4242")
  12. for i := 0; i < 4; i++ {
  13. slot := b.Next()
  14. if slot == nil {
  15. t.Fatalf("slot %d: Next returned nil before cap", i)
  16. }
  17. if cap(slot) != 32 || len(slot) != 0 {
  18. t.Fatalf("slot %d: got len=%d cap=%d want len=0 cap=32", i, len(slot), cap(slot))
  19. }
  20. // Write a marker byte.
  21. slot = append(slot, byte(i), byte(i+1), byte(i+2))
  22. b.Commit(len(slot), ap)
  23. }
  24. if b.Next() != nil {
  25. t.Fatalf("Next should return nil when full")
  26. }
  27. if b.Len() != 4 {
  28. t.Fatalf("Len=%d want 4", b.Len())
  29. }
  30. for i, buf := range b.bufs {
  31. if len(buf) != 3 || buf[0] != byte(i) {
  32. t.Errorf("buf %d: %x", i, buf)
  33. }
  34. if b.dsts[i] != ap {
  35. t.Errorf("dst %d: got %v want %v", i, b.dsts[i], ap)
  36. }
  37. }
  38. // Reset returns empty and Next works again.
  39. b.Reset()
  40. if b.Len() != 0 {
  41. t.Fatalf("after Reset Len=%d want 0", b.Len())
  42. }
  43. slot := b.Next()
  44. if slot == nil || cap(slot) != 32 {
  45. t.Fatalf("after Reset Next nil or wrong cap: %v cap=%d", slot == nil, cap(slot))
  46. }
  47. }
  48. func TestSendBatchSlotsDoNotOverlap(t *testing.T) {
  49. b := newSendBatch(3, 8)
  50. ap := netip.MustParseAddrPort("10.0.0.1:80")
  51. // Fill three slots, each with its own sentinel byte.
  52. for i := 0; i < 3; i++ {
  53. s := b.Next()
  54. s = append(s, byte(0xA0+i), byte(0xB0+i))
  55. b.Commit(len(s), ap)
  56. }
  57. for i, buf := range b.bufs {
  58. if buf[0] != byte(0xA0+i) || buf[1] != byte(0xB0+i) {
  59. t.Errorf("slot %d corrupted: %x", i, buf)
  60. }
  61. }
  62. }