selfvalidate_test.cxx 2.4 KB

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