allocator_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package amqp
  2. import (
  3. "math/rand"
  4. "testing"
  5. )
  6. func TestAllocatorFirstShouldBeTheLow(t *testing.T) {
  7. n, ok := newAllocator(1, 2).next()
  8. if !ok {
  9. t.Fatalf("expected to allocate between 1 and 2")
  10. }
  11. if want, got := 1, n; want != got {
  12. t.Fatalf("expected to first allocation to be 1")
  13. }
  14. }
  15. func TestAllocatorShouldBeBoundByHigh(t *testing.T) {
  16. a := newAllocator(1, 2)
  17. if n, ok := a.next(); n != 1 || !ok {
  18. t.Fatalf("expected to allocate between 1 and 2, got %d, %v", n, ok)
  19. }
  20. if n, ok := a.next(); n != 2 || !ok {
  21. t.Fatalf("expected to allocate between 1 and 2, got %d, %v", n, ok)
  22. }
  23. if _, ok := a.next(); ok {
  24. t.Fatalf("expected not to allocate outside of 1 and 2")
  25. }
  26. }
  27. func TestAllocatorStringShouldIncludeAllocatedRanges(t *testing.T) {
  28. a := newAllocator(1, 10)
  29. a.reserve(1)
  30. a.reserve(2)
  31. a.reserve(3)
  32. a.reserve(5)
  33. a.reserve(6)
  34. a.reserve(8)
  35. a.reserve(10)
  36. if want, got := "allocator[1..10] 1..3 5..6 8 10", a.String(); want != got {
  37. t.Fatalf("expected String of %q, got %q", want, got)
  38. }
  39. }
  40. func TestAllocatorShouldReuseReleased(t *testing.T) {
  41. a := newAllocator(1, 2)
  42. first, _ := a.next()
  43. if want, got := 1, first; want != got {
  44. t.Fatalf("expected allocation to be %d, got: %d", want, got)
  45. }
  46. second, _ := a.next()
  47. if want, got := 2, second; want != got {
  48. t.Fatalf("expected allocation to be %d, got: %d", want, got)
  49. }
  50. a.release(first)
  51. third, _ := a.next()
  52. if want, got := first, third; want != got {
  53. t.Fatalf("expected third allocation to be %d, got: %d", want, got)
  54. }
  55. _, ok := a.next()
  56. if want, got := false, ok; want != got {
  57. t.Fatalf("expected fourth allocation to saturate the pool")
  58. }
  59. }
  60. func TestAllocatorReleasesKeepUpWithAllocationsForAllSizes(t *testing.T) {
  61. const runs = 5
  62. const max = 13
  63. for lim := 1; lim < 2<<max; lim <<= 1 {
  64. a := newAllocator(0, lim)
  65. for i := 0; i < runs*lim; i++ {
  66. if i >= lim { // fills the allocator
  67. a.release(int(rand.Int63n(int64(lim))))
  68. }
  69. if _, ok := a.next(); !ok {
  70. t.Fatalf("expected %d runs of random release of size %d not to fail on allocation %d", runs, lim, i)
  71. }
  72. }
  73. }
  74. }