epgsql_ct.erl 2.5 KB

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