Skip to content

Commit

Permalink
fix extend message bug (#13)
Browse files Browse the repository at this point in the history
### Background

→ when cloning a message we always add a space separator but this is
wrong. Only do it sometimes.

### Changes

- fix bug

### Testing

- added regression tests
  • Loading branch information
drshriveer authored Sep 22, 2023
1 parent c0c6e4c commit 9089801
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 1 deletion.
11 changes: 10 additions & 1 deletion gerror/factory.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package gerror

import (
"strings"
)

// The Factory interface exposes only methods that can be used for cloning an error.
// But all errors implement this by default.
// This allows for dynamic and mutable errors without modifying the base.
Expand Down Expand Up @@ -118,8 +122,13 @@ func CloneBase[T factoryOf](
}

// handle message extension:
extMsg = strings.TrimSpace(extMsg)
if len(extMsg) > 0 {
clone.Message += " " + extMsg
if len(clone.Message) == 0 {
clone.Message = extMsg
} else {
clone.Message += " " + extMsg
}
}

// handle error inheritance:
Expand Down
67 changes: 67 additions & 0 deletions gerror/factory_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package gerror_test

import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/drshriveer/gtools/gerror"
)

func TestCloneBase(t *testing.T) {
t.Parallel()
ErrNoMessage := gerror.FactoryOf(&gerror.GError{
Name: "ErrBase",
Message: "",
Source: "",
})

tests := []struct {
description string
input gerror.Error

expectedName string
expectedMessage string
expectedSource string
expectedDetailTag string
}{
{
description: "add message does not include extra white space",
input: ErrNoMessage.Msg("hi! blah"),
expectedName: "ErrBase",
expectedSource: "gerror_test:TestCloneBase",
expectedMessage: "hi! blah",
},
{
description: "add message is trimmed",
input: ErrNoMessage.Msg(" hi! blah "),
expectedName: "ErrBase",
expectedSource: "gerror_test:TestCloneBase",
expectedMessage: "hi! blah",
},
{
description: "add message is trimmed + chaining",
input: ErrNoMessage.Msg(" hi! blah ").(*gerror.GError).Msg(" \t bye! "),
expectedName: "ErrBase",
expectedSource: "gerror_test:TestCloneBase",
expectedMessage: "hi! blah bye!",
},
{
description: "lots of whitespace is trimmed",
input: ErrNoMessage.Msg(" hi! blah \n"),
expectedName: "ErrBase",
expectedSource: "gerror_test:TestCloneBase",
expectedMessage: "hi! blah",
},
}

for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
t.Parallel()
assert.Equal(t, test.expectedName, test.input.ErrName())
assert.Equal(t, test.expectedMessage, test.input.ErrMessage())
assert.Equal(t, test.expectedSource, test.input.ErrSource())
assert.Equal(t, test.expectedDetailTag, test.input.ErrDetailTag())
})
}
}

0 comments on commit 9089801

Please sign in to comment.