Skip to content

Commit

Permalink
feat: add MustConvert
Browse files Browse the repository at this point in the history
This function calls Convert and panics if there is an error
  • Loading branch information
ccoVeille committed Dec 18, 2024
1 parent 214bd73 commit fb7490a
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
9 changes: 9 additions & 0 deletions conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,15 @@ func Convert[NumOut Number](orig any) (converted NumOut, err error) {
}
}

// MustConvert calls [Convert] to convert the value to the desired type, and panics if the conversion fails.
func MustConvert[NumOut Number](orig any) NumOut {
converted, err := Convert[NumOut](orig)
if err != nil {
panic(err)
}
return converted
}

func convertFromNumber[NumOut Number, NumIn Number](orig NumIn) (converted NumOut, err error) {
converted = NumOut(orig)

Expand Down
62 changes: 62 additions & 0 deletions conversion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package safecast_test
// This is why it needs to be tested in an architecture dependent way.

import (
"errors"
"fmt"
"math"
"testing"
Expand Down Expand Up @@ -1929,3 +1930,64 @@ func TestConvert(t *testing.T) {
}
})
}

func TestMustConvert(t *testing.T) {
// [TestConvert] tested all the cases
// here we are simply checking that the function panic on errors

t.Run("panic on error", func(t *testing.T) {
for name, input := range map[string]any{
"nil": nil,
"negative": -1,
"overflow": math.MaxInt,
"string": "cats",
} {
t.Run(name, func(t *testing.T) {
// configure validate there is no panic
defer func(t *testing.T) {
t.Helper()

r := recover()
if r == nil {
t.Fatal("did not panic")
}

err, ok := r.(error)
if !ok {
t.Fatalf("panic value is not an error: %v", r)
}

if !errors.Is(err, safecast.ErrConversionIssue) {
t.Fatalf("panic with unexpected error: %v", err)
}
}(t)

safecast.MustConvert[uint8](input)
})
}
})

t.Run("no panic", func(t *testing.T) {
for name, input := range map[string]any{
"number": 42,
"string": "42",
"octal": "0o52",
"float": 42.0,
} {
t.Run(name, func(t *testing.T) {
// configure a helper to validate there is no panic
defer func(t *testing.T) {
t.Helper()

err := recover()
if err != nil {
t.Fatalf("panic with %v", err)
}
}(t)

converted := safecast.MustConvert[int](input)
assertEqual(t, 42, converted)
})
}
})
}

0 comments on commit fb7490a

Please sign in to comment.