json_schema_test_suite.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include <filesystem>
  2. #include <gmock/gmock.h>
  3. #include <jvalidate/validation_result.h>
  4. #include <jvalidate/validator.h>
  5. inline std::filesystem::path const & JSONSchemaTestSuiteDir() {
  6. static auto const g_root =
  7. std::filesystem::path(__FILE__).parent_path().parent_path().parent_path();
  8. static auto const g_path = g_root / "thirdparty" / "JSON-Schema-Test-Suite";
  9. return g_path;
  10. }
  11. inline auto SchemaTests(std::string_view draft) {
  12. struct fs_iterator : std::filesystem::recursive_directory_iterator {
  13. using super = std::filesystem::recursive_directory_iterator;
  14. using value_type = std::filesystem::path;
  15. using super::super;
  16. std::filesystem::path operator*() const { return super::operator*().path(); }
  17. fs_iterator operator++() {
  18. do {
  19. super::operator++();
  20. } while (*this != fs_iterator() && super::operator*().is_directory());
  21. return *this;
  22. }
  23. };
  24. auto const dir = JSONSchemaTestSuiteDir() / "tests" / draft;
  25. return testing::ValuesIn(fs_iterator(dir), fs_iterator());
  26. }
  27. static auto SchemaTestName = [](auto const & info) {
  28. std::string name = std::get<1>(info.param).stem();
  29. std::transform(name.begin(), name.end(), name.begin(),
  30. [](char c) { return std::isalnum(c) ? c : '_'; });
  31. return name;
  32. };
  33. MATCHER_P(ValidatesAgainst, schema, "") {
  34. jvalidate::ValidationResult result;
  35. bool valid = jvalidate::Validator(schema).validate(arg, &result);
  36. *result_listener << result;
  37. return valid;
  38. }
  39. template <typename T>
  40. testing::Matcher<T> ValidatesAgainst(jvalidate::Schema const & schema, T const & test) {
  41. if (not jvalidate::adapter::AdapterFor<T const>(test)["valid"].as_boolean()) {
  42. return testing::Not(ValidatesAgainst(std::cref(schema)));
  43. }
  44. return ValidatesAgainst(std::cref(schema));
  45. }