emqx_utils_tests.erl 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2023-2024 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_utils_tests).
  17. -include_lib("eunit/include/eunit.hrl").
  18. foldl_while_test_() ->
  19. [
  20. ?_assertEqual(
  21. [3, 2, 1],
  22. emqx_utils:foldl_while(fun(X, Acc) -> {cont, [X | Acc]} end, [], [1, 2, 3])
  23. ),
  24. ?_assertEqual(
  25. [1],
  26. emqx_utils:foldl_while(
  27. fun
  28. (X, Acc) when X == 2 ->
  29. {halt, Acc};
  30. (X, Acc) ->
  31. {cont, [X | Acc]}
  32. end,
  33. [],
  34. [1, 2, 3]
  35. )
  36. ),
  37. ?_assertEqual(
  38. finished,
  39. emqx_utils:foldl_while(
  40. fun
  41. (X, _Acc) when X == 3 ->
  42. {halt, finished};
  43. (X, Acc) ->
  44. {cont, [X | Acc]}
  45. end,
  46. [],
  47. [1, 2, 3]
  48. )
  49. )
  50. ].
  51. to_binary_representation(Bin) when is_binary(Bin) ->
  52. Bytes = binary_to_list(Bin),
  53. iolist_to_binary([
  54. [$<, $<],
  55. lists:join($,, [
  56. integer_to_binary(B)
  57. || B <- Bytes
  58. ]),
  59. [$>, $>]
  60. ]).
  61. readable_error_msg_test_() ->
  62. [
  63. {"binary in nested structure with non-latin1 characters",
  64. ?_assert(begin
  65. %% An unexpected error that could occur and be returned via HTTP API.
  66. Text = <<"test中文"/utf8>>,
  67. Error = {badmatch, #{description => Text}},
  68. %% Output shouldn't contain the "exploded" bytes
  69. Exploded = to_binary_representation(Text),
  70. Formatted = emqx_utils:readable_error_msg(Error),
  71. %% Precondition: `+pc unicode' must be set on the VM.
  72. ?assertEqual(unicode, io:printable_range()),
  73. nomatch =:= re:run(Formatted, Exploded, [{capture, all, binary}])
  74. end)}
  75. ].