Skip to content

Commit

Permalink
Add FailureMessage.Err method and AssertionError type (#141)
Browse files Browse the repository at this point in the history
  • Loading branch information
lycis authored Sep 10, 2024
1 parent 7b197d1 commit 83844e9
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this library adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased](https://github.com/fluentassert/verify/compare/v1.1.0...HEAD)

### Added

- Add `FailureMessage.Err` method together with `AssertionError` type
to represent assertion results as `error` type.

## [1.1.0](https://github.com/fluentassert/verify/releases/tag/v1.1.0) - 2024-02-06

This release adds length assertions.
Expand Down
12 changes: 12 additions & 0 deletions assertion_error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package verify

// AssertionError is an error type used to represent failure messages from assertions.
// It is compatible with the error interface and can be used in instances where an error shall be returned instead of failing a test.
type AssertionError struct {
Message FailureMessage
}

// Error returns the failure message as a string. It makes AssertionError compatible with the error interface.
func (err *AssertionError) Error() string {
return string(err.Message)
}
9 changes: 9 additions & 0 deletions failmsg.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,12 @@ func (msg FailureMessage) Prefix(s string) FailureMessage {
}
return FailureMessage(s) + msg
}

// Err returns the failure message as an error type, or nil if the message is empty.
func (msg FailureMessage) Err() *AssertionError {
if msg == "" {
return nil
}

return &AssertionError{Message: msg}
}
12 changes: 12 additions & 0 deletions failmsg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,18 @@ func TestFailureMessage(t *testing.T) {
assertEqual(t, got, "[fail] errored")
})
})

t.Run("AsError", func(t *testing.T) {
t.Run("With Message", func(t *testing.T) {
got := verify.FailureMessage("failed").Err()
assertEqual(t, got.Error(), "failed")
})

t.Run("Empty", func(t *testing.T) {
got := verify.FailureMessage("").Err()
assertEqual(t, got, nil)
})
})
}

type errorMock struct {
Expand Down

0 comments on commit 83844e9

Please sign in to comment.