1
0

abstractServer.hpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #ifndef CPR_TEST_ABSTRACT_SERVER_SERVER_H
  2. #define CPR_TEST_ABSTRACT_SERVER_SERVER_H
  3. #include <atomic>
  4. #include <condition_variable>
  5. #include <gtest/gtest.h>
  6. #include <memory>
  7. #include <mutex>
  8. #include <string>
  9. #include "cpr/cpr.h"
  10. #include "mongoose.h"
  11. namespace cpr {
  12. // Helper struct for functions using timers to simulate slow connections
  13. struct TimerArg {
  14. mg_mgr* mgr;
  15. mg_connection* connection;
  16. unsigned long connection_id;
  17. mg_timer timer;
  18. unsigned counter;
  19. explicit TimerArg(mg_mgr* m, mg_connection* c, mg_timer&& t) : mgr{m}, connection{c}, connection_id{0}, timer{t}, counter{0} {}
  20. ~TimerArg() {
  21. mg_timer_free(&mgr->timers, &timer);
  22. }
  23. };
  24. class AbstractServer : public testing::Environment {
  25. public:
  26. ~AbstractServer() override = default;
  27. void SetUp() override;
  28. void TearDown() override;
  29. void Start();
  30. void Stop();
  31. virtual std::string GetBaseUrl() = 0;
  32. virtual uint16_t GetPort() = 0;
  33. virtual void acceptConnection(mg_connection* conn) = 0;
  34. virtual void OnRequest(mg_connection* conn, mg_http_message* msg) = 0;
  35. private:
  36. std::shared_ptr<std::thread> serverThread{nullptr};
  37. std::mutex server_mutex;
  38. std::condition_variable server_start_cv;
  39. std::condition_variable server_stop_cv;
  40. std::atomic<bool> should_run{false};
  41. void Run();
  42. protected:
  43. mg_mgr mgr{};
  44. std::vector<std::unique_ptr<TimerArg>> timer_args{};
  45. virtual mg_connection* initServer(mg_mgr* mgr, mg_event_handler_t event_handler) = 0;
  46. static std::string Base64Decode(const std::string& in);
  47. static void SendError(mg_connection* conn, int code, std::string& reason);
  48. static bool IsConnectionActive(mg_mgr* mgr, mg_connection* conn);
  49. static uint16_t GetRemotePort(const mg_connection* conn);
  50. static uint16_t GetLocalPort(const mg_connection* conn);
  51. };
  52. } // namespace cpr
  53. #endif