ipnet_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package ip
  2. import (
  3. "encoding/json"
  4. "net"
  5. "testing"
  6. )
  7. func mkIP4Net(s string, plen uint) IP4Net {
  8. ip, err := ParseIP4(s)
  9. if err != nil {
  10. panic(err)
  11. }
  12. return IP4Net{ip, plen}
  13. }
  14. func mkIP4(s string) IP4 {
  15. ip, err := ParseIP4(s)
  16. if err != nil {
  17. panic(err)
  18. }
  19. return ip
  20. }
  21. func TestIP4(t *testing.T) {
  22. nip := net.ParseIP("1.2.3.4")
  23. ip := FromIP(nip)
  24. a, b, c, d := ip.Octets()
  25. if a != 1 || b != 2 || c != 3 || d != 4 {
  26. t.Error("FromIP failed")
  27. }
  28. ip, err := ParseIP4("1.2.3.4")
  29. if err != nil {
  30. t.Error("ParseIP4 failed with: ", err)
  31. } else {
  32. a, b, c, d := ip.Octets()
  33. if a != 1 || b != 2 || c != 3 || d != 4 {
  34. t.Error("ParseIP4 failed")
  35. }
  36. }
  37. if ip.ToIP().String() != "1.2.3.4" {
  38. t.Error("ToIP failed")
  39. }
  40. if ip.String() != "1.2.3.4" {
  41. t.Error("String failed")
  42. }
  43. if ip.StringSep("*") != "1*2*3*4" {
  44. t.Error("StringSep failed")
  45. }
  46. j, err := json.Marshal(ip)
  47. if err != nil {
  48. t.Error("Marshal of IP4 failed: ", err)
  49. } else if string(j) != `"1.2.3.4"` {
  50. t.Error("Marshal of IP4 failed with unexpected value: ", j)
  51. }
  52. }
  53. func TestIP4Net(t *testing.T) {
  54. n1 := mkIP4Net("1.2.3.0", 24)
  55. if n1.ToIPNet().String() != "1.2.3.0/24" {
  56. t.Error("ToIPNet failed")
  57. }
  58. if !n1.Overlaps(n1) {
  59. t.Errorf("%s does not overlap %s", n1, n1)
  60. }
  61. n2 := mkIP4Net("1.2.0.0", 16)
  62. if !n1.Overlaps(n2) {
  63. t.Errorf("%s does not overlap %s", n1, n2)
  64. }
  65. n2 = mkIP4Net("1.2.4.0", 24)
  66. if n1.Overlaps(n2) {
  67. t.Errorf("%s overlaps %s", n1, n2)
  68. }
  69. n2 = mkIP4Net("7.2.4.0", 22)
  70. if n1.Overlaps(n2) {
  71. t.Errorf("%s overlaps %s", n1, n2)
  72. }
  73. if !n1.Contains(mkIP4("1.2.3.0")) {
  74. t.Error("Contains failed")
  75. }
  76. if !n1.Contains(mkIP4("1.2.3.4")) {
  77. t.Error("Contains failed")
  78. }
  79. if n1.Contains(mkIP4("1.2.4.0")) {
  80. t.Error("Contains failed")
  81. }
  82. j, err := json.Marshal(n1)
  83. if err != nil {
  84. t.Error("Marshal of IP4Net failed: ", err)
  85. } else if string(j) != `"1.2.3.0/24"` {
  86. t.Error("Marshal of IP4Net failed with unexpected value: ", j)
  87. }
  88. }