private SchemaVersion mapSchemaVersion(JsonSchemaVersion version)
        {
            SchemaVersion mappedVersion = SchemaVersion.None;

            if (version == JsonSchemaVersion.All)
            {
                mappedVersion = SchemaVersion.All;
            }
            if (version == JsonSchemaVersion.Draft04)
            {
                mappedVersion = SchemaVersion.Draft04;
            }
            if (version == JsonSchemaVersion.Draft06)
            {
                mappedVersion = SchemaVersion.Draft06;
            }
            if (version == JsonSchemaVersion.Draft07)
            {
                mappedVersion = SchemaVersion.Draft07;
            }
            if (version == JsonSchemaVersion.Draft2019_09)
            {
                mappedVersion = SchemaVersion.Draft08;
            }
            return(mappedVersion);
        }
示例#2
0
        /// <summary>
        /// Creates a new <see cref="Format"/> instance using a validation function.
        /// </summary>
        /// <param name="key">The name of the format.  This is the value that will appear in the schema.</param>
        /// <param name="supportedBy">The schema drafts supported by this keyword.</param>
        /// <param name="validate">The function by which the value is validated.</param>
        public Format(string key, JsonSchemaVersion supportedBy, Func <JsonValue, bool> validate)
        {
            ValidationFunction = validate;
            Key         = key;
            SupportedBy = supportedBy;

            _lookup[key] = this;
        }
示例#3
0
        /// <summary>
        /// Creates a new <see cref="StringFormat"/> instance using a validation function.
        /// </summary>
        /// <param name="key">The name of the format.  This is the value that will appear in the schema.</param>
        /// <param name="supportedBy">The schema drafts supported by this keyword.</param>
        /// <param name="validate">The function by which the string is validated.</param>
        public StringFormat(string key, JsonSchemaVersion supportedBy, Func <string, bool> validate)
        {
            ValidationFunction = validate;
            Key         = key;
            SupportedBy = supportedBy;

            _lookup.Add(key, this);
        }
示例#4
0
        /// <summary>
        /// Creates a new <see cref="Format"/> instance using a regular expression.
        /// </summary>
        /// <param name="key">The name of the format.  This is the value that will appear in the schema.</param>
        /// <param name="supportedBy">The schema drafts supported by this keyword.</param>
        /// <param name="regex">The validation regular expression.</param>
        /// <param name="isCaseSensitive">(optional) Whether the regular expression is to be processed as case-sensitive; the default is `false`.</param>
        public Format(string key, JsonSchemaVersion supportedBy, [RegexPattern] string regex, bool isCaseSensitive = false)
        {
            Key         = key;
            SupportedBy = supportedBy;
            if (regex != null)
            {
                ValidationRegex = new Regex(regex, isCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase);
            }

            _lookup[key] = this;
        }
