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

support apiVersion as path parameter #4691

Merged
merged 22 commits into from
Oct 17, 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
1 change: 0 additions & 1 deletion packages/http-client-csharp/eng/scripts/Generate.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ $failingSpecs = @(
Join-Path 'http' 'routes'
Join-Path 'http' 'serialization' 'encoded-name' 'json'
Join-Path 'http' 'server' 'endpoint' 'not-defined'
Join-Path 'http' 'server' 'path' 'multiple'
Join-Path 'http' 'server' 'versions' 'versioned'
Join-Path 'http' 'special-headers' 'conditional-request'
Join-Path 'http' 'special-headers' 'repeatability'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Licensed under the MIT License.

using System;
using System.ClientModel.Primitives;
using System.Linq;
using Microsoft.Generator.CSharp.ClientModel.Providers;
using Microsoft.Generator.CSharp.Expressions;
using Microsoft.Generator.CSharp.Primitives;
Expand Down Expand Up @@ -37,6 +39,11 @@ internal class StubLibraryVisitor : ScmLibraryVisitor
return null;
}

/* remove constructors for ClientOptions */
if (type.Implements.Any(i => i.Equals(typeof(ClientPipelineOptions))))
{
type.Update(constructors: []);
}
return type;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ protected override PropertyProvider[] BuildProperties()

