emqx_secret_tests.erl 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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_secret_tests).
  17. -include_lib("eunit/include/eunit.hrl").
  18. wrap_unwrap_test() ->
  19. ?assertEqual(
  20. 42,
  21. emqx_secret:unwrap(emqx_secret:wrap(42))
  22. ).
  23. unwrap_immediate_test() ->
  24. ?assertEqual(
  25. 42,
  26. emqx_secret:unwrap(42)
  27. ).
  28. wrap_unwrap_load_test_() ->
  29. Secret = <<"foobaz">>,
  30. {
  31. setup,
  32. fun() -> write_temp_file(Secret) end,
  33. fun(Filename) -> file:delete(Filename) end,
  34. fun(Filename) ->
  35. ?_assertEqual(
  36. Secret,
  37. emqx_secret:unwrap(emqx_secret:wrap_load({file, Filename}))
  38. )
  39. end
  40. }.
  41. wrap_load_term_test() ->
  42. ?assertEqual(
  43. {file, "no/such/file/i/swear"},
  44. emqx_secret:term(emqx_secret:wrap_load({file, "no/such/file/i/swear"}))
  45. ).
  46. wrap_unwrap_missing_file_test() ->
  47. ?assertThrow(
  48. #{msg := failed_to_read_secret_file, reason := "No such file or directory"},
  49. emqx_secret:unwrap(emqx_secret:wrap_load({file, "no/such/file/i/swear"}))
  50. ).
  51. wrap_term_test() ->
  52. ?assertEqual(
  53. 42,
  54. emqx_secret:term(emqx_secret:wrap(42))
  55. ).
  56. external_fun_term_error_test() ->
  57. Term = {foo, bar},
  58. ?assertError(
  59. badarg,
  60. emqx_secret:term(fun() -> Term end)
  61. ).
  62. write_temp_file(Bytes) ->
  63. Ts = erlang:system_time(millisecond),
  64. Filename = filename:join("/tmp", ?MODULE_STRING ++ integer_to_list(-Ts)),
  65. ok = file:write_file(Filename, Bytes),
  66. Filename.