Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge Dev Branch into Master #1967

Merged
merged 14 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/sonarcloud.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ on:
pull_request:
types: [opened, synchronize, reopened]
paths-ignore: '.vscode/**'
permissions:
contents: read
pull-requests: write
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
jobs:
Expand Down
4 changes: 2 additions & 2 deletions CodeSnippetsPipeline.Test/CodeSnippetsPipeline.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="NUnit" Version="4.0.1" />
<PackageReference Include="NUnit" Version="4.1.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="NUnit.Analyzers" Version="4.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<PackageReference Include="coverlet.collector" Version="6.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.msbuild" Version="6.0.0">
<PackageReference Include="coverlet.msbuild" Version="6.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="coverlet.collector" Version="6.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="xunit" Version="2.6.6" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.6">
<PackageReference Include="xunit" Version="2.7.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.7">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
56 changes: 34 additions & 22 deletions CodeSnippetsReflection.OpenAPI.Test/CSharpGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace CodeSnippetsReflection.OpenAPI.Test
public class CSharpGeneratorTests : OpenApiSnippetGeneratorTestBase
{
private readonly CSharpGenerator _generator = new();

[Fact]
public async Task GeneratesTheCorrectFluentApiPath() {
using var requestPayload = new HttpRequestMessage(HttpMethod.Get, $"{ServiceRootUrl}/me/messages");
Expand Down Expand Up @@ -39,7 +39,7 @@ public async Task GeneratesTheSnippetHeader() {
var result = _generator.GenerateCodeSnippet(snippetModel);
Assert.DoesNotContain("var graphClient = new GraphServiceClient(requestAdapter)", result); // no initialization statement present
Assert.Contains("// Code snippets are only available for the latest version. Current version is", result);// ensure version comment is present
Assert.Contains("// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client", result);// ensure initialization guidance is present
Assert.Contains("// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client", result);// ensure initialization guidance is present
}
[Fact]
public async Task GeneratesTheGetMethodCall() {
Expand Down Expand Up @@ -255,6 +255,18 @@ public async Task GeneratesSnippetForRequestWithSearchQueryOptionWithANDLogicalC
Assert.Contains("requestConfiguration.QueryParameters.Search", result);
Assert.Contains("requestConfiguration.QueryParameters.Search = \"\\\"displayName:di\\\" AND \\\"displayName:al\\\"\";", result);
}

[Theory]
[InlineData("/users/some-id/mailFolders/delta","GetAsDeltaGetResponseAsync")]
[InlineData("/appCatalogs/teamsApps?requiresReview=true","await graphClient.AppCatalogs.TeamsApps.PostAsync(", "POST")]
[InlineData("/me/photos/48x48/$value","Content.GetAsync(")]
public async Task ObsoleteGetAsyncReplacedWithGetAsLastNodeNameGetResponseAsync(string inputPath, string expectedSuffix, string method = "") {
using var requestPayload = new HttpRequestMessage(string.IsNullOrEmpty(method) ? HttpMethod.Get : new HttpMethod(method), $"{ServiceRootUrl}{inputPath}");
var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1SnippetMetadata());
var result = _generator.GenerateCodeSnippet(snippetModel);
Assert.Contains(expectedSuffix, result);
}

[Fact]
public async Task HandlesOdataTypeWhenGenerating() {
var sampleJson = @"
Expand Down Expand Up @@ -389,7 +401,7 @@ public async Task GenerateFindMeetingTime()
Assert.Contains("IsRequired = false,", result);
Assert.Contains("LocationEmailAddress = \"conf32room1368@imgeek.onmicrosoft.com\",", result);
}

[Theory]
[InlineData("sendMail")]
[InlineData("microsoft.graph.sendMail")]
Expand Down Expand Up @@ -432,7 +444,7 @@ public async Task FullyQualifiesActionRequestBodyType(string sendMailString)
Assert.Contains("using Microsoft.Graph.Users.Item.SendMail", result);
Assert.Contains("ToRecipients = new List<Recipient>", result);
}

[Fact]
public async Task TypeArgumentsForListArePlacedCorrectly()
{
Expand All @@ -452,7 +464,7 @@ public async Task TypeArgumentsForListArePlacedCorrectly()

Assert.Contains("new List<string>", result);
}

