Skip to content

Commit 775d25b

Browse files
committed
Add a repr() fallback for any non-JSON-serializable type
The inputs could be things that aren't generically recognizable, e.g., for plain numpy, they could be numpy ufuncs.
1 parent 98db893 commit 775d25b

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

reporting.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from types import BuiltinFunctionType, FunctionType
66
import dataclasses
77
import json
8+
import warnings
89

910
from hypothesis.strategies import SearchStrategy
1011

@@ -32,6 +33,14 @@ def to_json_serializable(o):
3233
if isinstance(o, list):
3334
return [to_json_serializable(i) for i in o]
3435

36+
# Ensure everything is JSON serializable. If this warning is issued, it
37+
# means the given type needs to be added above if possible.
38+
try:
39+
json.dumps(o)
40+
except TypeError:
41+
warnings.warn(f"{o!r} (of type {type(o)}) is not JSON-serializable. Using the repr instead.")
42+
return repr(o)
43+
3544
return o
3645

3746
@mark.optionalhook
@@ -49,9 +58,6 @@ def add_extra_json_metadata(request, json_metadata):
4958
"""
5059
def add_metadata(name, obj):
5160
obj = to_json_serializable(obj)
52-
# Ensure everything is JSON serializable. If this errors, it means the
53-
# given type needs to be added to to_json_serializable above.
54-
json.dumps(obj)
5561
json_metadata[name] = obj
5662

5763
test_module = request.module.__name__

0 commit comments

Comments
 (0)