internal/multierror: add tests

Signed-off-by: Andrew Keesler <ankeesler1@gmail.com>
This commit is contained in:
Andrew Keesler 2020-10-09 08:00:33 -04:00
parent b74486f305
commit fac4d074d0
No known key found for this signature in database
GPG Key ID: 167D21E5665FE20E
2 changed files with 47 additions and 11 deletions

View File

@ -1,6 +1,15 @@
// Copyright 2020 the Pinniped contributors. All Rights Reserved. // Copyright 2020 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
// Package multierror provides a type that can translate multiple errors into a Go error interface.
//
// A common use of this package is as follows.
// errs := multierror.New()
// for i := range stuff {
// err := doThing(i)
// errs.Add(err)
// }
// return errs.ErrOrNil()
package multierror package multierror
import ( import (
@ -8,31 +17,34 @@ import (
"strings" "strings"
) )
type multiError []error // MultiError holds a list of error's, that could potentially be empty.
//
// Use New() to create a MultiError.
type MultiError []error
func New() multiError { //nolint:golint // returning a private type for encapsulation purposes // New returns an empty MultiError.
func New() MultiError {
return make([]error, 0) return make([]error, 0)
} }
func (m *multiError) Add(err error) { // Add adds an error to the MultiError. The provided err must not be nil.
func (m *MultiError) Add(err error) {
*m = append(*m, err) *m = append(*m, err)
} }
func (m multiError) len() int { // Error implements the error.Error() interface method.
return len(m) func (m MultiError) Error() string {
}
func (m multiError) Error() string {
sb := strings.Builder{} sb := strings.Builder{}
_, _ = fmt.Fprintf(&sb, "%d errors:", m.len()) _, _ = fmt.Fprintf(&sb, "%d error(s):", len(m))
for _, err := range m { for _, err := range m {
_, _ = fmt.Fprintf(&sb, "\n- %s", err.Error()) _, _ = fmt.Fprintf(&sb, "\n- %s", err.Error())
} }
return sb.String() return sb.String()
} }
func (m multiError) ErrOrNil() error { // ErrOrNil returns either nil, if there are no errors in this MultiError, or an error, otherwise.
if m.len() > 0 { func (m MultiError) ErrOrNil() error {
if len(m) > 0 {
return m return m
} }
return nil return nil

View File

@ -0,0 +1,24 @@
// Copyright 2020 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package multierror
import (
"errors"
"testing"
"github.com/stretchr/testify/require"
)
func TestMultierror(t *testing.T) {
errs := New()
require.Nil(t, errs.ErrOrNil())
errs.Add(errors.New("some error 1"))
require.EqualError(t, errs.ErrOrNil(), "1 error(s):\n- some error 1")
errs.Add(errors.New("some error 2"))
errs.Add(errors.New("some error 3"))
require.EqualError(t, errs.ErrOrNil(), "3 error(s):\n- some error 1\n- some error 2\n- some error 3")
}