From 2f6b427036a2760aab3c2c29aeef0b6e0ba96282 Mon Sep 17 00:00:00 2001 From: Javier Chavarri Date: Tue, 21 Jan 2025 09:47:50 +0000 Subject: [PATCH 1/2] add failing test --- src/__tests__/Json_decode_test.ml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/__tests__/Json_decode_test.ml b/src/__tests__/Json_decode_test.ml index 88cca5a..99a236f 100644 --- a/src/__tests__/Json_decode_test.ml +++ b/src/__tests__/Json_decode_test.ml @@ -86,6 +86,12 @@ let () = test "single-character string" (fun () -> expect @@ string (Encode.char 'a') |> toEqual "a"); + test "object as string" (fun () -> + try + let (_ : string) = string (Encode.jsonDict (Js.Dict.empty ())) in + fail "should throw" + with DecodeError Json_error "Expected string, got {}" -> pass); + Test.throws string [ Bool; Float; Int; Null; Array; Object ]); describe "date" (fun () -> @@ -709,6 +715,13 @@ let () = test "int" (fun () -> expect @@ (either int (field "x" int)) (Encode.int 23) |> toEqual 23); + test "object as string in either" (fun () -> + try + let a = Encode.jsonDict (Js.Dict.empty ()) in + let (_ : string) = either string string a in + fail "should throw" + with DecodeError (Json_error "All decoders given to oneOf failed. Here are all the errors: \n- [object Object]\n- [object Object]\nAnd the JSON being decoded: {}") -> pass); + Test.throws (either int (field "x" int)) [ Bool; Float; String; Null; Array; Object; Char ]); From 611b1ddd156e70d6c09811bae6bde084242eaee6 Mon Sep 17 00:00:00 2001 From: Javier Chavarri Date: Tue, 21 Jan 2025 09:55:28 +0000 Subject: [PATCH 2/2] fix --- src/Json_decode.ml | 2 +- src/__tests__/Json_decode_test.ml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Json_decode.ml b/src/Json_decode.ml index 5abdf9b..580b631 100644 --- a/src/Json_decode.ml +++ b/src/Json_decode.ml @@ -178,7 +178,7 @@ let oneOf decoders json = | [] -> let formattedErrors = "\n- " - ^ Js.Array.join ~sep:"\n- " (Array.of_list (List.rev errors)) + ^ Js.Array.join ~sep:"\n- " (Array.of_list (List.rev_map error_to_string errors)) in error ({j|All decoders given to oneOf failed. Here are all the errors: $formattedErrors\nAnd the JSON being decoded: |j} diff --git a/src/__tests__/Json_decode_test.ml b/src/__tests__/Json_decode_test.ml index 99a236f..e0c0e30 100644 --- a/src/__tests__/Json_decode_test.ml +++ b/src/__tests__/Json_decode_test.ml @@ -720,7 +720,7 @@ let () = let a = Encode.jsonDict (Js.Dict.empty ()) in let (_ : string) = either string string a in fail "should throw" - with DecodeError (Json_error "All decoders given to oneOf failed. Here are all the errors: \n- [object Object]\n- [object Object]\nAnd the JSON being decoded: {}") -> pass); + with DecodeError (Json_error "All decoders given to oneOf failed. Here are all the errors: \n- Expected string, got {}\n- Expected string, got {}\nAnd the JSON being decoded: {}") -> pass); Test.throws (either int (field "x" int))