foreach (var p in _inputClient.Parameters)
{
if (!p.IsEndpoint && p.DefaultValue != null)
if (!p.IsEndpoint && !p.IsApiVersion && p.DefaultValue != null)
{
FormattableString? description = null;
if (p.Description != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,10 @@ protected override FieldProvider[] BuildFields()
{
if (!p.IsEndpoint)
{
var type = ClientModelPlugin.Instance.TypeFactory.CreateCSharpType(p.Type);
var type = p is { IsApiVersion: true, Type: InputEnumType enumType }
? ClientModelPlugin.Instance.TypeFactory.CreateCSharpType(enumType.ValueType)
: ClientModelPlugin.Instance.TypeFactory.CreateCSharpType(p.Type);

if (type != null)
{
FieldProvider field = new(
Expand Down Expand Up @@ -251,15 +254,15 @@ private IReadOnlyList<ParameterProvider> GetRequiredParameters()
ParameterProvider? currentParam = null;
foreach (var parameter in _allClientParameters)
{
currentParam = null;
if (parameter.IsRequired && !parameter.IsEndpoint && !parameter.IsApiVersion)
{
currentParam = ClientModelPlugin.Instance.TypeFactory.CreateParameter(parameter);
currentParam.Field = Fields.FirstOrDefault(f => f.Name == "_" + parameter.Name);
currentParam = CreateParameter(parameter);
requiredParameters.Add(currentParam);
}
if (parameter.Location == RequestLocation.Uri)
jorgerangel-msft marked this conversation as resolved.
Show resolved Hide resolved
{
_uriParameters.Add(currentParam ?? ClientModelPlugin.Instance.TypeFactory.CreateParameter(parameter));
_uriParameters.Add(currentParam ?? CreateParameter(parameter));
}
}

Expand All @@ -269,6 +272,13 @@ private IReadOnlyList<ParameterProvider> GetRequiredParameters()
return requiredParameters;
}

private ParameterProvider CreateParameter(InputParameter parameter)
{
var param = ClientModelPlugin.Instance.TypeFactory.CreateParameter(parameter);
param.Field = Fields.FirstOrDefault(f => f.Name == "_" + parameter.Name);
return param;
}

private MethodBodyStatement[] BuildPrimaryConstructorBody(IReadOnlyList<ParameterProvider> primaryConstructorParameters)
{
if (ClientOptions is null || ClientOptionsParameter is null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,10 +341,10 @@ private static void GetParamInfo(Dictionary<string, ParameterProvider> paramMap,
else
{
var paramProvider = paramMap[inputParam.Name];
if (paramProvider.Type.IsEnum)
type = paramProvider.Field is null ? paramProvider.Type : paramProvider.Field.Type;
chunyu3 marked this conversation as resolved.
Show resolved Hide resolved
if (type.IsEnum)
{
var csharpType = paramProvider.Field is null ? paramProvider.Type : paramProvider.Field.Type;
valueExpression = csharpType.ToSerial(paramProvider);
valueExpression = type.ToSerial(paramProvider);
format = null;
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -403,23 +403,78 @@ public void ValidateClientWithSpread(InputClient inputClient)
[Test]
public void TestApiVersionOfClient()
{
List<string> apiVersions = ["1.0", "2.0"];
var enumValues = apiVersions.Select(a => InputFactory.EnumMember.String(a, a));
var inputEnum = InputFactory.Enum("ServiceVersion", InputPrimitiveType.Int64, values: [.. enumValues], usage: InputModelTypeUsage.ApiVersionEnum);

MockHelpers.LoadMockPlugin(
apiVersions: () => apiVersions,
inputEnums: () => [inputEnum]);
var client = InputFactory.Client(TestClientName,
operations: [
InputFactory.Operation("OperationWithApiVersion",
parameters: [InputFactory.Parameter("apiVersion", InputPrimitiveType.String, isRequired: true, location: RequestLocation.Query, kind: InputOperationParameterKind.Client)])
parameters: [InputFactory.Parameter("apiVersion", InputPrimitiveType.String, isRequired: true, location: RequestLocation.Query, kind: InputOperationParameterKind.Client, isApiVersion: true)])
]);
var clientProvider = new ClientProvider(client);
Assert.IsNotNull(clientProvider);

/* verify that the client has apiVersion field */
Assert.IsNotNull(clientProvider.Fields.FirstOrDefault(f => f.Name.Equals("_apiVersion")));

/* verify that there is no apiVersion parameter in constructor. */
var apiVersionParameter = clientProvider.Constructors.Select(c => c.Signature.Parameters.FirstOrDefault(p => p.Name.Equals("apiVersion"))).FirstOrDefault();
Assert.IsNull(apiVersionParameter);

/* verify the apiVersion assignment in constructor body */
var primaryConstructor = clientProvider.Constructors.FirstOrDefault(
c => c.Signature?.Initializer == null && c.Signature?.Modifiers == MethodSignatureModifiers.Public);
Assert.IsNotNull(primaryConstructor);
var bodyStatements = primaryConstructor?.BodyStatements as MethodBodyStatements;
Assert.IsNotNull(bodyStatements);
Assert.IsTrue(bodyStatements!.Statements.Any(s => s.ToDisplayString().IndexOf("_apiVersion = options.Version;\n") != -1));

var method = clientProvider.Methods.FirstOrDefault(m => m.Signature.Name.Equals("OperationWithApiVersion"));
Assert.IsNotNull(method);
/* verify that the method does not have apiVersion parameter */
Assert.IsNull(method?.Signature.Parameters.FirstOrDefault(p => p.Name.Equals("apiVersion")));
}

[TestCaseSource(nameof(ValidateApiVersionPathParameterTestCases))]
public void TestApiVersionPathParameterOfClient(InputClient inputClient)
{
List<string> apiVersions = ["value1", "value2"];
var enumValues = apiVersions.Select(a => InputFactory.EnumMember.String(a, a));
var inputEnum = InputFactory.Enum("ServiceVersion", InputPrimitiveType.Int64, values: [.. enumValues], usage: InputModelTypeUsage.ApiVersionEnum);
MockHelpers.LoadMockPlugin(
apiVersions: () => apiVersions,
inputEnums: () => [inputEnum]);

var clientProvider = new ClientProvider(inputClient);
Assert.IsNotNull(clientProvider);

/* verify that the client has apiVersion field */
var apiVersionField = clientProvider.Fields.FirstOrDefault(f => f.Name.Equals("_apiVersion"));
Assert.IsNotNull(apiVersionField);
Assert.AreEqual(new CSharpType(typeof(string)), apiVersionField?.Type);

/* verify that there is no apiVersion parameter in constructor. */
var apiVersionParameter = clientProvider.Constructors.Select(c => c.Signature.Parameters.FirstOrDefault(p => p.Name.Equals("apiVersion"))).FirstOrDefault();
Assert.IsNull(apiVersionParameter);

/* verify the apiVersion assignment in constructor body */
var primaryConstructor = clientProvider.Constructors.FirstOrDefault(
c => c.Signature?.Initializer == null && c.Signature?.Modifiers == MethodSignatureModifiers.Public);
Assert.IsNotNull(primaryConstructor);
var bodyStatements = primaryConstructor?.BodyStatements as MethodBodyStatements;
Assert.IsNotNull(bodyStatements);
Assert.IsTrue(bodyStatements!.Statements.Any(s => s.ToDisplayString().IndexOf("_apiVersion = options.Version;\n") != -1));

var method = clientProvider.Methods.FirstOrDefault(m => m.Signature.Name.Equals("TestOperation"));
Assert.IsNotNull(method);
/* verify that the method does not have apiVersion parameter */
Assert.IsNull(method?.Signature.Parameters.FirstOrDefault(p => p.Name.Equals("apiVersion")));
}

private static InputClient GetEnumQueryParamClient()
=> InputFactory.Client(
TestClientName,
Expand Down Expand Up @@ -599,5 +654,79 @@ private static IEnumerable<TestCaseData> EndpointParamInitializationValueTestCas
defaultValue: InputFactory.Constant.String("mockValue")),
New.Instance(KnownParameters.Endpoint.Type, Literal("mockvalue")));
}

private static IEnumerable<TestCaseData> ValidateApiVersionPathParameterTestCases()
{
InputParameter endpointParameter = InputFactory.Parameter(
"endpoint",
InputPrimitiveType.String,
location: RequestLocation.Uri,
isRequired: true,
kind: InputOperationParameterKind.Client,
isEndpoint: true,
isApiVersion: false);

InputParameter stringApiVersionParameter = InputFactory.Parameter(
"apiVersion",
InputPrimitiveType.String,
location: RequestLocation.Uri,
isRequired: true,
kind: InputOperationParameterKind.Client,
isApiVersion: true);

InputParameter enumApiVersionParameter = InputFactory.Parameter(
"apiVersion",
InputFactory.Enum(
"InputEnum",
InputPrimitiveType.String,
usage: InputModelTypeUsage.Input,
isExtensible: true,
values:
[
InputFactory.EnumMember.String("value1", "value1"),
InputFactory.EnumMember.String("value2", "value2")
]),
location: RequestLocation.Uri,
isRequired: true,
kind: InputOperationParameterKind.Client,
isApiVersion: true);

yield return new TestCaseData(
InputFactory.Client(
"TestClient",
operations:
[
InputFactory.Operation(
"TestOperation",
uri: "{endpoint}/{apiVersion}",
parameters:
[
endpointParameter,
stringApiVersionParameter
])
],
parameters: [
endpointParameter,
stringApiVersionParameter
]));

yield return new TestCaseData(
InputFactory.Client(
"TestClient",
operations:
[
InputFactory.Operation(
"TestOperation",
parameters: [
endpointParameter,
enumApiVersionParameter
],
uri: "{endpoint}/{apiVersion}")
],
parameters: [
endpointParameter,
enumApiVersionParameter
]));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,21 @@ public void ValidateClientWithApiVersion()
Assert.IsTrue(bodyStatements!.Statements.Any(s => s.ToDisplayString() == "uri.AppendQuery(\"apiVersion\", _apiVersion, true);\n"));
}

[TestCaseSource(nameof(ValidateApiVersionPathParameterTestCases))]
public void ValidateClientWithApiVersionPathParameter(InputClient inputClient)
{
var clientProvider = new ClientProvider(inputClient);
var restClientProvider = new MockClientProvider(inputClient, clientProvider);
var method = restClientProvider.Methods.FirstOrDefault(m => m.Signature.Name == "CreateTestOperationRequest");
Assert.IsNotNull(method);
/* verify that there is no apiVersion parameter in method signature. */
Assert.IsNull(method?.Signature.Parameters.FirstOrDefault(p => p.Name.Equals("apiVersion")));
var bodyStatements = method?.BodyStatements as MethodBodyStatements;
Assert.IsNotNull(bodyStatements);
/* verify that it will use client _apiVersion field to append query parameter. */
Assert.IsTrue(bodyStatements!.Statements.Any(s => s.ToDisplayString() == "uri.AppendPath(_apiVersion, true);\n"));
}

private readonly static InputOperation BasicOperation = InputFactory.Operation(
"CreateMessage",
parameters:
Expand Down Expand Up @@ -370,5 +385,79 @@ protected override MethodProvider[] BuildMethods()

protected override TypeProvider[] BuildNestedTypes() => [];
}

private static IEnumerable<TestCaseData> ValidateApiVersionPathParameterTestCases()
{
InputParameter endpointParameter = InputFactory.Parameter(
"endpoint",
InputPrimitiveType.String,
location: RequestLocation.Uri,
isRequired: true,
kind: InputOperationParameterKind.Client,
isEndpoint: true,
isApiVersion: false);

InputParameter stringApiVersionParameter = InputFactory.Parameter(
"apiVersion",
InputPrimitiveType.String,
location: RequestLocation.Uri,
isRequired: true,
kind: InputOperationParameterKind.Client,
isApiVersion: true);

InputParameter enumApiVersionParameter = InputFactory.Parameter(
"apiVersion",
InputFactory.Enum(
"InputEnum",
InputPrimitiveType.String,
usage: InputModelTypeUsage.Input,
isExtensible: true,
values:
[
InputFactory.EnumMember.String("value1", "value1"),
InputFactory.EnumMember.String("value2", "value2")
]),
location: RequestLocation.Uri,
isRequired: true,
kind: InputOperationParameterKind.Client,
isApiVersion: true);

yield return new TestCaseData(
InputFactory.Client(
"TestClient",
operations:
[
InputFactory.Operation(
"TestOperation",
uri: "{endpoint}/{apiVersion}",
parameters:
[
endpointParameter,
stringApiVersionParameter
])
],
parameters: [
endpointParameter,
stringApiVersionParameter
]));

yield return new TestCaseData(
InputFactory.Client(
"TestClient",
operations:
[
InputFactory.Operation(
"TestOperation",
parameters: [
endpointParameter,
enumApiVersionParameter
],
uri: "{endpoint}/{apiVersion}")
],
parameters: [
endpointParameter,
enumApiVersionParameter
]));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@
"commandName": "Executable",
"executablePath": "$(SolutionDir)/../dist/generator/Microsoft.Generator.CSharp.exe"
},
"http-server-path-multiple": {
"commandLineArgs": "$(SolutionDir)/TestProjects/CadlRanch/http/server/path/multiple -p StubLibraryPlugin",
"commandName": "Executable",
"executablePath": "$(SolutionDir)/../dist/generator/Microsoft.Generator.CSharp.exe"
},
"http-server-path-single": {
"commandLineArgs": "$(SolutionDir)/TestProjects/CadlRanch/http/server/path/single -p StubLibraryPlugin",
"commandName": "Executable",
Expand Down
Loading
Loading