1
1
package render
2
2
3
3
import (
4
+ "encoding/json"
4
5
"fmt"
5
6
"io"
7
+ "math"
6
8
"net/http"
7
9
"net/http/httptest"
8
10
"strconv"
@@ -26,10 +28,43 @@ func TestJSON(t *testing.T) {
26
28
assert .Empty (t , rw .Fields ())
27
29
}
28
30
29
- func TestJSONPanics (t * testing.T ) {
30
- assert .Panics (t , func () {
31
- JSON (httptest .NewRecorder (), make (chan struct {}))
32
- })
31
+ func TestJSONPanicsOnUnsupportedType (t * testing.T ) {
32
+ jsonPanicTest [json.UnsupportedTypeError ](t , make (chan struct {}))
33
+ }
34
+
35
+ func TestJSONPanicsOnUnsupportedValue (t * testing.T ) {
36
+ jsonPanicTest [json.UnsupportedValueError ](t , math .NaN ())
37
+ }
38
+
39
+ func TestJSONPanicsOnMarshalerError (t * testing.T ) {
40
+ var v erroneousJSONMarshaler
41
+ jsonPanicTest [json.MarshalerError ](t , v )
42
+ }
43
+
44
+ type erroneousJSONMarshaler struct {}
45
+
46
+ func (erroneousJSONMarshaler ) MarshalJSON () ([]byte , error ) {
47
+ return nil , assert .AnError
48
+ }
49
+
50
+ func jsonPanicTest [T json.UnsupportedTypeError | json.UnsupportedValueError | json.MarshalerError ](t * testing.T , v any ) {
51
+ t .Helper ()
52
+
53
+ defer func () {
54
+ var err error
55
+ if r := recover (); r == nil {
56
+ t .Fatal ("expected panic" )
57
+ } else if e , ok := r .(error ); ! ok {
58
+ t .Fatalf ("did not panic with an error (%T)" , r )
59
+ } else {
60
+ err = e
61
+ }
62
+
63
+ var e * T
64
+ assert .ErrorAs (t , err , & e )
65
+ }()
66
+
67
+ JSON (httptest .NewRecorder (), v )
33
68
}
34
69
35
70
type renderableError struct {
0 commit comments