public void DoesNodeBelongToItemSubnamespace()
    {
        var doc = new OpenApiDocument
        {
            Paths = new(),
        };

        doc.Paths.Add("{param}", new() { });
        var node = OpenApiUrlTreeNode.Create(doc, Label);

        Assert.False(node.DoesNodeBelongToItemSubnamespace());
        Assert.True(node.Children.First().Value.DoesNodeBelongToItemSubnamespace());

        doc = new OpenApiDocument
        {
            Paths = new(),
        };
        doc.Paths.Add("param}", new() { });
        node = OpenApiUrlTreeNode.Create(doc, Label);
        Assert.False(node.Children.First().Value.DoesNodeBelongToItemSubnamespace());

        doc = new OpenApiDocument
        {
            Paths = new(),
        };
        doc.Paths.Add("{param", new() { });
        node = OpenApiUrlTreeNode.Create(doc, Label);
        Assert.False(node.Children.First().Value.DoesNodeBelongToItemSubnamespace());
    }
 private async static Task <OpenApiUrlTreeNode> GetV1TreeNode()
 {
     if (_v1TreeNode == null)
     {
         _v1TreeNode = await SnippetModelTests.GetTreeNode("https://raw.githubusercontent.com/microsoftgraph/msgraph-metadata/master/openapi/v1.0/openapi.yaml");
     }
     return(_v1TreeNode);
 }
    public void GetUrlTemplateCleansInvalidParameters()
    {
        var doc = new OpenApiDocument
        {
            Paths = new(),
        };

        doc.Paths.Add("{param-with-dashes}\\existing-segment", new()
        {
            Operations = new Dictionary <OperationType, OpenApiOperation> {
                { OperationType.Get, new() {
                      Parameters = new List <OpenApiParameter> {
                          new() {
                              Name     = "param-with-dashes",
                              In       = ParameterLocation.Path,
                              Required = true,
                              Schema   = new() {
                                  Type = "string"
                              }
                          },
                          new (){
                              Name   = "$select",
                              In     = ParameterLocation.Query,
                              Schema = new () {
                                  Type = "string"
                              }
                          },
                          new (){
                              Name   = "api-version",
                              In     = ParameterLocation.Query,
                              Schema = new () {
                                  Type = "string"
                              }
                          },
                          new (){
                              Name   = "api~topic",
                              In     = ParameterLocation.Query,
                              Schema = new () {
                                  Type = "string"
                              }
                          },
                          new (){
                              Name   = "api.encoding",
                              In     = ParameterLocation.Query,
                              Schema = new () {
                                  Type = "string"
                              }
                          }
                      }
                  } }
            }
        });
        var node = OpenApiUrlTreeNode.Create(doc, Label);

        Assert.Equal("{+baseurl}/{param%2Dwith%2Ddashes}/existing-segment{?%24select,api%2Dversion,api%7Etopic,api%2Eencoding}", node.Children.First().Value.GetUrlTemplate());
        // the query parameters will be decoded by a middleware at runtime before the request is executed
    }
}
        public void ThrowsArgumentNullExceptionForNullArgumentInAddAdditionalDataMethod()
        {
            var doc = OpenApiDocumentSample_1;

            var label    = "personal";
            var rootNode = OpenApiUrlTreeNode.Create(doc, label);

            Assert.Throws <ArgumentNullException>(() => rootNode.AddAdditionalData(null));
        }
        public void DefensiveProgramming()
        {
            var nodeMock    = OpenApiUrlTreeNode.Create();
            var requestMock = new Mock <HttpRequestMessage>().Object;

            Assert.Throws <ArgumentNullException>(() => new SnippetModel(null, "something", nodeMock));
            Assert.Throws <ArgumentNullException>(() => new SnippetModel(requestMock, null, nodeMock));
            Assert.Throws <ArgumentNullException>(() => new SnippetModel(requestMock, "something", null));
        }
        public void ThrowsArgumentNullExceptionForNullOrEmptyArgumentsInCreateMethod()
        {
            var doc = OpenApiDocumentSample_1;

            Assert.Throws <ArgumentNullException>(() => OpenApiUrlTreeNode.Create(doc, ""));
            Assert.Throws <ArgumentNullException>(() => OpenApiUrlTreeNode.Create(doc, null));
            Assert.Throws <ArgumentNullException>(() => OpenApiUrlTreeNode.Create(null, "beta"));
            Assert.Throws <ArgumentNullException>(() => OpenApiUrlTreeNode.Create(null, null));
            Assert.Throws <ArgumentNullException>(() => OpenApiUrlTreeNode.Create(null, ""));
        }
 public void Defensive()
 {
     Assert.False(OpenApiUrlTreeNodeExtensions.IsComplexPathWithAnyNumberOfParameters(null));
     Assert.False(OpenApiUrlTreeNodeExtensions.IsPathSegmentWithSingleSimpleParameter((OpenApiUrlTreeNode)null));
     Assert.False(OpenApiUrlTreeNodeExtensions.DoesNodeBelongToItemSubnamespace(null));
     Assert.Null(OpenApiUrlTreeNodeExtensions.GetPathItemDescription(null, null));
     Assert.Null(OpenApiUrlTreeNodeExtensions.GetPathItemDescription(null, Label));
     Assert.Null(OpenApiUrlTreeNodeExtensions.GetPathItemDescription(OpenApiUrlTreeNode.Create(), null));
     Assert.Null(OpenApiUrlTreeNodeExtensions.GetPathItemDescription(OpenApiUrlTreeNode.Create(), Label));
 }
