|
| 1 | +// Copyright 2021 ecodeclub |
| 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 ekit |
| 16 | + |
| 17 | +import ( |
| 18 | + "errors" |
| 19 | + "fmt" |
| 20 | + "testing" |
| 21 | + |
| 22 | + "github.com/stretchr/testify/assert" |
| 23 | +) |
| 24 | + |
| 25 | +func TestIfThenElse(t *testing.T) { |
| 26 | + i := 7 |
| 27 | + i = IfThenElse(false, i, 0) |
| 28 | + assert.Equal(t, i, 0) |
| 29 | +} |
| 30 | + |
| 31 | +func ExampleIfThenElse() { |
| 32 | + result := IfThenElse(true, "yes", "no") |
| 33 | + fmt.Println(result) |
| 34 | + |
| 35 | + // Output: |
| 36 | + // yes |
| 37 | +} |
| 38 | + |
| 39 | +func TestIfThenElseFunc(t *testing.T) { |
| 40 | + resp, err := IfThenElseFunc(true, func() (int, error) { |
| 41 | + return 0, nil |
| 42 | + }, func() (int, error) { |
| 43 | + return 1, errors.New("some error") |
| 44 | + }) |
| 45 | + assert.NoError(t, err) |
| 46 | + assert.Equal(t, resp, 0) |
| 47 | +} |
| 48 | + |
| 49 | +func ExampleIfThenElseFunc() { |
| 50 | + code, err := IfThenElseFunc(false, func() (code int, err error) { |
| 51 | + // do something when condition is true |
| 52 | + // ... |
| 53 | + return 0, nil |
| 54 | + }, func() (code int, err error) { |
| 55 | + // do something when condition is false |
| 56 | + // ... |
| 57 | + return 1, errors.New("some error when execute func2") |
| 58 | + }) |
| 59 | + fmt.Println(code) |
| 60 | + fmt.Println(err) |
| 61 | + |
| 62 | + // Output: |
| 63 | + // 1 |
| 64 | + // some error when execute func2 |
| 65 | +} |
0 commit comments