[Fact]
public async Task ModelsInNestedNamespacesAreDisambiguated()
{
Expand All @@ -473,7 +485,7 @@ public async Task ModelsInNestedNamespacesAreDisambiguated()
Assert.Contains("Type = IdentityType.ExternalGroup", result);
Assert.Contains("using Microsoft.Graph.Models.ExternalConnectors;", result);
}

[Fact]
public async Task ReplacesReservedTypeNames()
{
Expand All @@ -484,7 +496,7 @@ public async Task ReplacesReservedTypeNames()
// Assert `Directory` is replaced with `DirectoryObject`
Assert.Contains("await graphClient.Directory.AdministrativeUnits[\"{administrativeUnit-id}\"].ScopedRoleMembers.GetAsync()", result);
}

[Fact]
public async Task CorrectlyGeneratesEnumMember()
{
Expand Down Expand Up @@ -518,7 +530,7 @@ public async Task CorrectlyGeneratesEnumMember()
Assert.Contains("Type = RecurrencePatternType.Weekly,", result);
Assert.Contains("Type = RecurrenceRangeType.NoEnd,", result);
}

[Fact]
public async Task CorrectlyGeneratesMultipleFlagsEnumMembers()
{
Expand All @@ -536,7 +548,7 @@ public async Task CorrectlyGeneratesMultipleFlagsEnumMembers()

Assert.Contains("Status = RecordingStatus.NotRecording | RecordingStatus.Recording | RecordingStatus.Failed", result);
}

[Fact]
public async Task CorrectlyOptionalRequestBodyParameter()
{
Expand All @@ -546,7 +558,7 @@ public async Task CorrectlyOptionalRequestBodyParameter()

Assert.Contains("await graphClient.Teams[\"{team-id}\"].Archive.PostAsync(null);", result);
}

[Fact]
public async Task CorrectlyEvaluatesDatePropertyTypeRequestBodyParameter()
{
Expand All @@ -570,7 +582,7 @@ public async Task CorrectlyEvaluatesDatePropertyTypeRequestBodyParameter()
Assert.Contains("StartDate = new Date(DateTime.Parse(\"2017-09-04\")),", result);
Assert.Contains("EndDate = new Date(DateTime.Parse(\"2017-12-31\")),", result);
}

[Fact]
public async Task CorrectlyEvaluatesOdataActionRequestBodyParameter()
{
Expand Down Expand Up @@ -654,18 +666,18 @@ public async Task CorrectlyHandlesOdataFunction()
var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1SnippetMetadata());
var result = _generator.GenerateCodeSnippet(snippetModel);

Assert.Contains("await graphClient.Users.Delta.GetAsync", result);
Assert.Contains("await graphClient.Users.Delta.GetAsDeltaGetResponseAsync", result);
Assert.Contains("requestConfiguration.QueryParameters.Select = new string []{ \"displayName\",\"jobTitle\",\"mobilePhone\" };", result);
}

[Fact]
public async Task CorrectlyHandlesDateTimeOffsetInUrl()
{
using var requestPayload = new HttpRequestMessage(HttpMethod.Get, $"{ServiceRootUrl}/reports/getUserArchivedPrintJobs(userId='{{id}}',startDateTime=<timestamp>,endDateTime=<timestamp>)");
var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1SnippetMetadata());
var result = _generator.GenerateCodeSnippet(snippetModel);

Assert.Contains("await graphClient.Reports.GetUserArchivedPrintJobsWithUserIdWithStartDateTimeWithEndDateTime(DateTimeOffset.Parse(\"{endDateTime}\"),DateTimeOffset.Parse(\"{startDateTime}\"),\"{userId}\").GetAsync()", result);
Assert.Contains("await graphClient.Reports.GetUserArchivedPrintJobsWithUserIdWithStartDateTimeWithEndDateTime(DateTimeOffset.Parse(\"{endDateTime}\"),DateTimeOffset.Parse(\"{startDateTime}\"),\"{userId}\").GetAsGetUserArchivedPrintJobsWithUserIdWithStartDateTimeWithEndDateTimeGetResponseAsync()", result);
}