예제 #8
0
 public static string GetNodeNamespaceFromPath(this OpenApiUrlTreeNode currentNode, string prefix) =>
 prefix +
 ((currentNode?.Path?.Contains(pathNameSeparator) ?? false) ?
  (string.IsNullOrEmpty(prefix) ? string.Empty : ".")
  + currentNode?.Path
  ?.Split(pathNameSeparator, StringSplitOptions.RemoveEmptyEntries)
  ?.Where(x => !x.StartsWith('{'))
  ?.Aggregate((x, y) => $"{x}.{y}") :
  string.Empty)
 .ReplaceValueIdentifier();
        public void ThrowsArgumentNullExceptionForNullOrEmptyArgumentInHasOperationsMethod()
        {
            var doc = OpenApiDocumentSample_1;

            var label    = "personal";
            var rootNode = OpenApiUrlTreeNode.Create(doc, label);

            Assert.Throws <ArgumentNullException>(() => rootNode.HasOperations(null));
            Assert.Throws <ArgumentNullException>(() => rootNode.HasOperations(""));
        }
        public void ThrowsArgumentExceptionForDuplicateLabels()
        {
            var doc1 = OpenApiDocumentSample_1;

            var doc2 = OpenApiDocumentSample_2;

            var label1   = "personal";
            var rootNode = OpenApiUrlTreeNode.Create(doc1, label1);

            Assert.Throws <ArgumentException>(() => rootNode.Attach(doc2, label1));
        }
예제 #11
0
        public void GetIdentifier()
        {
            var doc = new OpenApiDocument {
                Paths = new(),
            };

            doc.Paths.Add("function(parm1)", new() {});
            var node = OpenApiUrlTreeNode.Create(doc, label);

            Assert.DoesNotContain("(", node.Children.First().Value.GetIdentifier());
        }
예제 #12
0
        ///<summary>
        /// Returns the class name for the node with more or less precision depending on the provided arguments
        ///</summary>
        public static string GetClassName(this OpenApiUrlTreeNode currentNode, string suffix = default, string prefix = default, OpenApiOperation operation = default)
        {
            var rawClassName = operation?.GetResponseSchema()?.Reference?.GetClassName() ??
                               currentNode?.GetIdentifier()?.ReplaceValueIdentifier();

            if ((currentNode?.DoesNodeBelongToItemSubnamespace() ?? false) && idClassNameCleanup.IsMatch(rawClassName))
            {
                rawClassName = idClassNameCleanup.Replace(rawClassName, string.Empty);
            }
            return(prefix + rawClassName + suffix);
        }
예제 #13
0
        public void Single_root_node_creates_single_request_builder_class()
        {
            var node       = OpenApiUrlTreeNode.Create();
            var mockLogger = new Mock <ILogger <KiotaBuilder> >();
            var builder    = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration()
            {
                ClientClassName = "Graph"
            });
            var codeModel = builder.CreateSourceModel(node);

            Assert.Single(codeModel.GetChildElements(true));
        }
