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.Msg()) s.Assert().Equal(http.StatusTeapot, err.Status()) } 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.Msg()) 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.Msg()) 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.SetStatus(http.StatusTooEarly).SetMsg("It's only %dAM", 2) s.Assert().Equal(http.StatusTooEarly, err.Status()) s.Assert().Equal("It's only 2AM", err.Msg()) s.Assert().Equal("Unable to BREW", err.Error()) err.SetMsg("I am so great") s.Assert().Equal("I am so great", err.Msg()) } func (s *ErrorfTestSuite) TestGetStatusOutsideRange() { var err ResponsableError = Errorf(5, "Hello") s.Assert().NotNil(err) s.Assert().Equal(http.StatusInternalServerError, err.Status()) err = Errorf(5, "Hello") s.Assert().NotNil(err) s.Assert().Equal(http.StatusInternalServerError, err.Status()) } func (s *ErrorfTestSuite) TestSetStatusOutsideRange() { var err SettableError = Errorf(http.StatusPaymentRequired, "Hello") s.Assert().NotNil(err) err.SetStatus(10) s.Assert().Equal(http.StatusPaymentRequired, err.Status()) err.SetStatus(600) s.Assert().Equal(http.StatusPaymentRequired, err.Status()) }