Files
moloapp/tests/src/openai/core/rig.h
T

60 lines
1.9 KiB
C++

#pragma once
// Shared test rig: an OpenAI ApiClient over MockTransport. The mock only
// records requests (and answers a documented fixture where a call parses its
// answer); no vendor behavior is scripted beyond the documented examples.
#include <memory>
#include <string>
#include "clients/transports/mock_transport.h"
#include "framework.h"
#include "openai/core/client.h"
namespace oai_test {
using molo::clients::ClientResponse;
using molo::clients::HeaderMap;
using molo::clients::Method;
using molo::clients::body::Json;
using molo::clients::transports::MockTransport;
inline ClientResponse ok(const std::string& body, const std::string& type = "application/json") {
HeaderMap h;
h.set("Content-Type", type);
return ClientResponse(200, h, body);
}
struct Rig {
MockTransport* mock;
std::shared_ptr<molo::llm::ApiClient> client;
explicit Rig(const std::string& key = "sk-test-KEY", const std::string& org = "",
const std::string& project = "") {
auto t = std::make_unique<MockTransport>();
mock = t.get();
client = molo::openai::core::OpenaiClient::with_transport(std::move(t), key, org, project);
}
// Answers the next call of method/path with `body`.
void answer(Method m, const std::string& path, const std::string& body = "{}",
const std::string& type = "application/json") {
mock->expect_response(m, "/v1" + path, ok(body, type));
}
Json last_body() const { return Json::parse(mock->seen().back().body); }
std::string last_target() const { return mock->seen().back().target; }
};
// True when `fn` throws an ApiError whose message contains `needle`.
template <typename F>
bool rejects(F&& fn, const std::string& needle = "") {
try {
fn();
} catch (const molo::llm::ApiError& e) {
return needle.empty() || e.message().find(needle) != std::string::npos;
}
return false;
}
inline Json parse(const char* text) { return Json::parse(text); }
} // namespace oai_test