예제 #14
0
        public void IsParameter()
        {
            var doc = new OpenApiDocument {
                Paths = new(),
            };

            doc.Paths.Add("{param}", new() {});
            var node = OpenApiUrlTreeNode.Create(doc, label);

            Assert.False(node.IsParameter());
            Assert.True(node.Children.First().Value.IsParameter());
        }
    public void SanitizesAtSign()
    {
        var doc = new OpenApiDocument
        {
            Paths = new(),
        };

        doc.Paths.Add("\\deviceManagement\\microsoft.graph.getRoleScopeTagsByIds(ids=@ids)", new() { });
        var node = OpenApiUrlTreeNode.Create(doc, Label);

        Assert.Equal("graph.deviceManagement.getRoleScopeTagsByIdsWithIds", node.Children.First().Value.GetNodeNamespaceFromPath("graph"));
    }
    public void IsComplexPathWithAnyNumberOfParameters()
    {
        var doc = new OpenApiDocument
        {
            Paths = new(),
        };

        doc.Paths.Add("function()", new() { });
        var node = OpenApiUrlTreeNode.Create(doc, Label);

        Assert.False(node.IsComplexPathWithAnyNumberOfParameters());
        Assert.True(node.Children.First().Value.IsComplexPathWithAnyNumberOfParameters());
    }
    public void GetNodeNamespaceFromPath()
    {
        var doc = new OpenApiDocument
        {
            Paths = new(),
        };

        doc.Paths.Add("\\users\\messages", new() { });
        var node = OpenApiUrlTreeNode.Create(doc, Label);

        Assert.Equal("graph.users.messages", node.Children.First().Value.GetNodeNamespaceFromPath("graph"));
        Assert.Equal("users.messages", node.Children.First().Value.GetNodeNamespaceFromPath(null));
    }
예제 #18
0
        public void GetsDescription()
        {
            var node = OpenApiUrlTreeNode.Create();

            node.PathItems.Add(label, new() {
                Description = "description",
                Summary     = "summary"
            });
            Assert.Equal(label, OpenApiUrlTreeNode.Create().GetPathItemDescription(label, label));
            Assert.Equal("description", node.GetPathItemDescription(label, label));
            node.PathItems[label].Description = null;
            Assert.Equal("summary", node.GetPathItemDescription(label, label));
        }
예제 #19
0
        public void Single_path_with_get_collection()
        {
            var node = OpenApiUrlTreeNode.Create();

            node.Attach("tasks", new OpenApiPathItem()
            {
                Operations =
                {
                    [OperationType.Get] = new OpenApiOperation()
                                            {
                                            Responses = new OpenApiResponses
                                            {
                                            ["200"] = new OpenApiResponse()
                                            {
                                            Content =
                                            {
                                            ["application/json"] = new OpenApiMediaType()
                                            {
                                            Schema = new OpenApiSchema
                                            {
                                            Type  = "array",
                                            Items = new OpenApiSchema
                                            {
                                            Type = "int"
                                            }
                                            }
                                            }
                                            }
                                            }
                                            }
                                            }
                }
            }, "default");
            var mockLogger = new Mock <ILogger <KiotaBuilder> >();
            var builder    = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration()
            {
                ClientClassName = "Graph"
            });
            var codeModel = builder.CreateSourceModel(node);

            var rootNamespace       = codeModel.GetChildElements(true).Single();
            var rootBuilder         = rootNamespace.GetChildElements(true).Single(e => e.Name == "Graph");
            var tasksProperty       = rootBuilder.GetChildElements(true).OfType <CodeProperty>().Single(e => e.Name == "Tasks");
            var tasksRequestBuilder = tasksProperty.Type as CodeType;

            Assert.NotNull(tasksRequestBuilder);
            var getMethod  = tasksRequestBuilder.TypeDefinition.GetChildElements(true).OfType <CodeMethod>().Single(e => e.Name == "Get");
            var returnType = getMethod.ReturnType;

            Assert.Equal(CodeTypeBase.CodeTypeCollectionKind.Array, returnType.CollectionKind);
        }
