public void TryParse(string pointerString, string[] segments)
        {
            Assert.IsTrue(JsonPointer.TryParse(pointerString, out var pointer));

            pointer.Segments.Length.Should().Be(segments.Length);
            pointer.Segments.Select(s => s.Value).Should().BeEquivalentTo(segments);
        }
        public void TestReplaceObjectValue()
        {
            using var doc   = JsonDocument.Parse(@"{
              ""baz"": ""qux"",
              ""foo"": ""bar""
            }");
            using var value = JsonDocument.Parse(@"""boo""");

            using var expected = JsonDocument.Parse(@"
            {
              ""baz"": ""boo"",
              ""foo"": ""bar""
            }
            ");

            var documentBuilder = new JsonDocumentBuilder(doc.RootElement);
            var valueBuilder    = new JsonDocumentBuilder(value.RootElement);

            JsonPointer location;

            Assert.IsTrue(JsonPointer.TryParse(@"/baz", out location));

            Assert.IsTrue(location.TryAdd(ref documentBuilder, valueBuilder));
            JsonDocument result = documentBuilder.ToJsonDocument();

            JsonElementEqualityComparer.Instance.Equals(expected.RootElement,
                                                        result.RootElement);
        }
Example #3
0
        /// <summary>
        /// Converts the URL representation of a reference to its structured equivalent.
        /// A return value indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="url">A URL containing a reference to convert.</param>
        /// <param name="result">
        /// When this method returns, contains the structured equivalent of the reference contained in <paramref name="url"/>,
        /// if the conversion succeeded, or default if the conversion failed. The conversion fails if the <paramref name="url"/> parameter
        /// is not in a format compliant with the Open API specification. This parameter is passed uninitialized;
        /// any value originally supplied in result will be overwritten.
        /// </param>
        /// <returns><c>true</c> if <paramref name="url"/> was converted successfully; otherwise, <c>false</c>.</returns>
        public static bool TryParseUrl(Uri url, out OasReference result)
        {
            if (url == null)
            {
                result = default;
                return(false);
            }

            // TODO: Handle escaped URL characters in pointer.

            string frag = null;

            if (url.IsAbsoluteUri && url.Fragment != null)
            {
                frag = url.GetComponents(UriComponents.Fragment, UriFormat.Unescaped);
                url  = new UriBuilder(url)
                {
                    Fragment = null
                }.Uri;
            }
            else if (!url.IsAbsoluteUri)
            {
                if (url.OriginalString == "#")
                {
                    result = default;
                    return(false);
                }

                var fragIndex = url.OriginalString.IndexOf('#');
                if (fragIndex < 0)
                {
                    // Do nothing.
                }
                else if (fragIndex == 0)
                {
                    frag = url.OriginalString.Substring(fragIndex + 1);
                    url  = null;
                }
                else
                {
                    frag = url.OriginalString.Substring(fragIndex + 1);
                    url  = new Uri(url.OriginalString.Substring(0, fragIndex), UriKind.Relative);
                }
            }

            if (frag != null && !JsonPointer.TryParse(frag, out var pointer))
            {
                result = default;
                return(false);
            }

            result = new OasReference(url, pointer);
            return(true);
        }
        public void GetWithNonexistentTarget()
        {
            using var doc = JsonDocument.Parse(@"{ ""foo"": ""bar"" }");

            JsonPointer pointer;

            Assert.IsTrue(JsonPointer.TryParse("/baz", out pointer));
            JsonElement value;

            Assert.IsFalse(pointer.TryGetValue(doc.RootElement, out value));
        }
        public void GetWithRefTest()
        {
            using var doc = JsonDocument.Parse(@"{""foo"": [""bar"", ""baz""]}");

            var         root = doc.RootElement;
            JsonPointer pointer;

            Assert.IsTrue(JsonPointer.TryParse("/foo/0", out pointer));
            JsonElement value;

            Assert.IsTrue(pointer.TryGetValue(root, out value));

            var comparer = JsonElementEqualityComparer.Instance;

            var expected = root.GetProperty("foo")[0];

            Assert.IsTrue(comparer.Equals(value, expected));
        }
        public void TestRemoveArrayElement()
        {
            using var doc = JsonDocument.Parse(@"{ ""foo"": [ ""bar"", ""qux"", ""baz"" ] }");

            using var expected = JsonDocument.Parse(@"{ ""foo"": [ ""bar"", ""baz"" ] }");

            var documentBuilder = new JsonDocumentBuilder(doc.RootElement);

            JsonPointer location;

            Assert.IsTrue(JsonPointer.TryParse(@"/foo/1", out location));

            Assert.IsTrue(location.TryRemove(ref documentBuilder));
            JsonDocument result = documentBuilder.ToJsonDocument();

            JsonElementEqualityComparer.Instance.Equals(expected.RootElement,
                                                        result.RootElement);
        }
        public void TestAddElementToArrayEnd()
        {
            using var doc   = JsonDocument.Parse(@"{ ""foo"": [""bar""] }");
            using var value = JsonDocument.Parse(@"""qux""");

            using var expected = JsonDocument.Parse(@"{ ""foo"": [""bar"", [""abc"", ""def""]] }");

            var documentBuilder = new JsonDocumentBuilder(doc.RootElement);
            var valueBuilder    = new JsonDocumentBuilder(value.RootElement);

            JsonPointer location;

            Assert.IsTrue(JsonPointer.TryParse(@"/foo/-", out location));

            Assert.IsTrue(location.TryAdd(ref documentBuilder, valueBuilder));
            JsonDocument result = documentBuilder.ToJsonDocument();

            JsonElementEqualityComparer.Instance.Equals(expected.RootElement,
                                                        result.RootElement);
        }
        public void Test2()
        {
            using var doc      = JsonDocument.Parse(@"{""foo"": [""bar"", ""baz""]}");
            using var expected = JsonDocument.Parse(@"""bar""");

            var root            = doc.RootElement;
            var documentBuilder = new JsonDocumentBuilder(root);

            JsonPointer pointer;

            Assert.IsTrue(JsonPointer.TryParse("/foo/0", out pointer));

            JsonDocumentBuilder value;

            Assert.IsTrue(pointer.TryGetValue(documentBuilder, out value));
            var result = value.ToJsonDocument();

            JsonElementEqualityComparer.Instance.Equals(expected.RootElement,
                                                        result.RootElement);
        }
        private static async Task <JsonElement?> ResolveReference(Uri uri, PathEvaluationOptions options)
        {
            var fragment = uri.Fragment;
            var baseUri  = string.IsNullOrWhiteSpace(fragment)
                                ? uri
                                : new Uri(uri.OriginalString.Replace(fragment, string.Empty));

            var document = await options.ExperimentalFeatures.DataReferenceDownload(baseUri);

            if (document == null)
            {
                return(null);
            }
            if (string.IsNullOrWhiteSpace(fragment))
            {
                return(document.RootElement);
            }
            if (!JsonPointer.TryParse(fragment, out var pointer))
            {
                return(null);
            }
            return(pointer.Evaluate(document.RootElement));
        }
Example #10
0
        /// <summary>
        /// Provides validation for the keyword.
        /// </summary>
        /// <param name="context">Contextual details for the validation process.</param>
        public void Validate(ValidationContext context)
        {
            var parts    = Reference.OriginalString.Split(new [] { '#' }, StringSplitOptions.None);
            var baseUri  = parts[0];
            var fragment = parts.Length > 1 ? parts[1] : null;

            Uri        newUri;
            JsonSchema baseSchema = null;

            if (!string.IsNullOrEmpty(baseUri))
            {
                if (Uri.TryCreate(baseUri, UriKind.Absolute, out newUri))
                {
                    baseSchema = context.Options.SchemaRegistry.Get(newUri);
                }
                else if (context.CurrentUri != null)
                {
                    var uriFolder = context.CurrentUri.OriginalString.EndsWith("/")
                                                ? context.CurrentUri
                                                : context.CurrentUri.GetParentUri();
                    newUri = uriFolder;
                    var newBaseUri = new Uri(uriFolder, baseUri);
                    if (!string.IsNullOrEmpty(fragment))
                    {
                        newUri = newBaseUri;
                    }
                    baseSchema = context.Options.SchemaRegistry.Get(newBaseUri);
                }
            }
            else
            {
                baseSchema = context.CurrentAnchor ?? context.SchemaRoot;
                newUri     = context.CurrentUri;
            }

            JsonSchema schema;

            if (!string.IsNullOrEmpty(fragment) && AnchorKeyword.AnchorPattern.IsMatch(fragment))
            {
                schema = context.Options.SchemaRegistry.Get(newUri, fragment);
            }
            else
            {
                if (baseSchema == null)
                {
                    context.IsValid = false;
                    context.Message = $"Could not resolve base URI `{baseUri}`";
                    return;
                }

                if (!string.IsNullOrEmpty(fragment))
                {
                    fragment = $"#{fragment}";
                    if (!JsonPointer.TryParse(fragment, out var pointer))
                    {
                        context.IsValid = false;
                        context.Message = $"Could not parse pointer `{fragment}`";
                        return;
                    }
                    (schema, newUri) = baseSchema.FindSubschema(pointer, newUri);
                }
                else
                {
                    schema = baseSchema;
                }
            }

            if (schema == null)
            {
                context.IsValid = false;
                context.Message = $"Could not resolve RecursiveReference `{Reference}`";
                return;
            }

            var subContext = ValidationContext.From(context, newUri: newUri);

            if (!ReferenceEquals(baseSchema, context.SchemaRoot))
            {
                subContext.SchemaRoot = baseSchema;
            }
            schema.ValidateSubschema(subContext);
            context.NestedContexts.Add(subContext);
            context.ConsolidateAnnotations();
            context.IsValid = subContext.IsValid;
        }
        public void ToUriFragmentTest()
        {
            JsonPointer pointer;
            string      fragment;
            string      location;

            location = "";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            Assert.IsTrue(fragment == "#");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));

            location = "/foo";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            Assert.IsTrue(fragment == "#/foo");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));

            location = "/foo/0";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            Assert.IsTrue(fragment == "#/foo/0");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));

            location = "/";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            Assert.IsTrue(fragment == "#/");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));

            location = "/a~1b";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            //Debug.WriteLine($"/a~1b");
            Assert.IsTrue(fragment == "#/a~1b");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));

            location = "/c%d";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            Assert.IsTrue(fragment == "#/c%25d");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));

            location = "/e^f";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            Assert.IsTrue(fragment == "#/e%5Ef");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));

            location = "/g|h";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            Assert.IsTrue(fragment == "#/g%7Ch");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));

            location = "/i\\j";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            Assert.IsTrue(fragment == "#/i%5Cj");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));

            location = "/k\"l";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            Assert.IsTrue(fragment == "#/k%22l");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));

            location = "/ ";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            Assert.IsTrue(fragment == "#/%20");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));

            location = "/m~0n";
            Assert.IsTrue(JsonPointer.TryParse(location, out pointer));
            fragment = pointer.ToUriFragment();
            //Debug.WriteLine($"/m~0n {fragment}");
            Assert.IsTrue(fragment == "#/m~0n");
            Assert.IsTrue(JsonPointer.TryParse(fragment, out pointer));
            Assert.IsTrue(pointer.ToString().Equals(location));
        }
