api_fixture.hpp 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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<SettingsStore> settings_;
  18. std::unique_ptr<KeyStore> keys_;
  19. std::unique_ptr<SessionStore> sessions_;
  20. std::unique_ptr<ApiServer> server_;
  21. std::thread serverThread_;
  22. int port_ = 0;
  23. std::string adminKey_;
  24. std::string project_; // a project the admin owns; tests create collections under it
  25. httplib::Server mockOpenAi_;
  26. std::thread mockThread_;
  27. int mockPort_ = 0, mockDim_ = 4;
  28. std::string settingsColl_ = "svapitest_api_settings";
  29. std::string keysColl_ = "svapitest_api_keys";
  30. std::string webuiDir_ = "/tmp/svapi_webui_test"; // sentinel SPA root for fallback tests
  31. void SetUp() override {
  32. db_ = connectOrNull();
  33. if (!db_) GTEST_SKIP() << "smartbotic-database not reachable";
  34. project_ = tmpName("apiproj");
  35. db_->client().dropCollection(settingsColl_);
  36. db_->client().dropCollection(keysColl_);
  37. db_->dropProject(project_);
  38. // DB v2.3.1 Stage-F caveat: dropProject does not delete collection data.
  39. // Drop the project's registry collection explicitly so ensure() starts fresh.
  40. db_->client().dropCollection(qualify(project_, "vectorapi_collections"));
  41. db_->ensureProject(project_);
  42. registry_ = std::make_unique<CollectionRegistry>(*db_);
  43. registry_->ensure(project_);
  44. settings_ = std::make_unique<SettingsStore>(*db_, settingsColl_, "current");
  45. settings_->bootstrap("");
  46. keys_ = std::make_unique<KeyStore>(*db_, keysColl_);
  47. keys_->bootstrap("");
  48. adminKey_ = keys_->list().at(0).key;
  49. sessions_ = std::make_unique<SessionStore>(std::chrono::minutes(60));
  50. mockOpenAi_.Post("/v1/embeddings", [this](const httplib::Request&, httplib::Response& res) {
  51. nlohmann::json emb = nlohmann::json::array();
  52. for (int i = 0; i < mockDim_; ++i) emb.push_back(0.1f * (i + 1));
  53. res.set_content(nlohmann::json{{"data", {{{"embedding", emb}}}}}.dump(), "application/json");
  54. });
  55. mockPort_ = mockOpenAi_.bind_to_any_port("127.0.0.1");
  56. mockThread_ = std::thread([this]{ mockOpenAi_.listen_after_bind(); });
  57. Settings s = *settings_->snapshot();
  58. s.openaiApiBase = "http://127.0.0.1:" + std::to_string(mockPort_);
  59. s.openaiApiKey = "test";
  60. settings_->save(s);
  61. std::filesystem::create_directories(webuiDir_);
  62. std::ofstream(webuiDir_ + "/index.html")
  63. << "<!doctype html><html><head><title>SVAPI_SPA_OK</title></head><body><div id=\"root\"></div></body></html>";
  64. ServerDeps deps{*db_, *settings_, *keys_, *registry_, *sessions_, webuiDir_, apiDocsDir()};
  65. server_ = std::make_unique<ApiServer>(std::move(deps));
  66. server_->registerRoutes();
  67. port_ = server_->bindToAnyPort("127.0.0.1");
  68. serverThread_ = std::thread([this]{ server_->listenAfterBind(); });
  69. httplib::Client probe("127.0.0.1", port_);
  70. for (int i = 0; i < 200; ++i) { if (probe.Get("/healthz")) break;
  71. std::this_thread::sleep_for(std::chrono::milliseconds(10)); }
  72. }
  73. void TearDown() override {
  74. if (server_) server_->stop();
  75. if (serverThread_.joinable()) serverThread_.join();
  76. mockOpenAi_.stop();
  77. if (mockThread_.joinable()) mockThread_.join();
  78. if (db_) { db_->client().dropCollection(settingsColl_);
  79. db_->client().dropCollection(keysColl_);
  80. db_->dropProject(project_); }
  81. }
  82. httplib::Client http(const std::string& bearer) {
  83. httplib::Client c("127.0.0.1", port_);
  84. c.set_default_headers({{"Authorization", "Bearer " + bearer}});
  85. return c;
  86. }
  87. httplib::Client admin() { return http(adminKey_); }
  88. httplib::Client noAuth() { return httplib::Client("127.0.0.1", port_); }
  89. static std::string apiDocsDir() { return SVAPI_API_DOCS_DIR; }
  90. };
  91. } // namespace svapi::testutil