11package spiceerrors
22
33import (
4+ "os"
45 "testing"
56
67 "github.com/stretchr/testify/assert"
@@ -14,3 +15,59 @@ func TestMustBug(t *testing.T) {
1415 require .Error (t , err )
1516 }, "The code did not panic" )
1617}
18+
19+ func TestMustSafecast (t * testing.T ) {
20+ require .True (t , IsInTests ())
21+
22+ // Test successful conversion
23+ t .Run ("successful conversion" , func (t * testing.T ) {
24+ result := MustSafecast [uint64 ](42 )
25+ assert .Equal (t , uint64 (42 ), result )
26+
27+ result2 := MustSafecast [int32 ](100 )
28+ assert .Equal (t , int32 (100 ), result2 )
29+ })
30+
31+ // Test that conversion failure panics in tests
32+ t .Run ("conversion failure panics in tests" , func (t * testing.T ) {
33+ assert .Panics (t , func () {
34+ // Try to convert a negative number to unsigned
35+ MustSafecast [uint64 ](- 1 )
36+ }, "Expected panic on invalid conversion" )
37+ })
38+
39+ // Test conversion from larger to smaller type that fits
40+ t .Run ("conversion within range" , func (t * testing.T ) {
41+ result := MustSafecast [uint32 ](uint64 (100 ))
42+ assert .Equal (t , uint32 (100 ), result )
43+ })
44+
45+ // Test production behavior (returns zero value without panic)
46+ t .Run ("production behavior returns zero on failure" , func (t * testing.T ) {
47+ // Temporarily simulate production by removing test flags from os.Args
48+ originalArgs := os .Args
49+ defer func () {
50+ os .Args = originalArgs
51+ }()
52+
53+ // Remove all -test.* flags to simulate production
54+ var nonTestArgs []string
55+ for _ , arg := range os .Args {
56+ if len (arg ) < 6 || arg [:6 ] != "-test." {
57+ nonTestArgs = append (nonTestArgs , arg )
58+ }
59+ }
60+ os .Args = nonTestArgs
61+
62+ // Verify we're now simulating production
63+ require .False (t , IsInTests (), "Should simulate production mode" )
64+
65+ // Test that conversion failure returns zero in production
66+ result := MustSafecast [uint64 ](- 1 )
67+ assert .Equal (t , uint64 (0 ), result , "Expected zero value in production mode" )
68+
69+ // Test overflow case
70+ result2 := MustSafecast [uint8 ](300 )
71+ assert .Equal (t , uint8 (0 ), result2 , "Expected zero value for overflow in production mode" )
72+ })
73+ }
0 commit comments