mysql_encode_tests.erl 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. %% coding: utf-8
  2. %% @doc This test suite does not require an actual MySQL connection.
  3. -module(mysql_encode_tests).
  4. -include_lib("eunit/include/eunit.hrl").
  5. encode_test() ->
  6. lists:foreach(
  7. fun ({Term, Sql}) ->
  8. ?assertEqual(iolist_to_binary(Sql),
  9. iolist_to_binary(mysql_encode:encode(Term)))
  10. end,
  11. [{null, "NULL"},
  12. {42, "42"},
  13. {3.14, "3.14"},
  14. {"isn't didn't", "'isn''t didn''t'"}, %% Escape single quotes.
  15. {"\\n", "'\\n'"}, %% Don't escape backslash.
  16. %% Unicode codepoints gets encoded as UTF-8
  17. {[<<"asdf">>, "ščžć€"],
  18. <<"'asdf",197,161,196,141,197,190,196,135,226,130,172,"'">>},
  19. %% Non-Unicode binary
  20. {<<255, 0, 255, 0>>, <<"'", 255, 0, 255, 0, "'">>},
  21. %% BIT(N)
  22. {<<255, 2:3>>, "b'11111111010'"},
  23. %% Explicit decimal
  24. {{decimal, 10.2}, "10.2"},
  25. {{decimal, "10.2"}, "10.2"},
  26. %% DATE
  27. {{2014, 11, 03}, "'2014-11-03'"},
  28. {{0, 0, 0}, "'0000-00-00'"},
  29. %% TIME
  30. {{0, {10, 11, 12}}, "'10:11:12'"},
  31. {{5, {0, 0, 1}}, "'120:00:01'"},
  32. {{-1, {23, 59, 59}}, "'-00:00:01'"},
  33. {{-1, {23, 59, 0}}, "'-00:01:00'"},
  34. {{-1, {23, 0, 0}}, "'-01:00:00'"},
  35. {{-1, {0, 0, 0}}, "'-24:00:00'"},
  36. {{-5, {10, 0, 0}}, "'-110:00:00'"},
  37. {{0, {0, 0, 0}}, "'00:00:00'"},
  38. %% TIME with microseconds
  39. {{0, {23, 59, 57.654321}}, "'23:59:57.654321'"},
  40. {{5, {0, 0, 1.1}}, "'120:00:01.100000'"},
  41. {{-1, {23, 59, 57.654321}}, "'-00:00:02.345679'"},
  42. {{-1, {23, 59, 0.0}}, "'-00:01:00.000000'"},
  43. {{-6, {23, 59, 57.0}}, "'-120:00:03.000000'"},
  44. %% DATETIME
  45. {{{2014, 12, 14}, {19, 39, 20}}, "'2014-12-14 19:39:20'"},
  46. {{{2014, 12, 14}, {0, 0, 0}}, "'2014-12-14 00:00:00'"},
  47. {{{0, 0, 0}, {0, 0, 0}}, "'0000-00-00 00:00:00'"},
  48. %% DATETIME with microseconds
  49. {{{2014, 11, 23}, {23, 59, 57.654321}}, "'2014-11-23 23:59:57.654321'"}]
  50. ).
  51. backslash_escape_test() ->
  52. ?assertEqual(<<"a'b\\\\c'd\\\\e">>,
  53. iolist_to_binary(mysql_encode:backslash_escape("a'b\\c'd\\e"))).