selfvalidate_test.cxx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <filesystem>
  4. #include <fstream>
  5. #include <iostream>
  6. #include <jvalidate/adapter.h>
  7. #include <jvalidate/adapters/jsoncpp.h>
  8. #include <jvalidate/enum.h>
  9. #include <jvalidate/schema.h>
  10. #include <jvalidate/status.h>
  11. #include <jvalidate/uri.h>
  12. #include <jvalidate/validator.h>
  13. #include <json/reader.h>
  14. #include <json/value.h>
  15. #include <json/writer.h>
  16. #include "./json_schema_test_suite.h"
  17. #include "./printer_helper.h"
  18. using jvalidate::schema::Version;
  19. using testing::Combine;
  20. using testing::TestWithParam;
  21. using testing::Values;
  22. bool load_file(std::filesystem::path const & path, Json::Value & out) {
  23. std::ifstream in(path);
  24. Json::CharReaderBuilder builder;
  25. return Json::parseFromStream(builder, in, &out, nullptr);
  26. }
  27. bool load_external_for_test(jvalidate::URI const & uri, Json::Value & out) {
  28. constexpr std::string_view g_fake_url = "localhost:1234/";
  29. if (uri.scheme() == "http" && uri.resource().starts_with(g_fake_url)) {
  30. std::string_view path = uri.resource().substr(g_fake_url.size());
  31. return load_file(JSONSchemaTestSuiteDir() / "remotes" / path, out);
  32. } else if (uri.scheme() == "file") {
  33. return load_file(uri.resource(), out);
  34. } else {
  35. return false;
  36. }
  37. }
  38. struct JsonSchema : TestWithParam<std::tuple<Version, std::filesystem::path>> {};
  39. TEST_P(JsonSchema, TestSuite) {
  40. auto const & [version, file] = GetParam();
  41. Json::Value spec;
  42. EXPECT_TRUE(load_file(file, spec));
  43. for (auto const & suite : spec) {
  44. std::cout << "\033[0;32m[ SUITE ] \033[0;0m" << suite["description"].asString() << std::endl;
  45. jvalidate::Schema schema(suite["schema"], version, &load_external_for_test);
  46. for (auto const & test : suite["tests"]) {
  47. try {
  48. std::cout << "\033[0;32m[ CASE ] \033[0;0m " << test["description"].asString()
  49. << std::endl;
  50. EXPECT_THAT(test["data"], ValidatesAgainst(schema, test));
  51. } catch (std::exception const & ex) { FAIL() << ex.what() << "\n" << test; }
  52. }
  53. }
  54. }
  55. INSTANTIATE_TEST_SUITE_P(Draft7, JsonSchema,
  56. Combine(Values(Version::Draft07), SchemaTests("draft7")), SchemaTestName);
  57. int main(int argc, char ** argv) {
  58. testing::InitGoogleMock(&argc, argv);
  59. return RUN_ALL_TESTS();
  60. }