#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "./json_schema_test_suite.h" using jvalidate::schema::Version; using testing::Combine; using testing::TestWithParam; using testing::Values; bool load_stream(std::istream & in, Json::Value & out) { Json::CharReaderBuilder builder; std::string error; return Json::parseFromStream(builder, in, &out, &error); } bool load_file(std::filesystem::path const & path, Json::Value & out) { std::ifstream in(path); return load_stream(in, out); } size_t transfer_to_buffer(char * data, size_t size, size_t nmemb, void * userdata) { std::stringstream & ss = *reinterpret_cast(userdata); size_t actual_size = size * nmemb; ss << std::string_view(data, actual_size); return actual_size; } bool load_external_for_test(jvalidate::URI const & uri, Json::Value & out) { constexpr std::string_view g_fake_url = "localhost:1234/"; if (uri.scheme().starts_with("http") && uri.resource().starts_with(g_fake_url)) { std::string_view path = uri.resource().substr(g_fake_url.size()); return load_file(JSONSchemaTestSuiteDir() / "remotes" / path, out); } else if (uri.scheme().starts_with("http")) { std::stringstream ss; if (CURL * curl = curl_easy_init(); curl) { curl_easy_setopt(curl, CURLOPT_URL, uri.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ss); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &transfer_to_buffer); CURLcode res = curl_easy_perform(curl); curl_easy_cleanup(curl); if (res == CURLE_OK) { return load_stream(ss, out); } } return false; } else if (uri.scheme() == "file") { return load_file(uri.resource(), out); } else { return false; } } struct JsonSchema : TestWithParam> {}; TEST_P(JsonSchema, TestSuite) { auto const & [version, file] = GetParam(); Json::Value spec; EXPECT_TRUE(load_file(file, spec)); for (auto const & suite : spec) { std::cout << "\033[0;32m[ SUITE ] \033[0;0m" << suite["description"].asString() << std::endl; try { jvalidate::Schema schema(suite["schema"], version, &load_external_for_test); for (auto const & test : suite["tests"]) { try { std::cout << "\033[0;32m[ CASE ] \033[0;0m " << test["description"].asString() << std::endl; EXPECT_THAT(test["data"], ValidatesAgainst(schema, test)) << suite["schema"]; } catch (std::exception const & ex) { ADD_FAILURE() << ex.what() << "\n" << test; } } } catch (std::exception const & ex) { ADD_FAILURE() << "when parsing schema: " << ex.what() << "\n" << suite["schema"]; } } } INSTANTIATE_TEST_SUITE_P(Draft7, JsonSchema, Combine(Values(Version::Draft07), SchemaTests("draft7")), SchemaTestName); int main(int argc, char ** argv) { testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); }