예제 #20
0
 public void Defensive()
 {
     Assert.Empty(OpenApiUrlTreeNodeExtensions.GetIdentifier(null));
     Assert.False(OpenApiUrlTreeNodeExtensions.IsFunction(null));
     Assert.False(OpenApiUrlTreeNodeExtensions.IsParameter(null));
     Assert.False(OpenApiUrlTreeNodeExtensions.DoesNodeBelongToItemSubnamespace(null));
     Assert.Empty(OpenApiUrlTreeNodeExtensions.GetComponentsReferenceIndex(null, null));
     Assert.Empty(OpenApiUrlTreeNodeExtensions.GetComponentsReferenceIndex(null, label));
     Assert.Empty(OpenApiUrlTreeNodeExtensions.GetComponentsReferenceIndex(OpenApiUrlTreeNode.Create(), null));
     Assert.Empty(OpenApiUrlTreeNodeExtensions.GetComponentsReferenceIndex(OpenApiUrlTreeNode.Create(), label));
     Assert.Null(OpenApiUrlTreeNodeExtensions.GetPathItemDescription(null, null));
     Assert.Null(OpenApiUrlTreeNodeExtensions.GetPathItemDescription(null, label));
     Assert.Null(OpenApiUrlTreeNodeExtensions.GetPathItemDescription(OpenApiUrlTreeNode.Create(), null));
     Assert.Null(OpenApiUrlTreeNodeExtensions.GetPathItemDescription(OpenApiUrlTreeNode.Create(), label));
 }
        public void CreateMultiplePathsWorks()
        {
            var doc = OpenApiDocumentSample_1;

            string label    = "assets";
            var    rootNode = OpenApiUrlTreeNode.Create(doc, label);

            Assert.NotNull(rootNode);
            Assert.Equal(2, rootNode.Children.Count);
            Assert.Equal("houses", rootNode.Children["houses"].Segment);
            Assert.Equal("cars", rootNode.Children["cars"].Segment);
            Assert.True(rootNode.PathItems.ContainsKey(label));
            Assert.True(rootNode.Children["houses"].PathItems.ContainsKey(label));
            Assert.True(rootNode.Children["cars"].PathItems.ContainsKey(label));
        }
        public void ThrowsArgumentNullExceptionForNullOrEmptyArgumentsInAttachMethod()
        {
            var doc1 = OpenApiDocumentSample_1;

            var doc2 = OpenApiDocumentSample_2;

            var label1   = "personal";
            var rootNode = OpenApiUrlTreeNode.Create(doc1, label1);

            Assert.Throws <ArgumentNullException>(() => rootNode.Attach(doc2, ""));
            Assert.Throws <ArgumentNullException>(() => rootNode.Attach(doc2, null));
            Assert.Throws <ArgumentNullException>(() => rootNode.Attach(null, "beta"));
            Assert.Throws <ArgumentNullException>(() => rootNode.Attach(null, null));
            Assert.Throws <ArgumentNullException>(() => rootNode.Attach(null, ""));
        }
        public void AttachDocumentWorks()
        {
            var doc1 = OpenApiDocumentSample_1;

            var doc2 = OpenApiDocumentSample_2;

            var label1   = "personal";
            var label2   = "business";
            var rootNode = OpenApiUrlTreeNode.Create(doc1, label1);

            rootNode.Attach(doc2, label2);

            Assert.NotNull(rootNode);
            Assert.Equal(4, rootNode.Children.Count);
            Assert.True(rootNode.Children["houses"].PathItems.ContainsKey(label1));
            Assert.True(rootNode.Children["offices"].PathItems.ContainsKey(label2));
        }
        public void CreateSingleRootWorks()
        {
            var doc = new OpenApiDocument()
            {
                Paths = new OpenApiPaths()
                {
                    ["/"] = new OpenApiPathItem()
                }
            };

            var label    = "v1.0";
            var rootNode = OpenApiUrlTreeNode.Create(doc, label);

            Assert.NotNull(rootNode);
            Assert.NotNull(rootNode.PathItems);
            Assert.False(rootNode.HasOperations(label));
            Assert.Equal(0, rootNode.Children.Count);
        }
        internal static async Task <OpenApiUrlTreeNode> GetTreeNode(string url)
        {
            Stream stream;

            if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                using var httpClient = new HttpClient();
                stream = await httpClient.GetStreamAsync(url);
            }
            else
            {
                stream = File.OpenRead(url);
            }
            var reader = new OpenApiStreamReader();
            var doc    = reader.Read(stream, out var diags);
            await stream.DisposeAsync();

            return(OpenApiUrlTreeNode.Create(doc, "default"));
        }
        public void SegmentIsParameterWorks()
        {
            var doc = new OpenApiDocument()
            {
                Paths = new OpenApiPaths()
                {
                    ["/"] = new OpenApiPathItem(),
                    ["/houses/apartments/{apartment-id}"] = new OpenApiPathItem()
                }
            };

            var label    = "properties";
            var rootNode = OpenApiUrlTreeNode.Create(doc, label);

            Assert.NotNull(rootNode);
            Assert.Equal(1, rootNode.Children.Count);
            Assert.NotNull(rootNode.Children["houses"].Children["apartments"].Children["{apartment-id}"].PathItems);
            Assert.True(rootNode.Children["houses"].Children["apartments"].Children["{apartment-id}"].IsParameter);
            Assert.Equal("{apartment-id}", rootNode.Children["houses"].Children["apartments"].Children["{apartment-id}"].Segment);
        }
        public void CreatePathWithoutRootWorks()
        {
            var doc = new OpenApiDocument()
            {
                Paths = new OpenApiPaths()
                {
                    ["/houses"] = new OpenApiPathItem()
                }
            };

            var label    = "cabin";
            var rootNode = OpenApiUrlTreeNode.Create(doc, label);

            Assert.NotNull(rootNode);
            Assert.NotNull(rootNode.PathItems);
            Assert.Equal(1, rootNode.Children.Count);
            Assert.Equal("houses", rootNode.Children["houses"].Segment);
            Assert.NotNull(rootNode.Children["houses"].PathItems);
            Assert.False(rootNode.Children["houses"].HasOperations("cabin"));
        }
        public void CreatePathsWithMultipleSegmentsWorks()
        {
            var doc = new OpenApiDocument()
            {
                Paths = new OpenApiPaths()
                {
                    ["/"] = new OpenApiPathItem(),
                    ["/houses/apartments/{apartment-id}"] = new OpenApiPathItem(),
                    ["/cars/coupes"] = new OpenApiPathItem()
                }
            };

            var label    = "assets";
            var rootNode = OpenApiUrlTreeNode.Create(doc, label);

            Assert.NotNull(rootNode);
            Assert.Equal(2, rootNode.Children.Count);
            Assert.NotNull(rootNode.Children["houses"].Children["apartments"].Children["{apartment-id}"].PathItems);
            Assert.True(rootNode.Children["houses"].Children["apartments"].Children["{apartment-id}"].PathItems.ContainsKey(label));
            Assert.True(rootNode.Children["cars"].Children["coupes"].PathItems.ContainsKey(label));
            Assert.True(rootNode.PathItems.ContainsKey(label));
            Assert.Equal("coupes", rootNode.Children["cars"].Children["coupes"].Segment);
        }
