epgsql_ct.erl 2.5 KB

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