epgsql_ct.erl 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. -module(epgsql_ct).
  2. -include_lib("common_test/include/ct.hrl").
  3. -include_lib("eunit/include/eunit.hrl").
  4. -export([
  5. connect_only/2,
  6. with_connection/2,
  7. with_connection/3,
  8. with_connection/4,
  9. with_rollback/2,
  10. with_min_version/4,
  11. flush/0
  12. ]).
  13. connect_only(Config, Args) ->
  14. #{pg_host := Host, pg_port := Port} = ?config(pg_config, Config),
  15. Module = ?config(module, Config),
  16. TestOpts = [{port, Port}],
  17. case Args of
  18. [User, Opts] -> Args2 = [User, TestOpts ++ Opts];
  19. [User, Pass, Opts] -> Args2 = [User, Pass, TestOpts ++ Opts];
  20. Opts -> Args2 = [TestOpts ++ Opts]
  21. end,
  22. {ok, C} = apply(Module, connect, [Host | Args2]),
  23. Module:close(C),
  24. flush().
  25. with_connection(Config, F) ->
  26. with_connection(Config, F, "epgsql_test", []).
  27. with_connection(Config, F, Args) ->
  28. with_connection(Config, F, "epgsql_test", Args).
  29. with_connection(Config, F, Username, Args) ->
  30. #{pg_host := Host, pg_port := Port} = ?config(pg_config, Config),
  31. Module = ?config(module, Config),
  32. Args2 = [{port, Port}, {database, "epgsql_test_db1"} | Args],
  33. {ok, C} = Module:connect(Host, Username, Args2),
  34. try
  35. F(C)
  36. after
  37. Module:close(C)
  38. end,
  39. flush().
  40. with_rollback(Config, F) ->
  41. Module = ?config(module, Config),
  42. with_connection(
  43. Config,
  44. fun(C) ->
  45. try
  46. Module:squery(C, "begin"),
  47. F(C)
  48. after
  49. Module:squery(C, "rollback")
  50. end
  51. end).
  52. with_min_version(Config, Min, F, Args) ->
  53. Module = ?config(module, Config),
  54. epgsql_ct:with_connection(Config, fun(C) ->
  55. {ok, Bin} = Module:get_parameter(C, <<"server_version">>),
  56. {ok, [{float, 1, Ver} | _], _} = erl_scan:string(binary_to_list(Bin)),
  57. case Ver >= Min of
  58. true -> F(C);
  59. false -> ?debugFmt("skipping test requiring PostgreSQL >= ~.2f~n", [Min])
  60. end
  61. end, Args).
  62. %% flush mailbox
  63. flush() ->
  64. ?assertEqual([], flush([])).
  65. flush(Acc) ->
  66. receive
  67. {'EXIT', _Pid, normal} -> flush(Acc);
  68. M -> flush([M | Acc])
  69. after
  70. 0 -> lists:reverse(Acc)
  71. end.