Skip to content

Commit

Permalink
introduce examples for MPG from typespec (#5014)
Browse files Browse the repository at this point in the history
* introduce the cache to parameter in examples

* use the examples instead

* add the examples

* add the ability

* add another example for delete

* refinement

* refinement

* flip the default value
  • Loading branch information
ArcturusZhang authored Aug 28, 2024
1 parent f15460a commit 3ce539e
Show file tree
Hide file tree
Showing 20 changed files with 665 additions and 118 deletions.
2 changes: 2 additions & 0 deletions src/AutoRest.CSharp/Common/AutoRest/Plugins/CSharpGen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ public async Task<GeneratedCodeWorkspace> ExecuteAsync(InputNamespace rootNamesp
InputNamespaceTransformer.Transform(rootNamespace);
MgmtContext.Initialize(new BuildContext<MgmtOutputLibrary>(rootNamespace, sourceInputModel));
await MgmtTarget.ExecuteAsync(project);
if (Configuration.GenerateSampleProject)
await MgmtTestTarget.ExecuteAsync(project, rootNamespace, sourceInputModel);
}
else
{
Expand Down
11 changes: 7 additions & 4 deletions src/AutoRest.CSharp/Common/Input/CodeModelConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,11 @@ private InputOperation CreateOperation(ServiceRequest serviceRequest, Operation
generateProtocolMethod: true,
generateConvenienceMethod: false,
crossLanguageDefinitionId: string.Empty, // in typespec input, this is to determine whether an operation has been renamed. We have separated configuration for that in swagger input, therefore we leave it empty here
keepClientDefaultValue: operationId is null ? false : Configuration.MethodsToKeepClientDefaultValue.Contains(operationId))
keepClientDefaultValue: operationId is null ? false : Configuration.MethodsToKeepClientDefaultValue.Contains(operationId),
examples: CreateOperationExamplesFromTestModeler(operation))
{
SpecName = operation.Language.Default.SerializedName ?? operation.Language.Default.Name
};
inputOperation.CodeModelExamples = CreateOperationExamples(inputOperation, operation);
return inputOperation;
}

Expand All @@ -172,8 +172,11 @@ private InputOperation CreateOperation(ServiceRequest serviceRequest, Operation
return operationId.Split('_')[0];
}

