config_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 config
  5. import "testing"
  6. func TestSplitHostPort(t *testing.T) {
  7. testcases := []struct {
  8. hostport string
  9. ip string
  10. zone string
  11. port string
  12. err bool // Should return an error (ie true for err != nil)
  13. }{
  14. {"0.0.0.0:67", "0.0.0.0", "", "67", false},
  15. {"192.0.2.0", "192.0.2.0", "", "", false},
  16. {"192.0.2.9%eth0", "192.0.2.9", "eth0", "", false},
  17. {"0.0.0.0%eth0:67", "0.0.0.0", "eth0", "67", false},
  18. {"0.0.0.0:20%eth0:67", "0.0.0.0", "eth0", "67", true},
  19. {"2001:db8::1:547", "", "", "547", true}, // [] mandatory for v6
  20. {"[::]:547", "::", "", "547", false},
  21. {"[fe80::1%eth0]", "fe80::1", "eth0", "", false},
  22. {"[fe80::1]:eth1", "fe80::1", "", "eth1", false}, // no validation of ports in this function
  23. {"fe80::1%eth0:547", "fe80::1", "eth0", "547", true}, // [] mandatory for v6 even with %zone
  24. {"fe80::1%eth0", "fe80::1", "eth0", "547", true}, // [] mandatory for v6 even without port
  25. {"[2001:db8::2]47", "fe80::1", "eth0", "547", true}, // garbage after []
  26. {"[ff02::1:2]%srv_u:547", "ff02::1:2", "srv_u", "547", true}, // FIXME: Linux `ss` format, we should accept but net.SplitHostPort doesn't
  27. {":http", "", "", "http", false},
  28. {"%eth0:80", "", "eth0", "80", false}, // janky, but looks valid enough for "[::%eth0]:80" imo
  29. {"%eth0", "", "eth0", "", false}, // janky
  30. {"fe80::1]:80", "fe80::1", "", "80", true}, // unbalanced ]
  31. {"fe80::1%eth0]", "fe80::1", "eth0", "", true}, // unbalanced ], no port
  32. {"", "", "", "", false}, // trivial case, still valid
  33. }
  34. for _, tc := range testcases {
  35. ip, zone, port, err := splitHostPort(tc.hostport)
  36. if tc.err != (err != nil) {
  37. errState := "not "
  38. if tc.err {
  39. errState = ""
  40. }
  41. t.Errorf("Mismatched error state: %s should %serror (got err: %v)\n", tc.hostport, errState, err)
  42. continue
  43. }
  44. if err == nil && (ip != tc.ip || zone != tc.zone || port != tc.port) {
  45. t.Errorf("%s => \"%s\", \"%s\", \"%s\" expected \"%s\",\"%s\",\"%s\"\n", tc.hostport, ip, zone, port, tc.ip, tc.zone, tc.port)
  46. }
  47. }
  48. }