[Fact]
Expand Down Expand Up @@ -693,7 +705,7 @@ public async Task CorrectlyHandlesDateInUrl2()
var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1SnippetMetadata());
var result = _generator.GenerateCodeSnippet(snippetModel);

Assert.Contains("await graphClient.Communications.CallRecords.MicrosoftGraphCallRecordsGetPstnCallsWithFromDateTimeWithToDateTime(DateTimeOffset.Parse(\"{fromDateTime}\"),DateTimeOffset.Parse(\"{toDateTime}\")).GetAsync();", result);
Assert.Contains("await graphClient.Communications.CallRecords.MicrosoftGraphCallRecordsGetPstnCallsWithFromDateTimeWithToDateTime(DateTimeOffset.Parse(\"{fromDateTime}\"),DateTimeOffset.Parse(\"{toDateTime}\")).GetAsGetPstnCallsWithFromDateTimeWithToDateTimeGetResponseAsync()", result);
}
[Fact]
public async Task CorrectlyHandlesEnumInUrl()
Expand All @@ -702,7 +714,7 @@ public async Task CorrectlyHandlesEnumInUrl()
var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1SnippetMetadata());
var result = _generator.GenerateCodeSnippet(snippetModel);

Assert.Contains("await graphClient.IdentityGovernance.AppConsent.AppConsentRequests.FilterByCurrentUserWithOn(\"reviewer\").GetAsync", result);
Assert.Contains("await graphClient.IdentityGovernance.AppConsent.AppConsentRequests.FilterByCurrentUserWithOn(\"reviewer\").GetAsFilterByCurrentUserWithOnGetResponseAsync", result);
}
[Fact]
public async Task GeneratesObjectsInArray() {
Expand Down Expand Up @@ -851,7 +863,7 @@ public async Task GeneratesPropertiesWithSpecialCharacters() {
Assert.Contains("MinimumSupportedOperatingSystem = new IosMinimumOperatingSystem", result);
Assert.Contains("V80 = true,", result);//Assert that the property was pascal cased
}

[Fact]
public async Task GeneratesCorrectTypeInCollectionInitializer() {
var sampleJson = @"{
Expand Down Expand Up @@ -901,7 +913,7 @@ public async Task GeneratesCorrectTypeInCollectionInitializer() {
Assert.Contains("new List<TaskObject>", result);//Assert the type is escaped in the collection initializzer.
Assert.Contains("using Microsoft.Graph.Models.IdentityGovernance", result);//Assert the type is escaped in the collection initializzer.
}

[Fact]
public async Task CorrectlyHandlesTypeFromInUrl()
{
Expand All @@ -921,7 +933,7 @@ public async Task MatchesPathWithPathParameter()

Assert.Contains("var result = await graphClient.Drives[\"{drive-id}\"].Items[\"{driveItem-id}\"].Workbook.Worksheets[\"{workbookWorksheet-id}\"].RangeWithAddress(\"{address}\").GetAsync()", result);
}

[Fact]
public async Task MatchesPathAlternateKeys()
{
Expand All @@ -932,7 +944,7 @@ public async Task MatchesPathAlternateKeys()
Assert.Contains("await graphClient.ApplicationsWithAppId(\"{appId}\").GetAsync(", result);
}
[Theory]
[InlineData("/me/drive/root/delta","graphClient.Drives[\"{drive-id}\"].Items[\"{driveItem-id}\"].Delta.GetAsync()")]
[InlineData("/me/drive/root/delta","graphClient.Drives[\"{drive-id}\"].Items[\"{driveItem-id}\"].Delta.GetAsDeltaGetResponseAsync()")]
[InlineData("/groups/{group-id}/drive/items/{item-id}/children","graphClient.Drives[\"{drive-id}\"].Items[\"{driveItem-id}\"].Children.GetAsync()")]
[InlineData("/me/drive","graphClient.Me.Drive.GetAsync()")]
[InlineData("/sites/{site-id}/drive/items/{item-id}/children","graphClient.Drives[\"{drive-id}\"].Items[\"{driveItem-id}\"].Children.GetAsync()")]
Expand All @@ -941,9 +953,9 @@ public async Task MatchesPathAlternateKeys()
[InlineData("/me/drive/items/{item-id}/children","graphClient.Drives[\"{drive-id}\"].Items[\"{driveItem-id}\"].Children.GetAsync()")]
[InlineData("/drive/bundles","graphClient.Drives[\"{drive-id}\"].Bundles.GetAsync()")]
[InlineData("/me/drive/special/documents","graphClient.Drives[\"{drive-id}\"].Special[\"{driveItem-id}\"].GetAsync()")]
[InlineData("/me/drive/root/search(q='Contoso%20Project')","graphClient.Drives[\"{drive-id}\"].Items[\"{driveItem-id}\"].SearchWithQ(\"{q}\").GetAsync()")]
[InlineData("/me/drive/root/search(q='Contoso%20Project')","graphClient.Drives[\"{drive-id}\"].Items[\"{driveItem-id}\"].SearchWithQ(\"{q}\").GetAsSearchWithQGetResponseAsync()")]
[InlineData("/me/drive/items/{id}/workbook/application/calculate","graphClient.Drives[\"{drive-id}\"].Items[\"{driveItem-id}\"].Workbook.Application.Calculate", "POST")]
public async Task GeneratesSnippetWithRemappedDriveCall(string inputPath, string expected, string method = "")
public async Task GeneratesSnippetWithRemappedDriveCall(string inputPath, string expected, string method = "")
{
using var requestPayload = new HttpRequestMessage(string.IsNullOrEmpty(method) ? HttpMethod.Get : new HttpMethod(method), $"{ServiceRootUrl}{inputPath}");
var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1SnippetMetadata());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.msbuild" Version="6.0.0">
<PackageReference Include="coverlet.msbuild" Version="6.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="moq" Version="4.20.70" />
<PackageReference Include="xunit" Version="2.6.6" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.6">
<PackageReference Include="xunit" Version="2.7.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.7">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<PackageReference Include="coverlet.collector" Version="6.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.22.0" />
<PackageReference Include="Microsoft.OpenApi.Readers" Version="1.6.13" />
<PackageReference Include="System.Text.Json" Version="8.0.1" />
<PackageReference Include="System.Text.Json" Version="8.0.2" />
</ItemGroup>

<PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
// ------------------------------------------------------------------------------------------------------------------------------------------------------

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Models;
using CodeSnippetsReflection.StringExtensions;
using CodeSnippetsReflection.OpenAPI.ModelGraph;

// THIS CLASS IS COPIED FROM KIOTA TO GET THE SAME NAMING CONVENTIONS, WE SHOULD FIND A WAY TO MUTUALIZE THE CODE
namespace CodeSnippetsReflection.OpenAPI {
Expand Down Expand Up @@ -35,7 +38,7 @@ private static IEnumerable<string> FlattenIfRequired(this IList<OpenApiSchema> s
var resultSet = schemas;
if(schemas.Count == 1 && string.IsNullOrEmpty(schemas.First().Title))
resultSet = schemas.FlattenEmptyEntries(subsequentGetter, 1);

return resultSet.Select(x => x.Title).Where(x => !string.IsNullOrEmpty(x));
}

Expand Down Expand Up @@ -72,7 +75,7 @@ public static bool IsOneOf(this OpenApiSchema schema)
}

public static IEnumerable<string> GetSchemaReferenceIds(this OpenApiSchema schema, HashSet<OpenApiSchema> visitedSchemas = null) {
visitedSchemas ??= new();
visitedSchemas ??= new();
if(schema != null && !visitedSchemas.Contains(schema)) {
visitedSchemas.Add(schema);
var result = new List<string>();
Expand All @@ -92,7 +95,7 @@ public static IEnumerable<string> GetSchemaReferenceIds(this OpenApiSchema schem
if(subSchemaReferences.Any())
result.AddRange(subSchemaReferences);
return result.Distinct();
} else
} else
return Enumerable.Empty<string>();
}
internal static IList<OpenApiSchema> FlattenEmptyEntries(this IList<OpenApiSchema> schemas, Func<OpenApiSchema, IList<OpenApiSchema>> subsequentGetter, int? maxDepth = default) {
Expand Down
Loading
Loading