| 1 | // Copyright 2020 CNI authors |
| 2 | // |
| 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 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package errors |
| 16 | |
| 17 | import ( |
| 18 | "errors" |
| 19 | "reflect" |
| 20 | "testing" |
| 21 | ) |
| 22 | |
| 23 | func TestAnnotate(t *testing.T) { |
| 24 | tests := []struct { |
| 25 | name string |
| 26 | existingErr error |
| 27 | contextMessage string |
| 28 | expectedErr error |
| 29 | }{ |
| 30 | { |
| 31 | "nil error", |
| 32 | nil, |
| 33 | "context", |
| 34 | nil, |
| 35 | }, |
| 36 | { |
| 37 | "normal case", |
| 38 | errors.New("existing error"), |
| 39 | "context", |
| 40 | errors.New("context: existing error"), |
| 41 | }, |
| 42 | } |
| 43 | |
| 44 | for _, test := range tests { |
| 45 | t.Run(test.name, func(t *testing.T) { |
| 46 | if !reflect.DeepEqual(Annotate(test.existingErr, test.contextMessage), test.expectedErr) { |
| 47 | t.Errorf("test case %s fails", test.name) |
| 48 | return |
| 49 | } |
| 50 | }) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | func TestAnnotatef(t *testing.T) { |
| 55 | tests := []struct { |
| 56 | name string |
| 57 | existingErr error |
| 58 | contextMessage string |
| 59 | contextArgs []interface{} |
| 60 | expectedErr error |
| 61 | }{ |
| 62 | { |
| 63 | "nil error", |
| 64 | nil, |
| 65 | "context", |
| 66 | nil, |
| 67 | nil, |
| 68 | }, |
| 69 | { |
| 70 | "normal case", |
| 71 | errors.New("existing error"), |
| 72 | "context", |
| 73 | nil, |
| 74 | errors.New("context: existing error"), |
| 75 | }, |
| 76 | { |
| 77 | "normal case with args", |
| 78 | errors.New("existing error"), |
| 79 | "context %s %d", |
| 80 | []interface{}{ |
| 81 | "arg", |
| 82 | 100, |
| 83 | }, |
| 84 | errors.New("context arg 100: existing error"), |
| 85 | }, |
| 86 | } |
| 87 | |
| 88 | for _, test := range tests { |
| 89 | t.Run(test.name, func(t *testing.T) { |
| 90 | if !reflect.DeepEqual(Annotatef(test.existingErr, test.contextMessage, test.contextArgs...), test.expectedErr) { |
| 91 | t.Errorf("test case %s fails", test.name) |
| 92 | return |
| 93 | } |
| 94 | }) |
| 95 | } |
| 96 | } |