selfvalidate_test.cxx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. auto status = jvalidate::Validator(schema).validate(test["data"]);
  51. EXPECT_THAT(status != jvalidate::Status::Reject, test["valid"].asBool()) << test["data"];
  52. } catch (std::exception const & ex) { FAIL() << ex.what() << "\n" << test; }
  53. }
  54. }
  55. }
  56. INSTANTIATE_TEST_SUITE_P(Draft7, JsonSchema,
  57. Combine(Values(Version::Draft07), SchemaTests("draft7")), SchemaTestName);
  58. int main(int argc, char ** argv) {
  59. testing::InitGoogleMock(&argc, argv);
  60. return RUN_ALL_TESTS();
  61. }