api_fixture.hpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. // Purge the previous run before dropping the project. Two database
  44. // caveats make this necessary, and both are invisible against a
  45. // throw-away database, which is why this only ever mattered once the
  46. // suite could run against a persistent one:
  47. // - dropProject does not delete collection data, so the collections
  48. // a previous run created still hold their documents; and
  49. // - dropCollection does not clear the collection's INDEX
  50. // declarations, so a unique index declared last run survives into
  51. // this one. A test that declares it again then gets
  52. // already_existed (success) where it expects a refusal.
  53. // Dropping each index before its collection is therefore the only way
  54. // to reach a clean slate. The project name is fixed, so without this
  55. // the suite is not idempotent.
  56. {
  57. CollectionRegistry stale(*db_);
  58. for (const auto& m : stale.list(project_)) {
  59. const std::string qc = qualify(project_, m.name);
  60. for (const auto& idx : db_->client().listIndexes(qc))
  61. db_->client().dropIndex(qc, idx.field);
  62. for (const auto& fields : db_->client().listCompositeUniqueIndexes(qc))
  63. db_->client().dropCompositeUniqueIndex(qc, fields);
  64. db_->client().dropCollection(qc);
  65. }
  66. }
  67. db_->dropProject(project_);
  68. db_->client().dropCollection(qualify(project_, "vectorapi_collections"));
  69. db_->ensureProject(project_);
  70. registry_ = std::make_unique<CollectionRegistry>(*db_);
  71. functions_ = std::make_unique<FunctionRegistry>(*db_);
  72. functionRuns_ = std::make_unique<FunctionRunLogStore>(*db_, 50);
  73. registry_->ensure(project_);
  74. settings_ = std::make_unique<SettingsStore>(*db_, settingsColl_, "current");
  75. settings_->bootstrap("");
  76. keys_ = std::make_unique<KeyStore>(*db_, keysColl_);
  77. keys_->bootstrap("");
  78. adminKey_ = keys_->list().at(0).key;
  79. sessions_ = std::make_unique<SessionStore>(std::chrono::minutes(60));
  80. mockOpenAi_.Post("/v1/embeddings", [this](const httplib::Request& req, httplib::Response& res) {
  81. lastEmbedUserAgent_ = req.get_header_value("User-Agent");
  82. lastEmbedAuth_ = req.get_header_value("Authorization");
  83. try { lastEmbedBody_ = nlohmann::json::parse(req.body); } catch (...) {}
  84. nlohmann::json emb = nlohmann::json::array();
  85. for (int i = 0; i < mockDim_; ++i) emb.push_back(0.1f * (i + 1));
  86. res.set_content(nlohmann::json{{"data", {{{"embedding", emb}}}}}.dump(), "application/json");
  87. });
  88. mockPort_ = mockOpenAi_.bind_to_any_port("127.0.0.1");
  89. mockThread_ = std::thread([this]{ mockOpenAi_.listen_after_bind(); });
  90. Settings s = *settings_->snapshot();
  91. s.openaiApiBase = "http://127.0.0.1:" + std::to_string(mockPort_);
  92. s.openaiApiKey = "test";
  93. settings_->save(s);
  94. std::filesystem::create_directories(webuiDir_);
  95. std::ofstream(webuiDir_ + "/index.html")
  96. << "<!doctype html><html><head><title>SVAPI_SPA_OK</title></head><body><div id=\"root\"></div></body></html>";
  97. // `runners` stays null: these tests have no function runner, and the
  98. // function routes answer 503 for that, which is itself worth asserting.
  99. ServerDeps deps{*db_, *settings_, *keys_, *registry_,
  100. *sessions_, *functions_, *functionRuns_, nullptr,
  101. webuiDir_, apiDocsDir()};
  102. server_ = std::make_unique<ApiServer>(std::move(deps));
  103. server_->registerRoutes();
  104. port_ = server_->bindToAnyPort("127.0.0.1");
  105. serverThread_ = std::thread([this]{ server_->listenAfterBind(); });
  106. httplib::Client probe("127.0.0.1", port_);
  107. for (int i = 0; i < 200; ++i) { if (probe.Get("/healthz")) break;
  108. std::this_thread::sleep_for(std::chrono::milliseconds(10)); }
  109. }
  110. void TearDown() override {
  111. if (server_) server_->stop();
  112. if (serverThread_.joinable()) serverThread_.join();
  113. mockOpenAi_.stop();
  114. if (mockThread_.joinable()) mockThread_.join();
  115. if (db_) { db_->client().dropCollection(settingsColl_);
  116. db_->client().dropCollection(keysColl_);
  117. db_->dropProject(project_); }
  118. }
  119. httplib::Client http(const std::string& bearer) {
  120. httplib::Client c("127.0.0.1", port_);
  121. c.set_default_headers({{"Authorization", "Bearer " + bearer}});
  122. return c;
  123. }
  124. httplib::Client admin() { return http(adminKey_); }
  125. httplib::Client noAuth() { return httplib::Client("127.0.0.1", port_); }
  126. static std::string apiDocsDir() { return SVAPI_API_DOCS_DIR; }
  127. // Send a single request with a specific key and extra headers (for origin/cache-control tests).
  128. // method: "GET", "POST", "PATCH", "PUT", "DELETE".
  129. // body/contentType: pass "" for requests without a body.
  130. httplib::Result request(const std::string& method, const std::string& path,
  131. const std::string& body, const std::string& contentType,
  132. const std::string& key,
  133. const httplib::Headers& extraHeaders = {}) {
  134. httplib::Headers hdrs = {{"Authorization", "Bearer " + key}};
  135. for (const auto& [k, v] : extraHeaders) hdrs.emplace(k, v);
  136. httplib::Client c("127.0.0.1", port_);
  137. c.set_default_headers(hdrs);
  138. if (method == "GET") return c.Get(path.c_str());
  139. if (method == "DELETE") return c.Delete(path.c_str());
  140. if (method == "POST") return c.Post(path.c_str(), body, contentType.c_str());
  141. if (method == "PUT") return c.Put(path.c_str(), body, contentType.c_str());
  142. if (method == "PATCH") return c.Patch(path.c_str(), body, contentType.c_str());
  143. throw std::invalid_argument("unsupported method: " + method);
  144. }
  145. };
  146. } // namespace svapi::testutil