error_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. Copyright 2016 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. "github.com/pkg/errors"
  16. "testing"
  17. )
  18. type pferror struct{}
  19. func (p *pferror) Preflight() bool { return true }
  20. func (p *pferror) Error() string { return "" }
  21. func TestCheckErr(t *testing.T) {
  22. var codeReturned int
  23. errHandle := func(err string, code int) {
  24. codeReturned = code
  25. }
  26. var tests = []struct {
  27. name string
  28. e error
  29. expected int
  30. }{
  31. {"error is nil", nil, 0},
  32. {"empty error", errors.New(""), DefaultErrorExitCode},
  33. {"preflight error", &pferror{}, PreFlightExitCode},
  34. }
  35. for _, rt := range tests {
  36. t.Run(rt.name, func(t *testing.T) {
  37. codeReturned = 0
  38. checkErr(rt.e, errHandle)
  39. if codeReturned != rt.expected {
  40. t.Errorf(
  41. "failed checkErr:\n\texpected: %d\n\t actual: %d",
  42. rt.expected,
  43. codeReturned,
  44. )
  45. }
  46. })
  47. }
  48. }
  49. func TestFormatErrMsg(t *testing.T) {
  50. errMsg1 := "specified version to upgrade to v1.9.0-alpha.3 is equal to or lower than the cluster version v1.10.0-alpha.0.69+638add6ddfb6d2. Downgrades are not supported yet"
  51. errMsg2 := "specified version to upgrade to v1.9.0-alpha.3 is higher than the kubeadm version v1.9.0-alpha.1.3121+84178212527295-dirty. Upgrade kubeadm first using the tool you used to install kubeadm"
  52. testCases := []struct {
  53. name string
  54. errs []error
  55. expect string
  56. }{
  57. {
  58. name: "two errors",
  59. errs: []error{
  60. errors.New(errMsg1),
  61. errors.New(errMsg2),
  62. },
  63. expect: "\t- " + errMsg1 + "\n" + "\t- " + errMsg2 + "\n",
  64. },
  65. {
  66. name: "one error",
  67. errs: []error{
  68. errors.New(errMsg1),
  69. },
  70. expect: "\t- " + errMsg1 + "\n",
  71. },
  72. }
  73. for _, testCase := range testCases {
  74. t.Run(testCase.name, func(t *testing.T) {
  75. got := FormatErrMsg(testCase.errs)
  76. if got != testCase.expect {
  77. t.Errorf("FormatErrMsg error, expect: %v, got: %v", testCase.expect, got)
  78. }
  79. })
  80. }
  81. }