server_test.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package main
  2. import (
  3. "net"
  4. "strconv"
  5. "testing"
  6. )
  7. func TestClientAddr(t *testing.T) {
  8. // good tests
  9. for _, test := range []struct {
  10. input string
  11. expected net.IP
  12. }{
  13. {"1.2.3.4", net.ParseIP("1.2.3.4")},
  14. {"1:2::3:4", net.ParseIP("1:2::3:4")},
  15. } {
  16. useraddr := clientAddr(test.input)
  17. host, port, err := net.SplitHostPort(useraddr)
  18. if err != nil {
  19. t.Errorf("clientAddr(%q) → SplitHostPort error %v", test.input, err)
  20. continue
  21. }
  22. if !test.expected.Equal(net.ParseIP(host)) {
  23. t.Errorf("clientAddr(%q) → host %q, not %v", test.input, host, test.expected)
  24. }
  25. portNo, err := strconv.Atoi(port)
  26. if err != nil {
  27. t.Errorf("clientAddr(%q) → port %q", test.input, port)
  28. continue
  29. }
  30. if portNo == 0 {
  31. t.Errorf("clientAddr(%q) → port %d", test.input, portNo)
  32. }
  33. }
  34. // bad tests
  35. for _, input := range []string{
  36. "",
  37. "abc",
  38. "1.2.3.4.5",
  39. "[12::34]",
  40. } {
  41. useraddr := clientAddr(input)
  42. if useraddr != "" {
  43. t.Errorf("clientAddr(%q) → %q, not %q", input, useraddr, "")
  44. }
  45. }
  46. }