예제 #29
0
        public static string GetIdentifier(this OpenApiUrlTreeNode currentNode)
        {
            if (currentNode == null)
            {
                return(string.Empty);
            }
            string identifier;

            if (currentNode.IsParameter())
            {
                identifier = currentNode.Segment.Substring(1, currentNode.Segment.Length - 2).ToPascalCase();
            }
            else
            {
                identifier = currentNode.Segment.ToPascalCase().Replace("()", "");
                var openParen = identifier.IndexOf("(");
                if (openParen >= 0)
                {
                    identifier = identifier.Substring(0, openParen);
                }
            }
            return(identifier);
        }
예제 #30
0
        private static void AddAllPathsEntries(OpenApiUrlTreeNode currentNode, Dictionary <string, HashSet <OpenApiUrlTreeNode> > index, string label)
        {
            if (currentNode == null || string.IsNullOrEmpty(label))
            {
                return;
            }

            if (currentNode.PathItems.ContainsKey(label) && currentNode.HasOperations(label))
            {
                var nodeOperations            = currentNode.PathItems[label].Operations.Values;
                var requestSchemasFirstLevel  = nodeOperations.SelectMany(x => x.RequestBody?.Content?.Values?.Select(y => y.Schema) ?? Enumerable.Empty <OpenApiSchema>());
                var responseSchemasFirstLevel = nodeOperations.SelectMany(x =>
                                                                          x?.Responses?.Values?.SelectMany(y =>
                                                                                                           y?.Content?.Values?.Select(z => z.Schema) ?? Enumerable.Empty <OpenApiSchema>()) ?? Enumerable.Empty <OpenApiSchema>());
                var operationFirstLevelSchemas = requestSchemasFirstLevel.Union(responseSchemasFirstLevel);

                operationFirstLevelSchemas.SelectMany(x => x.GetSchemaReferenceIds()).ToList().ForEach(x => {
                    if (index.TryGetValue(x, out var entry))
                    {
                        entry.Add(currentNode);
                    }
                    else
                    {
                        index.Add(x, new(new [] { currentNode }));
                    }
                });
            }

            if (currentNode.Children != null)
            {
                foreach (var child in currentNode.Children.Values)
                {
                    AddAllPathsEntries(child, index, label);
                }
            }
        }