diff --git a/CHANGELOG.md b/CHANGELOG.md index 929fb2083b..1fb6985f25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added compatibility all the way down to android API level 26 for Java. - Added support for enum and collection of enum return types for Java. - Added support for types with more than 500 discriminator entries in Java. +- Added a confirmation message once the generation is successful. [#1898](https://github.com/microsoft/kiota/issues/1898) ### Changed @@ -19,6 +20,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Changed the generated PHP deserializer code to use `fn` instead of `function`. [#1880](https://github.com/microsoft/kiota/pull/1880) - Fixes compile errors due to type ambiguity in generated models in dotnet. [#1881](https://github.com/microsoft/kiota/issues/1881) - Changes the ResponeHandler parameter in IRequestAdapter to be a RequestOption in dotnet [#1858](https://github.com/microsoft/kiota/issues/1858) +- File extensions are now stripped from property/namespace/class names. [#1892](https://github.com/microsoft/kiota/issues/1892) +- Missing host/server is now considered a warning instead of a critical error. [#1896](https://github.com/microsoft/kiota/issues/1896) +- Fixed a bug where info and show commands would crash in case of invalid description URL. [#1894](https://github.com/microsoft/kiota/issues/1894) +- Show command now reads descriptions directly from APIs.guru instead of their origin. [#1897](https://github.com/microsoft/kiota/issues/1897) ## [0.6.0] - 2022-10-06 diff --git a/src/Kiota.Builder/Extensions/OpenApiUrlTreeNodeExtensions.cs b/src/Kiota.Builder/Extensions/OpenApiUrlTreeNodeExtensions.cs index 2ac2d06895..7bfd2172c4 100644 --- a/src/Kiota.Builder/Extensions/OpenApiUrlTreeNodeExtensions.cs +++ b/src/Kiota.Builder/Extensions/OpenApiUrlTreeNodeExtensions.cs @@ -18,9 +18,11 @@ public static string GetNamespaceFromPath(this string currentPath, string prefix + currentPath ?.Split(pathNameSeparator, StringSplitOptions.RemoveEmptyEntries) ?.Select(replaceSingleParameterSegmentByItem) - ?.Select(static x => CleanupParametersFromPath((x ?? string.Empty).Split('.', StringSplitOptions.RemoveEmptyEntries) - ?.Select(static x => x.TrimStart('$')) //$ref from OData - .Last())) + ?.Select(static x => CleanupParametersFromPath((x ?? string.Empty) + .Split('.', StringSplitOptions.RemoveEmptyEntries) + .Select(static x => x.TrimStart('$')) //$ref from OData + .Except(SegmentsToSkipForClassNames, StringComparer.OrdinalIgnoreCase) + .Last())) ?.Select(static x => x.CleanupSymbolName()) ?.Aggregate(string.Empty, static (x, y) => $"{x}{GetDotIfBothNotNullOfEmpty(x, y)}{y}") : @@ -70,6 +72,8 @@ public static string GetClassName(this OpenApiUrlTreeNode currentNode, HashSet SegmentsToSkipForClassNames = new(6, StringComparer.OrdinalIgnoreCase) { + "json", + "xml", + "csv", + "yaml", + "yml", + "txt", + }; private static readonly Regex descriptionCleanupRegex = new (@"[\r\n\t]", RegexOptions.Compiled); public static string CleanupDescription(this string description) => string.IsNullOrEmpty(description) ? description : descriptionCleanupRegex.Replace(description, string.Empty); public static string GetPathItemDescription(this OpenApiUrlTreeNode currentNode, string label, string defaultValue = default) => @@ -96,10 +113,14 @@ public static bool IsPathSegmentWithSingleSimpleParameter(this OpenApiUrlTreeNod currentNode?.Segment.IsPathSegmentWithSingleSimpleParameter() ?? false; private static bool IsPathSegmentWithSingleSimpleParameter(this string currentSegment) { - return (currentSegment?.StartsWith(requestParametersChar) ?? false) && - currentSegment.EndsWith(requestParametersEndChar) && - currentSegment.Count(x => x == requestParametersChar) == 1; + if (string.IsNullOrEmpty(currentSegment)) return false; + + var segmentWithoutExtension = stripExtensionForIndexersRegex.Replace(currentSegment, string.Empty); + return segmentWithoutExtension.StartsWith(requestParametersChar) && + segmentWithoutExtension.EndsWith(requestParametersEndChar) && + segmentWithoutExtension.Count(x => x == requestParametersChar) == 1; } + private static readonly Regex stripExtensionForIndexersRegex = new(@"\.(?:json|yaml|yml|csv|txt)$", RegexOptions.Compiled); // so {param-name}.json is considered as indexer public static bool IsComplexPathWithAnyNumberOfParameters(this OpenApiUrlTreeNode currentNode) { return (currentNode?.Segment?.Contains(requestParametersSectionChar) ?? false) && currentNode.Segment.EndsWith(requestParametersSectionEndChar); @@ -139,7 +160,8 @@ private static string SanitizePathParameterNamesForUrlTemplate(string original) } public static string SanitizeParameterNameForUrlTemplate(this string original) { if(string.IsNullOrEmpty(original)) return original; - return Uri.EscapeDataString(original + return Uri.EscapeDataString(stripExtensionForIndexersRegex + .Replace(original, string.Empty) // {param-name}.json becomes {param-name} .TrimStart('{') .TrimEnd('}')) .Replace("-", "%2D") diff --git a/src/Kiota.Builder/KiotaBuilder.cs b/src/Kiota.Builder/KiotaBuilder.cs index 94319644f6..843102c9dc 100644 --- a/src/Kiota.Builder/KiotaBuilder.cs +++ b/src/Kiota.Builder/KiotaBuilder.cs @@ -154,7 +154,7 @@ public void FilterPathsByPatterns(OpenApiDocument doc, List includePattern private void SetApiRootUrl() { config.ApiRootUrl = openApiDocument.Servers.FirstOrDefault()?.Url.TrimEnd('/'); if(string.IsNullOrEmpty(config.ApiRootUrl)) - throw new InvalidOperationException("A servers entry (v3) or host + basePath + schemes properties (v2) must be present in the OpenAPI description."); + logger.LogWarning("A servers entry (v3) or host + basePath + schemes properties (v2) was not present in the OpenAPI description. The root URL will need to be set manually with the request adapter."); } private void StopLogAndReset(Stopwatch sw, string prefix) { sw.Stop(); diff --git a/src/Kiota.Builder/SearchProviders/APIsGuru/APIEntry.cs b/src/Kiota.Builder/SearchProviders/APIsGuru/APIEntry.cs index 68866e8113..d147b8cd85 100644 --- a/src/Kiota.Builder/SearchProviders/APIsGuru/APIEntry.cs +++ b/src/Kiota.Builder/SearchProviders/APIsGuru/APIEntry.cs @@ -12,9 +12,6 @@ public record ApiInformation { public ApiContact contact { get; set;} public string description { get; set;} public string title { get; set;} - public string version { get; set;} - [JsonPropertyName("x-origin")] - public List origin { get; set;} } public record ApiContact(string email, string name, Uri url); diff --git a/src/Kiota.Builder/SearchProviders/APIsGuru/APIsGuruSearchProvider.cs b/src/Kiota.Builder/SearchProviders/APIsGuru/APIsGuruSearchProvider.cs index 1287da7e94..77c992c12a 100644 --- a/src/Kiota.Builder/SearchProviders/APIsGuru/APIsGuruSearchProvider.cs +++ b/src/Kiota.Builder/SearchProviders/APIsGuru/APIsGuruSearchProvider.cs @@ -42,7 +42,7 @@ public async Task> SearchAsync(string term, st .Select(x => x.Value.versions.TryGetValue(GetVersionKey(singleCandidate, version, x), out var versionInfo) ? (x.Key, versionInfo, x.Value.versions.Keys.ToList()) : (x.Key, default, default)) .Where(static x => x.versionInfo is not null) .ToDictionary(static x => x.Key, - static x => new SearchResult(x.versionInfo.info?.title, x.versionInfo.info?.description, x.versionInfo.info?.contact?.url, x.versionInfo.info?.origin?.FirstOrDefault()?.url, x.Item3), + static x => new SearchResult(x.versionInfo.info?.title, x.versionInfo.info?.description, x.versionInfo.info?.contact?.url, x.versionInfo.swaggerUrl, x.Item3), StringComparer.OrdinalIgnoreCase); return results; } diff --git a/src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs index 8c5efbd014..1863edcda5 100644 --- a/src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs @@ -186,10 +186,12 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod me var requestAdapterPropertyName = requestAdapterProperty.Name.ToFirstCharacterUpperCase(); WriteSerializationRegistration(method.SerializerModules, writer, "RegisterDefaultSerializer"); WriteSerializationRegistration(method.DeserializerModules, writer, "RegisterDefaultDeserializer"); - writer.WriteLine($"if (string.IsNullOrEmpty({requestAdapterPropertyName}.BaseUrl)) {{"); - writer.IncreaseIndent(); - writer.WriteLine($"{requestAdapterPropertyName}.BaseUrl = \"{method.BaseUrl}\";"); - writer.CloseBlock(); + if (!string.IsNullOrEmpty(method.BaseUrl)) { + writer.WriteLine($"if (string.IsNullOrEmpty({requestAdapterPropertyName}.BaseUrl)) {{"); + writer.IncreaseIndent(); + writer.WriteLine($"{requestAdapterPropertyName}.BaseUrl = \"{method.BaseUrl}\";"); + writer.CloseBlock(); + } if (backingStoreParameter != null) writer.WriteLine($"{requestAdapterPropertyName}.EnableBackingStore({backingStoreParameter.Name});"); } diff --git a/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs index 9ccd06243c..1141a78fdc 100644 --- a/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs @@ -397,10 +397,12 @@ private void WriteApiConstructorBody(CodeClass parentClass, CodeMethod method, L var backingStoreParameter = method.Parameters.FirstOrDefault(x => x.IsOfKind(CodeParameterKind.BackingStore)); WriteSerializationRegistration(method.SerializerModules, writer, parentClass, "RegisterDefaultSerializer", "SerializationWriterFactory"); WriteSerializationRegistration(method.DeserializerModules, writer, parentClass, "RegisterDefaultDeserializer", "ParseNodeFactory"); - writer.WriteLine($"if m.{requestAdapterPropertyName}.GetBaseUrl() == \"\" {{"); - writer.IncreaseIndent(); - writer.WriteLine($"m.{requestAdapterPropertyName}.SetBaseUrl(\"{method.BaseUrl}\")"); - writer.CloseBlock(); + if (!string.IsNullOrEmpty(method.BaseUrl)) { + writer.WriteLine($"if m.{requestAdapterPropertyName}.GetBaseUrl() == \"\" {{"); + writer.IncreaseIndent(); + writer.WriteLine($"m.{requestAdapterPropertyName}.SetBaseUrl(\"{method.BaseUrl}\")"); + writer.CloseBlock(); + } if(backingStoreParameter != null) writer.WriteLine($"m.{requestAdapterPropertyName}.EnableBackingStore({backingStoreParameter.Name});"); } diff --git a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs index e4889b2f93..eb1d316792 100644 --- a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs @@ -248,10 +248,12 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod me var requestAdapterPropertyName = requestAdapterProperty.Name.ToFirstCharacterLowerCase(); WriteSerializationRegistration(method.SerializerModules, writer, "registerDefaultSerializer"); WriteSerializationRegistration(method.DeserializerModules, writer, "registerDefaultDeserializer"); - writer.WriteLine($"if ({requestAdapterPropertyName}.getBaseUrl() == null || {requestAdapterPropertyName}.getBaseUrl().isEmpty()) {{"); - writer.IncreaseIndent(); - writer.WriteLine($"{requestAdapterPropertyName}.setBaseUrl(\"{method.BaseUrl}\");"); - writer.CloseBlock(); + if(!string.IsNullOrEmpty(method.BaseUrl)) { + writer.WriteLine($"if ({requestAdapterPropertyName}.getBaseUrl() == null || {requestAdapterPropertyName}.getBaseUrl().isEmpty()) {{"); + writer.IncreaseIndent(); + writer.WriteLine($"{requestAdapterPropertyName}.setBaseUrl(\"{method.BaseUrl}\");"); + writer.CloseBlock(); + } if(backingStoreParameter != null) writer.WriteLine($"this.{requestAdapterPropertyName}.enableBackingStore({backingStoreParameter.Name});"); } diff --git a/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs index 6617e4d6da..26d2ccf685 100644 --- a/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs @@ -498,10 +498,12 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod co var requestAdapterProperty = parentClass.GetPropertyOfKind(CodePropertyKind.RequestAdapter); WriteSerializationRegistration(codeMethod.SerializerModules, writer, "registerDefaultSerializer"); WriteSerializationRegistration(codeMethod.DeserializerModules, writer, "registerDefaultDeserializer"); - writer.WriteLines($"if (empty({GetPropertyCall(requestAdapterProperty, string.Empty)}->getBaseUrl())) {{"); - writer.IncreaseIndent(); - writer.WriteLine($"{GetPropertyCall(requestAdapterProperty, string.Empty)}->setBaseUrl('{codeMethod.BaseUrl}');"); - writer.CloseBlock(); + if(!string.IsNullOrEmpty(codeMethod.BaseUrl)) { + writer.WriteLines($"if (empty({GetPropertyCall(requestAdapterProperty, string.Empty)}->getBaseUrl())) {{"); + writer.IncreaseIndent(); + writer.WriteLine($"{GetPropertyCall(requestAdapterProperty, string.Empty)}->setBaseUrl('{codeMethod.BaseUrl}');"); + writer.CloseBlock(); + } } private static void WriteSerializationRegistration(HashSet serializationModules, LanguageWriter writer, string methodName) { diff --git a/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs index 93224bec2f..2f5ebe2350 100644 --- a/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs @@ -97,10 +97,12 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod me var requestAdapterPropertyName = requestAdapterProperty.Name.ToSnakeCase(); WriteSerializationRegistration(method.SerializerModules, writer, "register_default_serializer"); WriteSerializationRegistration(method.DeserializerModules, writer, "register_default_deserializer"); - writer.WriteLine($"if not {requestAdapterPropertyName}.base_url:"); - writer.IncreaseIndent(); - writer.WriteLine($"{requestAdapterPropertyName}.base_url = \"{method.BaseUrl}\""); - writer.DecreaseIndent(); + if(!string.IsNullOrEmpty(method.BaseUrl)) { + writer.WriteLine($"if not {requestAdapterPropertyName}.base_url:"); + writer.IncreaseIndent(); + writer.WriteLine($"{requestAdapterPropertyName}.base_url = \"{method.BaseUrl}\""); + writer.DecreaseIndent(); + } if(backingStoreParameter != null) writer.WriteLine($"self.{requestAdapterPropertyName}.enable_backing_store({backingStoreParameter.Name})"); } diff --git a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs index 3c1b0af372..062a67db8a 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs @@ -79,7 +79,8 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod me var requestAdapterPropertyName = requestAdapterProperty.Name.ToSnakeCase(); if (method.Parameters.FirstOrDefault(x => x.IsOfKind(CodeParameterKind.RequestAdapter)) is CodeParameter requestAdapterParameter) writer.WriteLine($"@{requestAdapterPropertyName} = {requestAdapterParameter.Name.ToSnakeCase()}"); - writer.WriteLine($"{requestAdapterPropertyName}.set_base_url('{method.BaseUrl}')"); + if(!string.IsNullOrEmpty(method.BaseUrl)) + writer.WriteLine($"{requestAdapterPropertyName}.set_base_url('{method.BaseUrl}')"); } private static void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMethod, LanguageWriter writer, bool inherits) { if(inherits) diff --git a/src/Kiota.Builder/Writers/TypeScript/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/TypeScript/CodeMethodWriter.cs index 364b095294..8328a862f2 100644 --- a/src/Kiota.Builder/Writers/TypeScript/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/TypeScript/CodeMethodWriter.cs @@ -124,10 +124,12 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod me var requestAdapterPropertyName = requestAdapterProperty.Name.ToFirstCharacterLowerCase(); WriteSerializationRegistration(method.SerializerModules, writer, "registerDefaultSerializer"); WriteSerializationRegistration(method.DeserializerModules, writer, "registerDefaultDeserializer"); - writer.WriteLine($"if ({requestAdapterPropertyName}.baseUrl === undefined || {requestAdapterPropertyName}.baseUrl === \"\") {{"); - writer.IncreaseIndent(); - writer.WriteLine($"{requestAdapterPropertyName}.baseUrl = \"{method.BaseUrl}\";"); - writer.CloseBlock(); + if(!string.IsNullOrEmpty(method.BaseUrl)) { + writer.WriteLine($"if ({requestAdapterPropertyName}.baseUrl === undefined || {requestAdapterPropertyName}.baseUrl === \"\") {{"); + writer.IncreaseIndent(); + writer.WriteLine($"{requestAdapterPropertyName}.baseUrl = \"{method.BaseUrl}\";"); + writer.CloseBlock(); + } if(backingStoreParameter != null) writer.WriteLine($"this.{requestAdapterPropertyName}.enableBackingStore({backingStoreParameter.Name});"); } diff --git a/src/kiota/Handlers/KiotaGenerationCommandHandler.cs b/src/kiota/Handlers/KiotaGenerationCommandHandler.cs index 0460a28e18..95a7acba51 100644 --- a/src/kiota/Handlers/KiotaGenerationCommandHandler.cs +++ b/src/kiota/Handlers/KiotaGenerationCommandHandler.cs @@ -76,15 +76,16 @@ public override async Task InvokeAsync(InvocationContext context) try { await new KiotaBuilder(logger, Configuration.Generation).GenerateClientAsync(cancellationToken); + Console.WriteLine("Generation completed successfully"); DisplayInfoHint(language, Configuration.Generation.OpenAPIFilePath); DisplayGenerateAdvancedHint(includePatterns, excludePatterns, Configuration.Generation.OpenAPIFilePath); return 0; } catch (Exception ex) { #if DEBUG - logger.LogCritical(ex, "error generating the SDK: {exceptionMessage}", ex.Message); + logger.LogCritical(ex, "error generating the client: {exceptionMessage}", ex.Message); throw; // so debug tools go straight to the source of the exception when attached #else - logger.LogCritical("error generating the SDK: {exceptionMessage}", ex.Message); + logger.LogCritical("error generating the client: {exceptionMessage}", ex.Message); return 1; #endif } diff --git a/src/kiota/Handlers/KiotaInfoCommandHandler.cs b/src/kiota/Handlers/KiotaInfoCommandHandler.cs index e4add0678f..4f7c614288 100644 --- a/src/kiota/Handlers/KiotaInfoCommandHandler.cs +++ b/src/kiota/Handlers/KiotaInfoCommandHandler.cs @@ -10,6 +10,7 @@ using System.Threading.Tasks; using Kiota.Builder; using Kiota.Builder.Configuration; +using Microsoft.Extensions.Logging; namespace kiota.Handlers; internal class KiotaInfoCommandHandler : KiotaSearchBasedCommandHandler { @@ -51,12 +52,21 @@ public override async Task InvokeAsync(InvocationContext context) Configuration.Generation.Language = language.Value; var instructions = Configuration.Languages; - if(!string.IsNullOrEmpty(openapi)) { - var builder = new KiotaBuilder(logger, Configuration.Generation); - var result = await builder.GetLanguageInformationAsync(cancellationToken); - if (result != null) - instructions = result; - } + if(!string.IsNullOrEmpty(openapi)) + try { + var builder = new KiotaBuilder(logger, Configuration.Generation); + var result = await builder.GetLanguageInformationAsync(cancellationToken); + if (result != null) + instructions = result; + } catch (Exception ex) { +#if DEBUG + logger.LogCritical(ex, "error getting information from the description: {exceptionMessage}", ex.Message); + throw; // so debug tools go straight to the source of the exception when attached +#else + logger.LogCritical("error getting information from the description: {exceptionMessage}", ex.Message); + return 1; +#endif + } ShowLanguageInformation(language.Value, instructions); return 0; } diff --git a/src/kiota/Handlers/KiotaShowCommandHandler.cs b/src/kiota/Handlers/KiotaShowCommandHandler.cs index 751a9e931a..50da71ef4b 100644 --- a/src/kiota/Handlers/KiotaShowCommandHandler.cs +++ b/src/kiota/Handlers/KiotaShowCommandHandler.cs @@ -53,17 +53,28 @@ public override async Task InvokeAsync(InvocationContext context) Configuration.Generation.IncludePatterns = includePatterns.ToHashSet(); Configuration.Generation.ExcludePatterns = excludePatterns.ToHashSet(); Configuration.Generation.ClearCache = clearCache; - var urlTreeNode = await new KiotaBuilder(logger, Configuration.Generation).GetUrlTreeNodeAsync(cancellationToken); + try { + var urlTreeNode = await new KiotaBuilder(logger, Configuration.Generation).GetUrlTreeNodeAsync(cancellationToken); + + var builder = new StringBuilder(); + RenderNode(urlTreeNode, maxDepth, builder); + var tree = builder.ToString(); + Console.Write(tree); + if(descriptionProvided) + DisplayShowAdvancedHint(string.Empty, string.Empty, includePatterns, excludePatterns, openapi); + else + DisplayShowAdvancedHint(searchTerm, version, includePatterns, excludePatterns, openapi); + DisplayGenerateHint(openapi, includePatterns, excludePatterns); + } catch (Exception ex) { +#if DEBUG + logger.LogCritical(ex, "error showing the description: {exceptionMessage}", ex.Message); + throw; // so debug tools go straight to the source of the exception when attached +#else + logger.LogCritical("error showing the description: {exceptionMessage}", ex.Message); + return 1; +#endif + } - var builder = new StringBuilder(); - RenderNode(urlTreeNode, maxDepth, builder); - var tree = builder.ToString(); - Console.Write(tree); - if(descriptionProvided) - DisplayShowAdvancedHint(string.Empty, string.Empty, includePatterns, excludePatterns, openapi); - else - DisplayShowAdvancedHint(searchTerm, version, includePatterns, excludePatterns, openapi); - DisplayGenerateHint(openapi, includePatterns, excludePatterns); } return 0; } diff --git a/tests/Kiota.Builder.Tests/Extensions/OpenApiUrlTreeNodeExtensionsTests.cs b/tests/Kiota.Builder.Tests/Extensions/OpenApiUrlTreeNodeExtensionsTests.cs index 97384aaf6d..660e35a1f4 100644 --- a/tests/Kiota.Builder.Tests/Extensions/OpenApiUrlTreeNodeExtensionsTests.cs +++ b/tests/Kiota.Builder.Tests/Extensions/OpenApiUrlTreeNodeExtensionsTests.cs @@ -183,4 +183,51 @@ public void GetUrlTemplateCleansInvalidParameters() 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 } + [InlineData("\\reviews\\search.json", "reviews.search")] + [InlineData("\\members\\$ref", "members.ref")] + [Theory] + public void GetsNamespaceFromPath(string source, string expected) + { + Assert.Equal(expected, source.GetNamespaceFromPath(string.Empty)); + } + [Fact] + public void GetsClassNameWithIndexerAndExtension() { + var doc = new OpenApiDocument + { + Paths = new(), + }; + doc.Paths.Add("/reviews/{resource-type}.json", new() + { + Operations = new Dictionary { + { OperationType.Get, new() { + Parameters = new List { + new() { + Name = "resource-type", + In = ParameterLocation.Path, + Required = true, + Schema = new() { + Type = "string" + }, + Style = ParameterStyle.Simple, + } + }, + Responses = new OpenApiResponses() { + {"200", new() { + Content = new Dictionary() { + {"application/json", new() { + Schema = new () { + Type = "string" + } + }} + } + }} + } + } + } + } + }); + var node = OpenApiUrlTreeNode.Create(doc, Label); + var result = node.Children["reviews"].Children["{resource-type}.json"].GetClassName(new(){"application/json"}); + Assert.Equal("ResourceType", result); + } } diff --git a/tests/Kiota.Builder.Tests/KiotaBuilderTests.cs b/tests/Kiota.Builder.Tests/KiotaBuilderTests.cs index 9d309139ab..3969606cd8 100644 --- a/tests/Kiota.Builder.Tests/KiotaBuilderTests.cs +++ b/tests/Kiota.Builder.Tests/KiotaBuilderTests.cs @@ -23,15 +23,6 @@ namespace Kiota.Builder.Tests; public class KiotaBuilderTests { - [Fact] - public async Task ThrowsOnMissingServer() { - var tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); - await File.WriteAllLinesAsync(tempFilePath, new[] {"openapi: 3.0.0", "info:", " title: \"Todo API\"", " version: \"1.0.0\""}); - var mockLogger = new Mock>(); - var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = tempFilePath }); - await Assert.ThrowsAsync(() => builder.GenerateClientAsync(new())); - File.Delete(tempFilePath); - } [Fact] public async Task ParsesEnumDescriptions() { var tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());