bitmap_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2018-present the CoreDHCP Authors. All rights reserved
  2. // This source code is licensed under the MIT license found in the
  3. // LICENSE file in the root directory of this source tree.
  4. package bitmap
  5. import (
  6. "net"
  7. "testing"
  8. )
  9. func getAllocator() *Allocator {
  10. _, prefix, err := net.ParseCIDR("2001:db8::/56")
  11. if err != nil {
  12. panic(err)
  13. }
  14. alloc, err := NewBitmapAllocator(*prefix, 64)
  15. if err != nil {
  16. panic(err)
  17. }
  18. return alloc
  19. }
  20. func TestAlloc(t *testing.T) {
  21. alloc := getAllocator()
  22. net, err := alloc.Allocate(net.IPNet{})
  23. if err != nil {
  24. t.Fatal(err)
  25. }
  26. err = alloc.Free(net)
  27. if err != nil {
  28. t.Fatal(err)
  29. }
  30. err = alloc.Free(net)
  31. if err == nil {
  32. t.Fatal("Expected DoubleFree error")
  33. }
  34. }
  35. func TestExhaust(t *testing.T) {
  36. _, prefix, _ := net.ParseCIDR("2001:db8::/62")
  37. alloc, _ := NewBitmapAllocator(*prefix, 64)
  38. allocd := []net.IPNet{}
  39. for i := 0; i < 4; i++ {
  40. net, err := alloc.Allocate(net.IPNet{Mask: net.CIDRMask(64, 128)})
  41. if err != nil {
  42. t.Fatalf("Error before exhaustion: %v", err)
  43. }
  44. allocd = append(allocd, net)
  45. }
  46. _, err := alloc.Allocate(net.IPNet{})
  47. if err == nil {
  48. t.Fatalf("Successfully allocated more prefixes than there are in the pool")
  49. }
  50. err = alloc.Free(allocd[1])
  51. if err != nil {
  52. t.Fatalf("Could not free: %v", err)
  53. }
  54. net, err := alloc.Allocate(allocd[1])
  55. if err != nil {
  56. t.Fatalf("Could not reallocate after free: %v", err)
  57. }
  58. if !net.IP.Equal(allocd[1].IP) || net.Mask.String() != allocd[1].Mask.String() {
  59. t.Fatalf("Did not obtain the right network after free: got %v, expected %v", net, allocd[1])
  60. }
  61. }
  62. func TestOutOfPool(t *testing.T) {
  63. alloc := getAllocator()
  64. _, prefix, _ := net.ParseCIDR("fe80:abcd::/48")
  65. res, err := alloc.Allocate(*prefix)
  66. if err != nil {
  67. t.Fatalf("Failed to allocate with invalid hint: %v", err)
  68. }
  69. if !alloc.containing.Contains(res.IP) {
  70. t.Fatal("Obtained prefix outside of range: ", res)
  71. }
  72. if prefLen, totalLen := res.Mask.Size(); prefLen != 64 || totalLen != 128 {
  73. t.Fatalf("Prefixes have wrong size %d/%d", prefLen, totalLen)
  74. }
  75. }