Merge branch 'feature/v3' into validation-tests

This commit is contained in:
Michael Yanni 2019-12-17 13:17:16 -08:00
Родитель b3366dfb22 23128ef130
Коммит 29d8fcd34c
24 изменённых файлов: 501 добавлений и 186 удалений

Просмотреть файл

@ -47,7 +47,7 @@ $testNames = if ($name) { $name } else
#'azure-resource-x',
#'azure-special-properties',
#'body-array',
#'body-boolean',
'body-boolean',
#'body-boolean.quirks',
#'body-byte',
'body-complex',

Просмотреть файл

@ -117,7 +117,7 @@ namespace AutoRest.CSharp.V3.ClientModels
}
var request = new ClientMethodRequest(
httpRequest.Method.ToCoreRequestMethod() ?? RequestMethod.Get,
ToCoreRequestMethod(httpRequest.Method) ?? RequestMethod.Get,
ToParts(httpRequest.Uri, uriParameters),
ToPathParts(httpRequest.Path, pathParameters),
query.ToArray(),
@ -278,5 +278,19 @@ namespace AutoRest.CSharp.V3.ClientModels
yield return (currentPart.ToString(), true);
}
}
private static RequestMethod? ToCoreRequestMethod(HttpMethod method) => method switch
{
HttpMethod.Delete => RequestMethod.Delete,
HttpMethod.Get => RequestMethod.Get,
HttpMethod.Head => RequestMethod.Head,
HttpMethod.Options => (RequestMethod?)null,
HttpMethod.Patch => RequestMethod.Patch,
HttpMethod.Post => RequestMethod.Post,
HttpMethod.Put => RequestMethod.Put,
HttpMethod.Trace => null,
_ => null
};
}
}

Просмотреть файл

@ -20,8 +20,8 @@ namespace AutoRest.CSharp.V3.ClientModels
{ Type: AllSchemaTypes.Binary } => new BinaryTypeReference(false),
ArraySchema array => new CollectionTypeReference(CreateType(array.ElementType, false), isNullable),
DictionarySchema dictionary => new DictionaryTypeReference(new FrameworkTypeReference(typeof(string)), CreateType(dictionary.ElementType, false), isNullable),
NumberSchema number => new FrameworkTypeReference(number.ToFrameworkType(), isNullable),
_ when schema.Type.ToFrameworkCSharpType() is Type type => new FrameworkTypeReference(type, isNullable),
NumberSchema number => new FrameworkTypeReference(ToFrameworkNumberType(number), isNullable),
_ when ToFrameworkType(schema.Type) is Type type => new FrameworkTypeReference(type, isNullable),
_ => new SchemaTypeReference(schema, isNullable)
};
@ -48,5 +48,40 @@ namespace AutoRest.CSharp.V3.ClientModels
DurationSchema _ => SerializationFormat.Duration_ISO8601,
_ => SerializationFormat.Default
};
private static Type? ToFrameworkType(AllSchemaTypes schemaType) => schemaType switch
{
AllSchemaTypes.Boolean => typeof(bool),
AllSchemaTypes.ByteArray => null,
AllSchemaTypes.Char => typeof(char),
AllSchemaTypes.Date => typeof(DateTimeOffset),
AllSchemaTypes.DateTime => typeof(DateTimeOffset),
AllSchemaTypes.Duration => typeof(TimeSpan),
AllSchemaTypes.OdataQuery => typeof(string),
AllSchemaTypes.String => typeof(string),
AllSchemaTypes.Unixtime => typeof(DateTimeOffset),
AllSchemaTypes.Uri => typeof(Uri),
AllSchemaTypes.Uuid => typeof(string),
_ => null
};
private static Type ToFrameworkNumberType(NumberSchema schema) => schema.Type switch
{
AllSchemaTypes.Number => schema.Precision switch
{
32 => typeof(float),
128 => typeof(decimal),
_ => typeof(double)
},
// Assumes AllSchemaTypes.Integer
_ => schema.Precision switch
{
16 => typeof(short),
64 => typeof(long),
_ => typeof(int)
}
};
}
}

Просмотреть файл

