@@ -8,6 +8,7 @@ package safecast_test
88// This is why it needs to be tested in an architecture dependent way.
99
1010import (
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