Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add MustConvert #59

Merged
merged 1 commit into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
})
}
})
}
Loading