@ -8,12 +8,10 @@ using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using AutoRest.CSharp.V3.ClientModels;
using AutoRest.CSharp.V3.Pipeline;
using AutoRest.CSharp.V3.Utilities;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SerializationFormat = AutoRest.CSharp.V3.ClientModels.SerializationFormat;
namespace AutoRest.CSharp.V3.CodeGen
@ -116,15 +114,22 @@ namespace AutoRest.CSharp.V3.CodeGen
{
writer.Line($"using var content = new {writer.Type(typeof(Utf8JsonRequestContent))}();");
writer.Line($"var writer = content.{nameof(Utf8JsonRequestContent.JsonWriter)};");
var name = body.Value.IsConstant ? body.Value.Constant.ToValueString() : body.Value.Parameter.Name;
writer.ToSerializeCall(body.Value.Type, body.Format, _typeFactory, name, string.Empty, false);
//TODO: Workaround for JSON serialization not supporting the null constants
ConstantOrParameter value = body.Value;
if (value.IsConstant && value.Constant.Value == null)
{
value = ClientModelBuilderHelpers.StringConstant("");
}
writer.ToSerializeCall(value.Type, body.Format, _typeFactory, w => WriteConstantOrParameter(w, value));
writer.Line("request.Content = content;");
}
writer.Line("var response = await pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);");
WriteStatusCodeSwitch(writer, responseType, responseBody, headerModelType, operation);
WriteStatusCodeSwitch(writer, responseBody, headerModelType, operation);
}
var exceptionParameter = writer.Pair(typeof(Exception), "e");
@ -136,6 +141,24 @@ namespace AutoRest.CSharp.V3.CodeGen
}
}
private void WriteConstantOrParameter(CodeWriter writer, ConstantOrParameter constantOrParameter)
{
if (constantOrParameter.IsConstant)
{
WriteConstant(writer, constantOrParameter.Constant);
}
else
{
writer.Append(constantOrParameter.Parameter.Name);
var type = _typeFactory.CreateType(constantOrParameter.Type);
if (type.IsNullable && type.IsValueType)
{
writer.Append(".Value");
}
}
}
private void WriteParameterNullChecks(CodeWriter writer, ClientMethod operation)
{
foreach (ServiceClientMethodParameter parameter in operation.Parameters)
@ -209,21 +232,8 @@ namespace AutoRest.CSharp.V3.CodeGen
private void WritePathSegment(CodeWriter writer, PathSegment segment)
{
var value = segment.Value;
if (value.IsConstant)
{
writer.Append("request.Uri.AppendPath(");
WriteConstant(writer, value.Constant);
WriteSerializationFormat(writer, segment.Format);
writer.Comma();
writer.Literal(segment.Escape);
writer.Line(");");
return;
}
writer.Append("request.Uri.AppendPath(");
writer.Append(value.Parameter.Name);
WriteConstantOrParameter(writer, segment.Value);
WriteSerializationFormat(writer, segment.Format);
writer.Comma();
writer.Literal(segment.Escape);
@ -232,34 +242,30 @@ namespace AutoRest.CSharp.V3.CodeGen
private void WriteHeader(CodeWriter writer, RequestHeader header)
{
if (header.Value.IsConstant)
using (WriteValueNullCheck(writer, header.Value))
{
writer.Append("request.Headers.Add(");
writer.Literal(header.Name);
writer.Comma();
WriteConstant(writer, header.Value.Constant);
writer.Line(");");
return;
}
var parameter = header.Value.Parameter;
var type = _typeFactory.CreateType(parameter.Type);
using (type.IsNullable ? writer.If($"{parameter.Name} != null") : default)
{
writer.Append("request.Headers.Add(");
writer.Literal(header.Name);
writer.Comma();
writer.Append(parameter.Name);
if (type.IsNullable && type.IsValueType)
{
writer.Append(".Value");
}
WriteConstantOrParameter(writer, header.Value);
WriteSerializationFormat(writer, header.Format);
writer.Line(");");
}
}
private CodeWriter.CodeWriterScope WriteValueNullCheck(CodeWriter writer, ConstantOrParameter value)
{
if (value.IsConstant) return default;
var type = _typeFactory.CreateType(value.Type);
if (type.IsNullable)
{
return writer.If($"{value.Parameter.Name} != null");
}
return default;
}
private void WriteSerializationFormat(CodeWriter writer, SerializationFormat format)
{
var formatSpecifier = format.ToFormatSpecifier();
@ -298,40 +304,14 @@ namespace AutoRest.CSharp.V3.CodeGen
}
ConstantOrParameter value = queryParameter.Value;
if (value.IsConstant)
using (WriteValueNullCheck(writer, value))
{
writer.Append("request.Uri.");
writer.Append(method);
writer.Append("(");
writer.Literal(queryParameter.Name);
writer.Comma();
WriteConstant(writer, value.Constant);
if (delimiter != null)
{
writer.Comma();
writer.Literal(delimiter);
}
WriteSerializationFormat(writer, queryParameter.SerializationFormat);
writer.Comma();
writer.Literal(queryParameter.Escape);
writer.Line(");");
return;
}
var parameter = value.Parameter;
var type = _typeFactory.CreateType(parameter.Type);
using (parameter.Type.IsNullable ? writer.If($"{parameter.Name} != null") : default)
{
writer.Append("request.Uri.");
writer.Append(method);
writer.Append("(");
writer.Literal(queryParameter.Name);
writer.Comma();
writer.Append(parameter.Name);
if (type.IsNullable && type.IsValueType)
{
writer.Append(".Value");
}
WriteConstantOrParameter(writer, value);
if (delimiter != null)
{
writer.Comma();
@ -345,7 +325,7 @@ namespace AutoRest.CSharp.V3.CodeGen
}
//TODO: Do multiple status codes
private void WriteStatusCodeSwitch(CodeWriter writer, CSharpType responseType, ResponseBody? responseBody, CSharpType? headersModelType, ClientMethod operation)
private void WriteStatusCodeSwitch(CodeWriter writer, ResponseBody? responseBody, CSharpType? headersModelType, ClientMethod operation)
{
using (writer.Switch("response.Status"))
{
@ -365,9 +345,7 @@ namespace AutoRest.CSharp.V3.CodeGen
responseBody.Value,
responseBody.Format,
_typeFactory,
"document.RootElement",
writer.Type(responseType),
responseType.Name
w => w.Append("document.RootElement")
);
writer.SemicolonLine();
}

Просмотреть файл

@ -204,6 +204,12 @@ namespace AutoRest.CSharp.V3.CodeGen
return this;
}
public CodeWriter Append(CodeWriterDelegate writerDelegate)
{
writerDelegate(this);
return this;
}
public CodeWriter Comma() => Append(", ");
public CodeWriter Space() => Append(" ");
@ -248,6 +254,13 @@ namespace AutoRest.CSharp.V3.CodeGen
public override string? ToString() => _builder.ToString();
public static string Materialize(CodeWriterDelegate writer)
{
var codeWriter = new CodeWriter();
writer(codeWriter);
return codeWriter._builder.ToString();
}
internal readonly struct CodeWriterScope : IDisposable
{
private readonly CodeWriter _writer;

Просмотреть файл

@ -0,0 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace AutoRest.CSharp.V3.CodeGen
{
internal delegate void CodeWriterDelegate(CodeWriter writer);
}

Просмотреть файл

@ -4,61 +4,11 @@
using System;
using System.Collections.Generic;
using AutoRest.CSharp.V3.ClientModels;
using AutoRest.CSharp.V3.CodeGen;
using AutoRest.CSharp.V3.Pipeline.Generated;
using Azure.Core;
using SerializationFormat = AutoRest.CSharp.V3.ClientModels.SerializationFormat;
namespace AutoRest.CSharp.V3.Pipeline
namespace AutoRest.CSharp.V3.CodeGen
{
internal static class Extensions
internal static class JsonSerializerExtensions
{
public static Type? ToFrameworkCSharpType(this AllSchemaTypes schemaType) => schemaType switch
{
AllSchemaTypes.Boolean => typeof(bool),
AllSchemaTypes.ByteArray => null,
AllSchemaTypes.Char => typeof(char),
AllSchemaTypes.Date => typeof(DateTimeOffset),
AllSchemaTypes.DateTime => typeof(DateTimeOffset),
AllSchemaTypes.Duration => typeof(TimeSpan),
AllSchemaTypes.OdataQuery => typeof(string),
AllSchemaTypes.String => typeof(string),
AllSchemaTypes.Unixtime => typeof(DateTimeOffset),
AllSchemaTypes.Uri => typeof(Uri),
AllSchemaTypes.Uuid => typeof(string),
_ => null
};
public static Type ToFrameworkType(this NumberSchema schema) => schema.Type switch
{
AllSchemaTypes.Number => schema.Precision switch
{
32 => typeof(float),
128 => typeof(decimal),
_ => typeof(double)
},
// Assumes AllSchemaTypes.Integer
_ => schema.Precision switch
{
16 => typeof(short),
64 => typeof(long),
_ => typeof(int)
}
};
public static RequestMethod? ToCoreRequestMethod(this HttpMethod method) => method switch
{
HttpMethod.Delete => RequestMethod.Delete,
HttpMethod.Get => RequestMethod.Get,
HttpMethod.Head => RequestMethod.Head,
HttpMethod.Options => (RequestMethod?)null,
HttpMethod.Patch => RequestMethod.Patch,
HttpMethod.Post => RequestMethod.Post,
HttpMethod.Put => RequestMethod.Put,
HttpMethod.Trace => null,
_ => null
};
private static readonly Func<string, bool, SerializationFormat, string?> NumberSerializer =
(vn, nu, f) => $"writer.WriteNumberValue({vn}{(nu ? ".Value" : string.Empty)});";
private static Func<string, bool, SerializationFormat, string?> StringSerializer(bool includeToString = false) =>
@ -124,7 +74,7 @@ namespace AutoRest.CSharp.V3.Pipeline
{ typeof(Uri), (n, f) => null } //TODO: Figure out how to get the Uri type here, so we can do 'new Uri(GetString())'
};
private static void WriteSerializeClientObject(CodeWriter writer, string name, CSharpType type)
private static void WriteSerializeClientObject(CodeWriter writer, CodeWriterDelegate name, CSharpType type)
{
writer.AppendType(type.WithNullable(false))
.Append("Serializer.Serialize(")
@ -133,7 +83,7 @@ namespace AutoRest.CSharp.V3.Pipeline
.SemicolonLine();
}
private static void WriteSerializeClientEnum(CodeWriter writer, string name, bool isNullable, bool isStringBased)
private static void WriteSerializeClientEnum(CodeWriter writer, CodeWriterDelegate name, bool isNullable, bool isStringBased)
{
writer.Append("writer.WriteStringValue(");
writer.Append(name);
@ -145,7 +95,7 @@ namespace AutoRest.CSharp.V3.Pipeline
writer.Line(");");
}
private static void WriteSerializeSchemaTypeReference(CodeWriter writer, SchemaTypeReference type, TypeFactory typeFactory, string name)
private static void WriteSerializeSchemaTypeReference(CodeWriter writer, SchemaTypeReference type, TypeFactory typeFactory, CodeWriterDelegate name)
{
switch (typeFactory.ResolveReference(type))
{
@ -161,33 +111,25 @@ namespace AutoRest.CSharp.V3.Pipeline
}
}
private static void WriteSerializeBinaryTypeReference(CodeWriter writer, string name)
private static void WriteSerializeBinaryTypeReference(CodeWriter writer, CodeWriterDelegate name)
{
writer.Append("writer.WriteBase64StringValue(");
writer.Append(name);
writer.Line(");");
}
private static void WriteSerializeDefault(CodeWriter writer, ClientTypeReference type, SerializationFormat format, TypeFactory typeFactory, string name)
private static void WriteSerializeDefault(CodeWriter writer, ClientTypeReference type, SerializationFormat format, TypeFactory typeFactory, CodeWriterDelegate name)
{
var frameworkType = typeFactory.CreateType(type)?.FrameworkType ?? typeof(void);
writer.Line(TypeSerializers[frameworkType](name, type.IsNullable, format) ?? "writer.WriteNullValue();");
writer.Line(TypeSerializers[frameworkType](CodeWriter.Materialize(name), type.IsNullable, format) ?? "writer.WriteNullValue();");
}
public static void ToSerializeCall(this CodeWriter writer, ClientTypeReference type, SerializationFormat format, TypeFactory typeFactory, string name, string serializedName, bool includePropertyName = true, bool quoteSerializedName = true)
public static void ToSerializeCall(this CodeWriter writer, ClientTypeReference type, SerializationFormat format, TypeFactory typeFactory, CodeWriterDelegate name, CodeWriterDelegate? serializedName = null)
{
if (includePropertyName)
if (serializedName != null)
{
writer.Append("writer.WritePropertyName(");
if (quoteSerializedName)
{
writer.Append("\"");
}
writer.Append(serializedName);
if (quoteSerializedName)
{
writer.Append("\"");
}
writer.Line(");");
}
@ -205,7 +147,7 @@ namespace AutoRest.CSharp.V3.Pipeline
}
}
private static void WriteDeserializeClientObject(CodeWriter writer, CSharpType cSharpType, string name)
private static void WriteDeserializeClientObject(CodeWriter writer, CSharpType cSharpType, CodeWriterDelegate name)
{
writer.AppendType(cSharpType)
.Append("Serializer.Deserialize(")
@ -213,7 +155,7 @@ namespace AutoRest.CSharp.V3.Pipeline
.Append(")");
}
private static void WriteDeserializeClientEnum(CodeWriter writer, CSharpType cSharpType, string name, bool isStringBased)
private static void WriteDeserializeClientEnum(CodeWriter writer, CSharpType cSharpType, CodeWriterDelegate name, bool isStringBased)
{
if (isStringBased)
{
@ -231,7 +173,7 @@ namespace AutoRest.CSharp.V3.Pipeline
writer.Append("()");
}
private static void WriteDeserializeSchemaTypeReference(CodeWriter writer, CSharpType cSharpType, SchemaTypeReference type, TypeFactory typeFactory, string name)
private static void WriteDeserializeSchemaTypeReference(CodeWriter writer, CSharpType cSharpType, SchemaTypeReference type, TypeFactory typeFactory, CodeWriterDelegate name)
{
switch (typeFactory.ResolveReference(type))
{
@ -247,19 +189,19 @@ namespace AutoRest.CSharp.V3.Pipeline
}
}
private static void WriteDeserializeBinaryTypeReference(CodeWriter writer, string name)
private static void WriteDeserializeBinaryTypeReference(CodeWriter writer, CodeWriterDelegate name)
{
writer.Append(name);
writer.Append(".GetBytesFromBase64()");
}
private static void WriteDeserializeDefault(CodeWriter writer, CSharpType cSharpType, SerializationFormat format, string name)
private static void WriteDeserializeDefault(CodeWriter writer, CSharpType cSharpType, SerializationFormat format, CodeWriterDelegate name)
{
var frameworkType = cSharpType?.FrameworkType ?? typeof(void);
writer.Append(TypeDeserializers[frameworkType](name, format) ?? "null");
writer.Append(TypeDeserializers[frameworkType](CodeWriter.Materialize(name), format) ?? "null");
}
public static void ToDeserializeCall(this CodeWriter writer, ClientTypeReference type, SerializationFormat format, TypeFactory typeFactory, string name, string typeText, string typeName)
public static void ToDeserializeCall(this CodeWriter writer, ClientTypeReference type, SerializationFormat format, TypeFactory typeFactory, CodeWriterDelegate name)
{
CSharpType cSharpType = typeFactory.CreateType(type).WithNullable(false);
switch (type)
@ -275,11 +217,5 @@ namespace AutoRest.CSharp.V3.Pipeline
return;
}
}
public static string ToValueString(this ClientConstant schema)
{
var value = schema.Value;
return $"{((value is string || value == null) ? $"\"{value}\"" : value)}";
}
}
}