Example #12
0
        internal static bool TryParse(string s, out OasFieldExpression result, ref int index, bool respectDelimiter)
        {
            var i = index;

            if (s == null || !StartsWith(s, "$", i++))
            {
                result = default;
                return(false);
            }

            if (StartsWith(s, "url", i))
            {
                i += 3;
                if (respectDelimiter && !StartsWith(s, "}", i))
                {
                    result = default;
                    return(false);
                }

                index  = i;
                result = Url();
                return(true);
            }

            if (StartsWith(s, "method", i))
            {
                i += 6;
                if (respectDelimiter && !StartsWith(s, "}", i))
                {
                    result = default;
                    return(false);
                }

                index  = i;
                result = Method();
                return(true);
            }

            if (StartsWith(s, "statusCode", i))
            {
                i += 10;
                if (respectDelimiter && !StartsWith(s, "}", i))
                {
                    result = default;
                    return(false);
                }

                index  = i;
                result = StatusCode();
                return(true);
            }

            if (!StartsWith(s, "re", i))
            {
                result = default;
                return(false);
            }
            i += 2;

            OasFieldExpressionType type;

            if (StartsWith(s, "quest.", i))
            {
                i   += 6;
                type = OasFieldExpressionType.Request;
            }
            else if (StartsWith(s, "sponse.", i))
            {
                i   += 7;
                type = OasFieldExpressionType.Response;
            }
            else
            {
                result = default;
                return(false);
            }

            OasFieldExpressionSource source;

            if (StartsWith(s, "header.", i))
            {
                i     += 7;
                source = OasFieldExpressionSource.Header;
            }
            else if (StartsWith(s, "query.", i))
            {
                i     += 6;
                source = OasFieldExpressionSource.Query;
            }
            else if (StartsWith(s, "path.", i))
            {
                i     += 5;
                source = OasFieldExpressionSource.Path;
            }
            else if (StartsWith(s, "body#", i))
            {
                i     += 5;
                source = OasFieldExpressionSource.Body;
            }
            else
            {
                result = default;
                return(false);
            }

            if (i == s.Length)
            {
                result = default;
                return(false);
            }

            string name;

            if (respectDelimiter)
            {
                var j = s.IndexOf('}', i + 1);
                if (j < 0)
                {
                    result = default;
                    return(false);
                }
                name = s.Substring(i, j - i);
                i    = j;
            }
            else
            {
                name = s.Substring(i);
                i    = s.Length;
            }

            if (source == OasFieldExpressionSource.Header)
            {
                if (!TryValidateToken(name))
                {
                    result = default;
                    return(false);
                }
                result = new OasFieldExpression(type, source, name);
            }
            else if (source == OasFieldExpressionSource.Body)
            {
                if (!JsonPointer.TryParse(name, out var pointer))
                {
                    result = default;
                    return(false);
                }
                result = new OasFieldExpression(type, pointer);
            }
            else
            {
                result = new OasFieldExpression(type, source, name);
            }

            index = i;
            return(true);
        }
 public void TryParseExpectUriEncodedGetPlain()
 {
     Assert.IsFalse(JsonPointer.TryParse("/one/2/three", out _, JsonPointerKind.UriEncoded));
 }
 public void TryParseExpectPlainGetUriEncoded()
 {
     Assert.IsFalse(JsonPointer.TryParse("#/one/2/three", out _, JsonPointerKind.Plain));
 }
 public void TryParseFailure(string pointerString)
 {
     Assert.False(JsonPointer.TryParse(pointerString, out _));
 }