You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
2.4 KiB

  1. % This file is part of Jiffy released under the MIT license.
  2. % See the LICENSE file for more information.
  3. -module(jiffy_tests).
  4. -include_lib("proper/include/proper.hrl").
  5. -include_lib("eunit/include/eunit.hrl").
  6. proper_test_() ->
  7. PropErOpts = [
  8. {to_file, user},
  9. {max_size, 30},
  10. {numtests, 1000}
  11. ],
  12. {timeout, 3600, ?_assertEqual([], proper:module(jiffy_tests, PropErOpts))}.
  13. prop_encode_decode() ->
  14. ?FORALL(Data, json(),
  15. begin
  16. %io:format(standard_error, "Data: ~p~n", [Data]),
  17. Data == jiffy:decode(jiffy:encode(Data))
  18. end
  19. ).
  20. prop_encode_not_crash() ->
  21. ?FORALL(Data, any(), begin catch jiffy:encode(Data), true end).
  22. prop_decode_not_crash_bin() ->
  23. ?FORALL(Data, binary(), begin catch jiffy:decode(Data), true end).
  24. prop_decode_not_crash_any() ->
  25. ?FORALL(Data, any(), begin catch jiffy:decode(Data), true end).
  26. % JSON Generation
  27. json_null() ->
  28. null.
  29. json_boolean() ->
  30. oneof([true, false]).
  31. json_number() ->
  32. oneof([integer(), float()]).
  33. json_string() ->
  34. escaped_utf8_bin().
  35. json_list(S) when S =< 0 ->
  36. [];
  37. json_list(S) ->
  38. ?LETSHRINK(
  39. [ListSize],
  40. [integer(0, S)],
  41. vector(ListSize, json_text(S - ListSize))
  42. ).
  43. json_object(S) when S =< 0 ->
  44. {[]};
  45. json_object(S) ->
  46. ?LETSHRINK(
  47. [ObjectSize],
  48. [integer(0, S)],
  49. {vector(ObjectSize, {json_string(), json_text(S - ObjectSize)})}
  50. ).
  51. json_value() ->
  52. oneof([
  53. json_null(),
  54. json_boolean(),
  55. json_string(),
  56. json_number()
  57. ]).
  58. json_text(S) when S > 0 ->
  59. ?LAZY(oneof([
  60. json_list(S),
  61. json_object(S)
  62. ]));
  63. json_text(_) ->
  64. json_value().
  65. json() ->
  66. ?SIZED(S, json_text(S)).
  67. %% XXX: Add generators
  68. %
  69. % We should add generators that generate JSON binaries directly
  70. % so we can test things that aren't produced by the encoder.
  71. %
  72. % We should also have a version of the JSON generator that inserts
  73. % errors into the JSON that we can test for.
  74. escaped_utf8_bin() ->
  75. ?SUCHTHAT(Bin,
  76. ?LET(S, ?SUCHTHAT(L, list(escaped_char()), L /= []),
  77. unicode:characters_to_binary(S, unicode, utf8)),
  78. is_binary(Bin)
  79. ).
  80. escaped_char() ->
  81. ?LET(C, char(),
  82. case C of
  83. $" -> "\\\"";
  84. C when C == 65534 -> 65533;
  85. C when C == 65535 -> 65533;
  86. C when C > 1114111 -> 1114111;
  87. C -> C
  88. end
  89. ).