net_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package util
  14. import (
  15. "errors"
  16. "os"
  17. "strings"
  18. "testing"
  19. )
  20. func TestGetHostname(t *testing.T) {
  21. hostname, err := os.Hostname()
  22. testCases := []struct {
  23. desc string
  24. hostname string
  25. result string
  26. expectedErr error
  27. }{
  28. {
  29. desc: "overridden hostname",
  30. hostname: "overridden",
  31. result: "overridden",
  32. expectedErr: nil,
  33. },
  34. {
  35. desc: "overridden hostname uppercase",
  36. hostname: "OVERRIDDEN",
  37. result: "overridden",
  38. expectedErr: nil,
  39. },
  40. {
  41. desc: "hostname contains only spaces",
  42. hostname: " ",
  43. result: "",
  44. expectedErr: errors.New("empty hostname is invalid"),
  45. },
  46. {
  47. desc: "empty parameter",
  48. hostname: "",
  49. result: strings.ToLower(hostname),
  50. expectedErr: err,
  51. },
  52. }
  53. for _, tc := range testCases {
  54. t.Run(tc.desc, func(t *testing.T) {
  55. result, err := GetHostname(tc.hostname)
  56. if err != nil && tc.expectedErr == nil {
  57. t.Errorf("unexpected error: %v", err)
  58. }
  59. if err == nil && tc.expectedErr != nil {
  60. t.Errorf("expected error %v, got nil", tc.expectedErr)
  61. }
  62. if tc.result != result {
  63. t.Errorf("unexpected result: %s, expected: %s", result, tc.result)
  64. }
  65. })
  66. }
  67. }