annotation_test.cxx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "gmock/gmock-matchers.h"
  2. #include <string_view>
  3. #include <gmock/gmock.h>
  4. #include <gtest/gtest.h>
  5. #include <jvalidate/adapter.h>
  6. #include <jvalidate/adapters/jsoncpp.h>
  7. #include <jvalidate/detail/pointer.h>
  8. #include <jvalidate/enum.h>
  9. #include <jvalidate/schema.h>
  10. #include <jvalidate/status.h>
  11. #include <jvalidate/uri.h>
  12. #include <jvalidate/validation_result.h>
  13. #include <jvalidate/validator.h>
  14. #include <json/reader.h>
  15. #include <json/value.h>
  16. using enum jvalidate::schema::Version;
  17. auto operator""_jptr(char const * data, size_t len) {
  18. return jvalidate::detail::Pointer(std::string_view{data, len});
  19. }
  20. Json::Value operator""_json(char const * data, size_t len) {
  21. Json::Value value;
  22. Json::CharReaderBuilder builder;
  23. std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
  24. std::string error;
  25. if (not reader->parse(data, data + len, &value, &error)) {
  26. throw std::runtime_error(error);
  27. }
  28. return value;
  29. }
  30. auto validate(Json::Value const & schema_doc, Json::Value const & instance_doc) {
  31. jvalidate::Schema const schema(schema_doc, Draft2020_12);
  32. jvalidate::ValidationResult result;
  33. (void)jvalidate::Validator(schema).validate(instance_doc, &result);
  34. return result;
  35. }
  36. MATCHER_P(HasAnnotationsFor, doc_path, "") { return arg.has_annotation(doc_path); }
  37. MATCHER_P2(HasAnnotationAt, doc_path, schema_path, "") {
  38. return arg.has_annotation(doc_path, schema_path);
  39. }
  40. MATCHER_P3(AnnotationAt, doc_path, schema_path, matcher, "") {
  41. auto const * anno = arg.annotation(doc_path, schema_path);
  42. if (not anno) {
  43. return false;
  44. }
  45. return testing::ExplainMatchResult(matcher, *anno, result_listener);
  46. }
  47. TEST(Annotation, AttachesFormattingAnnotation) {
  48. auto const schema = R"({
  49. "format": "uri"
  50. })"_json;
  51. auto const instance = R"("http://json-schema.org")"_json;
  52. jvalidate::ValidationResult result = validate(schema, instance);
  53. EXPECT_THAT(result, AnnotationAt(""_jptr, "/format"_jptr, "format 'uri'"));
  54. }
  55. int main(int argc, char ** argv) {
  56. testing::InitGoogleMock(&argc, argv);
  57. return RUN_ALL_TESTS();
  58. }