whitelist_net_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package whitelist
  2. import (
  3. "encoding/json"
  4. "net"
  5. "testing"
  6. )
  7. func TestMarshalNet(t *testing.T) {
  8. tv := map[string]*BasicNet{
  9. "test-a": NewBasicNet(),
  10. "test-b": NewBasicNet(),
  11. }
  12. _, n, err := net.ParseCIDR("192.168.3.0/24")
  13. if err != nil {
  14. t.Fatalf("%v", err)
  15. }
  16. tv["test-a"].Add(n)
  17. _, n, err = net.ParseCIDR("192.168.7.0/24")
  18. if err != nil {
  19. t.Fatalf("%v", err)
  20. }
  21. tv["test-a"].Add(n)
  22. out, err := json.Marshal(tv)
  23. if err != nil {
  24. t.Fatalf("%v", err)
  25. }
  26. var tvPrime map[string]*BasicNet
  27. err = json.Unmarshal(out, &tvPrime)
  28. if err != nil {
  29. t.Fatalf("%v", err)
  30. }
  31. }
  32. func TestMarshalNetFail(t *testing.T) {
  33. wl := NewBasicNet()
  34. badInput := `192.168.3.1/24,127.0.0.1/32`
  35. if err := wl.UnmarshalJSON([]byte(badInput)); err == nil {
  36. t.Fatal("Expected failure unmarshaling bad JSON input.")
  37. }
  38. badInput = `"192.168.3.1,127.0.0.256"`
  39. if err := wl.UnmarshalJSON([]byte(badInput)); err == nil {
  40. t.Fatal("Expected failure unmarshaling bad JSON input.")
  41. }
  42. }
  43. var testNet *BasicNet
  44. func testAddNet(wl NetACL, ns string, t *testing.T) {
  45. _, n, err := net.ParseCIDR(ns)
  46. if err != nil {
  47. t.Fatalf("%v", err)
  48. }
  49. wl.Add(n)
  50. }
  51. func testDelNet(wl NetACL, ns string, t *testing.T) {
  52. _, n, err := net.ParseCIDR(ns)
  53. if err != nil {
  54. t.Fatalf("%v", err)
  55. }
  56. wl.Remove(n)
  57. }
  58. func TestAdd(t *testing.T) {
  59. // call this to make sure it doesn't panic, and to make sure
  60. // these code paths are executed.
  61. testNet = NewBasicNet()
  62. testNet.Add(nil)
  63. testAddNet(testNet, "192.168.3.0/24", t)
  64. }
  65. func TestRemove(t *testing.T) {
  66. testNet.Remove(nil)
  67. testDelNet(testNet, "192.168.1.1/32", t)
  68. testDelNet(testNet, "192.168.3.0/24", t)
  69. }
  70. func TestFailPermitted(t *testing.T) {
  71. var ip = []byte{0, 0}
  72. if testNet.Permitted(ip) {
  73. t.Fatal("Expected failure checking invalid IP address.")
  74. }
  75. }