test87.cxx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "pqxx/config-public-compiler.h"
  2. #include <cctype>
  3. #include <cerrno>
  4. #include <cstring>
  5. #include <ctime>
  6. #include <iostream>
  7. #include <pqxx/internal/header-pre.hxx>
  8. #include <pqxx/internal/wait.hxx>
  9. #include <pqxx/internal/header-post.hxx>
  10. #include <pqxx/notification>
  11. #include <pqxx/transaction>
  12. #include <pqxx/transactor>
  13. #include "test_helpers.hxx"
  14. // Test program for libpqxx. Send notification to self, and wait on the
  15. // socket's connection for it to come in. In a simple situation you'd use
  16. // connection::await_notification() for this, but that won't let you wait for
  17. // multiple sockets.
  18. namespace
  19. {
  20. // Sample implementation of notification receiver.
  21. class TestListener final : public pqxx::notification_receiver
  22. {
  23. bool m_done;
  24. public:
  25. explicit TestListener(pqxx::connection &conn, std::string Name) :
  26. pqxx::notification_receiver(conn, Name), m_done(false)
  27. {}
  28. void operator()(std::string const &, int be_pid) override
  29. {
  30. m_done = true;
  31. PQXX_CHECK_EQUAL(
  32. be_pid, conn().backendpid(),
  33. "Notification came from wrong backend process.");
  34. std::cout << "Received notification: " << channel() << " pid=" << be_pid
  35. << std::endl;
  36. }
  37. bool done() const { return m_done; }
  38. };
  39. void test_087()
  40. {
  41. pqxx::connection conn;
  42. std::string const NotifName{"my notification"};
  43. TestListener L{conn, NotifName};
  44. pqxx::perform([&conn, &L] {
  45. pqxx::work tx{conn};
  46. tx.exec0("NOTIFY " + tx.quote_name(L.channel()));
  47. tx.commit();
  48. });
  49. int notifs{0};
  50. for (int i{0}; (i < 20) and not L.done(); ++i)
  51. {
  52. PQXX_CHECK_EQUAL(notifs, 0, "Got unexpected notifications.");
  53. std::cout << ".";
  54. pqxx::internal::wait_fd(conn.sock(), true, false);
  55. notifs = conn.get_notifs();
  56. }
  57. std::cout << std::endl;
  58. PQXX_CHECK(L.done(), "No notification received.");
  59. PQXX_CHECK_EQUAL(notifs, 1, "Got unexpected number of notifications.");
  60. }
  61. } // namespace
  62. PQXX_REGISTER_TEST(test_087);