Просмотреть файл

@ -5,7 +5,6 @@ using System;
using System.Linq;
using System.Text.Json;
using AutoRest.CSharp.V3.ClientModels;
using AutoRest.CSharp.V3.Pipeline;
using AutoRest.CSharp.V3.Plugins;
using AutoRest.CSharp.V3.Utilities;
@ -40,7 +39,7 @@ namespace AutoRest.CSharp.V3.CodeGen
writer.Line($"writer.WriteStartArray(\"{serializedName}\");");
using (writer.ForEach($"var item in {name}"))
{
writer.ToSerializeCall(array.ItemType, format, _typeFactory, "item", serializedName, false);
writer.ToSerializeCall(array.ItemType, format, _typeFactory, w => w.Append("item"));
}
writer.Line("writer.WriteEndArray();");
@ -52,14 +51,14 @@ namespace AutoRest.CSharp.V3.CodeGen
writer.Line($"writer.WriteStartObject(\"{serializedName}\");");
using (writer.ForEach($"var item in {name}"))
{
writer.ToSerializeCall(dictionary.ValueType, format, _typeFactory, "item.Value", "item.Key", true, false);
writer.ToSerializeCall(dictionary.ValueType, format, _typeFactory, w => w.Append("item.Value"), w => w.Append("item.Key"));
}
writer.Line("writer.WriteEndObject();");
return;
}
writer.ToSerializeCall(type, format, _typeFactory, name, serializedName);
writer.ToSerializeCall(type, format, _typeFactory, w => w.Append(name), w => w.Literal(serializedName));
}
private void ReadProperty(CodeWriter writer, ClientObjectProperty property)
@ -87,11 +86,8 @@ namespace AutoRest.CSharp.V3.CodeGen
using (writer.ForEach("var item in property.Value.EnumerateArray()"))
{
var elementType = _typeFactory.CreateType(array.ItemType);
var elementTypeName = elementType.Name;
var elementTypeText = writer.Type(elementType);
writer.Append($"result.{name}.Add(");
writer.ToDeserializeCall(array.ItemType, format, _typeFactory, "item", elementTypeText, elementTypeName);
writer.ToDeserializeCall(array.ItemType, format, _typeFactory, w => w.Append("item"));
writer.Line(");");
}
return;
@ -102,23 +98,19 @@ namespace AutoRest.CSharp.V3.CodeGen
using (writer.ForEach("var item in property.Value.EnumerateObject()"))
{
var elementType = _typeFactory.CreateType(dictionary.ValueType);
var elementTypeName = elementType.Name;
var elementTypeText = writer.Type(elementType);
writer.Append($"result.{name}.Add(item.Name, ");
writer.ToDeserializeCall(dictionary.ValueType, format, _typeFactory, "item.Value", elementTypeText, elementTypeName);
writer.ToDeserializeCall(dictionary.ValueType, format, _typeFactory, w => w.Append("item.Value"));
writer.Line(");");
}
return;
}
var t = writer.Type(propertyType);
if (propertyType.IsNullable)
{
WriteNullCheck(writer);
}
writer.Append($"result.{name} = ");
writer.ToDeserializeCall(type, format, _typeFactory, "property.Value", t, t);
writer.ToDeserializeCall(type, format, _typeFactory, w => w.Append("property.Value"));
writer.Line(";");
}
@ -156,7 +148,7 @@ namespace AutoRest.CSharp.V3.CodeGen
var type = _typeFactory.CreateType(implementation.Type);
var localName = type.Name.ToVariableName();
writer.Append("case ").AppendType(type).Space().Append(localName).Append(":").Line();
writer.ToSerializeCall(implementation.Type, SerializationFormat.Default, _typeFactory, localName, "", includePropertyName: false);
writer.ToSerializeCall(implementation.Type, SerializationFormat.Default, _typeFactory, w => w.Append(localName));
writer.Line("return;");
}
}
@ -201,13 +193,11 @@ namespace AutoRest.CSharp.V3.CodeGen
{
foreach (var implementation in model.Discriminator.Implementations)
{
var type = _typeFactory.CreateType(implementation.Type);
writer
.Append("case ")
.Literal(implementation.Key)
.Append(": return ")
.ToDeserializeCall(implementation.Type, SerializationFormat.Default, _typeFactory, "element", writer.Type(type), "");
.ToDeserializeCall(implementation.Type, SerializationFormat.Default, _typeFactory, w => w.Append("element"));
writer.SemicolonLine();
}
}

