emqx_http_lib_tests.erl 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2021 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_http_lib_tests).
  17. -include_lib("proper/include/proper.hrl").
  18. -include_lib("eunit/include/eunit.hrl").
  19. uri_encode_decode_test_() ->
  20. Opts = [{numtests, 1000}, {to_file, user}],
  21. {timeout, 10,
  22. fun() -> ?assert(proper:quickcheck(prop_run(), Opts)) end}.
  23. prop_run() ->
  24. ?FORALL(Generated, prop_uri(), test_prop_uri(iolist_to_binary(Generated))).
  25. prop_uri() ->
  26. proper_types:non_empty(proper_types:list(proper_types:union([prop_char(), prop_reserved()]))).
  27. prop_char() -> proper_types:integer(32, 126).
  28. prop_reserved() ->
  29. proper_types:oneof([$;, $:, $@, $&, $=, $+, $,, $/, $?,
  30. $#, $[, $], $<, $>, $\", ${, $}, $|,
  31. $\\, $', $^, $%, $ ]).
  32. test_prop_uri(URI) ->
  33. Encoded = emqx_http_lib:uri_encode(URI),
  34. Decoded1 = emqx_http_lib:uri_decode(Encoded),
  35. ?assertEqual(URI, Decoded1),
  36. Decoded2 = uri_string:percent_decode(Encoded),
  37. ?assertEqual(URI, Decoded2),
  38. true.
  39. uri_parse_test_() ->
  40. [ {"default port http",
  41. fun() -> ?assertMatch({ok, #{port := 80, scheme := http, host := "localhost"}},
  42. emqx_http_lib:uri_parse("localhost"))
  43. end
  44. }
  45. , {"default port https",
  46. fun() -> ?assertMatch({ok, #{port := 443, scheme := https}},
  47. emqx_http_lib:uri_parse("https://localhost"))
  48. end
  49. }
  50. , {"bad url",
  51. fun() -> ?assertMatch({error, {invalid_uri, _}},
  52. emqx_http_lib:uri_parse("https://localhost:notnumber"))
  53. end
  54. }
  55. , {"normalise",
  56. fun() -> ?assertMatch({ok, #{scheme := https}},
  57. emqx_http_lib:uri_parse("HTTPS://127.0.0.1"))
  58. end
  59. }
  60. , {"unsupported_scheme",
  61. fun() -> ?assertEqual({error, {unsupported_scheme, <<"wss">>}},
  62. emqx_http_lib:uri_parse("wss://127.0.0.1"))
  63. end
  64. }
  65. ].