private IReadOnlyList<InputOperationExample> CreateOperationExamples(InputOperation inputOperation, Operation operation)
private IReadOnlyList<InputOperationExample>? CreateOperationExamplesFromTestModeler(Operation operation)
{
if (!Configuration.AzureArm)
return null;

var result = new List<InputOperationExample>();
var exampleOperation = _codeModel.TestModel?.MockTest.ExampleGroups?.FirstOrDefault(g => g.Operation == operation);
if (exampleOperation is null)
Expand All @@ -183,7 +186,7 @@ private IReadOnlyList<InputOperationExample> CreateOperationExamples(InputOperat
foreach (var example in exampleOperation.Examples)
{
var parameters = example.AllParameters
.Select(p => new InputParameterExample(CreateOperationParameter(p.Parameter), CreateExampleValue(p.ExampleValue)))
.Select(p => new InputParameterExample(_parametersCache[p.Parameter](), CreateExampleValue(p.ExampleValue)))
.ToList();
result.Add(new InputOperationExample(example.Name, null, example.OriginalFile!, parameters));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ public static InputOperation RemoveApiVersionParam(InputOperation operation)
private IReadOnlyList<InputOperationExample> EnsureExamples()
{
// see if we need to generate the mock examples
if (Configuration.ExamplesDirectory != null)
if (Configuration.ExamplesDirectory != null || Configuration.AzureArm)
{
return Array.Empty<InputOperationExample>();
}
Expand All @@ -133,8 +133,6 @@ private IReadOnlyList<InputOperationExample> EnsureExamples()
return ExampleMockValueBuilder.BuildOperationExamples(this);
}

public IReadOnlyList<InputOperationExample> CodeModelExamples { get; internal set; } = Array.Empty<InputOperationExample>();

public bool IsLongRunning => LongRunning != null;
public string Name { get; internal set; }
public string? ResourceName { get; }
Expand Down
10 changes: 5 additions & 5 deletions src/AutoRest.CSharp/MgmtTest/AutoRest/MgmtTestOutputLibrary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using System.Collections.Generic;
using System.Linq;
using AutoRest.CSharp.Common.Input;
using AutoRest.CSharp.Input;
using AutoRest.CSharp.Mgmt.AutoRest;
using AutoRest.CSharp.Mgmt.Output;
using AutoRest.CSharp.MgmtTest.Models;
Expand All @@ -18,11 +17,12 @@ namespace AutoRest.CSharp.MgmtTest.AutoRest
internal class MgmtTestOutputLibrary
{
private readonly InputNamespace _inputNamespace;
private readonly MgmtTestConfiguration _mgmtTestConfiguration;
private readonly HashSet<string> _skippedOperations;

public MgmtTestOutputLibrary(InputNamespace inputNamespace)
{
_inputNamespace = inputNamespace;
_mgmtTestConfiguration = Configuration.MgmtTestConfiguration!;
_skippedOperations = new HashSet<string>(Configuration.MgmtTestConfiguration?.SkippedOperations ?? []);
}

private IEnumerable<MgmtSampleProvider>? _samples;
Expand All @@ -46,13 +46,13 @@ private Dictionary<MgmtTypeProvider, List<MockTestCase>> EnsureMockTestCases()
{
foreach (var inputOperation in client.Operations)
{
foreach (var example in inputOperation.CodeModelExamples)
foreach (var example in inputOperation.Examples)
{
// we need to find which resource or resource collection this test case belongs
var operationId = inputOperation.OperationId!;

// skip this operation if we find it in the `skipped-operations` configuration
if (_mgmtTestConfiguration.SkippedOperations.Contains(operationId))
if (_skippedOperations.Contains(operationId))
continue;

var providerAndOperations = FindCarriersFromOperationId(operationId);
Expand Down
10 changes: 4 additions & 6 deletions src/AutoRest.CSharp/MgmtTest/AutoRest/MgmtTestTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using System.IO;
using System.Threading.Tasks;
using AutoRest.CSharp.Common.Input;
using AutoRest.CSharp.Input;
using AutoRest.CSharp.Input.Source;
using AutoRest.CSharp.Mgmt.AutoRest;
using AutoRest.CSharp.MgmtTest.AutoRest;
Expand All @@ -27,7 +26,6 @@ internal class MgmtTestTarget
public static async Task ExecuteAsync(GeneratedCodeWorkspace project, InputNamespace inputNamespace, SourceInputModel? sourceInputModel)
{
Debug.Assert(inputNamespace.Clients is not null);
Debug.Assert(Configuration.MgmtTestConfiguration is not null);
MgmtTestOutputLibrary library;
if (sourceInputModel == null)
{
Expand All @@ -43,20 +41,20 @@ public static async Task ExecuteAsync(GeneratedCodeWorkspace project, InputNames
library = new MgmtTestOutputLibrary(inputNamespace);
}

if (Configuration.MgmtTestConfiguration.Mock)
if (Configuration.MgmtTestConfiguration?.Mock ?? false)
{
WriteMockTests(project, library);
}

if (Configuration.MgmtTestConfiguration.Sample)
if (Configuration.MgmtTestConfiguration?.Sample ?? Configuration.GenerateSampleProject)
{
WriteSamples(project, library);
}

if (_overriddenProjectFilenames.TryGetValue(project, out var overriddenFilenames))
throw new InvalidOperationException($"At least one file was overridden during the generation process. Filenames are: {string.Join(", ", overriddenFilenames)}");

if (Configuration.MgmtTestConfiguration.ClearOutputFolder)
if (Configuration.MgmtTestConfiguration?.ClearOutputFolder ?? false)
{
ClearOutputFolder();
}
Expand Down Expand Up @@ -172,7 +170,7 @@ private static string GetOutputFolder(string defaultOutputPath)
// Azure.ResourceManager.XXX \ src \ Generated <- default sdk source output folder
// \ samples(or tests) \ Generated <- default sample output folder defined in msbuild
if (folder.EndsWith(SOURCE_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase))
return FormatPath(Path.Combine(folder, $"../..", defaultOutputPath));
return FormatPath(Path.Combine(folder, $"../../{defaultOutputPath}"));
else if (folder.EndsWith(SAMPLE_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase) || folder.EndsWith(MOCK_TEST_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase))
return folder;
else
Expand Down
1 change: 1 addition & 0 deletions test/TestProjects/MgmtTypeSpec/Configuration.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"operationId": "Foos_CreateOrUpdate",
"title": "Create a foo",
"parameters": {
"subscriptionId": "00000000-0000-0000-0000-000000000000",
"resourceGroupName": "myRg",
"fooName": "myFoo",
"resource": {
"properties": {
"serviceUrl": "https://myService.com",
"something": "for test only"
}
}
},
"responses": {
"200": {
"body": {
"id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myRg/providers/MgmtTypeSpec/foos/myFoo",
"name": "myFoo",
"type": "MgmtTypeSpec/foos",
"properties": {
"serviceUrl": "https://myService.com",
"something": "for test only"
}
}
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"operationId": "Foos_Get",
"title": "Get a foo",
"parameters": {
"subscriptionId": "00000000-0000-0000-0000-000000000000",
"resourceGroupName": "myRg",
"fooName": "myFoo"
},
"responses": {
"204": {}
}
}

23 changes: 23 additions & 0 deletions test/TestProjects/MgmtTypeSpec/examples/2024-05-01/Foos_Get.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"operationId": "Foos_Get",
"title": "Get a foo",
"parameters": {
"subscriptionId": "00000000-0000-0000-0000-000000000000",
"resourceGroupName": "myRg",
"fooName": "myFoo"
},
"responses": {
"200": {
"body": {
"id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myRg/providers/MgmtTypeSpec/foos/myFoo",
"name": "myFoo",
"type": "MgmtTypeSpec/foos",
"properties": {
"serviceUrl": "https://myService.com",
"something": "for test only"
}
}
}
}
}

2 changes: 1 addition & 1 deletion test/TestProjects/MgmtTypeSpec/main.tsp
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ enum Versions {
/** Azure Cosmos DB for Mongo vCore clusters api version 2024-03-01-preview. */
@useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1)
@useDependency(Azure.Core.Versions.v1_0_Preview_1)
v1,
v2024_05_01: "2024-05-01",
}
Loading

0 comments on commit 3ce539e

Please sign in to comment.