Просмотреть файл

@ -0,0 +1,51 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Text.Json;
using System.Threading.Tasks;
using AutoRest.TestServer.Tests.Infrastructure;
using body_boolean;
using NUnit.Framework;
namespace AutoRest.TestServer.Tests
{
public class BooleanTests : TestServerTestBase
{
public BooleanTests(TestServerVersion version) : base(version, "bool") { }
[Test]
public Task GetBoolFalse() => Test(async (host, pipeline) =>
{
var result = await BoolOperations.GetFalseAsync(ClientDiagnostics, pipeline, host);
Assert.False(result.Value);
});
[Test]
public Task GetBoolInvalid() => Test((host, pipeline) =>
{
Assert.ThrowsAsync(Is.InstanceOf<JsonException>(), async () => await BoolOperations.GetInvalidAsync(ClientDiagnostics, pipeline, host));
});
[Test]
[Ignore("Nullable return types are not implemented")]
public Task GetBoolNull() => Test(async (host, pipeline) =>
{
var result = await BoolOperations.GetNullAsync(ClientDiagnostics, pipeline, host);
Assert.False(result.Value);
});
[Test]
public Task GetBoolTrue() => Test(async (host, pipeline) =>
{
var result = await BoolOperations.GetTrueAsync(ClientDiagnostics, pipeline, host);
Assert.True(result.Value);
});
[Test]
public Task PutBoolFalse() => TestStatus(async (host, pipeline) => await BoolOperations.PutFalseAsync(ClientDiagnostics, pipeline, host));
[Test]
public Task PutBoolTrue() => TestStatus(async (host, pipeline) => await BoolOperations.PutTrueAsync(ClientDiagnostics, pipeline, host));
}
}

