Skip to content

Commit 18f613b

Browse files
committed
feat: add MustConvert
This function calls Convert and panics if there is an error
1 parent 214bd73 commit 18f613b

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

conversion.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,15 @@ func Convert[NumOut Number](orig any) (converted NumOut, err error) {
6161
}
6262
}
6363

64+
// MustConvert calls [Convert] to convert the value to the desired type, and panics if the conversion fails.
65+
func MustConvert[NumOut Number](orig any) NumOut {
66+
converted, err := Convert[NumOut](orig)
67+
if err != nil {
68+
panic(err)
69+
}
70+
return converted
71+
}
72+
6473
func convertFromNumber[NumOut Number, NumIn Number](orig NumIn) (converted NumOut, err error) {
6574
converted = NumOut(orig)
6675

conversion_test.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ package safecast_test
88
// This is why it needs to be tested in an architecture dependent way.
99

1010
import (
11+
"errors"
1112
"fmt"
1213
"math"
1314
"testing"
@@ -1929,3 +1930,64 @@ func TestConvert(t *testing.T) {
19291930
}
19301931
})
19311932
}
1933+
1934+
func TestMustConvert(t *testing.T) {
1935+
// [TestConvert] tested all the cases
1936+
// here we are simply checking that the function panic on errors
1937+
1938+
t.Run("panic on error", func(t *testing.T) {
1939+
for name, input := range map[string]any{
1940+
"nil": nil,
1941+
"negative": -1,
1942+
"overflow": math.MaxInt,
1943+
"string": "cats",
1944+
} {
1945+
t.Run(name, func(t *testing.T) {
1946+
// configure validate there is no panic
1947+
defer func(t *testing.T) {
1948+
t.Helper()
1949+
1950+
r := recover()
1951+
if r == nil {
1952+
t.Fatal("did not panic")
1953+
}
1954+
1955+
err, ok := r.(error)
1956+
if !ok {
1957+
t.Fatalf("panic value is not an error: %v", r)
1958+
}
1959+
1960+
if !errors.Is(err, safecast.ErrConversionIssue) {
1961+
t.Fatalf("panic with unexpected error: %v", err)
1962+
}
1963+
}(t)
1964+
1965+
safecast.MustConvert[uint8](input)
1966+
})
1967+
}
1968+
})
1969+
1970+
t.Run("no panic", func(t *testing.T) {
1971+
for name, input := range map[string]any{
1972+
"number": 42,
1973+
"string": "42",
1974+
"octal": "0o52",
1975+
"float": 42.0,
1976+
} {
1977+
t.Run(name, func(t *testing.T) {
1978+
// configure a helper to validate there is no panic
1979+
defer func(t *testing.T) {
1980+
t.Helper()
1981+
1982+
err := recover()
1983+
if err != nil {
1984+
t.Fatalf("panic with %v", err)
1985+
}
1986+
}(t)
1987+
1988+
converted := safecast.MustConvert[int](input)
1989+
assertEqual(t, 42, converted)
1990+
})
1991+
}
1992+
})
1993+
}

0 commit comments

Comments
 (0)