api_fixture.hpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. #pragma once
  2. #include "db_test_util.hpp"
  3. #include "server.hpp"
  4. #include <gtest/gtest.h>
  5. #include <httplib.h>
  6. #include <chrono>
  7. #include <filesystem>
  8. #include <fstream>
  9. #include <memory>
  10. #include <thread>
  11. #include <vector>
  12. namespace svapi::testutil {
  13. class ApiFixture : public ::testing::Test {
  14. protected:
  15. std::unique_ptr<DbGateway> db_;
  16. std::unique_ptr<CollectionRegistry> registry_;
  17. std::unique_ptr<FunctionRegistry> functions_;
  18. std::unique_ptr<FunctionRunLogStore> functionRuns_;
  19. std::unique_ptr<SettingsStore> settings_;
  20. std::unique_ptr<KeyStore> keys_;
  21. std::unique_ptr<SessionStore> sessions_;
  22. std::unique_ptr<ApiServer> server_;
  23. std::thread serverThread_;
  24. int port_ = 0;
  25. std::string adminKey_;
  26. std::string project_; // a project the admin owns; tests create collections under it
  27. httplib::Server mockOpenAi_;
  28. std::thread mockThread_;
  29. int mockPort_ = 0, mockDim_ = 4;
  30. // What the last outbound embedding request actually carried, so tests can
  31. // assert on the request we send to a provider, not just on our own helpers.
  32. std::string lastEmbedUserAgent_, lastEmbedAuth_;
  33. nlohmann::json lastEmbedBody_ = nlohmann::json::object();
  34. std::string settingsColl_ = "svapitest_api_settings";
  35. std::string keysColl_ = "svapitest_api_keys";
  36. std::string webuiDir_ = "/tmp/svapi_webui_test"; // sentinel SPA root for fallback tests
  37. void SetUp() override {
  38. db_ = connectOrNull();
  39. if (!db_) GTEST_SKIP() << "smartbotic-database not reachable";
  40. project_ = tmpName("apiproj");
  41. db_->client().dropCollection(settingsColl_);
  42. db_->client().dropCollection(keysColl_);
  43. db_->dropProject(project_);
  44. // DB v2.3.1 Stage-F caveat: dropProject does not delete collection data.
  45. // Drop the project's registry collection explicitly so ensure() starts fresh.
  46. db_->client().dropCollection(qualify(project_, "vectorapi_collections"));
  47. db_->ensureProject(project_);
  48. registry_ = std::make_unique<CollectionRegistry>(*db_);
  49. functions_ = std::make_unique<FunctionRegistry>(*db_);
  50. functionRuns_ = std::make_unique<FunctionRunLogStore>(*db_, 50);
  51. registry_->ensure(project_);
  52. settings_ = std::make_unique<SettingsStore>(*db_, settingsColl_, "current");
  53. settings_->bootstrap("");
  54. keys_ = std::make_unique<KeyStore>(*db_, keysColl_);
  55. keys_->bootstrap("");
  56. adminKey_ = keys_->list().at(0).key;
  57. sessions_ = std::make_unique<SessionStore>(std::chrono::minutes(60));
  58. mockOpenAi_.Post("/v1/embeddings", [this](const httplib::Request& req, httplib::Response& res) {
  59. lastEmbedUserAgent_ = req.get_header_value("User-Agent");
  60. lastEmbedAuth_ = req.get_header_value("Authorization");
  61. try { lastEmbedBody_ = nlohmann::json::parse(req.body); } catch (...) {}
  62. nlohmann::json emb = nlohmann::json::array();
  63. for (int i = 0; i < mockDim_; ++i) emb.push_back(0.1f * (i + 1));
  64. res.set_content(nlohmann::json{{"data", {{{"embedding", emb}}}}}.dump(), "application/json");
  65. });
  66. mockPort_ = mockOpenAi_.bind_to_any_port("127.0.0.1");
  67. mockThread_ = std::thread([this]{ mockOpenAi_.listen_after_bind(); });
  68. Settings s = *settings_->snapshot();
  69. s.openaiApiBase = "http://127.0.0.1:" + std::to_string(mockPort_);
  70. s.openaiApiKey = "test";
  71. settings_->save(s);
  72. std::filesystem::create_directories(webuiDir_);
  73. std::ofstream(webuiDir_ + "/index.html")
  74. << "<!doctype html><html><head><title>SVAPI_SPA_OK</title></head><body><div id=\"root\"></div></body></html>";
  75. // `runners` stays null: these tests have no function runner, and the
  76. // function routes answer 503 for that, which is itself worth asserting.
  77. ServerDeps deps{*db_, *settings_, *keys_, *registry_,
  78. *sessions_, *functions_, *functionRuns_, nullptr,
  79. webuiDir_, apiDocsDir()};
  80. server_ = std::make_unique<ApiServer>(std::move(deps));
  81. server_->registerRoutes();
  82. port_ = server_->bindToAnyPort("127.0.0.1");
  83. serverThread_ = std::thread([this]{ server_->listenAfterBind(); });
  84. httplib::Client probe("127.0.0.1", port_);
  85. for (int i = 0; i < 200; ++i) { if (probe.Get("/healthz")) break;
  86. std::this_thread::sleep_for(std::chrono::milliseconds(10)); }
  87. }
  88. void TearDown() override {
  89. if (server_) server_->stop();
  90. if (serverThread_.joinable()) serverThread_.join();
  91. mockOpenAi_.stop();
  92. if (mockThread_.joinable()) mockThread_.join();
  93. if (db_) { db_->client().dropCollection(settingsColl_);
  94. db_->client().dropCollection(keysColl_);
  95. db_->dropProject(project_); }
  96. }
  97. httplib::Client http(const std::string& bearer) {
  98. httplib::Client c("127.0.0.1", port_);
  99. c.set_default_headers({{"Authorization", "Bearer " + bearer}});
  100. return c;
  101. }
  102. httplib::Client admin() { return http(adminKey_); }
  103. httplib::Client noAuth() { return httplib::Client("127.0.0.1", port_); }
  104. static std::string apiDocsDir() { return SVAPI_API_DOCS_DIR; }
  105. // Send a single request with a specific key and extra headers (for origin/cache-control tests).
  106. // method: "GET", "POST", "PATCH", "PUT", "DELETE".
  107. // body/contentType: pass "" for requests without a body.
  108. httplib::Result request(const std::string& method, const std::string& path,
  109. const std::string& body, const std::string& contentType,
  110. const std::string& key,
  111. const httplib::Headers& extraHeaders = {}) {
  112. httplib::Headers hdrs = {{"Authorization", "Bearer " + key}};
  113. for (const auto& [k, v] : extraHeaders) hdrs.emplace(k, v);
  114. httplib::Client c("127.0.0.1", port_);
  115. c.set_default_headers(hdrs);
  116. if (method == "GET") return c.Get(path.c_str());
  117. if (method == "DELETE") return c.Delete(path.c_str());
  118. if (method == "POST") return c.Post(path.c_str(), body, contentType.c_str());
  119. if (method == "PUT") return c.Put(path.c_str(), body, contentType.c_str());
  120. if (method == "PATCH") return c.Patch(path.c_str(), body, contentType.c_str());
  121. throw std::invalid_argument("unsupported method: " + method);
  122. }
  123. };
  124. } // namespace svapi::testutil