Просмотреть файл

@ -45,7 +45,6 @@ namespace AutoRest.TestServer.Tests
});
[Test]
[Ignore("Unit time in json not implemented")]
public Task GetUnixTime() => TestStatus(async (host, pipeline) =>
{
var response = await IntOperations.GetUnixTimeAsync(ClientDiagnostics, pipeline, host);
@ -92,7 +91,7 @@ namespace AutoRest.TestServer.Tests
public Task PutLongMin() => TestStatus(async (host, pipeline) => await IntOperations.PutMin64Async(ClientDiagnostics, pipeline, long.MinValue, host));
[Test]
[Ignore("Unit time in json not implemented")]
[IgnoreOnTestServer(TestServerVersion.V2, "No match")]
public Task PutUnixTime() => TestStatus(async (host, pipeline) => await IntOperations.PutUnixTimeDateAsync(ClientDiagnostics, pipeline, DateTimeOffset.FromUnixTimeSeconds(1460505600), host));
}
}

Просмотреть файл

@ -0,0 +1,52 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Text.Json;
namespace body_boolean.Models.V100
{
public partial class ErrorSerializer
{
internal static void Serialize(Error model, Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (model.Status != null)
{
writer.WritePropertyName("status");
writer.WriteNumberValue(model.Status.Value);
}
if (model.Message != null)
{
writer.WritePropertyName("message");
writer.WriteStringValue(model.Message);
}
writer.WriteEndObject();
}
internal static Error Deserialize(JsonElement element)
{
var result = new Error();
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("status"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
result.Status = property.Value.GetInt32();
continue;
}
if (property.NameEquals("message"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
result.Message = property.Value.GetString();
continue;
}
}
return result;
}
}
}

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace body_boolean.Models.V100
{
public partial class Error
{
public int? Status { get; set; }
public string? Message { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,223 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
namespace body_boolean
{
internal static class BoolOperations
{
public static async ValueTask<Response<bool>> GetTrueAsync(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string host = "http://localhost:3000", CancellationToken cancellationToken = default)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
using var scope = clientDiagnostics.CreateScope("body_boolean.GetTrue");
scope.Start();
try
{
var request = pipeline.CreateRequest();
request.Method = RequestMethod.Get;
request.Uri.Reset(new Uri($"{host}"));
request.Uri.AppendPath("/bool/true", false);
var response = await pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
switch (response.Status)
{
case 200:
{
using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false);
var value = document.RootElement.GetBoolean();
return Response.FromValue(value, response);
}
default:
throw new Exception();
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
public static async ValueTask<Response> PutTrueAsync(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string host = "http://localhost:3000", CancellationToken cancellationToken = default)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
using var scope = clientDiagnostics.CreateScope("body_boolean.PutTrue");
scope.Start();
try
{
var request = pipeline.CreateRequest();
request.Method = RequestMethod.Put;
request.Uri.Reset(new Uri($"{host}"));
request.Uri.AppendPath("/bool/true", false);
request.Headers.Add("Content-Type", "application/json");
using var content = new Utf8JsonRequestContent();
var writer = content.JsonWriter;
writer.WriteBooleanValue(true);
request.Content = content;
var response = await pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
switch (response.Status)
{
case 200:
return response;
default:
throw new Exception();
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
public static async ValueTask<Response<bool>> GetFalseAsync(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string host = "http://localhost:3000", CancellationToken cancellationToken = default)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
using var scope = clientDiagnostics.CreateScope("body_boolean.GetFalse");
scope.Start();
try
{
var request = pipeline.CreateRequest();
request.Method = RequestMethod.Get;
request.Uri.Reset(new Uri($"{host}"));
request.Uri.AppendPath("/bool/false", false);
var response = await pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
switch (response.Status)
{
case 200:
{
using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false);
var value = document.RootElement.GetBoolean();
return Response.FromValue(value, response);
}
default:
throw new Exception();
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
public static async ValueTask<Response> PutFalseAsync(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string host = "http://localhost:3000", CancellationToken cancellationToken = default)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
using var scope = clientDiagnostics.CreateScope("body_boolean.PutFalse");
scope.Start();
try
{
var request = pipeline.CreateRequest();
request.Method = RequestMethod.Put;
request.Uri.Reset(new Uri($"{host}"));
request.Uri.AppendPath("/bool/false", false);
request.Headers.Add("Content-Type", "application/json");
using var content = new Utf8JsonRequestContent();
var writer = content.JsonWriter;
writer.WriteBooleanValue(false);
request.Content = content;
var response = await pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
switch (response.Status)
{
case 200:
return response;
default:
throw new Exception();
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
public static async ValueTask<Response<bool>> GetNullAsync(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string host = "http://localhost:3000", CancellationToken cancellationToken = default)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
using var scope = clientDiagnostics.CreateScope("body_boolean.GetNull");
scope.Start();
try
{
var request = pipeline.CreateRequest();
request.Method = RequestMethod.Get;
request.Uri.Reset(new Uri($"{host}"));
request.Uri.AppendPath("/bool/null", false);
var response = await pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
switch (response.Status)
{
case 200:
{
using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false);
var value = document.RootElement.GetBoolean();
return Response.FromValue(value, response);
}
default:
throw new Exception();
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
public static async ValueTask<Response<bool>> GetInvalidAsync(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string host = "http://localhost:3000", CancellationToken cancellationToken = default)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
using var scope = clientDiagnostics.CreateScope("body_boolean.GetInvalid");
scope.Start();
try
{
var request = pipeline.CreateRequest();
request.Method = RequestMethod.Get;
request.Uri.Reset(new Uri($"{host}"));
request.Uri.AppendPath("/bool/invalid", false);
var response = await pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
switch (response.Status)
{
case 200:
{
using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false);
var value = document.RootElement.GetBoolean();
return Response.FromValue(value, response);
}
default:
throw new Exception();
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}

Просмотреть файл

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Nullable>annotations</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Core" Version="1.0.0" />
<PackageReference Include="System.Text.Json" Version="4.6.0" />
</ItemGroup>
</Project>

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Text.Json;
namespace body_complex.Models.V20160229

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Text.Json;

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Text.Json;
namespace body_complex.Models.V20160229

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Text.Json;
namespace body_complex.Models.V20160229

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Text.Json;
namespace body_complex.Models.V20160229

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Text.Json;
namespace body_complex.Models.V20160229

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Text.Json;

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Text.Json;

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Text.Json;

Просмотреть файл

@ -512,7 +512,7 @@ namespace body_number
request.Headers.Add("Content-Type", "application/json");
using var content = new Utf8JsonRequestContent();
var writer = content.JsonWriter;
writer.WriteNumberValue(99999999.99);
writer.WriteNumberValue(99999999.99M);
request.Content = content;
var response = await pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
switch (response.Status)
@ -581,7 +581,7 @@ namespace body_number
request.Headers.Add("Content-Type", "application/json");
using var content = new Utf8JsonRequestContent();
var writer = content.JsonWriter;
writer.WriteNumberValue(-99999999.99);
writer.WriteNumberValue(-99999999.99M);
request.Content = content;
var response = await pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
switch (response.Status)