diff --git a/tools/WrapperGenerator.Tests/ActionFunctionTests.cs b/tools/WrapperGenerator.Tests/ActionFunctionTests.cs index 05dd361ab6d..2b6c25f543a 100644 --- a/tools/WrapperGenerator.Tests/ActionFunctionTests.cs +++ b/tools/WrapperGenerator.Tests/ActionFunctionTests.cs @@ -249,6 +249,22 @@ public void EmitsNoContentActionWithoutAnOutputType() Assert.Contains("public bool? SaveToSentItems", source, StringComparison.Ordinal); } + [Theory] + [InlineData("post", "PostPath", "Post", "Post")] + [InlineData("delete", "DeletePath", "Delete", "Delete")] + [InlineData("microsoft.graph.post", "MicrosoftGraphPost", "MicrosoftGraphPost", "Post")] + public void KeepsReservedNavigationEscapesOutOfRequestBodyTypes( + string segment, string navigation, string typeNamespace, string typeName) + { + var yaml = SendMailYaml.Replace("sendMail", segment, StringComparison.Ordinal); + var (_, source) = Generate(yaml, $"InvokeMgUser{typeName}.g.cs"); + + Assert.Contains($"client.Users[UserId].{navigation}.PostAsync(body,", source, StringComparison.Ordinal); + Assert.Contains($"new global::Microsoft.Graph.PowerShell.Test.Client.Users.Item.{typeNamespace}.{typeName}PostRequestBody()", source, StringComparison.Ordinal); + Assert.Contains("public bool? SaveToSentItems", source, StringComparison.Ordinal); + Assert.Contains($"[GraphRoute(\"POST\", \"/users/{{user-id}}/{segment}\")]", source, StringComparison.Ordinal); + } + // An action with no request body: kiota's PostAsync takes no body argument, so emitting one // would not compile. private const string RestoreYaml = """ diff --git a/tools/WrapperGenerator.Tests/ReservedNavigationTests.cs b/tools/WrapperGenerator.Tests/ReservedNavigationTests.cs new file mode 100644 index 00000000000..ce93e8fce49 --- /dev/null +++ b/tools/WrapperGenerator.Tests/ReservedNavigationTests.cs @@ -0,0 +1,101 @@ +using System; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.OpenApi; +using Microsoft.OpenApi.Reader; +using WrapperGenerator; +using Xunit; + +namespace WrapperGenerator.Tests; + +public sealed class ReservedNavigationTests +{ + [Theory] + // Kiota 1.36.1 output: only navigation properties get Path, not namespaces or types. + [InlineData("/widgets/{widget-id}/post", OperationKind.Action, + "Widgets[WidgetId].PostPath", "Widgets.Item.Post", "Post", "MgWidgetPost")] + [InlineData("/widgets/{widget-id}/delete", OperationKind.Action, + "Widgets[WidgetId].DeletePath", "Widgets.Item.Delete", "Delete", "MgWidgetDelete")] + [InlineData("/widgets/{widget-id}/microsoft.graph.post", OperationKind.Action, + "Widgets[WidgetId].MicrosoftGraphPost", "Widgets.Item.MicrosoftGraphPost", "MicrosoftGraphPost", "MgWidgetPost")] + [InlineData("/widgets/{widget-id}/postAndSend", OperationKind.Action, + "Widgets[WidgetId].PostAndSend", "Widgets.Item.PostAndSend", "PostAndSend", "MgWidgetPostAndSend")] + [InlineData("/functions/post()", OperationKind.Function, + "Functions.PostPath", "Functions.Post", "Post", "MgFunctionPost")] + [InlineData("/functions/post(value='{value}')", OperationKind.Function, + "Functions.PostWithValue()", "Functions.PostWithValue", "PostWithValue", "MgFunctionPostWithValue")] + public void EscapesOnlyTheTypedNavigationProperty(string path, OperationKind kind, + string expression, string typeNamespace, string typeMember, string noun) + { + var naming = Naming.Resolve(new OperationInfo( + kind == OperationKind.Action ? HttpMethod.Post : HttpMethod.Get, path, null, kind)); + + Assert.Equal(expression, naming.BuilderExpression); + Assert.Equal(typeNamespace, naming.OperationTypeNamespace); + Assert.Equal(typeMember, naming.OperationMemberName); + Assert.Equal(noun, naming.Noun); + Assert.Equal(typeMember == "MicrosoftGraphPost" ? "Post" : typeMember, naming.OperationTypeName); + Assert.Equal(path, naming.SourcePath); + } + + [Fact] + public void EscapesIntermediateResourcePropertiesWithoutChangingParametersOrNouns() + { + var naming = Naming.Resolve(new OperationInfo(HttpMethod.Get, "/resources/post/{post-id}")); + Assert.Equal("Resources.PostPath[PostId]", naming.BuilderExpression); + Assert.Equal("MgResourcePost", naming.Noun); + Assert.Equal(["PostId"], naming.PathParamNames); + Assert.Empty(naming.OperationTypeNamespace); + Assert.Equal("Post", Naming.ParseOperationSegment("post").MemberName); + } + + [Theory] + [InlineData("journals", "journal-id", "Journal")] + [InlineData("purchaseInvoices", "purchaseInvoice-id", "PurchaseInvoice")] + [InlineData("salesInvoices", "salesInvoice-id", "SaleInvoice")] + public async Task GeneratesTheActualFinancialsPostActionWithItsOriginalContract( + string collection, string id, string noun) + { + var cancellationToken = TestContext.Current.CancellationToken; + var directory = AppContext.BaseDirectory; + while (directory is not null && + !File.Exists(Path.Combine(directory, "openApiDocs_KiotaCompat", "beta", "Financials.yml"))) + directory = Path.GetDirectoryName(directory); + Assert.NotNull(directory); + + var settings = new OpenApiReaderSettings(); + settings.AddYamlReader(); + using var stream = File.OpenRead(Path.Combine(directory, "openApiDocs_KiotaCompat", "beta", "Financials.yml")); + var result = await OpenApiDocument.LoadAsync(stream, settings: settings, cancellationToken: cancellationToken); + Assert.NotNull(result.Document); + var path = $"/financials/companies/{{company-id}}/{collection}/{{{id}}}/post"; + IncludePathFilter.Apply(result.Document, [path + "#POST"]); + Assert.Single(result.Document.Paths); + Assert.Equal($"financial.company.{(collection == "journals" ? "journal" : collection[..^1])}_post", + result.Document.Paths[path].Operations![HttpMethod.Post].OperationId); + + var output = Path.Combine(Path.GetTempPath(), "wrapper-reserved-navigation", Guid.NewGuid().ToString("N")); + try + { + var config = new GeneratorConfig("ReservedNavigation.Client", output, UseCollisionData: false); + await new PowerShellWrapperGenerationService(result.Document, config, NullLogger.Instance, apiVersion: "beta") + .GenerateAsync(cancellationToken); + var file = Assert.Single(Directory.GetFiles(output, "*.g.cs")); + Assert.Equal($"InvokeMgFinancialCompany{noun}Post.g.cs", Path.GetFileName(file)); + var source = await File.ReadAllTextAsync(file, cancellationToken); + Assert.Contains($".{collection[..1].ToUpperInvariant() + collection[1..]}[{id.ToPascalCase('-')}].PostPath.PostAsync(requestConfiguration", source, StringComparison.Ordinal); + Assert.Contains($"[GraphRoute(\"POST\", \"{path}\")]", source, StringComparison.Ordinal); + Assert.Contains("GetRequestAdapter(\"beta\")", source, StringComparison.Ordinal); + Assert.Contains("SupportsShouldProcess = true", source, StringComparison.Ordinal); + Assert.DoesNotContain("var body = new", source, StringComparison.Ordinal); + Assert.DoesNotContain("PostPathPostRequestBody", source, StringComparison.Ordinal); + } + finally + { + if (Directory.Exists(output)) + Directory.Delete(output, recursive: true); + } + } +} diff --git a/tools/WrapperGenerator/CmdletNaming.cs b/tools/WrapperGenerator/CmdletNaming.cs index ac5bd1f20bd..dc0c3523770 100644 --- a/tools/WrapperGenerator/CmdletNaming.cs +++ b/tools/WrapperGenerator/CmdletNaming.cs @@ -111,8 +111,8 @@ public sealed record CmdletNaming( // Pascal-cased and every {id} segment replaced by "Item", e.g. "Users.Item.AssignLicense". // Empty for a resource operation, which has no per-operation types. string OperationTypeNamespace = "", - // The kiota builder member for the action/function segment, and the last segment of the - // namespace its generated types live in. + // The Kiota builder type stem for the action/function segment, also used in its namespace. + // Not the escaped navigation property: PostPath still refers to PostRequestBuilder. string OperationMemberName = "", // The prefix kiota gives those generated types ("AssignLicense" -> // AssignLicensePostRequestBody). It differs from OperationMemberName for a @@ -569,19 +569,17 @@ public static bool IsSupportedODataSegment(string segment) return EmittableODataSegments.ContainsKey(segment); } - // Kiota renames a builder property whose name would clash with a request method the builder - // declares: a /delete segment is exposed as DeletePath, not Delete. The rename is scoped to + // Kiota reserves request-method names for navigation properties: a /delete segment is + // exposed as DeletePath, not Delete. The rename is scoped to // the property — the generated namespace keeps the segment name // (…UsedRange.Delete.DeleteRequestBuilder DeletePath), and sibling segments that are not // method names (Clear, EntireColumn) are untouched. // - // Only "delete" occurs: of the 9,116 distinct routes in the configured v1.0 specs, 24 carry a - // /delete segment and none carries /get, /post, /patch, /put or /head. Mapping the other - // method names would encode a prediction no spec exercises, so only the observed clash is - // encoded; a new one appears as a module compile error rather than silently binding the - // wrong member. + // Verified with Kiota 1.36.1: Files' /delete and Financials beta's /post use this escape. + // Keep the mapping bounded to observed names; operation namespaces, request-body types, + // qualified names and parameterized function methods must not acquire the property suffix. private static string AvoidRequestMethodClash(string memberName) => - memberName == "Delete" ? "DeletePath" : memberName; + memberName is "Delete" or "Post" ? memberName + "Path" : memberName; // Whether a list GET and an item GET form a mergeable pair for the public Get-MgX // dispatcher: the item's path must extend the list's path by exactly one id, either diff --git a/tools/WrapperGenerator/docs/edge-cases/kiota-alignment-edge-cases.md b/tools/WrapperGenerator/docs/edge-cases/kiota-alignment-edge-cases.md index ec2051b5cf4..75e8bf82a6f 100644 --- a/tools/WrapperGenerator/docs/edge-cases/kiota-alignment-edge-cases.md +++ b/tools/WrapperGenerator/docs/edge-cases/kiota-alignment-edge-cases.md @@ -61,6 +61,29 @@ others exist. - **References:** kiota's CSharpReservedClassNamesProvider; PowerShellWrapperGenerationService.KiotaReservedModelNames. +## Reserved request-builder navigation: post -> PostPath + +- **Class:** kiota-symbol-prediction +- **Status:** handled (property-only escape; production-spec regression tests) +- **Evidence:** Kiota 1.36.1 exposes Financials beta's literal `/post` action as + `PostPath` on the journal, purchase-invoice and sales-invoice item builders. The + wrapper predicted `.Post.PostAsync` and all three calls failed with CS1061. + An isolated client generated from those three actual spec paths reproduces the + failures before the fix and compiles with the corrected wrappers afterward. + The existing `/delete` escape also remains verified against Kiota 1.36.1. +- **Decision:** extend `Naming.AvoidRequestMethodClash` from `Delete` to the observed + `Post` property. Do not suffix namespaces, request-builder classes, request-body + types or cmdlet nouns: `/post` still uses namespace `Post`, `PostRequestBuilder` + and (when a body exists) `PostPostRequestBody`. Qualified + `microsoft.graph.post`, parameterized `post(value='{value}')`, and `postAndSend` + retain their original members; zero-argument `post()` and intermediate resource + `/post` navigations use `PostPath`. These shapes were generated and compiled + against actual Kiota output, without modifying generated C#. +- **Migration impact:** none to public names, parameter binding, source routes, + HTTP methods or default-route selection; fixes typed internal navigation only. +- **References:** `ReservedNavigationTests`; `ActionFunctionTests.KeepsReservedNavigationEscapesOutOfRequestBodyTypes`; + `openApiDocs_KiotaCompat/beta/Financials.yml`. + ## A model that shares its name with a kiota sub-namespace moves inside it - **Class:** kiota-symbol-prediction