test04.cxx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <cerrno>
  2. #include <chrono>
  3. #include <cstring>
  4. #include <ctime>
  5. #include <pqxx/internal/header-pre.hxx>
  6. #include <pqxx/internal/wait.hxx>
  7. #include <pqxx/internal/header-post.hxx>
  8. #include <pqxx/notification>
  9. #include <pqxx/transaction>
  10. #include <pqxx/transactor>
  11. #include "test_helpers.hxx"
  12. using namespace pqxx;
  13. // Example program for libpqxx. Send notification to self.
  14. namespace
  15. {
  16. int Backend_PID{0};
  17. // Sample implementation of notification receiver.
  18. class TestListener final : public notification_receiver
  19. {
  20. bool m_done;
  21. public:
  22. explicit TestListener(connection &conn) :
  23. notification_receiver(conn, "listen"), m_done(false)
  24. {}
  25. virtual void operator()(std::string const &, int be_pid) override
  26. {
  27. m_done = true;
  28. PQXX_CHECK_EQUAL(
  29. be_pid, Backend_PID, "Notification came from wrong backend process.");
  30. }
  31. bool done() const { return m_done; }
  32. };
  33. void test_004()
  34. {
  35. connection conn;
  36. TestListener L{conn};
  37. // Trigger our notification receiver.
  38. perform([&conn, &L] {
  39. work tx(conn);
  40. tx.exec0("NOTIFY " + conn.quote_name(L.channel()));
  41. Backend_PID = conn.backendpid();
  42. tx.commit();
  43. });
  44. int notifs{0};
  45. for (int i{0}; (i < 20) and not L.done(); ++i)
  46. {
  47. PQXX_CHECK_EQUAL(notifs, 0, "Got unexpected notifications.");
  48. // Sleep for one second. I'm not proud of this, but how does one inject
  49. // a change to the built-in clock in a static language?
  50. pqxx::internal::wait_for(1'000'000u);
  51. notifs = conn.get_notifs();
  52. }
  53. PQXX_CHECK_NOT_EQUAL(L.done(), false, "No notification received.");
  54. PQXX_CHECK_EQUAL(notifs, 1, "Got too many notifications.");
  55. }
  56. PQXX_REGISTER_TEST(test_004);
  57. } // namespace