test_notification.cxx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <chrono>
  2. #include <pqxx/internal/header-pre.hxx>
  3. #include <pqxx/internal/wait.hxx>
  4. #include <pqxx/internal/header-post.hxx>
  5. #include <pqxx/nontransaction>
  6. #include <pqxx/notification>
  7. #include "../test_helpers.hxx"
  8. namespace
  9. {
  10. class TestReceiver final : public pqxx::notification_receiver
  11. {
  12. public:
  13. std::string payload;
  14. int backend_pid;
  15. TestReceiver(pqxx::connection &c, std::string const &channel_name) :
  16. pqxx::notification_receiver(c, channel_name),
  17. payload(),
  18. backend_pid(0)
  19. {}
  20. virtual void
  21. operator()(std::string const &payload_string, int backend) override
  22. {
  23. this->payload = payload_string;
  24. this->backend_pid = backend;
  25. }
  26. };
  27. void test_receive(
  28. pqxx::transaction_base &t, std::string const &channel,
  29. char const payload[] = nullptr)
  30. {
  31. pqxx::connection &conn(t.conn());
  32. std::string SQL{"NOTIFY \"" + channel + "\""};
  33. if (payload != nullptr)
  34. SQL += ", " + t.quote(payload);
  35. TestReceiver receiver{t.conn(), channel};
  36. // Clear out any previously pending notifications that might otherwise
  37. // confuse the test.
  38. conn.get_notifs();
  39. // Notify, and receive.
  40. t.exec(SQL);
  41. t.commit();
  42. int notifs{0};
  43. for (int i{0}; (i < 10) and (notifs == 0);
  44. ++i, pqxx::internal::wait_for(1'000'000u))
  45. notifs = conn.get_notifs();
  46. PQXX_CHECK_EQUAL(notifs, 1, "Got wrong number of notifications.");
  47. PQXX_CHECK_EQUAL(receiver.backend_pid, conn.backendpid(), "Bad pid.");
  48. if (payload == nullptr)
  49. PQXX_CHECK(std::empty(receiver.payload), "Unexpected payload.");
  50. else
  51. PQXX_CHECK_EQUAL(receiver.payload, payload, "Bad payload.");
  52. }
  53. void test_notification()
  54. {
  55. pqxx::connection conn;
  56. TestReceiver receiver(conn, "mychannel");
  57. PQXX_CHECK_EQUAL(receiver.channel(), "mychannel", "Bad channel.");
  58. pqxx::work tx{conn};
  59. test_receive(tx, "channel1");
  60. pqxx::nontransaction u(conn);
  61. test_receive(u, "channel2", "payload");
  62. }
  63. PQXX_REGISTER_TEST(test_notification);
  64. } // namespace