responsable-errors/errorf_test.go
2024-01-17 15:51:28 -06:00

104 lines
2.8 KiB
Go

package errors
import (
"errors"
"net/http"
"testing"
"github.com/stretchr/testify/suite"
)
func TestErrorf(t *testing.T) {
suite.Run(t, new(ErrorfTestSuite))
}
type ErrorfTestSuite struct {
suite.Suite
}
func (s *ErrorfTestSuite) TestNoWrap() {
var err ResponsableError = Errorf(http.StatusTeapot, "%d is more than %d", 42, 13)
s.Assert().NotNil(err)
_, ok := err.(UnwrappableError)
s.Assert().False(ok)
_, ok = err.(UnwrappableErrors)
s.Assert().False(ok)
exp := "42 is more than 13"
s.Assert().Equal(exp, err.Error())
s.Assert().Equal(exp, err.GetMsg())
s.Assert().Equal(http.StatusTeapot, err.GetStatus())
}
func (s *ErrorfTestSuite) TestWrapOne() {
var wrapped error = errors.New("Here is my handle.")
var err ResponsableError = Errorf(http.StatusTeapot, "I'm a little teapot. %w", wrapped)
s.Assert().NotNil(err)
we, ok := err.(UnwrappableError)
s.Assert().True(ok)
_, ok = err.(UnwrappableErrors)
s.Assert().False(ok)
exp := "I'm a little teapot. Here is my handle."
s.Assert().Equal(exp, we.Error())
s.Assert().Equal(exp, we.GetMsg())
s.Assert().Same(wrapped, we.Unwrap())
}
func (s *ErrorfTestSuite) TestWrapTwo() {
var wrappedOne error = errors.New("short and stout")
var wrappedTwo error = errors.New("Here is my handle.")
var err ResponsableError = Errorf(http.StatusTeapot, "I'm a little teapot: %w. %w", wrappedOne, wrappedTwo)
s.Assert().NotNil(err)
_, ok := err.(UnwrappableError)
s.Assert().False(ok)
we, ok := err.(UnwrappableErrors)
s.Assert().True(ok)
exp := "I'm a little teapot: short and stout. Here is my handle."
s.Assert().Equal(exp, we.Error())
s.Assert().Equal(exp, we.GetMsg())
unwrapped := we.Unwrap()
s.Assert().Len(unwrapped, 2)
s.Assert().Same(wrappedOne, unwrapped[0])
s.Assert().Same(wrappedTwo, unwrapped[1])
}
func (s *ErrorfTestSuite) TestSet() {
var err SettableError = Errorf(http.StatusTeapot, "Unable to BREW")
s.Assert().NotNil(err)
err.Status(http.StatusTooEarly).Msg("It's only %dAM", 2)
s.Assert().Equal(http.StatusTooEarly, err.GetStatus())
s.Assert().Equal("It's only 2AM", err.GetMsg())
s.Assert().Equal("Unable to BREW", err.Error())
err.Msg("I am so great")
s.Assert().Equal("I am so great", err.GetMsg())
}
func (s *ErrorfTestSuite) TestGetStatusOutsideRange() {
var err ResponsableError = Errorf(5, "Hello")
s.Assert().NotNil(err)
s.Assert().Equal(http.StatusInternalServerError, err.GetStatus())
err = Errorf(5, "Hello")
s.Assert().NotNil(err)
s.Assert().Equal(http.StatusInternalServerError, err.GetStatus())
}
func (s *ErrorfTestSuite) TestSetStatusOutsideRange() {
var err SettableError = Errorf(http.StatusPaymentRequired, "Hello")
s.Assert().NotNil(err)
err.Status(10)
s.Assert().Equal(http.StatusPaymentRequired, err.GetStatus())
err.Status(600)
s.Assert().Equal(http.StatusPaymentRequired, err.GetStatus())
}