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());
    }
    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 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 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));
 }
        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, ""));
        }
Esempio n. 8
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());
        }
        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));
        }
Esempio n. 10
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"));
    }
Esempio n. 12
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));
        }
    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));
    }
    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());
    }
Esempio n. 15
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));
        }
Esempio n. 16
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);
        }
        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 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));
        }
Esempio n. 19
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 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);
        }
        public void AttachPathWorks()
        {
            var doc = OpenApiDocumentSample_1;

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

            var pathItem1 = new OpenApiPathItem
            {
                Operations = new Dictionary <OperationType, OpenApiOperation>
                {
                    {
                        OperationType.Get, new OpenApiOperation
                        {
                            OperationId = "motorcycles.ListMotorcycle",
                            Responses   = new OpenApiResponses()
                            {
                                {
                                    "200", new OpenApiResponse()
                                    {
                                        Description = "Retrieved entities"
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var path1 = "/motorcycles";

            rootNode.Attach(path1, pathItem1, label1);

            var pathItem2 = new OpenApiPathItem
            {
                Operations = new Dictionary <OperationType, OpenApiOperation>
                {
                    {
                        OperationType.Get, new OpenApiOperation
                        {
                            OperationId = "computers.ListComputer",
                            Responses   = new OpenApiResponses()
                            {
                                {
                                    "200", new OpenApiResponse()
                                    {
                                        Description = "Retrieved entities"
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var path2  = "/computers";
            var label2 = "business";

            rootNode.Attach(path2, pathItem2, label2);

            Assert.Equal(4, rootNode.Children.Count);
            Assert.True(rootNode.Children.ContainsKey(path1.Substring(1)));
            Assert.True(rootNode.Children.ContainsKey(path2.Substring(1)));
            Assert.True(rootNode.Children[path1.Substring(1)].PathItems.ContainsKey(label1));
            Assert.True(rootNode.Children[path2.Substring(1)].PathItems.ContainsKey(label2));
        }
        public void AdditionalDataWorks()
        {
            var doc = OpenApiDocumentSample_1;

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

            var additionalData1 = new Dictionary <string, List <string> >
            {
                { "DatePurchased", new List <string> {
                      "21st April 2021"
                  } },
                { "Location", new List <string> {
                      "Seattle, WA"
                  } },
                { "TotalEstimateValue", new List <string> {
                      "USD 2 Million"
                  } },
                { "Owner", new List <string> {
                      "John Doe, Mr"
                  } }
            };

            rootNode.AddAdditionalData(additionalData1);

            var additionalData2 = new Dictionary <string, List <string> >
            {
                { "Bedrooms", new List <string> {
                      "Five"
                  } }
            };

            rootNode.Children["houses"].AddAdditionalData(additionalData2);

            var additionalData3 = new Dictionary <string, List <string> >
            {
                { "Categories", new List <string> {
                      "Coupe", "Sedan", "Convertible"
                  } }
            };

            rootNode.Children["cars"].AddAdditionalData(additionalData3);

            Assert.Equal(4, rootNode.AdditionalData.Count);
            Assert.True(rootNode.AdditionalData.ContainsKey("DatePurchased"));
            Assert.Collection(rootNode.AdditionalData["Location"],
                              item =>
            {
                Assert.Equal("Seattle, WA", item);
            });
            Assert.Collection(rootNode.Children["houses"].AdditionalData["Bedrooms"],
                              item =>
            {
                Assert.Equal("Five", item);
            });
            Assert.Collection(rootNode.Children["cars"].AdditionalData["Categories"],
                              item =>
            {
                Assert.Equal("Coupe", item);
            },
                              item =>
            {
                Assert.Equal("Sedan", item);
            },
                              item =>
            {
                Assert.Equal("Convertible", item);
            });
        }
        public void CreateUrlSpaceWithoutOpenApiDocument()
        {
            var rootNode = OpenApiUrlTreeNode.Create();

            Assert.NotNull(rootNode);
        }
        public void HasOperationsWorks()
        {
            var doc1 = new OpenApiDocument()
            {
                Paths = new OpenApiPaths()
                {
                    ["/"]              = new OpenApiPathItem(),
                    ["/houses"]        = new OpenApiPathItem(),
                    ["/cars/{car-id}"] = new OpenApiPathItem()
                    {
                        Operations = new Dictionary <OperationType, OpenApiOperation>
                        {
                            {
                                OperationType.Get, new OpenApiOperation
                                {
                                    OperationId = "cars.GetCar",
                                    Responses   = new OpenApiResponses()
                                    {
                                        {
                                            "200", new OpenApiResponse()
                                            {
                                                Description = "Retrieved entity"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var doc2 = new OpenApiDocument()
            {
                Paths = new OpenApiPaths()
                {
                    ["/cars/{car-id}"] = new OpenApiPathItem()
                    {
                        Operations = new Dictionary <OperationType, OpenApiOperation>
                        {
                            {
                                OperationType.Get, new OpenApiOperation
                                {
                                    OperationId = "cars.GetCar",
                                    Responses   = new OpenApiResponses()
                                    {
                                        {
                                            "200", new OpenApiResponse()
                                            {
                                                Description = "Retrieved entity"
                                            }
                                        }
                                    }
                                }
                            },
                            {
                                OperationType.Put, new OpenApiOperation
                                {
                                    OperationId = "cars.UpdateCar",
                                    Responses   = new OpenApiResponses()
                                    {
                                        {
                                            "204", new OpenApiResponse()
                                            {
                                                Description = "Success."
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

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

            rootNode.Attach(doc2, label2);

            Assert.NotNull(rootNode);

            Assert.Equal(2, rootNode.Children["cars"].Children["{car-id}"].PathItems.Count);
            Assert.True(rootNode.Children["cars"].Children["{car-id}"].PathItems.ContainsKey(label1));
            Assert.True(rootNode.Children["cars"].Children["{car-id}"].PathItems.ContainsKey(label2));

            Assert.False(rootNode.Children["houses"].HasOperations(label1));
            Assert.True(rootNode.Children["cars"].Children["{car-id}"].HasOperations(label1));
            Assert.True(rootNode.Children["cars"].Children["{car-id}"].HasOperations(label2));
            Assert.Single(rootNode.Children["cars"].Children["{car-id}"].PathItems[label1].Operations);
            Assert.Equal(2, rootNode.Children["cars"].Children["{car-id}"].PathItems[label2].Operations.Count);
        }