示例#5
0
        /// <summary>
        /// Creates a new <see cref="StringFormat"/> instance using a regular expression.
        /// </summary>
        /// <param name="key">The name of the format.  This is the value that will appear in the schema.</param>
        /// <param name="supportedBy">The schema drafts supported by this keyword.</param>
        /// <param name="regex">The validation regular expression.</param>
        /// <param name="isCaseSensitive">Whether the regular expression is to be processed as case-sensitive.</param>
        public StringFormat(string key, JsonSchemaVersion supportedBy, string regex, bool isCaseSensitive = false)
        {
            Key         = key;
            SupportedBy = supportedBy;
            if (regex != null)
            {
                ValidationRegex = new Regex(regex, isCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase);
            }

            _lookup.Add(key, this);
        }
        private void _ResolveLocalReference(Uri baseUri, JsonSchemaVersion supportedVersions)
        {
            if (!_resolvedFragment.Any())
            {
                Resolved = _resolvedRoot;
                return;
            }

            Log.Schema(() => $"Resolving local reference {_resolvedFragment}");
            Resolved = _resolvedRoot !.ResolveSubschema(_resolvedFragment !, baseUri, supportedVersions);
        }
 public static string GetSchemaUri(this JsonSchemaVersion version)
 {
     return(version switch
     {
         JsonSchemaVersion.Draft201909 => Draft201909,
         JsonSchemaVersion.Draft07 => Draft07,
         JsonSchemaVersion.Draft06 => Draft06,
         JsonSchemaVersion.Draft04 => Draft04,
         JsonSchemaVersion.Draft03 => Draft03,
         _ => throw new NotSupportedException(),
     });
        /// <summary>
        /// Resolves any subschemas during resolution of a `$ref` during validation.
        /// </summary>
        /// <param name="pointer">A <see cref="JsonPointer"/> to the target schema.</param>
        /// <param name="baseUri">The current base URI.</param>
        /// <param name="supportedVersions">Indicates the root schema's supported versions.</param>
        /// <returns>The referenced schema, if it exists; otherwise null.</returns>
        public JsonSchema?ResolveSubschema(JsonPointer pointer, Uri baseUri, JsonSchemaVersion supportedVersions)
        {
            var first = pointer.FirstOrDefault();

            if (first == null)
            {
                return(null);
            }

            var keyword = this.FirstOrDefault(k => k.PropertyName == first);

            return(keyword?.ResolveSubschema(new JsonPointer(pointer.Skip(1)), baseUri, supportedVersions));
        }
示例#9
0
        /// <summary>
        /// Resolves any subschemas during resolution of a `$ref` during validation.
        /// </summary>
        /// <param name="pointer">A <see cref="JsonPointer"/> to the target schema.</param>
        /// <param name="baseUri">The current base URI.</param>
        /// <param name="supportedVersions">Indicates the root schema's supported versions.</param>
        /// <returns>The referenced schema, if it exists; otherwise null.</returns>
        public JsonSchema?ResolveSubschema(JsonPointer pointer, Uri baseUri, JsonSchemaVersion supportedVersions)
        {
            var first = pointer.FirstOrDefault();

            if (first == null)
            {
                return(null);
            }

            if (!int.TryParse(first, out var index) || index < 0 || index >= Count)
            {
                return(null);
            }

            return(this[index].ResolveSubschema(new JsonPointer(pointer.Skip(1)), baseUri, supportedVersions));
        }
        /// <summary>
        /// Resolves any subschemas during resolution of a `$ref` during validation.
        /// </summary>
        /// <param name="pointer">A <see cref="JsonPointer"/> to the target schema.</param>
        /// <param name="baseUri">The current base URI.</param>
        /// <param name="supportedVersions">Indicates the root schema's supported versions.</param>
        /// <returns>The referenced schema, if it exists; otherwise null.</returns>
        public JsonSchema?ResolveSubschema(JsonPointer pointer, Uri baseUri, JsonSchemaVersion supportedVersions)
        {
            var first = pointer.FirstOrDefault();

            if (first == null)
            {
                return(null);
            }

            if (!TryGetValue(first, out var schema))
            {
                return(null);
            }

            return(schema.ResolveSubschema(new JsonPointer(pointer.Skip(1)), baseUri, supportedVersions));
        }
        private static IEnumerable <TestCaseData> _LoadSchemaJson(string draft, JsonSchemaVersion version)
        {
            var testsPath = System.IO.Path.Combine(TestContext.CurrentContext.WorkDirectory, RootTestsFolder, $"{draft}\\").AdjustForOS();

            if (!Directory.Exists(testsPath))
            {
                return(Enumerable.Empty <TestCaseData>());
            }

            var fileNames = Directory.GetFiles(testsPath, "*.json", SearchOption.AllDirectories);

            var allTests = new List <TestCaseData>();

            foreach (var fileName in fileNames)
            {
                var shortFileName = System.IO.Path.GetFileNameWithoutExtension(fileName);
                var contents      = File.ReadAllText(fileName);
                var json          = JsonValue.Parse(contents);

                foreach (var testSet in json.Array)
                {
                    var schemaJson = testSet.Object["schema"];
                    foreach (var testJson in testSet.Object["tests"].Array)
                    {
                        var isOptional = fileName.Contains("optional");
                        var testName   = $"{shortFileName}.{testSet.Object["description"].String}.{testJson.Object["description"].String}.{draft}".Replace(' ', '_');
                        if (isOptional)
                        {
                            testName = $"optional.{testName}";
                        }
                        allTests.Add(new TestCaseData(fileName, testSet.Object["description"].String, testJson, schemaJson, version, isOptional, testName)
                        {
                            TestName = testName
                        });
                    }
                }
            }

            return(allTests);
        }
 /// <summary>
 /// Resolves any subschemas during resolution of a `$ref` during validation.
 /// </summary>
 /// <param name="pointer">A <see cref="JsonPointer"/> to the target schema.</param>
 /// <param name="baseUri">The current base URI.</param>
 /// <param name="supportedVersions">Indicates the root schema's supported versions.</param>
 /// <returns>The referenced schema, if it exists; otherwise null.</returns>
 /// <implementationNotes>
 /// If the keyword contains no subschemas, simply return null.
 /// If the keyword contains a subschema, simply pass the call to <see cref="JsonSchema.ResolveSubschema"/>.
 /// </implementationNotes>
 public JsonSchema?ResolveSubschema(JsonPointer pointer, Uri baseUri, JsonSchemaVersion supportedVersions)
 {
     return(null);
 }
示例#13
0
 /// <summary>
 /// Resolves any subschemas during resolution of a `$ref` during validation.
 /// </summary>
 /// <param name="pointer">A <see cref="JsonPointer"/> to the target schema.</param>
 /// <param name="baseUri">The current base URI.</param>
 /// <param name="supportedVersions">Indicates the root schema's supported versions.</param>
 /// <returns>The referenced schema, if it exists; otherwise null.</returns>
 public JsonSchema?ResolveSubschema(JsonPointer pointer, Uri baseUri, JsonSchemaVersion supportedVersions)
 {
     return(Value.ResolveSubschema(pointer, baseUri, supportedVersions));
 }
        private static void _Run(string fileName, string setDescription, JsonValue testJson, JsonValue schemaJson, JsonSchemaVersion version, bool isOptional)
        {
            using (new TestExecutionContext.IsolatedContext())
            {
                try
                {
                    var test   = _serializer.Deserialize <SchemaTest>(testJson);
                    var schema = _serializer.Deserialize <JsonSchema>(schemaJson);
                    schema.ProcessingVersion = version;

                    var results = schema.Validate(test.Data, new JsonSchemaOptions {
                        OutputFormat = SchemaValidationOutputFormat.Verbose
                    });

                    if (test.Valid != results.IsValid)
                    {
                        Console.WriteLine(string.Join("\n", _serializer.Serialize(results).GetIndentedString()));
                    }
                    Assert.AreEqual(test.Valid, results.IsValid);
                    if (test.Output != null)
                    {
                        Assert.AreEqual(test.Output.Basic, results.Flatten());
                        Assert.AreEqual(test.Output.Detailed, results.Condense());
                        Assert.AreEqual(test.Output.Verbose, results);
                    }

                    if (!fileName.Contains("draft2019-09"))
                    {
                        return;
                    }

                    var exportTestsValue = Environment.GetEnvironmentVariable("EXPORT_JSON_TEST_SUITE_RESULTS");

                    if (!bool.TryParse(exportTestsValue, out var exportTests) || !exportTests)
                    {
                        return;
                    }

                    test.OutputGeneration = results;

                    List <SchemaTestSet> testSets = null;
                    SchemaTestSet        testSet  = null;
                    var outputFile = System.IO.Path.Combine(OutputFolder, System.IO.Path.GetFileName(fileName));
                    if (File.Exists(outputFile))
                    {
                        var fileContents = File.ReadAllText(outputFile);
                        var fileJson     = JsonValue.Parse(fileContents);
                        testSets = _serializer.Deserialize <List <SchemaTestSet> >(fileJson);
                        testSet  = testSets.FirstOrDefault(s => s.Description == setDescription);
                    }

                    if (testSets == null)
                    {
                        testSets = new List <SchemaTestSet>();
                    }

                    if (testSet == null)
                    {
                        testSet = new SchemaTestSet
                        {
                            Description = setDescription,
                            Schema      = schema,
                            Tests       = new List <SchemaTest>()
                        };
                        testSets.Add(testSet);
                    }

                    testSet.Tests.Add(test);

                    var outputJson = _serializer.Serialize(testSets);
                    File.WriteAllText(outputFile, outputJson.GetIndentedString());
                }
                catch (Exception e)
                {
                    if (e is SchemaLoadException sle)
                    {
                        Console.WriteLine(sle.MetaValidation.ToJson(new JsonSerializer()).GetIndentedString());
                    }

                    Console.WriteLine(fileName);
                    Console.WriteLine("\nSchema");
                    Console.WriteLine(schemaJson.GetIndentedString());
                    Console.WriteLine("\nTest");
                    Console.WriteLine(testJson.GetIndentedString());

                    if (isOptional)
                    {
                        Assert.Inconclusive("This is an acceptable failure.  Test case failed, but was marked as 'optional'.");
                    }
                    throw;
                }
            }
        }
        public void Run(string fileName, string setDescription, JsonValue testJson, JsonValue schemaJson, JsonSchemaVersion version, bool isOptional, string testName)
        {
            Console.WriteLine(testName);
            Console.WriteLine();

            //if (testName == "ref.escaped_pointer_ref.slash_invalid.draft2019-09")
            //	Debugger.Break();
            _Run(fileName, setDescription, testJson, schemaJson, version, isOptional);
        }
示例#16
0
        private void WriteSchemaVersion(JsonSchemaVersion version)
        {
            var uri = version.GetSchemaUri();

            writer.WriteString(Keys.Schema, uri);
        }