From dcb9da28de4399a557c9fe56c6730f9f067861ff Mon Sep 17 00:00:00 2001 From: Tim M <49349513+TimothyMakkison@users.noreply.github.com> Date: Fri, 14 Jun 2024 07:32:26 +0100 Subject: [PATCH] feat: run csharpier (#1715) Co-authored-by: Chris Pulman --- .../ITypeSymbolExtensions.cs | 1 - .../InterfaceStubGenerator.cs | 11 +- Refit.Benchmarks/EndToEndBenchmark.cs | 85 +- .../HttpClientFactoryExtensions.cs | 1 - .../NewtonsoftJsonContentSerializer.cs | 17 +- .../AuthenticatedClientHandlerTests.cs | 10 +- .../CamelCaseUrlParameterKeyFormatter.cs | 9 +- ...rSeparatedPropertyNamesContractResolver.cs | 6 +- Refit.Tests/ExceptionFactoryTests.cs | 15 +- Refit.Tests/FormValueMultimapTests.cs | 2 - Refit.Tests/GitHubApi.cs | 6 +- .../HttpClientFactoryExtensionsTests.cs | 11 +- Refit.Tests/IDefaultInterfaceMethodTests.cs | 2 - Refit.Tests/IFooWithOtherAttribute.cs | 1 - Refit.Tests/InheritedGenericInterfacesApi.cs | 1 - Refit.Tests/InheritedInterfacesApi.cs | 1 - .../InheritedInterfacesInSeparateFileApi.cs | 1 - Refit.Tests/IntegrationTestHelper.cs | 4 +- Refit.Tests/InterfaceStubGenerator.cs | 22 +- Refit.Tests/MultipartTests.cs | 55 +- Refit.Tests/NamespaceCollisionApi.cs | 2 +- Refit.Tests/NamespaceOverlapApi.cs | 2 +- Refit.Tests/RefitSettings.cs | 23 +- Refit.Tests/RequestBuilder.cs | 1785 +++++++++++++---- Refit.Tests/ResponseTests.cs | 61 +- Refit.Tests/RestService.cs | 156 +- Refit.Tests/SerializedContentTests.cs | 26 +- Refit.Tests/TypeCollisionApiA.cs | 2 - Refit.Tests/TypeCollisionApiB.cs | 2 - ...crementalSourceGeneratorVerifier`1+Test.cs | 1 - .../CSharpSourceGeneratorVerifier`1+Test.cs | 1 - Refit.Tests/Verifiers/CSharpVerifierHelper.cs | 1 - Refit.Tests/XmlContentSerializerTests.cs | 3 +- Refit/ApiException.cs | 11 +- Refit/ApiResponse.cs | 17 +- Refit/Attributes.cs | 1 - Refit/CamelCaseUrlParameterKeyFormatter.cs | 15 +- Refit/JsonContentSerializer.cs | 3 +- Refit/MultipartItem.cs | 10 +- Refit/PushStreamContent.cs | 3 +- Refit/RefitSettings.cs | 118 +- Refit/RequestBuilder.cs | 14 +- Refit/RequestBuilderImplementation.cs | 562 ++++-- Refit/RestMethodInfo.cs | 25 +- .../HttpClientDiagnosticsHandler.cs | 4 +- samples/Meow.Common/Services/CatsService.cs | 8 +- samples/Meow.Common/Services/ITheCatsAPI.cs | 6 +- samples/Meow/Program.cs | 8 +- 48 files changed, 2180 insertions(+), 951 deletions(-) diff --git a/InterfaceStubGenerator.Shared/ITypeSymbolExtensions.cs b/InterfaceStubGenerator.Shared/ITypeSymbolExtensions.cs index 2c48c5ce0..8ef02f60b 100644 --- a/InterfaceStubGenerator.Shared/ITypeSymbolExtensions.cs +++ b/InterfaceStubGenerator.Shared/ITypeSymbolExtensions.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; - using Microsoft.CodeAnalysis; namespace Refit.Generator diff --git a/InterfaceStubGenerator.Shared/InterfaceStubGenerator.cs b/InterfaceStubGenerator.Shared/InterfaceStubGenerator.cs index 185ec6cfd..ba2aab388 100644 --- a/InterfaceStubGenerator.Shared/InterfaceStubGenerator.cs +++ b/InterfaceStubGenerator.Shared/InterfaceStubGenerator.cs @@ -3,7 +3,6 @@ using System.Collections.Immutable; using System.Linq; using System.Text; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -171,8 +170,8 @@ ImmutableArray candidateInterfaces continue; // The interface has no refit methods, but its base interfaces might - var hasDerivedRefit = ifaceSymbol.AllInterfaces - .SelectMany(i => i.GetMembers().OfType()) + var hasDerivedRefit = ifaceSymbol + .AllInterfaces.SelectMany(i => i.GetMembers().OfType()) .Any(m => IsRefitMethod(m, httpMethodBaseAttributeSymbol)); if (hasDerivedRefit) @@ -292,7 +291,7 @@ public static void Initialize() var keyName = group.Key.Name; int value; - while(keyCount.TryGetValue(keyName, out value)) + while (keyCount.TryGetValue(keyName, out value)) { keyName = $"{keyName}{++value}"; } @@ -398,8 +397,8 @@ partial class {ns}{classDeclaration} .ToList(); // get methods for all inherited - var derivedMethods = interfaceSymbol.AllInterfaces - .SelectMany(i => i.GetMembers().OfType()) + var derivedMethods = interfaceSymbol + .AllInterfaces.SelectMany(i => i.GetMembers().OfType()) .ToList(); // Look for disposable diff --git a/Refit.Benchmarks/EndToEndBenchmark.cs b/Refit.Benchmarks/EndToEndBenchmark.cs index f925c0639..792f6912f 100644 --- a/Refit.Benchmarks/EndToEndBenchmark.cs +++ b/Refit.Benchmarks/EndToEndBenchmark.cs @@ -1,5 +1,4 @@ using System.Net; - using AutoFixture; using BenchmarkDotNet.Attributes; @@ -142,9 +141,9 @@ public async Task Task_Async() await refitClient[Serializer][HttpStatusCode].GetUsersTaskAsync(); break; case HttpVerb.Post: - await refitClient[Serializer][HttpStatusCode].PostUsersTaskAsync( - users[ModelCount] - ); + await refitClient[Serializer] + [HttpStatusCode] + .PostUsersTaskAsync(users[ModelCount]); break; default: throw new ArgumentOutOfRangeException(nameof(Verb)); @@ -164,13 +163,13 @@ public async Task TaskString_Async() switch (Verb) { case HttpVerb.Get: - return await refitClient[Serializer][ - HttpStatusCode - ].GetUsersTaskStringAsync(); + return await refitClient[Serializer] + [HttpStatusCode] + .GetUsersTaskStringAsync(); case HttpVerb.Post: - return await refitClient[Serializer][ - HttpStatusCode - ].PostUsersTaskStringAsync(users[ModelCount]); + return await refitClient[Serializer] + [HttpStatusCode] + .PostUsersTaskStringAsync(users[ModelCount]); default: throw new ArgumentOutOfRangeException(nameof(Verb)); } @@ -191,13 +190,13 @@ public async Task TaskStream_Async() switch (Verb) { case HttpVerb.Get: - return await refitClient[Serializer][ - HttpStatusCode - ].GetUsersTaskStreamAsync(); + return await refitClient[Serializer] + [HttpStatusCode] + .GetUsersTaskStreamAsync(); case HttpVerb.Post: - return await refitClient[Serializer][ - HttpStatusCode - ].PostUsersTaskStreamAsync(users[ModelCount]); + return await refitClient[Serializer] + [HttpStatusCode] + .PostUsersTaskStreamAsync(users[ModelCount]); default: throw new ArgumentOutOfRangeException(nameof(Verb)); } @@ -218,13 +217,13 @@ public async Task TaskHttpContent_Async() switch (Verb) { case HttpVerb.Get: - return await refitClient[Serializer][ - HttpStatusCode - ].GetUsersTaskHttpContentAsync(); + return await refitClient[Serializer] + [HttpStatusCode] + .GetUsersTaskHttpContentAsync(); case HttpVerb.Post: - return await refitClient[Serializer][ - HttpStatusCode - ].PostUsersTaskHttpContentAsync(users[ModelCount]); + return await refitClient[Serializer] + [HttpStatusCode] + .PostUsersTaskHttpContentAsync(users[ModelCount]); default: throw new ArgumentOutOfRangeException(nameof(Verb)); } @@ -243,13 +242,13 @@ public async Task TaskHttpResponseMessage_Async() switch (Verb) { case HttpVerb.Get: - return await refitClient[Serializer][ - HttpStatusCode - ].GetUsersTaskHttpResponseMessageAsync(); + return await refitClient[Serializer] + [HttpStatusCode] + .GetUsersTaskHttpResponseMessageAsync(); case HttpVerb.Post: - return await refitClient[Serializer][ - HttpStatusCode - ].PostUsersTaskHttpResponseMessageAsync(users[ModelCount]); + return await refitClient[Serializer] + [HttpStatusCode] + .PostUsersTaskHttpResponseMessageAsync(users[ModelCount]); default: throw new ArgumentOutOfRangeException(nameof(Verb)); } @@ -261,13 +260,13 @@ public IObservable ObservableHttpResponseMessage() switch (Verb) { case HttpVerb.Get: - return refitClient[Serializer][ - HttpStatusCode - ].GetUsersObservableHttpResponseMessage(); + return refitClient[Serializer] + [HttpStatusCode] + .GetUsersObservableHttpResponseMessage(); case HttpVerb.Post: - return refitClient[Serializer][ - HttpStatusCode - ].PostUsersObservableHttpResponseMessage(users[ModelCount]); + return refitClient[Serializer] + [HttpStatusCode] + .PostUsersObservableHttpResponseMessage(users[ModelCount]); default: throw new ArgumentOutOfRangeException(nameof(Verb)); } @@ -283,9 +282,9 @@ public async Task> TaskT_Async() case HttpVerb.Get: return await refitClient[Serializer][HttpStatusCode].GetUsersTaskTAsync(); case HttpVerb.Post: - return await refitClient[Serializer][HttpStatusCode].PostUsersTaskTAsync( - users[ModelCount] - ); + return await refitClient[Serializer] + [HttpStatusCode] + .PostUsersTaskTAsync(users[ModelCount]); default: throw new ArgumentOutOfRangeException(nameof(Verb)); } @@ -304,13 +303,13 @@ public async Task>> TaskApiResponseT_Async() switch (Verb) { case HttpVerb.Get: - return await refitClient[Serializer][ - HttpStatusCode - ].GetUsersTaskApiResponseTAsync(); + return await refitClient[Serializer] + [HttpStatusCode] + .GetUsersTaskApiResponseTAsync(); case HttpVerb.Post: - return await refitClient[Serializer][ - HttpStatusCode - ].PostUsersTaskApiResponseTAsync(users[ModelCount]); + return await refitClient[Serializer] + [HttpStatusCode] + .PostUsersTaskApiResponseTAsync(users[ModelCount]); default: throw new ArgumentOutOfRangeException(nameof(Verb)); } diff --git a/Refit.HttpClientFactory/HttpClientFactoryExtensions.cs b/Refit.HttpClientFactory/HttpClientFactoryExtensions.cs index 27f5a0f72..0ea65b1a7 100644 --- a/Refit.HttpClientFactory/HttpClientFactoryExtensions.cs +++ b/Refit.HttpClientFactory/HttpClientFactoryExtensions.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Net.Http; using System.Reflection; - using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Http; diff --git a/Refit.Newtonsoft.Json/NewtonsoftJsonContentSerializer.cs b/Refit.Newtonsoft.Json/NewtonsoftJsonContentSerializer.cs index 05d9b7ff7..925704bac 100644 --- a/Refit.Newtonsoft.Json/NewtonsoftJsonContentSerializer.cs +++ b/Refit.Newtonsoft.Json/NewtonsoftJsonContentSerializer.cs @@ -1,7 +1,6 @@ using System.Net.Http; using System.Reflection; using System.Text; - using Newtonsoft.Json; namespace Refit @@ -13,12 +12,15 @@ namespace Refit /// Creates a new instance with the specified parameters /// /// The serialization settings to use for the current instance - public sealed class NewtonsoftJsonContentSerializer(JsonSerializerSettings? jsonSerializerSettings) : IHttpContentSerializer + public sealed class NewtonsoftJsonContentSerializer( + JsonSerializerSettings? jsonSerializerSettings + ) : IHttpContentSerializer { /// /// The instance providing the JSON serialization settings to use /// - readonly Lazy jsonSerializerSettings = new( + readonly Lazy jsonSerializerSettings = + new( () => jsonSerializerSettings ?? JsonConvert.DefaultSettings?.Invoke() @@ -78,10 +80,11 @@ public HttpContent ToHttpContent(T item) return propertyInfo switch { null => throw new ArgumentNullException(nameof(propertyInfo)), - _ => propertyInfo - .GetCustomAttributes(true) - .Select(a => a.PropertyName) - .FirstOrDefault() + _ + => propertyInfo + .GetCustomAttributes(true) + .Select(a => a.PropertyName) + .FirstOrDefault() }; } } diff --git a/Refit.Tests/AuthenticatedClientHandlerTests.cs b/Refit.Tests/AuthenticatedClientHandlerTests.cs index 33969a040..7dce85749 100644 --- a/Refit.Tests/AuthenticatedClientHandlerTests.cs +++ b/Refit.Tests/AuthenticatedClientHandlerTests.cs @@ -4,9 +4,8 @@ using System.Net.Http; using System.Text; using System.Threading.Tasks; -using RichardSzalay.MockHttp; - using Refit; // for the code gen +using RichardSzalay.MockHttp; using Xunit; namespace Refit.Tests; @@ -44,8 +43,7 @@ [HeaderCollection] IDictionary headers ); } - public interface IInheritedAuthenticatedServiceWithHeaders - : IAuthenticatedServiceWithHeaders + public interface IInheritedAuthenticatedServiceWithHeaders : IAuthenticatedServiceWithHeaders { [Get("/get-inherited-thing")] Task GetInheritedThing(); @@ -61,9 +59,7 @@ public interface IAuthenticatedServiceWithHeaders [Fact] public void DefaultHandlerIsHttpClientHandler() { - var handler = new AuthenticatedHttpClientHandler( - ((_, _) => Task.FromResult(string.Empty)) - ); + var handler = new AuthenticatedHttpClientHandler(((_, _) => Task.FromResult(string.Empty))); Assert.IsType(handler.InnerHandler); } diff --git a/Refit.Tests/CamelCaseUrlParameterKeyFormatter.cs b/Refit.Tests/CamelCaseUrlParameterKeyFormatter.cs index 64997411c..210909068 100644 --- a/Refit.Tests/CamelCaseUrlParameterKeyFormatter.cs +++ b/Refit.Tests/CamelCaseUrlParameterKeyFormatter.cs @@ -24,9 +24,14 @@ public void FormatKey_Returns_ExpectedValue() { var urlParameterKeyFormatter = new CamelCaseUrlParameterKeyFormatter(); - var refitSettings = new RefitSettings { UrlParameterKeyFormatter = urlParameterKeyFormatter }; + var refitSettings = new RefitSettings + { + UrlParameterKeyFormatter = urlParameterKeyFormatter + }; var fixture = new RequestBuilderImplementation(refitSettings); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary) + ); var complexQuery = new CamelCaselTestsRequest { diff --git a/Refit.Tests/DeliminatorSeparatedPropertyNamesContractResolver.cs b/Refit.Tests/DeliminatorSeparatedPropertyNamesContractResolver.cs index 3df2387d3..b90277c4b 100644 --- a/Refit.Tests/DeliminatorSeparatedPropertyNamesContractResolver.cs +++ b/Refit.Tests/DeliminatorSeparatedPropertyNamesContractResolver.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; -using System.Text; -using System; +using System; +using System.Collections.Generic; using System.Globalization; +using System.Text; using Newtonsoft.Json.Serialization; namespace Refit.Tests; diff --git a/Refit.Tests/ExceptionFactoryTests.cs b/Refit.Tests/ExceptionFactoryTests.cs index ea2bba891..d795b9c82 100644 --- a/Refit.Tests/ExceptionFactoryTests.cs +++ b/Refit.Tests/ExceptionFactoryTests.cs @@ -2,11 +2,8 @@ using System.Net; using System.Net.Http; using System.Threading.Tasks; - using Refit; // for the code gen - using RichardSzalay.MockHttp; - using Xunit; namespace Refit.Tests; @@ -83,9 +80,7 @@ public async Task ProvideFactoryWhichAlwaysReturnsException_WithResult() var fixture = RestService.For("http://api", settings); - var thrownException = await Assert.ThrowsAsync( - () => fixture.GetWithResult() - ); + var thrownException = await Assert.ThrowsAsync(() => fixture.GetWithResult()); Assert.Equal(exception, thrownException); handler.VerifyNoOutstandingExpectation(); @@ -102,15 +97,11 @@ public async Task ProvideFactoryWhichAlwaysReturnsException_WithoutResult() ExceptionFactory = _ => Task.FromResult(exception) }; - handler - .Expect(HttpMethod.Put, "http://api/put-without-result") - .Respond(HttpStatusCode.OK); + handler.Expect(HttpMethod.Put, "http://api/put-without-result").Respond(HttpStatusCode.OK); var fixture = RestService.For("http://api", settings); - var thrownException = await Assert.ThrowsAsync( - () => fixture.PutWithoutResult() - ); + var thrownException = await Assert.ThrowsAsync(() => fixture.PutWithoutResult()); Assert.Equal(exception, thrownException); handler.VerifyNoOutstandingExpectation(); diff --git a/Refit.Tests/FormValueMultimapTests.cs b/Refit.Tests/FormValueMultimapTests.cs index 30ead5998..47742ea07 100644 --- a/Refit.Tests/FormValueMultimapTests.cs +++ b/Refit.Tests/FormValueMultimapTests.cs @@ -2,9 +2,7 @@ using System.Linq; using System.Runtime.Serialization; using System.Text.Json.Serialization; - using Newtonsoft.Json; - using Xunit; namespace Refit.Tests; diff --git a/Refit.Tests/GitHubApi.cs b/Refit.Tests/GitHubApi.cs index 2b739c157..ce9bb87e6 100644 --- a/Refit.Tests/GitHubApi.cs +++ b/Refit.Tests/GitHubApi.cs @@ -6,7 +6,6 @@ using System.Threading; using System.Threading.Tasks; using Refit; // InterfaceStubGenerator looks for this - using static System.Math; // This is here to verify https://github.com/reactiveui/refit/issues/283 namespace Refit.Tests; @@ -64,10 +63,7 @@ public interface IGitHubApi IObservable GetUserCamelCase(string userName); [Get("/orgs/{orgname}/members")] - Task> GetOrgMembers( - string orgName, - CancellationToken cancellationToken = default - ); + Task> GetOrgMembers(string orgName, CancellationToken cancellationToken = default); [Get("/search/users")] Task FindUsers(string q); diff --git a/Refit.Tests/HttpClientFactoryExtensionsTests.cs b/Refit.Tests/HttpClientFactoryExtensionsTests.cs index 9dc666e5d..87a73698c 100644 --- a/Refit.Tests/HttpClientFactoryExtensionsTests.cs +++ b/Refit.Tests/HttpClientFactoryExtensionsTests.cs @@ -2,9 +2,8 @@ namespace Refit.Tests; -using Microsoft.Extensions.DependencyInjection; - using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; using Xunit; public class HttpClientFactoryExtensionsTests @@ -124,9 +123,7 @@ public void HttpClientSettingsAreInjectableGivenTypeArgument() [Fact] public void HttpClientSettingsCanBeProvidedStaticallyGivenGenericArgument() { - var contentSerializer = new SystemTextJsonContentSerializer( - new JsonSerializerOptions() - ); + var contentSerializer = new SystemTextJsonContentSerializer(new JsonSerializerOptions()); var serviceCollection = new ServiceCollection(); serviceCollection.AddRefitClient( new RefitSettings() { ContentSerializer = contentSerializer } @@ -143,9 +140,7 @@ public void HttpClientSettingsCanBeProvidedStaticallyGivenGenericArgument() [Fact] public void HttpClientSettingsCanBeProvidedStaticallyGivenTypeArgument() { - var contentSerializer = new SystemTextJsonContentSerializer( - new JsonSerializerOptions() - ); + var contentSerializer = new SystemTextJsonContentSerializer(new JsonSerializerOptions()); var serviceCollection = new ServiceCollection(); serviceCollection.AddRefitClient( new RefitSettings() { ContentSerializer = contentSerializer } diff --git a/Refit.Tests/IDefaultInterfaceMethodTests.cs b/Refit.Tests/IDefaultInterfaceMethodTests.cs index 1112d53e2..5dde0c4e7 100644 --- a/Refit.Tests/IDefaultInterfaceMethodTests.cs +++ b/Refit.Tests/IDefaultInterfaceMethodTests.cs @@ -5,9 +5,7 @@ using System.Net.Http; using System.Text; using System.Threading.Tasks; - using RichardSzalay.MockHttp; - using Xunit; namespace Refit.Tests; diff --git a/Refit.Tests/IFooWithOtherAttribute.cs b/Refit.Tests/IFooWithOtherAttribute.cs index 9592c7ba1..ec13b4cda 100644 --- a/Refit.Tests/IFooWithOtherAttribute.cs +++ b/Refit.Tests/IFooWithOtherAttribute.cs @@ -1,6 +1,5 @@ using System.ComponentModel; using System.Threading.Tasks; - using Refit; interface IFooWithOtherAttribute diff --git a/Refit.Tests/InheritedGenericInterfacesApi.cs b/Refit.Tests/InheritedGenericInterfacesApi.cs index 5aea963df..bc222163c 100644 --- a/Refit.Tests/InheritedGenericInterfacesApi.cs +++ b/Refit.Tests/InheritedGenericInterfacesApi.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json; - using Refit; // InterfaceStubGenerator looks for this using static System.Math; // This is here to verify https://github.com/reactiveui/refit/issues/283 diff --git a/Refit.Tests/InheritedInterfacesApi.cs b/Refit.Tests/InheritedInterfacesApi.cs index 5aa5e590c..937e3bdc6 100644 --- a/Refit.Tests/InheritedInterfacesApi.cs +++ b/Refit.Tests/InheritedInterfacesApi.cs @@ -3,7 +3,6 @@ using System.Threading.Tasks; using Refit; // InterfaceStubGenerator looks for this using Refit.Tests.SeparateNamespaceWithModel; - using static System.Math; // This is here to verify https://github.com/reactiveui/refit/issues/283 namespace Refit.Tests diff --git a/Refit.Tests/InheritedInterfacesInSeparateFileApi.cs b/Refit.Tests/InheritedInterfacesInSeparateFileApi.cs index 1e3e95fea..0a8751ba0 100644 --- a/Refit.Tests/InheritedInterfacesInSeparateFileApi.cs +++ b/Refit.Tests/InheritedInterfacesInSeparateFileApi.cs @@ -1,5 +1,4 @@ using System.Threading.Tasks; - using Refit; // InterfaceStubGenerator looks for this namespace Refit.Tests.SeparateNamespace; diff --git a/Refit.Tests/IntegrationTestHelper.cs b/Refit.Tests/IntegrationTestHelper.cs index 9c7c751b7..e40568114 100644 --- a/Refit.Tests/IntegrationTestHelper.cs +++ b/Refit.Tests/IntegrationTestHelper.cs @@ -19,9 +19,7 @@ public static string GetPath(params string[] paths) return (new FileInfo(paths.Aggregate(ret, Path.Combine))).FullName; } - public static string GetIntegrationTestRootDirectory( - [CallerFilePath] string filePath = default - ) + public static string GetIntegrationTestRootDirectory([CallerFilePath] string filePath = default) { // XXX: This is an evil hack, but it's okay for a unit test // We can't use Assembly.Location because unit test runners love diff --git a/Refit.Tests/InterfaceStubGenerator.cs b/Refit.Tests/InterfaceStubGenerator.cs index 094c58ed8..9c77605e5 100644 --- a/Refit.Tests/InterfaceStubGenerator.cs +++ b/Refit.Tests/InterfaceStubGenerator.cs @@ -5,15 +5,11 @@ using System.Linq; using System.Reflection; using System.Threading.Tasks; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Testing; - using Refit.Generator; - using Xunit; - using Task = System.Threading.Tasks.Task; using VerifyCS = Refit.Tests.CSharpSourceGeneratorVerifier; using VerifyCSV2 = Refit.Tests.CSharpIncrementalSourceGeneratorVerifier; @@ -46,9 +42,7 @@ static InterfaceStubGeneratorTests() #if NET461 ReferenceAssemblies = ReferenceAssemblies .AddAssemblies(ImmutableArray.Create("System.Web")) - .AddPackages( - ImmutableArray.Create(new PackageIdentity("System.Net.Http", "4.3.4")) - ); + .AddPackages(ImmutableArray.Create(new PackageIdentity("System.Net.Http", "4.3.4"))); #endif } @@ -115,9 +109,7 @@ static CSharpCompilation CreateCompilation(params string[] sourceFiles) public async Task NoRefitInterfacesSmokeTest() { #if NET462 - var input = File.ReadAllText( - IntegrationTestHelper.GetPath("IInterfaceWithoutRefit.cs") - ); + var input = File.ReadAllText(IntegrationTestHelper.GetPath("IInterfaceWithoutRefit.cs")); #else var input = await File.ReadAllTextAsync( IntegrationTestHelper.GetPath("IInterfaceWithoutRefit.cs") @@ -1070,9 +1062,7 @@ public RefitTestsTestNestedINestedGitHubApi(global::System.Net.Http.HttpClient c public async Task GenerateInterfaceStubsWithoutNamespaceSmokeTest() { #if NET462 - var input = File.ReadAllText( - IntegrationTestHelper.GetPath("IServiceWithoutNamespace.cs") - ); + var input = File.ReadAllText(IntegrationTestHelper.GetPath("IServiceWithoutNamespace.cs")); #else var input = await File.ReadAllTextAsync( IntegrationTestHelper.GetPath("IServiceWithoutNamespace.cs") @@ -1249,11 +1239,7 @@ public IServiceWithoutNamespace(global::System.Net.Http.HttpClient client, globa { (typeof(InterfaceStubGeneratorV2), "PreserveAttribute.g.cs", output1), (typeof(InterfaceStubGeneratorV2), "Generated.g.cs", output1_5), - ( - typeof(InterfaceStubGeneratorV2), - "IServiceWithoutNamespace.g.cs", - output2 - ), + (typeof(InterfaceStubGeneratorV2), "IServiceWithoutNamespace.g.cs", output2), }, }, }.RunAsync(); diff --git a/Refit.Tests/MultipartTests.cs b/Refit.Tests/MultipartTests.cs index cb3638f3f..f5b668f6b 100644 --- a/Refit.Tests/MultipartTests.cs +++ b/Refit.Tests/MultipartTests.cs @@ -4,14 +4,14 @@ using System.Linq; using System.Net; using System.Net.Http; +using System.Net.Http.Headers; using System.Reflection; -using System.Threading.Tasks; -using Xunit; -using Refit; +using System.Text; using System.Threading; +using System.Threading.Tasks; using Newtonsoft.Json; -using System.Text; -using System.Net.Http.Headers; +using Refit; +using Xunit; namespace Refit.Tests; @@ -60,10 +60,7 @@ Task UploadStringWithHeaderAndRequestProperty( [Multipart] [Post("/")] - Task UploadFileInfo( - IEnumerable fileInfos, - FileInfo anotherFile - ); + Task UploadFileInfo(IEnumerable fileInfos, FileInfo anotherFile); [Multipart] [Post("/")] @@ -366,10 +363,7 @@ public async Task MultipartUploadShouldWorkWithStreamPart() Assert.Single(parts); Assert.Equal("stream", parts[0].Headers.ContentDisposition.Name); - Assert.Equal( - "test-streampart.pdf", - parts[0].Headers.ContentDisposition.FileName - ); + Assert.Equal("test-streampart.pdf", parts[0].Headers.ContentDisposition.FileName); Assert.Equal("application/pdf", parts[0].Headers.ContentType.MediaType); using var str = await parts[0].ReadAsStreamAsync(); @@ -399,10 +393,7 @@ public async Task MultipartUploadShouldWorkWithStreamPartWithNamedMultipart() Assert.Single(parts); Assert.Equal("test-stream", parts[0].Headers.ContentDisposition.Name); - Assert.Equal( - "test-streampart.pdf", - parts[0].Headers.ContentDisposition.FileName - ); + Assert.Equal("test-streampart.pdf", parts[0].Headers.ContentDisposition.FileName); Assert.Equal("application/pdf", parts[0].Headers.ContentType.MediaType); using var str = await parts[0].ReadAsStreamAsync(); @@ -436,10 +427,7 @@ public async Task MultipartUploadShouldWorkWithStreamPartAndQuery() Assert.Single(parts); Assert.Equal("stream", parts[0].Headers.ContentDisposition.Name); - Assert.Equal( - "test-streampart.pdf", - parts[0].Headers.ContentDisposition.FileName - ); + Assert.Equal("test-streampart.pdf", parts[0].Headers.ContentDisposition.FileName); Assert.Equal("application/pdf", parts[0].Headers.ContentType.MediaType); using var str = await parts[0].ReadAsStreamAsync(); @@ -469,10 +457,7 @@ public async Task MultipartUploadShouldWorkWithByteArrayPart() Assert.Single(parts); - Assert.Equal( - "ByteArrayPartParamAlias", - parts[0].Headers.ContentDisposition.Name - ); + Assert.Equal("ByteArrayPartParamAlias", parts[0].Headers.ContentDisposition.Name); Assert.Equal( "test-bytearraypart.pdf", parts[0].Headers.ContentDisposition.FileName @@ -511,10 +496,7 @@ public async Task MultipartUploadShouldWorkWithFileInfoPart() Assert.Equal(3, parts.Count); Assert.Equal("fileInfos", parts[0].Headers.ContentDisposition.Name); - Assert.Equal( - "test-fileinfopart.pdf", - parts[0].Headers.ContentDisposition.FileName - ); + Assert.Equal("test-fileinfopart.pdf", parts[0].Headers.ContentDisposition.FileName); Assert.Equal("application/pdf", parts[0].Headers.ContentType.MediaType); using (var str = await parts[0].ReadAsStreamAsync()) using (var src = GetTestFileStream("Test Files/Test.pdf")) @@ -535,10 +517,7 @@ public async Task MultipartUploadShouldWorkWithFileInfoPart() } Assert.Equal("anotherFile", parts[2].Headers.ContentDisposition.Name); - Assert.Equal( - "additionalfile.pdf", - parts[2].Headers.ContentDisposition.FileName - ); + Assert.Equal("additionalfile.pdf", parts[2].Headers.ContentDisposition.FileName); Assert.Equal("application/pdf", parts[2].Headers.ContentType.MediaType); using (var str = await parts[2].ReadAsStreamAsync()) using (var src = GetTestFileStream("Test Files/Test.pdf")) @@ -596,8 +575,7 @@ string mediaType ) { if ( - Activator.CreateInstance(contentSerializerType) - is not IHttpContentSerializer serializer + Activator.CreateInstance(contentSerializerType) is not IHttpContentSerializer serializer ) { throw new ArgumentException( @@ -646,8 +624,7 @@ string mediaType ) { if ( - Activator.CreateInstance(contentSerializerType) - is not IHttpContentSerializer serializer + Activator.CreateInstance(contentSerializerType) is not IHttpContentSerializer serializer ) { throw new ArgumentException( @@ -872,9 +849,7 @@ internal static Stream GetTestFileStream(string relativeFilePath) // get resource stream var fullName = assembly .GetManifestResourceNames() - .FirstOrDefault( - name => name.EndsWith(relativeName, StringComparison.InvariantCulture) - ); + .FirstOrDefault(name => name.EndsWith(relativeName, StringComparison.InvariantCulture)); if (fullName == null) { throw new Exception( diff --git a/Refit.Tests/NamespaceCollisionApi.cs b/Refit.Tests/NamespaceCollisionApi.cs index 9930a2ad7..95fce7c27 100644 --- a/Refit.Tests/NamespaceCollisionApi.cs +++ b/Refit.Tests/NamespaceCollisionApi.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; -using SomeType = CollisionA.SomeType; using CollisionB; using Refit; // InterfaceStubGenerator looks for this +using SomeType = CollisionA.SomeType; namespace Refit.Tests { diff --git a/Refit.Tests/NamespaceOverlapApi.cs b/Refit.Tests/NamespaceOverlapApi.cs index e09fc2ae6..296019019 100644 --- a/Refit.Tests/NamespaceOverlapApi.cs +++ b/Refit.Tests/NamespaceOverlapApi.cs @@ -1,9 +1,9 @@ using System; using System.Threading.Tasks; using Common.Helper; -using Refit.Tests.Common; // InterfaceStubGenerator looks for this using Refit; +using Refit.Tests.Common; namespace Refit.Tests { diff --git a/Refit.Tests/RefitSettings.cs b/Refit.Tests/RefitSettings.cs index 5e2dceaf5..0a79be7ec 100644 --- a/Refit.Tests/RefitSettings.cs +++ b/Refit.Tests/RefitSettings.cs @@ -18,13 +18,30 @@ public void Can_CreateRefitSettings_WithoutException() exception = Record.Exception(() => new RefitSettings(contentSerializer)); Assert.Null(exception); - exception = Record.Exception(() => new RefitSettings(contentSerializer, urlParameterFormatter)); + exception = Record.Exception( + () => new RefitSettings(contentSerializer, urlParameterFormatter) + ); Assert.Null(exception); - exception = Record.Exception(() => new RefitSettings(contentSerializer, urlParameterFormatter, formUrlEncodedParameterFormatter)); + exception = Record.Exception( + () => + new RefitSettings( + contentSerializer, + urlParameterFormatter, + formUrlEncodedParameterFormatter + ) + ); Assert.Null(exception); - exception = Record.Exception(() => new RefitSettings(contentSerializer, urlParameterFormatter, formUrlEncodedParameterFormatter, urlParameterKeyFormatter)); + exception = Record.Exception( + () => + new RefitSettings( + contentSerializer, + urlParameterFormatter, + formUrlEncodedParameterFormatter, + urlParameterKeyFormatter + ) + ); Assert.Null(exception); } } diff --git a/Refit.Tests/RequestBuilder.cs b/Refit.Tests/RequestBuilder.cs index b976584cd..074853af0 100644 --- a/Refit.Tests/RequestBuilder.cs +++ b/Refit.Tests/RequestBuilder.cs @@ -9,9 +9,7 @@ using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; - using Microsoft.AspNetCore.WebUtilities; - using Xunit; namespace Refit.Tests @@ -53,138 +51,289 @@ public interface IRestMethodInfoTests Task FetchAnImage(int width, int height); [Get("/foo/bar/{id}")] - IObservable FetchSomeStuffWithBody([AliasAs("id")] int anId, [Body] Dictionary theData); + IObservable FetchSomeStuffWithBody( + [AliasAs("id")] int anId, + [Body] Dictionary theData + ); [Post("/foo/bar/{id}")] - IObservable PostSomeUrlEncodedStuff([AliasAs("id")] int anId, [Body(BodySerializationMethod.UrlEncoded)] Dictionary theData); + IObservable PostSomeUrlEncodedStuff( + [AliasAs("id")] int anId, + [Body(BodySerializationMethod.UrlEncoded)] Dictionary theData + ); [Get("/foo/bar/{id}")] - IObservable FetchSomeStuffWithAuthorizationSchemeSpecified([AliasAs("id")] int anId, [Authorize("Bearer")] string token); + IObservable FetchSomeStuffWithAuthorizationSchemeSpecified( + [AliasAs("id")] int anId, + [Authorize("Bearer")] string token + ); [Get("/foo/bar/{id}")] [Headers("Api-Version: 2", "Accept: application/json")] Task FetchSomeStuffWithHardcodedHeaders(int id); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithDynamicHeader(int id, [Header("Authorization")] string authorization); + Task FetchSomeStuffWithDynamicHeader( + int id, + [Header("Authorization")] string authorization + ); [Get("/foo")] - Task FetchSomeStuffWithDynamicHeaderQueryParamAndArrayQueryParam([Header("Authorization")] string authorization, int id, [Query(CollectionFormat.Multi)] string[] someArray, [Property("SomeProperty")] object someValue); + Task FetchSomeStuffWithDynamicHeaderQueryParamAndArrayQueryParam( + [Header("Authorization")] string authorization, + int id, + [Query(CollectionFormat.Multi)] string[] someArray, + [Property("SomeProperty")] object someValue + ); #region [HeaderCollection] interface methods [Get("/foo/bar/{id}")] - [Headers("Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", "Accept: application/json")] - Task FetchSomeStuffWithDynamicHeaderCollection(int id, [HeaderCollection] IDictionary headers); + [Headers( + "Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", + "Accept: application/json" + )] + Task FetchSomeStuffWithDynamicHeaderCollection( + int id, + [HeaderCollection] IDictionary headers + ); [Put("/foo/bar/{id}")] - Task PutSomeStuffWithCustomHeaderCollection(int id, [Body] object body, [HeaderCollection] IDictionary headers); + Task PutSomeStuffWithCustomHeaderCollection( + int id, + [Body] object body, + [HeaderCollection] IDictionary headers + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithCustomHeaderCollection(int id, [Body] object body, [HeaderCollection] IDictionary headers); + Task PostSomeStuffWithCustomHeaderCollection( + int id, + [Body] object body, + [HeaderCollection] IDictionary headers + ); [Patch("/foo/bar/{id}")] - Task PatchSomeStuffWithCustomHeaderCollection(int id, [Body] object body, [HeaderCollection] IDictionary headers); + Task PatchSomeStuffWithCustomHeaderCollection( + int id, + [Body] object body, + [HeaderCollection] IDictionary headers + ); [Put("/foo/bar/{id}")] - Task PutSomeStuffWithoutBodyAndCustomHeaderCollection(int id, [HeaderCollection] IDictionary headers); + Task PutSomeStuffWithoutBodyAndCustomHeaderCollection( + int id, + [HeaderCollection] IDictionary headers + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithoutBodyAndCustomHeaderCollection(int id, [HeaderCollection] IDictionary headers); + Task PostSomeStuffWithoutBodyAndCustomHeaderCollection( + int id, + [HeaderCollection] IDictionary headers + ); [Patch("/foo/bar/{id}")] - Task PatchSomeStuffWithoutBodyAndCustomHeaderCollection(int id, [HeaderCollection] IDictionary headers); + Task PatchSomeStuffWithoutBodyAndCustomHeaderCollection( + int id, + [HeaderCollection] IDictionary headers + ); [Put("/foo/bar/{id}")] - Task PutSomeStuffWithInferredBodyAndWithDynamicHeaderCollection(int id, [HeaderCollection] IDictionary headers, object inferredBody); + Task PutSomeStuffWithInferredBodyAndWithDynamicHeaderCollection( + int id, + [HeaderCollection] IDictionary headers, + object inferredBody + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithInferredBodyAndWithDynamicHeaderCollection(int id, [HeaderCollection] IDictionary headers, object inferredBody); + Task PostSomeStuffWithInferredBodyAndWithDynamicHeaderCollection( + int id, + [HeaderCollection] IDictionary headers, + object inferredBody + ); [Patch("/foo/bar/{id}")] - Task PatchSomeStuffWithInferredBodyAndWithDynamicHeaderCollection(int id, [HeaderCollection] IDictionary headers, object inferredBody); + Task PatchSomeStuffWithInferredBodyAndWithDynamicHeaderCollection( + int id, + [HeaderCollection] IDictionary headers, + object inferredBody + ); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithDynamicHeaderCollectionAndAuthorize(int id, [Authorize] string value, [HeaderCollection] IDictionary headers); + Task FetchSomeStuffWithDynamicHeaderCollectionAndAuthorize( + int id, + [Authorize] string value, + [HeaderCollection] IDictionary headers + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithDynamicHeaderCollectionAndAuthorize(int id, [Authorize] string value, [HeaderCollection] IDictionary headers); + Task PostSomeStuffWithDynamicHeaderCollectionAndAuthorize( + int id, + [Authorize] string value, + [HeaderCollection] IDictionary headers + ); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeader(int id, [Header("Authorization")] string value, [HeaderCollection] IDictionary headers); + Task FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeader( + int id, + [Header("Authorization")] string value, + [HeaderCollection] IDictionary headers + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithDynamicHeaderCollectionAndDynamicHeader(int id, [Header("Authorization")] string value, [HeaderCollection] IDictionary headers); + Task PostSomeStuffWithDynamicHeaderCollectionAndDynamicHeader( + int id, + [Header("Authorization")] string value, + [HeaderCollection] IDictionary headers + ); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeaderOrderFlipped(int id, [HeaderCollection] IDictionary headers, [Header("Authorization")] string value); + Task FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeaderOrderFlipped( + int id, + [HeaderCollection] IDictionary headers, + [Header("Authorization")] string value + ); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithPathMemberInCustomHeaderAndDynamicHeaderCollection([Header("X-PathMember")] int id, [HeaderCollection] IDictionary headers); + Task FetchSomeStuffWithPathMemberInCustomHeaderAndDynamicHeaderCollection( + [Header("X-PathMember")] int id, + [HeaderCollection] IDictionary headers + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithPathMemberInCustomHeaderAndDynamicHeaderCollection([Header("X-PathMember")] int id, [HeaderCollection] IDictionary headers); + Task PostSomeStuffWithPathMemberInCustomHeaderAndDynamicHeaderCollection( + [Header("X-PathMember")] int id, + [HeaderCollection] IDictionary headers + ); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithHeaderCollection(int id, [HeaderCollection] IDictionary headers, int baz); + Task FetchSomeStuffWithHeaderCollection( + int id, + [HeaderCollection] IDictionary headers, + int baz + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithHeaderCollection(int id, [HeaderCollection] IDictionary headers, int baz); + Task PostSomeStuffWithHeaderCollection( + int id, + [HeaderCollection] IDictionary headers, + int baz + ); [Get("/foo/bar")] - Task FetchSomeStuffWithDuplicateHeaderCollection([HeaderCollection] IDictionary headers, [HeaderCollection] IDictionary headers2); + Task FetchSomeStuffWithDuplicateHeaderCollection( + [HeaderCollection] IDictionary headers, + [HeaderCollection] IDictionary headers2 + ); [Post("/foo/bar")] - Task PostSomeStuffWithDuplicateHeaderCollection([HeaderCollection] IDictionary headers, [HeaderCollection] IDictionary headers2); + Task PostSomeStuffWithDuplicateHeaderCollection( + [HeaderCollection] IDictionary headers, + [HeaderCollection] IDictionary headers2 + ); [Get("/foo")] - Task FetchSomeStuffWithHeaderCollectionQueryParamAndArrayQueryParam([HeaderCollection] IDictionary headers, int id, [Query(CollectionFormat.Multi)] string[] someArray, [Property("SomeProperty")] object someValue); + Task FetchSomeStuffWithHeaderCollectionQueryParamAndArrayQueryParam( + [HeaderCollection] IDictionary headers, + int id, + [Query(CollectionFormat.Multi)] string[] someArray, + [Property("SomeProperty")] object someValue + ); [Post("/foo")] - Task PostSomeStuffWithHeaderCollectionQueryParamAndArrayQueryParam([HeaderCollection] IDictionary headers, int id, [Query(CollectionFormat.Multi)] string[] someArray, [Property("SomeProperty")] object someValue); + Task PostSomeStuffWithHeaderCollectionQueryParamAndArrayQueryParam( + [HeaderCollection] IDictionary headers, + int id, + [Query(CollectionFormat.Multi)] string[] someArray, + [Property("SomeProperty")] object someValue + ); [Get("/foo")] - Task FetchSomeStuffWithHeaderCollectionOfUnsupportedType([HeaderCollection] string headers); + Task FetchSomeStuffWithHeaderCollectionOfUnsupportedType( + [HeaderCollection] string headers + ); [Post("/foo")] - Task PostSomeStuffWithHeaderCollectionOfUnsupportedType([HeaderCollection] string headers); + Task PostSomeStuffWithHeaderCollectionOfUnsupportedType( + [HeaderCollection] string headers + ); #endregion #region [Property] interface methods [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someValue); + Task FetchSomeStuffWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someValue + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithDynamicRequestProperty(int id, [Body] object body, [Property("SomeProperty")] object someValue); + Task PostSomeStuffWithDynamicRequestProperty( + int id, + [Body] object body, + [Property("SomeProperty")] object someValue + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithDynamicRequestProperties(int id, [Body] object body, [Property("SomeProperty")] object someValue, [Property("SomeOtherProperty")] object someOtherValue); + Task PostSomeStuffWithDynamicRequestProperties( + int id, + [Body] object body, + [Property("SomeProperty")] object someValue, + [Property("SomeOtherProperty")] object someOtherValue + ); [Put("/foo/bar/{id}")] - Task PutSomeStuffWithoutBodyAndWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someValue); + Task PutSomeStuffWithoutBodyAndWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someValue + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithoutBodyAndWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someValue); + Task PostSomeStuffWithoutBodyAndWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someValue + ); [Patch("/foo/bar/{id}")] - Task PatchSomeStuffWithoutBodyAndWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someValue); + Task PatchSomeStuffWithoutBodyAndWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someValue + ); [Put("/foo/bar/{id}")] - Task PutSomeStuffWithInferredBodyAndWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someValue, object inferredBody); + Task PutSomeStuffWithInferredBodyAndWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someValue, + object inferredBody + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithInferredBodyAndWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someValue, object inferredBody); + Task PostSomeStuffWithInferredBodyAndWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someValue, + object inferredBody + ); [Patch("/foo/bar/{id}")] - Task PatchSomeStuffWithInferredBodyAndWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someValue, object inferredBody); + Task PatchSomeStuffWithInferredBodyAndWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someValue, + object inferredBody + ); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithDynamicRequestPropertyWithDuplicateKey(int id, [Property("SomeProperty")] object someValue1, [Property("SomeProperty")] object someValue2); + Task FetchSomeStuffWithDynamicRequestPropertyWithDuplicateKey( + int id, + [Property("SomeProperty")] object someValue1, + [Property("SomeProperty")] object someValue2 + ); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithDynamicRequestPropertyWithoutKey(int id, [Property] object someValue, [Property("")] object someOtherValue); + Task FetchSomeStuffWithDynamicRequestPropertyWithoutKey( + int id, + [Property] object someValue, + [Property("")] object someOtherValue + ); #endregion @@ -231,7 +380,10 @@ public interface IRestMethodInfoTests Task TooManyComplexTypes(Dictionary theData, Dictionary theData1); [Post("/foo")] - Task ManyComplexTypes(Dictionary theData, [Body] Dictionary theData1); + Task ManyComplexTypes( + Dictionary theData, + [Body] Dictionary theData1 + ); [Post("/foo")] Task PostWithDictionaryQuery([Query] Dictionary theData); @@ -240,22 +392,40 @@ public interface IRestMethodInfoTests Task PostWithComplexTypeQuery([Query] ComplexQueryObject queryParams); [Post("/foo")] - Task ImpliedComplexQueryType(ComplexQueryObject queryParams, [Body] Dictionary theData1); + Task ImpliedComplexQueryType( + ComplexQueryObject queryParams, + [Body] Dictionary theData1 + ); [Get("/api/{id}")] - Task MultipleQueryAttributes(int id, [Query] string text = null, [Query] int? optionalId = null, [Query(CollectionFormat = CollectionFormat.Multi)] string[] filters = null); + Task MultipleQueryAttributes( + int id, + [Query] string text = null, + [Query] int? optionalId = null, + [Query(CollectionFormat = CollectionFormat.Multi)] string[] filters = null + ); [Get("/api/{id}")] - Task NullableValues(int id, string text = null, int? optionalId = null, [Query(CollectionFormat = CollectionFormat.Multi)] string[] filters = null); + Task NullableValues( + int id, + string text = null, + int? optionalId = null, + [Query(CollectionFormat = CollectionFormat.Multi)] string[] filters = null + ); [Get("/api/{id}")] Task IEnumerableThrowingError([Query(CollectionFormat.Multi)] IEnumerable values); - + [Get("/foo")] List InvalidGenericReturnType(); } - public enum TestEnum { A, B, C } + public enum TestEnum + { + A, + B, + C + } public class ComplexQueryObject { @@ -297,16 +467,23 @@ public void TooManyComplexTypesThrows() { var fixture = new RestMethodInfoInternal( input, - input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.TooManyComplexTypes))); + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.TooManyComplexTypes)) + ); }); - } [Fact] public void ManyComplexTypes() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.ManyComplexTypes))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.ManyComplexTypes)) + ); Assert.Single(fixture.QueryParameterMap); Assert.NotNull(fixture.BodyParameterInfo); @@ -320,7 +497,10 @@ public void ManyComplexTypes() public void DefaultBodyParameterDetected(string interfaceMethodName) { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName)); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ); Assert.Empty(fixture.QueryParameterMap); Assert.NotNull(fixture.BodyParameterInfo); @@ -330,7 +510,12 @@ public void DefaultBodyParameterDetected(string interfaceMethodName) public void DefaultBodyParameterNotDetectedForGet() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.GetWithBodyDetected))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.GetWithBodyDetected)) + ); Assert.Single(fixture.QueryParameterMap); Assert.Null(fixture.BodyParameterInfo); @@ -340,7 +525,12 @@ public void DefaultBodyParameterNotDetectedForGet() public void PostWithDictionaryQueryParameter() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PostWithDictionaryQuery))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.PostWithDictionaryQuery)) + ); Assert.Single(fixture.QueryParameterMap); Assert.Null(fixture.BodyParameterInfo); @@ -350,7 +540,12 @@ public void PostWithDictionaryQueryParameter() public void PostWithObjectQueryParameterHasSingleQueryParameterValue() { var input = typeof(IRestMethodInfoTests); - var fixtureParams = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PostWithComplexTypeQuery))); + var fixtureParams = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.PostWithComplexTypeQuery)) + ); Assert.Single(fixtureParams.QueryParameterMap); Assert.Equal("queryParams", fixtureParams.QueryParameterMap[0]); @@ -362,13 +557,11 @@ public void PostWithObjectQueryParameterHasCorrectQuerystring() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.PostWithComplexTypeQuery)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.PostWithComplexTypeQuery) + ); - var param = new ComplexQueryObject - { - TestAlias1 = "one", - TestAlias2 = "two" - }; + var param = new ComplexQueryObject { TestAlias1 = "one", TestAlias2 = "two" }; var output = factory(new object[] { param }); @@ -382,7 +575,9 @@ public void PostWithObjectQueryParameterWithEnumList_Multi() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.PostWithComplexTypeQuery)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.PostWithComplexTypeQuery) + ); var param = new ComplexQueryObject { @@ -391,7 +586,10 @@ public void PostWithObjectQueryParameterWithEnumList_Multi() var output = factory(new object[] { param }); - Assert.Equal("/foo?listOfEnumMulti=A&listOfEnumMulti=B", output.RequestUri.PathAndQuery); + Assert.Equal( + "/foo?listOfEnumMulti=A&listOfEnumMulti=B", + output.RequestUri.PathAndQuery + ); } [Fact] @@ -399,7 +597,9 @@ public void PostWithObjectQueryParameterWithObjectListWithProvidedEnumValues_Mul { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.PostWithComplexTypeQuery)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.PostWithComplexTypeQuery) + ); var param = new ComplexQueryObject { @@ -408,7 +608,10 @@ public void PostWithObjectQueryParameterWithObjectListWithProvidedEnumValues_Mul var output = factory(new object[] { param }); - Assert.Equal("/foo?ObjectCollectionMulti=A&ObjectCollectionMulti=B", output.RequestUri.PathAndQuery); + Assert.Equal( + "/foo?ObjectCollectionMulti=A&ObjectCollectionMulti=B", + output.RequestUri.PathAndQuery + ); } [Fact] @@ -416,7 +619,9 @@ public void PostWithObjectQueryParameterWithEnumList_Csv() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.PostWithComplexTypeQuery)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.PostWithComplexTypeQuery) + ); var param = new ComplexQueryObject { @@ -433,7 +638,9 @@ public void PostWithObjectQueryParameterWithObjectListWithProvidedEnumValues_Csv { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.PostWithComplexTypeQuery)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.PostWithComplexTypeQuery) + ); var param = new ComplexQueryObject { @@ -449,7 +656,9 @@ public void PostWithObjectQueryParameterWithObjectListWithProvidedEnumValues_Csv public void ObjectQueryParameterWithInnerCollectionHasCorrectQuerystring() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.ComplexTypeQueryWithInnerCollection)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.ComplexTypeQueryWithInnerCollection) + ); var param = new ComplexQueryObject { TestCollection = new[] { 1, 2, 3 } }; var output = factory(new object[] { param }); @@ -462,7 +671,12 @@ public void ObjectQueryParameterWithInnerCollectionHasCorrectQuerystring() public void MultipleQueryAttributesWithNulls() { var input = typeof(IRestMethodInfoTests); - var fixtureParams = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.MultipleQueryAttributes))); + var fixtureParams = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.MultipleQueryAttributes)) + ); Assert.Equal(3, fixtureParams.QueryParameterMap.Count); } @@ -475,7 +689,12 @@ public void GarbagePathsShouldThrow() try { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.GarbagePath))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.GarbagePath)) + ); } catch (ArgumentException) { @@ -493,7 +712,16 @@ public void MissingParametersShouldBlowUp() try { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffMissingParameters))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof(IRestMethodInfoTests.FetchSomeStuffMissingParameters) + ) + ); } catch (ArgumentException) { @@ -507,18 +735,26 @@ public void MissingParametersShouldBlowUp() public void ParameterMappingSmokeTest() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuff))); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuff)) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); Assert.Null(fixture.BodyParameterInfo); } - + [Fact] public void ParameterMappingWithTheSameIdInAFewPlaces() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithTheSameId))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithTheSameId)) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -529,19 +765,38 @@ public void ParameterMappingWithTheSameIdInAFewPlaces() public void ParameterMappingWithTheSameIdInTheQueryParameter() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithTheIdInAParameterMultipleTimes))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof( + IRestMethodInfoTests.FetchSomeStuffWithTheIdInAParameterMultipleTimes + ) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); Assert.Null(fixture.BodyParameterInfo); } - [Fact] public void ParameterMappingWithRoundTrippingSmokeTest() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithRoundTrippingParam))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof(IRestMethodInfoTests.FetchSomeStuffWithRoundTrippingParam) + ) + ); Assert.Equal("path", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.RoundTripping, fixture.ParameterMap[0].Type); Assert.Equal("id", fixture.ParameterMap[1].Name); @@ -558,8 +813,16 @@ public void ParameterMappingWithNonStringRoundTrippingShouldThrow() { var fixture = new RestMethodInfoInternal( input, - input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithNonStringRoundTrippingParam)) - ); + input + .GetMethods() + .First( + x => + x.Name + == nameof( + IRestMethodInfoTests.FetchSomeStuffWithNonStringRoundTrippingParam + ) + ) + ); }); } @@ -567,7 +830,12 @@ public void ParameterMappingWithNonStringRoundTrippingShouldThrow() public void ParameterMappingWithQuerySmokeTest() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithQueryParam))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithQueryParam)) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Equal("search", fixture.QueryParameterMap[1]); @@ -578,7 +846,16 @@ public void ParameterMappingWithQuerySmokeTest() public void ParameterMappingWithHardcodedQuerySmokeTest() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithHardcodedQueryParam))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof(IRestMethodInfoTests.FetchSomeStuffWithHardcodedQueryParam) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -589,7 +866,12 @@ public void ParameterMappingWithHardcodedQuerySmokeTest() public void AliasMappingShouldWork() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithAlias))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithAlias)) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -600,7 +882,10 @@ public void AliasMappingShouldWork() public void MultipleParametersPerSegmentShouldWork() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchAnImage))); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchAnImage)) + ); Assert.Equal("width", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Equal("height", fixture.ParameterMap[1].Name); @@ -613,7 +898,12 @@ public void MultipleParametersPerSegmentShouldWork() public void FindTheBodyParameter() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithBody))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithBody)) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); @@ -626,7 +916,18 @@ public void FindTheBodyParameter() public void FindTheAuthorizeParameter() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithAuthorizationSchemeSpecified))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof( + IRestMethodInfoTests.FetchSomeStuffWithAuthorizationSchemeSpecified + ) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); @@ -639,7 +940,12 @@ public void FindTheAuthorizeParameter() public void AllowUrlEncodedContent() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PostSomeUrlEncodedStuff))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.PostSomeUrlEncodedStuff)) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); @@ -652,15 +958,30 @@ public void AllowUrlEncodedContent() public void HardcodedHeadersShouldWork() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithHardcodedHeaders))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof(IRestMethodInfoTests.FetchSomeStuffWithHardcodedHeaders) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); Assert.Null(fixture.BodyParameterInfo); - Assert.True(fixture.Headers.ContainsKey("Api-Version"), "Headers include Api-Version header"); + Assert.True( + fixture.Headers.ContainsKey("Api-Version"), + "Headers include Api-Version header" + ); Assert.Equal("2", fixture.Headers["Api-Version"]); - Assert.True(fixture.Headers.ContainsKey("User-Agent"), "Headers include User-Agent header"); + Assert.True( + fixture.Headers.ContainsKey("User-Agent"), + "Headers include User-Agent header" + ); Assert.Equal("RefitTestClient", fixture.Headers["User-Agent"]); Assert.True(fixture.Headers.ContainsKey("Accept"), "Headers include Accept header"); Assert.Equal("application/json", fixture.Headers["Accept"]); @@ -671,7 +992,14 @@ public void HardcodedHeadersShouldWork() public void DynamicHeadersShouldWork() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicHeader))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicHeader) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -679,7 +1007,10 @@ public void DynamicHeadersShouldWork() Assert.Null(fixture.BodyParameterInfo); Assert.Equal("Authorization", fixture.HeaderParameterMap[1]); - Assert.True(fixture.Headers.ContainsKey("User-Agent"), "Headers include User-Agent header"); + Assert.True( + fixture.Headers.ContainsKey("User-Agent"), + "Headers include User-Agent header" + ); Assert.Equal("RefitTestClient", fixture.Headers["User-Agent"]); Assert.Equal(2, fixture.Headers.Count); } @@ -690,7 +1021,18 @@ public void DynamicHeadersShouldWork() public void DynamicHeaderCollectionShouldWork() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicHeaderCollection))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof( + IRestMethodInfoTests.FetchSomeStuffWithDynamicHeaderCollection + ) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -698,13 +1040,25 @@ public void DynamicHeaderCollectionShouldWork() Assert.Empty(fixture.PropertyParameterMap); Assert.Null(fixture.BodyParameterInfo); - Assert.True(fixture.Headers.ContainsKey("Authorization"), "Headers include Authorization header"); - Assert.Equal("SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", fixture.Headers["Authorization"]); + Assert.True( + fixture.Headers.ContainsKey("Authorization"), + "Headers include Authorization header" + ); + Assert.Equal( + "SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", + fixture.Headers["Authorization"] + ); Assert.True(fixture.Headers.ContainsKey("Accept"), "Headers include Accept header"); Assert.Equal("application/json", fixture.Headers["Accept"]); - Assert.True(fixture.Headers.ContainsKey("User-Agent"), "Headers include User-Agent header"); + Assert.True( + fixture.Headers.ContainsKey("User-Agent"), + "Headers include User-Agent header" + ); Assert.Equal("RefitTestClient", fixture.Headers["User-Agent"]); - Assert.True(fixture.Headers.ContainsKey("Api-Version"), "Headers include Api-Version header"); + Assert.True( + fixture.Headers.ContainsKey("Api-Version"), + "Headers include Api-Version header" + ); Assert.Equal("1", fixture.Headers["Api-Version"]); Assert.Equal(4, fixture.Headers.Count); @@ -719,7 +1073,10 @@ public void DynamicHeaderCollectionShouldWork() public void DynamicHeaderCollectionShouldWorkWithBody(string interfaceMethodName) { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName)); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -735,11 +1092,16 @@ public void DynamicHeaderCollectionShouldWorkWithBody(string interfaceMethodName [Theory] [InlineData(nameof(IRestMethodInfoTests.PutSomeStuffWithoutBodyAndCustomHeaderCollection))] [InlineData(nameof(IRestMethodInfoTests.PostSomeStuffWithoutBodyAndCustomHeaderCollection))] - [InlineData(nameof(IRestMethodInfoTests.PatchSomeStuffWithoutBodyAndCustomHeaderCollection))] + [InlineData( + nameof(IRestMethodInfoTests.PatchSomeStuffWithoutBodyAndCustomHeaderCollection) + )] public void DynamicHeaderCollectionShouldWorkWithoutBody(string interfaceMethodName) { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName)); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -753,13 +1115,24 @@ public void DynamicHeaderCollectionShouldWorkWithoutBody(string interfaceMethodN } [Theory] - [InlineData(nameof(IRestMethodInfoTests.PutSomeStuffWithInferredBodyAndWithDynamicHeaderCollection))] - [InlineData(nameof(IRestMethodInfoTests.PostSomeStuffWithInferredBodyAndWithDynamicHeaderCollection))] - [InlineData(nameof(IRestMethodInfoTests.PatchSomeStuffWithInferredBodyAndWithDynamicHeaderCollection))] + [InlineData( + nameof(IRestMethodInfoTests.PutSomeStuffWithInferredBodyAndWithDynamicHeaderCollection) + )] + [InlineData( + nameof(IRestMethodInfoTests.PostSomeStuffWithInferredBodyAndWithDynamicHeaderCollection) + )] + [InlineData( + nameof( + IRestMethodInfoTests.PatchSomeStuffWithInferredBodyAndWithDynamicHeaderCollection + ) + )] public void DynamicHeaderCollectionShouldWorkWithInferredBody(string interfaceMethodName) { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName)); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -774,12 +1147,19 @@ public void DynamicHeaderCollectionShouldWorkWithInferredBody(string interfaceMe } [Theory] - [InlineData(nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicHeaderCollectionAndAuthorize))] - [InlineData(nameof(IRestMethodInfoTests.PostSomeStuffWithDynamicHeaderCollectionAndAuthorize))] + [InlineData( + nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicHeaderCollectionAndAuthorize) + )] + [InlineData( + nameof(IRestMethodInfoTests.PostSomeStuffWithDynamicHeaderCollectionAndAuthorize) + )] public void DynamicHeaderCollectionShouldWorkWithAuthorize(string interfaceMethodName) { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName)); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -793,12 +1173,19 @@ public void DynamicHeaderCollectionShouldWorkWithAuthorize(string interfaceMetho } [Theory] - [InlineData(nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeader))] - [InlineData(nameof(IRestMethodInfoTests.PostSomeStuffWithDynamicHeaderCollectionAndDynamicHeader))] + [InlineData( + nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeader) + )] + [InlineData( + nameof(IRestMethodInfoTests.PostSomeStuffWithDynamicHeaderCollectionAndDynamicHeader) + )] public void DynamicHeaderCollectionShouldWorkWithDynamicHeader(string interfaceMethodName) { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName)); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -812,7 +1199,18 @@ public void DynamicHeaderCollectionShouldWorkWithDynamicHeader(string interfaceM Assert.True(fixture.HeaderCollectionParameterMap.Contains(2)); input = typeof(IRestMethodInfoTests); - fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeaderOrderFlipped))); + fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof( + IRestMethodInfoTests.FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeaderOrderFlipped + ) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -827,12 +1225,25 @@ public void DynamicHeaderCollectionShouldWorkWithDynamicHeader(string interfaceM } [Theory] - [InlineData(nameof(IRestMethodInfoTests.FetchSomeStuffWithPathMemberInCustomHeaderAndDynamicHeaderCollection))] - [InlineData(nameof(IRestMethodInfoTests.PostSomeStuffWithPathMemberInCustomHeaderAndDynamicHeaderCollection))] - public void DynamicHeaderCollectionShouldWorkWithPathMemberDynamicHeader(string interfaceMethodName) + [InlineData( + nameof( + IRestMethodInfoTests.FetchSomeStuffWithPathMemberInCustomHeaderAndDynamicHeaderCollection + ) + )] + [InlineData( + nameof( + IRestMethodInfoTests.PostSomeStuffWithPathMemberInCustomHeaderAndDynamicHeaderCollection + ) + )] + public void DynamicHeaderCollectionShouldWorkWithPathMemberDynamicHeader( + string interfaceMethodName + ) { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName)); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -852,7 +1263,10 @@ public void DynamicHeaderCollectionShouldWorkWithPathMemberDynamicHeader(string public void DynamicHeaderCollectionInMiddleOfParamsShouldWork(string interfaceMethodName) { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName)); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Null(fixture.AuthorizeParameterInfo); @@ -871,16 +1285,33 @@ public void DynamicHeaderCollectionShouldOnlyAllowOne(string interfaceMethodName { var input = typeof(IRestMethodInfoTests); - Assert.Throws(() => new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName))); + Assert.Throws( + () => + new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ) + ); } [Theory] - [InlineData(nameof(IRestMethodInfoTests.FetchSomeStuffWithHeaderCollectionQueryParamAndArrayQueryParam))] - [InlineData(nameof(IRestMethodInfoTests.PostSomeStuffWithHeaderCollectionQueryParamAndArrayQueryParam))] + [InlineData( + nameof( + IRestMethodInfoTests.FetchSomeStuffWithHeaderCollectionQueryParamAndArrayQueryParam + ) + )] + [InlineData( + nameof( + IRestMethodInfoTests.PostSomeStuffWithHeaderCollectionQueryParamAndArrayQueryParam + ) + )] public void DynamicHeaderCollectionShouldWorkWithProperty(string interfaceMethodName) { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName)); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ); Assert.Null(fixture.BodyParameterInfo); Assert.Null(fixture.AuthorizeParameterInfo); @@ -895,12 +1326,24 @@ public void DynamicHeaderCollectionShouldWorkWithProperty(string interfaceMethod } [Theory] - [InlineData(nameof(IRestMethodInfoTests.FetchSomeStuffWithHeaderCollectionOfUnsupportedType))] - [InlineData(nameof(IRestMethodInfoTests.PostSomeStuffWithHeaderCollectionOfUnsupportedType))] - public void DynamicHeaderCollectionShouldOnlyWorkWithSupportedSemantics(string interfaceMethodName) + [InlineData( + nameof(IRestMethodInfoTests.FetchSomeStuffWithHeaderCollectionOfUnsupportedType) + )] + [InlineData( + nameof(IRestMethodInfoTests.PostSomeStuffWithHeaderCollectionOfUnsupportedType) + )] + public void DynamicHeaderCollectionShouldOnlyWorkWithSupportedSemantics( + string interfaceMethodName + ) { var input = typeof(IRestMethodInfoTests); - Assert.Throws(() => new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName))); + Assert.Throws( + () => + new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ) + ); } #endregion @@ -911,7 +1354,16 @@ public void DynamicHeaderCollectionShouldOnlyWorkWithSupportedSemantics(string i public void DynamicRequestPropertiesShouldWork() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicRequestProperty))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicRequestProperty) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -925,7 +1377,16 @@ public void DynamicRequestPropertiesShouldWork() public void DynamicRequestPropertyShouldWorkWithBody() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PostSomeStuffWithDynamicRequestProperty))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof(IRestMethodInfoTests.PostSomeStuffWithDynamicRequestProperty) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -941,7 +1402,18 @@ public void DynamicRequestPropertyShouldWorkWithBody() public void DynamicRequestPropertiesShouldWorkWithBody() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PostSomeStuffWithDynamicRequestProperties))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof( + IRestMethodInfoTests.PostSomeStuffWithDynamicRequestProperties + ) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -954,15 +1426,23 @@ public void DynamicRequestPropertiesShouldWorkWithBody() Assert.Equal("SomeOtherProperty", fixture.PropertyParameterMap[3]); } - [Theory] - [InlineData(nameof(IRestMethodInfoTests.PutSomeStuffWithoutBodyAndWithDynamicRequestProperty))] - [InlineData(nameof(IRestMethodInfoTests.PostSomeStuffWithoutBodyAndWithDynamicRequestProperty))] - [InlineData(nameof(IRestMethodInfoTests.PatchSomeStuffWithoutBodyAndWithDynamicRequestProperty))] + [InlineData( + nameof(IRestMethodInfoTests.PutSomeStuffWithoutBodyAndWithDynamicRequestProperty) + )] + [InlineData( + nameof(IRestMethodInfoTests.PostSomeStuffWithoutBodyAndWithDynamicRequestProperty) + )] + [InlineData( + nameof(IRestMethodInfoTests.PatchSomeStuffWithoutBodyAndWithDynamicRequestProperty) + )] public void DynamicRequestPropertyShouldWorkWithoutBody(string interfaceMethodName) { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName)); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -975,13 +1455,22 @@ public void DynamicRequestPropertyShouldWorkWithoutBody(string interfaceMethodNa } [Theory] - [InlineData(nameof(IRestMethodInfoTests.PutSomeStuffWithInferredBodyAndWithDynamicRequestProperty))] - [InlineData(nameof(IRestMethodInfoTests.PostSomeStuffWithInferredBodyAndWithDynamicRequestProperty))] - [InlineData(nameof(IRestMethodInfoTests.PatchSomeStuffWithInferredBodyAndWithDynamicRequestProperty))] + [InlineData( + nameof(IRestMethodInfoTests.PutSomeStuffWithInferredBodyAndWithDynamicRequestProperty) + )] + [InlineData( + nameof(IRestMethodInfoTests.PostSomeStuffWithInferredBodyAndWithDynamicRequestProperty) + )] + [InlineData( + nameof(IRestMethodInfoTests.PatchSomeStuffWithInferredBodyAndWithDynamicRequestProperty) + )] public void DynamicRequestPropertyShouldWorkWithInferredBody(string interfaceMethodName) { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == interfaceMethodName)); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == interfaceMethodName) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -998,7 +1487,18 @@ public void DynamicRequestPropertyShouldWorkWithInferredBody(string interfaceMet public void DynamicRequestPropertiesWithoutKeysShouldDefaultKeyToParameterName() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicRequestPropertyWithoutKey))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof( + IRestMethodInfoTests.FetchSomeStuffWithDynamicRequestPropertyWithoutKey + ) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -1013,7 +1513,18 @@ public void DynamicRequestPropertiesWithoutKeysShouldDefaultKeyToParameterName() public void DynamicRequestPropertiesWithDuplicateKeysDontBlowUp() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicRequestPropertyWithDuplicateKey))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof( + IRestMethodInfoTests.FetchSomeStuffWithDynamicRequestPropertyWithDuplicateKey + ) + ) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -1030,7 +1541,12 @@ public void DynamicRequestPropertiesWithDuplicateKeysDontBlowUp() public void ValueTypesDontBlowUpBuffered() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.OhYeahValueTypes))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.OhYeahValueTypes)) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -1045,7 +1561,12 @@ public void ValueTypesDontBlowUpBuffered() public void ValueTypesDontBlowUpUnBuffered() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.OhYeahValueTypesUnbuffered))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.OhYeahValueTypesUnbuffered)) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -1060,7 +1581,12 @@ public void ValueTypesDontBlowUpUnBuffered() public void StreamMethodPullWorks() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PullStreamMethod))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.PullStreamMethod)) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); Assert.Empty(fixture.QueryParameterMap); @@ -1075,7 +1601,10 @@ public void StreamMethodPullWorks() public void ReturningTaskShouldWork() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.VoidPost))); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.VoidPost)) + ); Assert.Equal("id", fixture.ParameterMap[0].Name); Assert.Equal(ParameterType.Normal, fixture.ParameterMap[0].Type); @@ -1091,7 +1620,12 @@ public void SyncMethodsShouldThrow() try { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.AsyncOnlyBuddy))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.AsyncOnlyBuddy)) + ); } catch (ArgumentException) { @@ -1105,7 +1639,10 @@ public void SyncMethodsShouldThrow() public void UsingThePatchAttributeSetsTheCorrectMethod() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PatchSomething))); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PatchSomething)) + ); Assert.Equal("PATCH", fixture.HttpMethod.Method); } @@ -1114,7 +1651,10 @@ public void UsingThePatchAttributeSetsTheCorrectMethod() public void UsingOptionsAttribute() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IDummyHttpApi.SendOptions))); + var fixture = new RestMethodInfoInternal( + input, + input.GetMethods().First(x => x.Name == nameof(IDummyHttpApi.SendOptions)) + ); Assert.Equal("OPTIONS", fixture.HttpMethod.Method); } @@ -1123,7 +1663,12 @@ public void UsingOptionsAttribute() public void ApiResponseShouldBeSet() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PostReturnsApiResponse))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.PostReturnsApiResponse)) + ); Assert.True(fixture.IsApiResponse); } @@ -1132,7 +1677,12 @@ public void ApiResponseShouldBeSet() public void ApiResponseShouldNotBeSet() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.PostReturnsNonApiResponse))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First(x => x.Name == nameof(IRestMethodInfoTests.PostReturnsNonApiResponse)) + ); Assert.False(fixture.IsApiResponse); } @@ -1141,20 +1691,40 @@ public void ApiResponseShouldNotBeSet() public void ParameterMappingWithHeaderQueryParamAndQueryArrayParam() { var input = typeof(IRestMethodInfoTests); - var fixture = new RestMethodInfoInternal(input, input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.FetchSomeStuffWithDynamicHeaderQueryParamAndArrayQueryParam))); + var fixture = new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => + x.Name + == nameof( + IRestMethodInfoTests.FetchSomeStuffWithDynamicHeaderQueryParamAndArrayQueryParam + ) + ) + ); Assert.Equal("GET", fixture.HttpMethod.Method); Assert.Equal(2, fixture.QueryParameterMap.Count); Assert.Single(fixture.HeaderParameterMap); Assert.Single(fixture.PropertyParameterMap); } - + [Fact] public void GenericReturnTypeIsNotTaskOrObservableShouldThrow() { var input = typeof(IRestMethodInfoTests); - Assert.Throws(() => new RestMethodInfoInternal(input, - input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.InvalidGenericReturnType)))); + Assert.Throws( + () => + new RestMethodInfoInternal( + input, + input + .GetMethods() + .First( + x => x.Name == nameof(IRestMethodInfoTests.InvalidGenericReturnType) + ) + ) + ); } } @@ -1174,7 +1744,10 @@ public interface IDummyHttpApi Task FetchSomeStuffWithHardcodedQueryParameter(int id); [Get("/foo/bar/{id}?baz=bamf")] - Task FetchSomeStuffWithHardcodedAndOtherQueryParameters(int id, [AliasAs("search_for")] string searchQuery); + Task FetchSomeStuffWithHardcodedAndOtherQueryParameters( + int id, + [AliasAs("search_for")] string searchQuery + ); [Get("/{id}/{width}x{height}/foo")] Task FetchSomethingWithMultipleParametersPerSegment(int id, int width, int height); @@ -1203,65 +1776,136 @@ public interface IDummyHttpApi [Get("/foo/bar/{id}")] [Headers("Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==")] - Task FetchSomeStuffWithDynamicHeader(int id, [Header("Authorization")] string authorization); + Task FetchSomeStuffWithDynamicHeader( + int id, + [Header("Authorization")] string authorization + ); [Get("/foo/bar/{id}")] Task FetchSomeStuffWithCustomHeader(int id, [Header("X-Emoji")] string custom); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithPathMemberInCustomHeader([Header("X-PathMember")] int id, [Header("X-Emoji")] string custom); + Task FetchSomeStuffWithPathMemberInCustomHeader( + [Header("X-PathMember")] int id, + [Header("X-Emoji")] string custom + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithCustomHeader(int id, [Body] object body, [Header("X-Emoji")] string emoji); + Task PostSomeStuffWithCustomHeader( + int id, + [Body] object body, + [Header("X-Emoji")] string emoji + ); [Get("/foo/bar/{id}")] - [Headers("Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", "Accept: application/json")] - Task FetchSomeStuffWithDynamicHeaderCollection(int id, [HeaderCollection] IDictionary headers); + [Headers( + "Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", + "Accept: application/json" + )] + Task FetchSomeStuffWithDynamicHeaderCollection( + int id, + [HeaderCollection] IDictionary headers + ); [Delete("/foo/bar/{id}")] - [Headers("Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", "Accept: application/json")] - Task DeleteSomeStuffWithDynamicHeaderCollection(int id, [HeaderCollection] IDictionary headers); + [Headers( + "Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", + "Accept: application/json" + )] + Task DeleteSomeStuffWithDynamicHeaderCollection( + int id, + [HeaderCollection] IDictionary headers + ); [Put("/foo/bar/{id}")] - [Headers("Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", "Accept: application/json")] - Task PutSomeStuffWithDynamicHeaderCollection(int id, [HeaderCollection] IDictionary headers); + [Headers( + "Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", + "Accept: application/json" + )] + Task PutSomeStuffWithDynamicHeaderCollection( + int id, + [HeaderCollection] IDictionary headers + ); [Post("/foo/bar/{id}")] - [Headers("Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", "Accept: application/json")] - Task PostSomeStuffWithDynamicHeaderCollection(int id, [HeaderCollection] IDictionary headers); + [Headers( + "Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", + "Accept: application/json" + )] + Task PostSomeStuffWithDynamicHeaderCollection( + int id, + [HeaderCollection] IDictionary headers + ); [Patch("/foo/bar/{id}")] - [Headers("Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", "Accept: application/json")] - Task PatchSomeStuffWithDynamicHeaderCollection(int id, [HeaderCollection] IDictionary headers); + [Headers( + "Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", + "Accept: application/json" + )] + Task PatchSomeStuffWithDynamicHeaderCollection( + int id, + [HeaderCollection] IDictionary headers + ); [Get("/foo/bar/{id}")] [Headers("Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==")] - Task FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeader(int id, [Header("Authorization")] string value, [HeaderCollection] IDictionary headers); + Task FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeader( + int id, + [Header("Authorization")] string value, + [HeaderCollection] IDictionary headers + ); [Get("/foo/bar/{id}")] [Headers("Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==")] - Task FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeaderOrderFlipped(int id, [HeaderCollection] IDictionary headers, [Header("Authorization")] string value); + Task FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeaderOrderFlipped( + int id, + [HeaderCollection] IDictionary headers, + [Header("Authorization")] string value + ); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someProperty); + Task FetchSomeStuffWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someProperty + ); [Delete("/foo/bar/{id}")] - Task DeleteSomeStuffWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someProperty); + Task DeleteSomeStuffWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someProperty + ); [Put("/foo/bar/{id}")] - Task PutSomeStuffWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someProperty); + Task PutSomeStuffWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someProperty + ); [Post("/foo/bar/{id}")] - Task PostSomeStuffWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someProperty); + Task PostSomeStuffWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someProperty + ); [Patch("/foo/bar/{id}")] - Task PatchSomeStuffWithDynamicRequestProperty(int id, [Property("SomeProperty")] object someProperty); + Task PatchSomeStuffWithDynamicRequestProperty( + int id, + [Property("SomeProperty")] object someProperty + ); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithDynamicRequestPropertyWithDuplicateKey(int id, [Property("SomeProperty")] object someValue1, [Property("SomeProperty")] object someValue2); + Task FetchSomeStuffWithDynamicRequestPropertyWithDuplicateKey( + int id, + [Property("SomeProperty")] object someValue1, + [Property("SomeProperty")] object someValue2 + ); [Get("/foo/bar/{id}")] - Task FetchSomeStuffWithDynamicRequestPropertyWithoutKey(int id, [Property] object someValue, [Property("")] object someOtherValue); + Task FetchSomeStuffWithDynamicRequestPropertyWithoutKey( + int id, + [Property] object someValue, + [Property("")] object someOtherValue + ); [Get("/string")] Task FetchSomeStuffWithoutFullPath(); @@ -1270,24 +1914,42 @@ public interface IDummyHttpApi Task FetchSomeStuffWithVoid(); [Get("/void/{id}/path")] - Task FetchSomeStuffWithVoidAndQueryAlias(string id, [AliasAs("a")] string valueA, [AliasAs("b")] string valueB); + Task FetchSomeStuffWithVoidAndQueryAlias( + string id, + [AliasAs("a")] string valueA, + [AliasAs("b")] string valueB + ); [Get("/foo")] Task FetchSomeStuffWithNonFormattableQueryParams(bool b, char c); [Post("/foo/bar/{id}")] - Task PostSomeUrlEncodedStuff(int id, [Body(BodySerializationMethod.UrlEncoded)] object content); + Task PostSomeUrlEncodedStuff( + int id, + [Body(BodySerializationMethod.UrlEncoded)] object content + ); [Post("/foo/bar/{id}")] - Task PostSomeAliasedUrlEncodedStuff(int id, [Body(BodySerializationMethod.UrlEncoded)] SomeRequestData content); + Task PostSomeAliasedUrlEncodedStuff( + int id, + [Body(BodySerializationMethod.UrlEncoded)] SomeRequestData content + ); string SomeOtherMethod(); [Put("/foo/bar/{id}")] - Task PutSomeContentWithAuthorization(int id, [Body] object content, [Header("Authorization")] string authorization); + Task PutSomeContentWithAuthorization( + int id, + [Body] object content, + [Header("Authorization")] string authorization + ); [Put("/foo/bar/{id}")] - Task PutSomeStuffWithDynamicContentType(int id, [Body] string content, [Header("Content-Type")] string contentType); + Task PutSomeStuffWithDynamicContentType( + int id, + [Body] string content, + [Header("Content-Type")] string contentType + ); [Post("/foo/bar/{id}")] Task PostAValueType(int id, [Body] Guid? content); @@ -1304,7 +1966,6 @@ public interface IDummyHttpApi [Get("/query")] Task QueryWithEnumerable(IEnumerable numbers); - [Get("/query")] Task QueryWithArray(int[] numbers); @@ -1333,25 +1994,37 @@ public interface IDummyHttpApi Task QueryWithDictionaryWithEnumKey([Query] IDictionary query); [Get("/foo")] - Task QueryWithDictionaryWithPrefix([Query(".", "dictionary")] IDictionary query); + Task QueryWithDictionaryWithPrefix( + [Query(".", "dictionary")] IDictionary query + ); [Get("/foo")] Task QueryWithDictionaryWithNumericKey([Query] IDictionary query); [Get("/query")] - Task QueryWithEnumerableFormattedAsMulti([Query(CollectionFormat.Multi)] IEnumerable lines); + Task QueryWithEnumerableFormattedAsMulti( + [Query(CollectionFormat.Multi)] IEnumerable lines + ); [Get("/query")] - Task QueryWithEnumerableFormattedAsCsv([Query(CollectionFormat.Csv)] IEnumerable lines); + Task QueryWithEnumerableFormattedAsCsv( + [Query(CollectionFormat.Csv)] IEnumerable lines + ); [Get("/query")] - Task QueryWithEnumerableFormattedAsSsv([Query(CollectionFormat.Ssv)] IEnumerable lines); + Task QueryWithEnumerableFormattedAsSsv( + [Query(CollectionFormat.Ssv)] IEnumerable lines + ); [Get("/query")] - Task QueryWithEnumerableFormattedAsTsv([Query(CollectionFormat.Tsv)] IEnumerable lines); + Task QueryWithEnumerableFormattedAsTsv( + [Query(CollectionFormat.Tsv)] IEnumerable lines + ); [Get("/query")] - Task QueryWithEnumerableFormattedAsPipes([Query(CollectionFormat.Pipes)] IEnumerable lines); + Task QueryWithEnumerableFormattedAsPipes( + [Query(CollectionFormat.Pipes)] IEnumerable lines + ); [Get("/query")] Task QueryWithObjectWithPrivateGetters(Person person); @@ -1367,7 +2040,12 @@ public interface IDummyHttpApi Task QueryWithTypeWithEnum(TypeFooWithEnumMember foo); [Get("/api/{id}")] - Task QueryWithOptionalParameters(int id, [Query] string text = null, [Query] int? optionalId = null, [Query(CollectionFormat = CollectionFormat.Multi)] string[] filters = null); + Task QueryWithOptionalParameters( + int id, + [Query] string text = null, + [Query] int? optionalId = null, + [Query(CollectionFormat = CollectionFormat.Multi)] string[] filters = null + ); [Delete("/api/bar")] Task ClearWithEnumMember([Query] FooWithEnumMember foo); @@ -1381,13 +2059,14 @@ public interface IDummyHttpApi [Multipart] [Post("/companies/{companyId}/{path}")] - Task> UploadFile(int companyId, - string path, - [AliasAs("file")] StreamPart stream, - [Header("Authorization")] string authorization, - bool overwrite = false, - [AliasAs("fileMetadata")] string metadata = null); - + Task> UploadFile( + int companyId, + string path, + [AliasAs("file")] StreamPart stream, + [Header("Authorization")] string authorization, + bool overwrite = false, + [AliasAs("fileMetadata")] string metadata = null + ); [Post("/foo")] Task PostWithComplexTypeQuery([Query] ComplexQueryObject queryParams); @@ -1396,11 +2075,22 @@ Task> UploadFile(int companyId, Task ComplexTypeQueryWithInnerCollection([Query] ComplexQueryObject queryParams); [Get("/api/{obj.someProperty}")] - Task QueryWithOptionalParametersPathBoundObject(PathBoundObject obj, [Query] string text = null, [Query] int? optionalId = null, [Query(CollectionFormat = CollectionFormat.Multi)] string[] filters = null); + Task QueryWithOptionalParametersPathBoundObject( + PathBoundObject obj, + [Query] string text = null, + [Query] int? optionalId = null, + [Query(CollectionFormat = CollectionFormat.Multi)] string[] filters = null + ); [Headers("Accept:application/json", "X-API-V: 125")] [Get("/api/someModule/deviceList?controlId={control_id}")] - Task QueryWithHeadersBeforeData([Header("Authorization")] string authorization, [Header("X-Lng")] string twoLetterLang, string search, [AliasAs("control_id")] string controlId, string secret); + Task QueryWithHeadersBeforeData( + [Header("Authorization")] string authorization, + [Header("X-Lng")] string twoLetterLang, + string search, + [AliasAs("control_id")] string controlId, + string secret + ); [Get("/query")] [QueryUriFormat(UriFormat.Unescaped)] @@ -1418,6 +2108,7 @@ interface ICancellableMethods { [Get("/foo")] Task GetWithCancellation(CancellationToken token = default); + [Get("/foo")] Task GetWithCancellationAndReturn(CancellationToken token = default); } @@ -1464,12 +2155,17 @@ public TestHttpMessageHandler(string content = "test") ContentFactory = () => Content; } - protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + protected override async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken + ) { RequestMessage = request; if (request.Content != null) { - SendContent = await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + SendContent = await request + .Content.ReadAsStringAsync(cancellationToken) + .ConfigureAwait(false); } CancellationToken = cancellationToken; @@ -1497,7 +2193,11 @@ public string Format(object value, ICustomAttributeProvider attributeProvider, T // Converts enums to ints and adds a suffix to strings to test that both dictionary keys and values are formatted. public class TestEnumUrlParameterFormatter : DefaultUrlParameterFormatter { - public override string Format(object parameterValue, ICustomAttributeProvider attributeProvider, Type type) + public override string Format( + object parameterValue, + ICustomAttributeProvider attributeProvider, + Type type + ) { if (parameterValue is TestEnum enumValue) { @@ -1518,7 +2218,11 @@ public override string Format(object parameterValue, ICustomAttributeProvider at public class TestEnumerableUrlParameterFormatter : DefaultUrlParameterFormatter { - public override string Format(object parameterValue, ICustomAttributeProvider attributeProvider, Type type) + public override string Format( + object parameterValue, + ICustomAttributeProvider attributeProvider, + Type type + ) { if (parameterValue is IEnumerable enu) { @@ -1526,7 +2230,10 @@ public override string Format(object parameterValue, ICustomAttributeProvider at } if (parameterValue is IEnumerable en) { - return string.Join(",", en.Cast().Select(o => base.Format(o, attributeProvider, type))); + return string.Join( + ",", + en.Cast().Select(o => base.Format(o, attributeProvider, type)) + ); } return base.Format(parameterValue, attributeProvider, type); @@ -1535,7 +2242,6 @@ public override string Format(object parameterValue, ICustomAttributeProvider at public class RequestBuilderTests { - [Fact] public void MethodsShouldBeCancellableDefault() { @@ -1587,7 +2293,15 @@ public void HttpContentAsApiResponseTest() var mpc = new MultipartContent("foosubtype"); - var task = (Task>)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/") }, new object[] { mpc }); + var task = + (Task>) + factory( + new HttpClient(testHttpMessageHandler) + { + BaseAddress = new Uri("http://api/") + }, + new object[] { mpc } + ); task.Wait(); Assert.NotNull(task.Result.Headers); @@ -1611,7 +2325,15 @@ public void HttpContentTest() var mpc = new MultipartContent("foosubtype"); - var task = (Task)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/") }, new object[] { mpc }); + var task = + (Task) + factory( + new HttpClient(testHttpMessageHandler) + { + BaseAddress = new Uri("http://api/") + }, + new object[] { mpc } + ); task.Wait(); Assert.Equal(testHttpMessageHandler.RequestMessage.Content, mpc); @@ -1633,7 +2355,15 @@ public void StreamResponseAsApiResponseTest() writer.Flush(); streamResponse.Seek(0L, SeekOrigin.Begin); - var task = (Task>)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/") }, new object[] { "test-file" }); + var task = + (Task>) + factory( + new HttpClient(testHttpMessageHandler) + { + BaseAddress = new Uri("http://api/") + }, + new object[] { "test-file" } + ); task.Wait(); Assert.NotNull(task.Result.Headers); @@ -1661,7 +2391,15 @@ public void StreamResponseTest() writer.Flush(); streamResponse.Seek(0L, SeekOrigin.Begin); - var task = (Task)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/") }, new object[] { "test-file" }); + var task = + (Task) + factory( + new HttpClient(testHttpMessageHandler) + { + BaseAddress = new Uri("http://api/") + }, + new object[] { "test-file" } + ); task.Wait(); using var reader = new StreamReader(task.Result); @@ -1671,15 +2409,9 @@ public void StreamResponseTest() [Fact] public void MethodsThatDontHaveAnHttpMethodShouldFail() { - var failureMethods = new[] { - "SomeOtherMethod", - "weofjwoeijfwe", - null, - }; + var failureMethods = new[] { "SomeOtherMethod", "weofjwoeijfwe", null, }; - var successMethods = new[] { - "FetchSomeStuff", - }; + var successMethods = new[] { "FetchSomeStuff", }; foreach (var v in failureMethods) { @@ -1719,7 +2451,9 @@ public void MethodsThatDontHaveAnHttpMethodShouldFail() public void HardcodedQueryParamShouldBeInUrl() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithHardcodedQueryParameter"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomeStuffWithHardcodedQueryParameter" + ); var output = factory(new object[] { 6 }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -1730,7 +2464,9 @@ public void HardcodedQueryParamShouldBeInUrl() public void ParameterizedQueryParamsShouldBeInUrl() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithHardcodedAndOtherQueryParameters"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomeStuffWithHardcodedAndOtherQueryParameters" + ); var output = factory(new object[] { 6, "foo" }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -1741,7 +2477,9 @@ public void ParameterizedQueryParamsShouldBeInUrl() public void ParameterizedValuesShouldBeInUrlMoreThanOnce() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.SomeApiThatUsesParameterMoreThanOnceInTheUrl)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.SomeApiThatUsesParameterMoreThanOnceInTheUrl) + ); var output = factory(new object[] { 6 }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -1753,11 +2491,16 @@ public void ParameterizedValuesShouldBeInUrlMoreThanOnce() [InlineData("aaa/bbb/ccc", "/foo/bar/aaa/bbb/ccc/1")] [InlineData("aaa", "/foo/bar/aaa/1")] [InlineData("aa a/bb-b", "/foo/bar/aa%20a/bb-b/1")] - public void RoundTrippingParameterizedQueryParamsShouldBeInUrl(string path, string expectedQuery) + public void RoundTrippingParameterizedQueryParamsShouldBeInUrl( + string path, + string expectedQuery + ) { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithRoundTrippingParam"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomeStuffWithRoundTrippingParam" + ); var output = factory(new object[] { path, 1 }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -1769,7 +2512,9 @@ public void ParameterizedNullQueryParamsShouldBeBlankInUrl() { var fixture = new RequestBuilderImplementation(); var factory = fixture.BuildRequestFactoryForMethod("PostWithQueryStringParameters"); - var output = factory(new object[] { new FileInfo(typeof(RequestBuilderTests).Assembly.Location), null }); + var output = factory( + new object[] { new FileInfo(typeof(RequestBuilderTests).Assembly.Location), null } + ); var uri = new Uri(new Uri("http://api"), output.RequestUri); Assert.Equal("/foo?name=", uri.PathAndQuery); @@ -1779,7 +2524,9 @@ public void ParameterizedNullQueryParamsShouldBeBlankInUrl() public void ParametersShouldBePutAsExplicitQueryString() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.QueryWithExplicitParameters)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.QueryWithExplicitParameters) + ); var output = factory(new object[] { "value1", "value2" }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -1802,7 +2549,9 @@ public void QueryParamShouldFormat() public void ParameterizedQueryParamsShouldBeInUrlAndValuesEncoded() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithHardcodedAndOtherQueryParameters"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomeStuffWithHardcodedAndOtherQueryParameters" + ); var output = factory(new object[] { 6, "push!=pull&push" }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -1814,31 +2563,43 @@ public void ParameterizedQueryParamsShouldBeInUrlAndValuesEncoded() public void ParameterizedQueryParamsShouldBeInUrlAndValuesEncodedWhenMixedReplacementAndQuery() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithVoidAndQueryAlias"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomeStuffWithVoidAndQueryAlias" + ); var output = factory(new object[] { "6 & 7/8", "test@example.com", "push!=pull" }); var uri = new Uri(new Uri("http://api"), output.RequestUri); - Assert.Equal("/void/6%20%26%207%2F8/path?a=test%40example.com&b=push%21%3Dpull", uri.PathAndQuery); + Assert.Equal( + "/void/6%20%26%207%2F8/path?a=test%40example.com&b=push%21%3Dpull", + uri.PathAndQuery + ); } [Fact] public void QueryParamWithPathDelimiterShouldBeEncoded() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithVoidAndQueryAlias"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomeStuffWithVoidAndQueryAlias" + ); var output = factory(new object[] { "6/6", "test@example.com", "push!=pull" }); var uri = new Uri(new Uri("http://api"), output.RequestUri); - Assert.Equal("/void/6%2F6/path?a=test%40example.com&b=push%21%3Dpull", uri.PathAndQuery); + Assert.Equal( + "/void/6%2F6/path?a=test%40example.com&b=push%21%3Dpull", + uri.PathAndQuery + ); } [Fact] public void ParameterizedQueryParamsShouldBeInUrlAndValuesEncodedWhenMixedReplacementAndQueryBadId() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithVoidAndQueryAlias"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomeStuffWithVoidAndQueryAlias" + ); var output = factory(new object[] { "6", "test@example.com", "push!=pull" }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -1850,7 +2611,9 @@ public void ParameterizedQueryParamsShouldBeInUrlAndValuesEncodedWhenMixedReplac public void NonFormattableQueryParamsShouldBeIncluded() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithNonFormattableQueryParams"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomeStuffWithNonFormattableQueryParams" + ); var output = factory(new object[] { true, 'x' }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -1862,7 +2625,9 @@ public void NonFormattableQueryParamsShouldBeIncluded() public void MultipleParametersInTheSameSegmentAreGeneratedProperly() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomethingWithMultipleParametersPerSegment"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomethingWithMultipleParametersPerSegment" + ); var output = factory(new object[] { 6, 1024, 768 }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -1874,12 +2639,17 @@ public void HardcodedHeadersShouldBeInHeaders() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.FetchSomeStuffWithHardcodedHeaders)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.FetchSomeStuffWithHardcodedHeaders) + ); var output = factory(new object[] { 6 }); Assert.True(output.Headers.Contains("User-Agent"), "Headers include User-Agent header"); Assert.Equal("RefitTestClient", output.Headers.UserAgent.ToString()); - Assert.True(output.Headers.Contains("Api-Version"), "Headers include Api-Version header"); + Assert.True( + output.Headers.Contains("Api-Version"), + "Headers include Api-Version header" + ); Assert.Equal("2", output.Headers.GetValues("Api-Version").Single()); Assert.True(output.Headers.Contains("Accept"), "Headers include Accept header"); Assert.Equal("application/json", output.Headers.Accept.ToString()); @@ -1889,24 +2659,35 @@ public void HardcodedHeadersShouldBeInHeaders() public void EmptyHardcodedHeadersShouldBeInHeaders() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithEmptyHardcodedHeader"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomeStuffWithEmptyHardcodedHeader" + ); var output = factory(new object[] { 6 }); Assert.True(output.Headers.Contains("User-Agent"), "Headers include User-Agent header"); Assert.Equal("RefitTestClient", output.Headers.UserAgent.ToString()); - Assert.True(output.Headers.Contains("Api-Version"), "Headers include Api-Version header"); + Assert.True( + output.Headers.Contains("Api-Version"), + "Headers include Api-Version header" + ); Assert.Equal("", output.Headers.GetValues("Api-Version").Single()); } + [Fact] public void NullHardcodedHeadersShouldNotBeInHeaders() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithNullHardcodedHeader"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomeStuffWithNullHardcodedHeader" + ); var output = factory(new object[] { 6 }); Assert.True(output.Headers.Contains("User-Agent"), "Headers include User-Agent header"); Assert.Equal("RefitTestClient", output.Headers.UserAgent.ToString()); - Assert.False(output.Headers.Contains("Api-Version"), "Headers include Api-Version header"); + Assert.False( + output.Headers.Contains("Api-Version"), + "Headers include Api-Version header" + ); } [Fact] @@ -1916,7 +2697,15 @@ public void ReadStringContentWithMetadata() var factory = fixture.BuildRestResultFuncForMethod("FetchSomeStringWithMetadata"); var testHttpMessageHandler = new TestHttpMessageHandler(); - var task = (Task>)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/") }, new object[] { 42 }); + var task = + (Task>) + factory( + new HttpClient(testHttpMessageHandler) + { + BaseAddress = new Uri("http://api/") + }, + new object[] { 42 } + ); task.Wait(); Assert.NotNull(task.Result.Headers); @@ -1932,10 +2721,15 @@ public void ReadStringContentWithMetadata() public void ContentHeadersCanBeHardcoded() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("PostSomeStuffWithHardCodedContentTypeHeader"); + var factory = fixture.BuildRequestFactoryForMethod( + "PostSomeStuffWithHardCodedContentTypeHeader" + ); var output = factory(new object[] { 6, "stuff" }); - Assert.True(output.Content.Headers.Contains("Content-Type"), "Content headers include Content-Type header"); + Assert.True( + output.Content.Headers.Contains("Content-Type"), + "Content headers include Content-Type header" + ); Assert.Equal("literally/anything", output.Content.Headers.ContentType.ToString()); } @@ -1946,7 +2740,7 @@ public void DynamicHeaderShouldBeInHeaders() var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithDynamicHeader"); var output = factory(new object[] { 6, "Basic RnVjayB5ZWFoOmhlYWRlcnMh" }); - Assert.NotNull(output.Headers.Authorization);//, "Headers include Authorization header"); + Assert.NotNull(output.Headers.Authorization); //, "Headers include Authorization header"); Assert.Equal("RnVjayB5ZWFoOmhlYWRlcnMh", output.Headers.Authorization.Parameter); } @@ -1979,17 +2773,22 @@ public void NullDynamicHeaderShouldNotBeInHeaders() var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithDynamicHeader"); var output = factory(new object[] { 6, null }); - Assert.Null(output.Headers.Authorization);//, "Headers include Authorization header"); + Assert.Null(output.Headers.Authorization); //, "Headers include Authorization header"); } [Fact] public void PathMemberAsCustomDynamicHeaderShouldBeInHeaders() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithPathMemberInCustomHeader"); + var factory = fixture.BuildRequestFactoryForMethod( + "FetchSomeStuffWithPathMemberInCustomHeader" + ); var output = factory(new object[] { 6, ":joy_cat:" }); - Assert.True(output.Headers.Contains("X-PathMember"), "Headers include X-PathMember header"); + Assert.True( + output.Headers.Contains("X-PathMember"), + "Headers include X-PathMember header" + ); Assert.Equal("6", output.Headers.GetValues("X-PathMember").First()); } @@ -2000,10 +2799,19 @@ public void AddCustomHeadersToRequestHeadersOnly() var factory = fixture.BuildRequestFactoryForMethod("PostSomeStuffWithCustomHeader"); var output = factory(new object[] { 6, new { Foo = "bar" }, ":smile_cat:" }); - Assert.True(output.Headers.Contains("Api-Version"), "Headers include Api-Version header"); + Assert.True( + output.Headers.Contains("Api-Version"), + "Headers include Api-Version header" + ); Assert.True(output.Headers.Contains("X-Emoji"), "Headers include X-Emoji header"); - Assert.False(output.Content.Headers.Contains("Api-Version"), "Content headers include Api-Version header"); - Assert.False(output.Content.Headers.Contains("X-Emoji"), "Content headers include X-Emoji header"); + Assert.False( + output.Content.Headers.Contains("Api-Version"), + "Content headers include Api-Version header" + ); + Assert.False( + output.Content.Headers.Contains("X-Emoji"), + "Content headers include X-Emoji header" + ); } [Theory] @@ -2016,8 +2824,8 @@ public void HeaderCollectionShouldBeInHeaders(string interfaceMethodName) { var headerCollection = new Dictionary { - {"key1", "val1"}, - {"key2", "val2"} + { "key1", "val1" }, + { "key2", "val2" } }; var fixture = new RequestBuilderImplementation(); @@ -2026,11 +2834,20 @@ public void HeaderCollectionShouldBeInHeaders(string interfaceMethodName) Assert.True(output.Headers.Contains("User-Agent"), "Headers include User-Agent header"); Assert.Equal("RefitTestClient", output.Headers.GetValues("User-Agent").First()); - Assert.True(output.Headers.Contains("Api-Version"), "Headers include Api-Version header"); + Assert.True( + output.Headers.Contains("Api-Version"), + "Headers include Api-Version header" + ); Assert.Equal("1", output.Headers.GetValues("Api-Version").First()); - Assert.True(output.Headers.Contains("Authorization"), "Headers include Authorization header"); - Assert.Equal("SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", output.Headers.GetValues("Authorization").First()); + Assert.True( + output.Headers.Contains("Authorization"), + "Headers include Authorization header" + ); + Assert.Equal( + "SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", + output.Headers.GetValues("Authorization").First() + ); Assert.True(output.Headers.Contains("Accept"), "Headers include Accept header"); Assert.Equal("application/json", output.Headers.GetValues("Accept").First()); @@ -2046,21 +2863,33 @@ public void LastWriteWinsWhenHeaderCollectionAndDynamicHeader() var authHeader = "LetMeIn"; var headerCollection = new Dictionary { - {"Authorization", "OpenSesame"} + { "Authorization", "OpenSesame" } }; var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeader)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeader) + ); var output = factory(new object[] { 6, authHeader, headerCollection }); - Assert.True(output.Headers.Contains("Authorization"), "Headers include Authorization header"); + Assert.True( + output.Headers.Contains("Authorization"), + "Headers include Authorization header" + ); Assert.Equal("OpenSesame", output.Headers.GetValues("Authorization").First()); fixture = new RequestBuilderImplementation(); - factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeaderOrderFlipped)); + factory = fixture.BuildRequestFactoryForMethod( + nameof( + IDummyHttpApi.FetchSomeStuffWithDynamicHeaderCollectionAndDynamicHeaderOrderFlipped + ) + ); output = factory(new object[] { 6, headerCollection, authHeader }); - Assert.True(output.Headers.Contains("Authorization"), "Headers include Authorization header"); + Assert.True( + output.Headers.Contains("Authorization"), + "Headers include Authorization header" + ); Assert.Equal(authHeader, output.Headers.GetValues("Authorization").First()); } @@ -2078,11 +2907,20 @@ public void NullHeaderCollectionDoesntBlowUp(string interfaceMethodName) Assert.True(output.Headers.Contains("User-Agent"), "Headers include User-Agent header"); Assert.Equal("RefitTestClient", output.Headers.GetValues("User-Agent").First()); - Assert.True(output.Headers.Contains("Api-Version"), "Headers include Api-Version header"); + Assert.True( + output.Headers.Contains("Api-Version"), + "Headers include Api-Version header" + ); Assert.Equal("1", output.Headers.GetValues("Api-Version").First()); - Assert.True(output.Headers.Contains("Authorization"), "Headers include Authorization header"); - Assert.Equal("SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", output.Headers.GetValues("Authorization").First()); + Assert.True( + output.Headers.Contains("Authorization"), + "Headers include Authorization header" + ); + Assert.Equal( + "SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==", + output.Headers.GetValues("Authorization").First() + ); Assert.True(output.Headers.Contains("Accept"), "Headers include Accept header"); Assert.Equal("application/json", output.Headers.GetValues("Accept").First()); } @@ -2092,17 +2930,25 @@ public void HeaderCollectionCanUnsetHeaders() { var headerCollection = new Dictionary { - {"Authorization", ""}, - {"Api-Version", null} + { "Authorization", "" }, + { "Api-Version", null } }; var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.FetchSomeStuffWithDynamicHeaderCollection)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.FetchSomeStuffWithDynamicHeaderCollection) + ); var output = factory(new object[] { 6, headerCollection }); - Assert.True(!output.Headers.Contains("Api-Version"), "Headers does not include Api-Version header"); + Assert.True( + !output.Headers.Contains("Api-Version"), + "Headers does not include Api-Version header" + ); - Assert.True(output.Headers.Contains("Authorization"), "Headers include Authorization header"); + Assert.True( + output.Headers.Contains("Authorization"), + "Headers include Authorization header" + ); Assert.Equal("", output.Headers.GetValues("Authorization").First()); } @@ -2121,15 +2967,18 @@ public void DynamicRequestPropertiesShouldBeInProperties(string interfaceMethodN #if NET6_0_OR_GREATER Assert.NotEmpty(output.Options); - Assert.Equal(someProperty, ((IDictionary)output.Options)["SomeProperty"]); + Assert.Equal( + someProperty, + ((IDictionary)output.Options)["SomeProperty"] + ); #endif #pragma warning disable CS0618 // Type or member is obsolete Assert.NotEmpty(output.Properties); Assert.Equal(someProperty, output.Properties["SomeProperty"]); #pragma warning restore CS0618 // Type or member is obsolete - } + [Fact] public void OptionsFromSettingsShouldBeInProperties() { @@ -2137,23 +2986,35 @@ public void OptionsFromSettingsShouldBeInProperties() string valueProp1 = "TestValue"; const string nameProp2 = "UnitTest.Property2"; object valueProp2 = new List() { "123", "345" }; - var fixture = new RequestBuilderImplementation(new RefitSettings() - { - HttpRequestMessageOptions = new Dictionary() + var fixture = new RequestBuilderImplementation( + new RefitSettings() { - [nameProp1] = valueProp1, - [nameProp2] = valueProp2, - }, - }); + HttpRequestMessageOptions = new Dictionary() + { + [nameProp1] = valueProp1, + [nameProp2] = valueProp2, + }, + } + ); var factory = fixture.BuildRequestFactoryForMethod(nameof(IContainAandB.Ping)); var output = factory(Array.Empty()); #if NET6_0_OR_GREATER Assert.NotEmpty(output.Options); - Assert.True(output.Options.TryGetValue(new HttpRequestOptionsKey(nameProp1), out var resultValueProp1)); + Assert.True( + output.Options.TryGetValue( + new HttpRequestOptionsKey(nameProp1), + out var resultValueProp1 + ) + ); Assert.Equal(valueProp1, resultValueProp1); - Assert.True(output.Options.TryGetValue(new HttpRequestOptionsKey>(nameProp2), out var resultValueProp2)); + Assert.True( + output.Options.TryGetValue( + new HttpRequestOptionsKey>(nameProp2), + out var resultValueProp2 + ) + ); Assert.Equal(valueProp2, resultValueProp2); #else Assert.NotEmpty(output.Properties); @@ -2161,7 +3022,7 @@ public void OptionsFromSettingsShouldBeInProperties() Assert.IsType(resultValueProp1); Assert.Equal(valueProp1, (string)resultValueProp1); - Assert.True(output.Properties.TryGetValue(nameProp2, out var resultValueProp2)); + Assert.True(output.Properties.TryGetValue(nameProp2, out var resultValueProp2)); Assert.IsType>(resultValueProp2); Assert.Equal(valueProp2, (List)resultValueProp2); #endif @@ -2176,9 +3037,11 @@ public void InterfaceTypeShouldBeInProperties() #pragma warning disable CS0618 // Type or member is obsolete Assert.NotEmpty(output.Properties); - Assert.Equal(typeof(IContainAandB), output.Properties[HttpRequestMessageOptions.InterfaceType]); + Assert.Equal( + typeof(IContainAandB), + output.Properties[HttpRequestMessageOptions.InterfaceType] + ); #pragma warning restore CS0618 // Type or member is obsolete - } [Fact] @@ -2191,10 +3054,22 @@ public void RestMethodInfoShouldBeInProperties() #if NET6_0_OR_GREATER Assert.NotEmpty(output.Options); - Assert.True(output.Options.TryGetValue(new HttpRequestOptionsKey(HttpRequestMessageOptions.RestMethodInfo), out var restMethodInfo)); + Assert.True( + output.Options.TryGetValue( + new HttpRequestOptionsKey( + HttpRequestMessageOptions.RestMethodInfo + ), + out var restMethodInfo + ) + ); #else Assert.NotEmpty(output.Properties); - Assert.True(output.Properties.TryGetValue(HttpRequestMessageOptions.RestMethodInfo, out var restMethodInfoObj)); + Assert.True( + output.Properties.TryGetValue( + HttpRequestMessageOptions.RestMethodInfo, + out var restMethodInfoObj + ) + ); Assert.IsType(restMethodInfoObj); var restMethodInfo = restMethodInfoObj as RestMethodInfo; #endif @@ -2207,13 +3082,18 @@ public void DynamicRequestPropertiesWithDefaultKeysShouldBeInProperties() var someProperty = new object(); var someOtherProperty = new object(); var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.FetchSomeStuffWithDynamicRequestPropertyWithoutKey)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.FetchSomeStuffWithDynamicRequestPropertyWithoutKey) + ); var output = factory(new object[] { 6, someProperty, someOtherProperty }); #if NET6_0_OR_GREATER Assert.NotEmpty(output.Options); Assert.Equal(someProperty, ((IDictionary)output.Options)["someValue"]); - Assert.Equal(someOtherProperty, ((IDictionary)output.Options)["someOtherValue"]); + Assert.Equal( + someOtherProperty, + ((IDictionary)output.Options)["someOtherValue"] + ); #endif #pragma warning disable CS0618 // Type or member is obsolete @@ -2229,13 +3109,17 @@ public void DynamicRequestPropertiesWithDuplicateKeyShouldOverwritePreviousPrope var someProperty = new object(); var someOtherProperty = new object(); var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.FetchSomeStuffWithDynamicRequestPropertyWithDuplicateKey)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.FetchSomeStuffWithDynamicRequestPropertyWithDuplicateKey) + ); var output = factory(new object[] { 6, someProperty, someOtherProperty }); - #if NET6_0_OR_GREATER Assert.Equal(3, output.Options.Count()); - Assert.Equal(someOtherProperty, ((IDictionary)output.Options)["SomeProperty"]); + Assert.Equal( + someOtherProperty, + ((IDictionary)output.Options)["SomeProperty"] + ); #endif #pragma warning disable CS0618 // Type or member is obsolete @@ -2251,10 +3135,19 @@ public void HttpClientShouldPrefixedAbsolutePathToTheRequestUri() var factory = fixture.BuildRestResultFuncForMethod("FetchSomeStuffWithoutFullPath"); var testHttpMessageHandler = new TestHttpMessageHandler(); - var task = (Task)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/foo/bar") }, Array.Empty()); + var task = (Task)factory( + new HttpClient(testHttpMessageHandler) + { + BaseAddress = new Uri("http://api/foo/bar") + }, + Array.Empty() + ); task.Wait(); - Assert.Equal("http://api/foo/bar/string", testHttpMessageHandler.RequestMessage.RequestUri.ToString()); + Assert.Equal( + "http://api/foo/bar/string", + testHttpMessageHandler.RequestMessage.RequestUri.ToString() + ); } [Fact] @@ -2264,10 +3157,19 @@ public void HttpClientForVoidMethodShouldPrefixedAbsolutePathToTheRequestUri() var factory = fixture.BuildRestResultFuncForMethod("FetchSomeStuffWithVoid"); var testHttpMessageHandler = new TestHttpMessageHandler(); - var task = (Task)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/foo/bar") }, Array.Empty()); + var task = (Task)factory( + new HttpClient(testHttpMessageHandler) + { + BaseAddress = new Uri("http://api/foo/bar") + }, + Array.Empty() + ); task.Wait(); - Assert.Equal("http://api/foo/bar/void", testHttpMessageHandler.RequestMessage.RequestUri.ToString()); + Assert.Equal( + "http://api/foo/bar/void", + testHttpMessageHandler.RequestMessage.RequestUri.ToString() + ); } [Fact] @@ -2277,10 +3179,16 @@ public void HttpClientShouldNotPrefixEmptyAbsolutePathToTheRequestUri() var factory = fixture.BuildRestResultFuncForMethod("FetchSomeStuff"); var testHttpMessageHandler = new TestHttpMessageHandler(); - var task = (Task)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/") }, new object[] { 42 }); + var task = (Task)factory( + new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/") }, + new object[] { 42 } + ); task.Wait(); - Assert.Equal("http://api/foo/bar/42", testHttpMessageHandler.RequestMessage.RequestUri.ToString()); + Assert.Equal( + "http://api/foo/bar/42", + testHttpMessageHandler.RequestMessage.RequestUri.ToString() + ); } [Fact] @@ -2288,9 +3196,11 @@ public void DontBlowUpWithDynamicAuthorizationHeaderAndContent() { var fixture = new RequestBuilderImplementation(); var factory = fixture.BuildRequestFactoryForMethod("PutSomeContentWithAuthorization"); - var output = factory(new object[] { 7, new { Octocat = "Dunetocat" }, "Basic RnVjayB5ZWFoOmhlYWRlcnMh" }); + var output = factory( + new object[] { 7, new { Octocat = "Dunetocat" }, "Basic RnVjayB5ZWFoOmhlYWRlcnMh" } + ); - Assert.NotNull(output.Headers.Authorization);//, "Headers include Authorization header"); + Assert.NotNull(output.Headers.Authorization); //, "Headers include Authorization header"); Assert.Equal("RnVjayB5ZWFoOmhlYWRlcnMh", output.Headers.Authorization.Parameter); } @@ -2298,12 +3208,16 @@ public void DontBlowUpWithDynamicAuthorizationHeaderAndContent() public void SuchFlexibleContentTypeWow() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("PutSomeStuffWithDynamicContentType"); - var output = factory(new object[] { 7, "such \"refit\" is \"amaze\" wow", "text/dson" }); + var factory = fixture.BuildRequestFactoryForMethod( + "PutSomeStuffWithDynamicContentType" + ); + var output = factory( + new object[] { 7, "such \"refit\" is \"amaze\" wow", "text/dson" } + ); - Assert.NotNull(output.Content);//, "Request has content"); - Assert.NotNull(output.Content.Headers.ContentType);//, "Headers include Content-Type header"); - Assert.Equal("text/dson", output.Content.Headers.ContentType.MediaType);//, "Content-Type header has the expected value"); + Assert.NotNull(output.Content); //, "Request has content"); + Assert.NotNull(output.Content.Headers.ContentType); //, "Headers include Content-Type header"); + Assert.Equal("text/dson", output.Content.Headers.ContentType.MediaType); //, "Content-Type header has the expected value"); } [Fact] @@ -2312,14 +3226,17 @@ public void BodyContentGetsUrlEncoded() var fixture = new RequestBuilderImplementation(); var factory = fixture.RunRequest("PostSomeUrlEncodedStuff"); var output = factory( - new object[] { + new object[] + { 6, - new { + new + { Foo = "Something", Bar = 100, Baz = "" // explicitly use blank to preserve value that would be stripped if null } - }); + } + ); Assert.Equal("Foo=Something&Bar=100&Baz=", output.SendContent); } @@ -2330,14 +3247,12 @@ public void FormFieldGetsAliased() var fixture = new RequestBuilderImplementation(); var factory = fixture.RunRequest("PostSomeAliasedUrlEncodedStuff"); var output = factory( - new object[] { + new object[] + { 6, - new SomeRequestData { - ReadablePropertyName = 99 - } - }); - - + new SomeRequestData { ReadablePropertyName = 99 } + } + ); Assert.Equal("rpn=99", output.SendContent); } @@ -2345,7 +3260,10 @@ public void FormFieldGetsAliased() [Fact] public void CustomParmeterFormatter() { - var settings = new RefitSettings { UrlParameterFormatter = new TestUrlParameterFormatter("custom-parameter") }; + var settings = new RefitSettings + { + UrlParameterFormatter = new TestUrlParameterFormatter("custom-parameter") + }; var fixture = new RequestBuilderImplementation(settings); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuff"); @@ -2358,7 +3276,10 @@ public void CustomParmeterFormatter() [Fact] public void QueryStringWithEnumerablesCanBeFormatted() { - var settings = new RefitSettings { UrlParameterFormatter = new TestEnumerableUrlParameterFormatter() }; + var settings = new RefitSettings + { + UrlParameterFormatter = new TestEnumerableUrlParameterFormatter() + }; var fixture = new RequestBuilderImplementation(settings); var factory = fixture.BuildRequestFactoryForMethod("QueryWithEnumerable"); @@ -2371,7 +3292,10 @@ public void QueryStringWithEnumerablesCanBeFormatted() [Fact] public void QueryStringWithArrayCanBeFormatted() { - var settings = new RefitSettings { UrlParameterFormatter = new TestEnumerableUrlParameterFormatter() }; + var settings = new RefitSettings + { + UrlParameterFormatter = new TestEnumerableUrlParameterFormatter() + }; var fixture = new RequestBuilderImplementation(settings); var factory = fixture.BuildRequestFactoryForMethod("QueryWithArray"); @@ -2408,10 +3332,9 @@ public void QueryStringWithArrayCanBeFormattedByAttributeWithMultiple() [Fact] public void QueryStringWithArrayCanBeFormattedByDefaultSetting() { - var fixture = new RequestBuilderImplementation(new RefitSettings - { - CollectionFormat = CollectionFormat.Multi - }); + var fixture = new RequestBuilderImplementation( + new RefitSettings { CollectionFormat = CollectionFormat.Multi } + ); var factory = fixture.BuildRequestFactoryForMethod("QueryWithArray"); var output = factory(new object[] { new[] { 1, 2, 3 } }); @@ -2422,10 +3345,9 @@ public void QueryStringWithArrayCanBeFormattedByDefaultSetting() [Fact] public void DefaultCollectionFormatCanBeOverridenByQueryAttribute() { - var fixture = new RequestBuilderImplementation(new RefitSettings - { - CollectionFormat = CollectionFormat.Multi - }); + var fixture = new RequestBuilderImplementation( + new RefitSettings { CollectionFormat = CollectionFormat.Multi } + ); var factory = fixture.BuildRequestFactoryForMethod("QueryWithArrayFormattedAsCsv"); var output = factory(new object[] { new[] { 1, 2, 3 } }); @@ -2438,7 +3360,9 @@ public void RequestWithParameterInMultiplePlaces() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.FetchSomeStuffWithTheSameId)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.FetchSomeStuffWithTheSameId) + ); var output = factory(new object[] { "theId" }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -2455,14 +3379,15 @@ public void RequestWithParameterInAQueryParameterMultipleTimes() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.FetchSomeStuffWithTheIdInAParameterMultipleTimes)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.FetchSomeStuffWithTheIdInAParameterMultipleTimes) + ); var output = factory(new object[] { "theId" }); var uri = new Uri(new Uri("http://api"), output.RequestUri); Assert.Equal("/foo/bar?param=first%20theId%20and%20second%20theId", uri.PathAndQuery); } - [Theory] [InlineData("QueryWithArrayFormattedAsMulti", "/query?numbers=1&numbers=2&numbers=3")] [InlineData("QueryWithArrayFormattedAsCsv", "/query?numbers=1%2C2%2C3")] @@ -2483,28 +3408,34 @@ public void QueryStringWithArrayFormatted(string apiMethodName, string expectedQ [Fact] public void QueryStringWithArrayFormattedAsSsvAndItemsFormattedIndividually() { - var settings = new RefitSettings { UrlParameterFormatter = new TestUrlParameterFormatter("custom-parameter") }; + var settings = new RefitSettings + { + UrlParameterFormatter = new TestUrlParameterFormatter("custom-parameter") + }; var fixture = new RequestBuilderImplementation(settings); var factory = fixture.BuildRequestFactoryForMethod("QueryWithArrayFormattedAsSsv"); var output = factory(new object[] { new int[] { 1, 2, 3 } }); var uri = new Uri(new Uri("http://api"), output.RequestUri); - Assert.Equal("/query?numbers=custom-parameter%20custom-parameter%20custom-parameter", uri.PathAndQuery); + Assert.Equal( + "/query?numbers=custom-parameter%20custom-parameter%20custom-parameter", + uri.PathAndQuery + ); } [Fact] public void QueryStringWithEnumerablesCanBeFormattedEnumerable() { - var settings = new RefitSettings { UrlParameterFormatter = new TestEnumerableUrlParameterFormatter() }; + var settings = new RefitSettings + { + UrlParameterFormatter = new TestEnumerableUrlParameterFormatter() + }; var fixture = new RequestBuilderImplementation(settings); var factory = fixture.BuildRequestFactoryForMethod("QueryWithEnumerable"); - var list = new List - { - 1, 2, 3 - }; + var list = new List { 1, 2, 3 }; var output = factory(new object[] { list }); @@ -2513,7 +3444,10 @@ public void QueryStringWithEnumerablesCanBeFormattedEnumerable() } [Theory] - [InlineData("QueryWithEnumerableFormattedAsMulti", "/query?lines=first&lines=second&lines=third")] + [InlineData( + "QueryWithEnumerableFormattedAsMulti", + "/query?lines=first&lines=second&lines=third" + )] [InlineData("QueryWithEnumerableFormattedAsCsv", "/query?lines=first%2Csecond%2Cthird")] [InlineData("QueryWithEnumerableFormattedAsSsv", "/query?lines=first%20second%20third")] [InlineData("QueryWithEnumerableFormattedAsTsv", "/query?lines=first%09second%09third")] @@ -2524,12 +3458,7 @@ public void QueryStringWithEnumerableFormatted(string apiMethodName, string expe var factory = fixture.BuildRequestFactoryForMethod(apiMethodName); - var lines = new List - { - "first", - "second", - "third" - }; + var lines = new List { "first", "second", "third" }; var output = factory(new object[] { lines }); @@ -2544,11 +3473,7 @@ public void QueryStringExcludesPropertiesWithPrivateGetters() var factory = fixture.BuildRequestFactoryForMethod("QueryWithObjectWithPrivateGetters"); - var person = new Person - { - FirstName = "Mickey", - LastName = "Mouse" - }; + var person = new Person { FirstName = "Mickey", LastName = "Mouse" }; var output = factory(new object[] { person }); @@ -2559,7 +3484,10 @@ public void QueryStringExcludesPropertiesWithPrivateGetters() [Theory] [InlineData(FooWithEnumMember.A, "/query?foo=A")] [InlineData(FooWithEnumMember.B, "/query?foo=b")] - public void QueryStringUsesEnumMemberAttribute(FooWithEnumMember queryParameter, string expectedQuery) + public void QueryStringUsesEnumMemberAttribute( + FooWithEnumMember queryParameter, + string expectedQuery + ) { var fixture = new RequestBuilderImplementation(); var factory = fixture.BuildRequestFactoryForMethod("QueryWithEnum"); @@ -2573,12 +3501,17 @@ public void QueryStringUsesEnumMemberAttribute(FooWithEnumMember queryParameter, [Theory] [InlineData(FooWithEnumMember.A, "/query?foo=A")] [InlineData(FooWithEnumMember.B, "/query?foo=b")] - public void QueryStringUsesEnumMemberAttributeInTypeWithEnum(FooWithEnumMember queryParameter, string expectedQuery) + public void QueryStringUsesEnumMemberAttributeInTypeWithEnum( + FooWithEnumMember queryParameter, + string expectedQuery + ) { var fixture = new RequestBuilderImplementation(); var factory = fixture.BuildRequestFactoryForMethod("QueryWithTypeWithEnum"); - var output = factory(new object[] { new TypeFooWithEnumMember { Foo = queryParameter } }); + var output = factory( + new object[] { new TypeFooWithEnumMember { Foo = queryParameter } } + ); var uri = new Uri(new Uri("http://api"), output.RequestUri); Assert.Equal(expectedQuery, uri.PathAndQuery); @@ -2613,14 +3546,23 @@ public void TestNullableQueryStringParamsWithANull(string expectedQuery) public void TestNullableQueryStringParamsWithANullAndPathBoundObject(string expectedQuery) { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod("QueryWithOptionalParametersPathBoundObject"); - var output = factory(new object[] { new PathBoundObject() { SomeProperty = 123, SomeProperty2 = "test" }, "title", null, new string[] { "A", "B" } }); + var factory = fixture.BuildRequestFactoryForMethod( + "QueryWithOptionalParametersPathBoundObject" + ); + var output = factory( + new object[] + { + new PathBoundObject() { SomeProperty = 123, SomeProperty2 = "test" }, + "title", + null, + new string[] { "A", "B" } + } + ); var uri = new Uri(new Uri("http://api"), output.RequestUri); Assert.Equal(expectedQuery, uri.PathAndQuery); } - [Fact] [UseCulture("es-ES")] // Spain uses a , instead of a . public void DefaultParameterFormatterIsInvariant() @@ -2695,7 +3637,9 @@ public void MultipartPostWithAliasAndHeader() public void PostBlobByteWithAlias() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.Blob_Post_Byte)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.Blob_Post_Byte) + ); var bytes = new byte[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; @@ -2712,7 +3656,9 @@ public void PostBlobByteWithAlias() public void QueryWithAliasAndHeadersWorks() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.QueryWithHeadersBeforeData)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.QueryWithHeadersBeforeData) + ); var authHeader = "theAuth"; var langHeader = "LnG"; @@ -2720,13 +3666,16 @@ public void QueryWithAliasAndHeadersWorks() var controlIdParam = "theControlId"; var secretValue = "theSecret"; - - - var output = factory(new object[] { authHeader, langHeader, searchParam, controlIdParam, secretValue }); + var output = factory( + new object[] { authHeader, langHeader, searchParam, controlIdParam, secretValue } + ); var uri = new Uri(new Uri("http://api"), output.RequestUri); - Assert.Equal($"/api/someModule/deviceList?controlId={controlIdParam}&search={searchParam}&secret={secretValue}", uri.PathAndQuery); + Assert.Equal( + $"/api/someModule/deviceList?controlId={controlIdParam}&search={searchParam}&secret={secretValue}", + uri.PathAndQuery + ); Assert.Equal(langHeader, output.Headers.GetValues("X-LnG").FirstOrDefault()); Assert.Equal(authHeader, output.Headers.Authorization?.Scheme); } @@ -2735,7 +3684,11 @@ class RequestBuilderMock : IRequestBuilder { public int CallCount { get; private set; } - public Func BuildRestResultFuncForMethod(string methodName, Type[] parameterTypes = null, Type[] genericArgumentTypes = null) + public Func BuildRestResultFuncForMethod( + string methodName, + Type[] parameterTypes = null, + Type[] genericArgumentTypes = null + ) { CallCount++; return null; @@ -2748,10 +3701,24 @@ public void CachedRequestBuilderCallInternalBuilderForParametersWithSameNamesBut var internalBuilder = new RequestBuilderMock(); var cachedBuilder = new CachedRequestBuilderImplementation(internalBuilder); - cachedBuilder.BuildRestResultFuncForMethod("TestMethodName", new[] { typeof(CollisionA.SomeType) }); - cachedBuilder.BuildRestResultFuncForMethod("TestMethodName", new[] { typeof(CollisionB.SomeType) }); - cachedBuilder.BuildRestResultFuncForMethod("TestMethodName", null, new[] { typeof(CollisionA.SomeType) }); - cachedBuilder.BuildRestResultFuncForMethod("TestMethodName", null, new[] { typeof(CollisionB.SomeType) }); + cachedBuilder.BuildRestResultFuncForMethod( + "TestMethodName", + new[] { typeof(CollisionA.SomeType) } + ); + cachedBuilder.BuildRestResultFuncForMethod( + "TestMethodName", + new[] { typeof(CollisionB.SomeType) } + ); + cachedBuilder.BuildRestResultFuncForMethod( + "TestMethodName", + null, + new[] { typeof(CollisionA.SomeType) } + ); + cachedBuilder.BuildRestResultFuncForMethod( + "TestMethodName", + null, + new[] { typeof(CollisionB.SomeType) } + ); Assert.Equal(4, internalBuilder.CallCount); } @@ -2760,7 +3727,9 @@ public void CachedRequestBuilderCallInternalBuilderForParametersWithSameNamesBut public void DictionaryQueryWithEnumKeyProducesCorrectQueryString() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.QueryWithDictionaryWithEnumKey)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.QueryWithDictionaryWithEnumKey) + ); var dict = new Dictionary { @@ -2778,7 +3747,9 @@ public void DictionaryQueryWithEnumKeyProducesCorrectQueryString() public void DictionaryQueryWithPrefix() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.QueryWithDictionaryWithPrefix)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.QueryWithDictionaryWithPrefix) + ); var dict = new Dictionary { @@ -2796,13 +3767,11 @@ public void DictionaryQueryWithPrefix() public void DictionaryQueryWithNumericKeyProducesCorrectQueryString() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.QueryWithDictionaryWithNumericKey)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.QueryWithDictionaryWithNumericKey) + ); - var dict = new Dictionary - { - { 1, "value1" }, - { 2, "value2" }, - }; + var dict = new Dictionary { { 1, "value1" }, { 2, "value2" }, }; var output = factory(new object[] { dict }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -2817,7 +3786,9 @@ public void DictionaryQueryWithCustomFormatterProducesCorrectQueryString() var refitSettings = new RefitSettings { UrlParameterFormatter = urlParameterFormatter }; var fixture = new RequestBuilderImplementation(refitSettings); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.QueryWithDictionaryWithEnumKey)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.QueryWithDictionaryWithEnumKey) + ); var dict = new Dictionary { @@ -2828,19 +3799,21 @@ public void DictionaryQueryWithCustomFormatterProducesCorrectQueryString() var output = factory(new object[] { dict }); var uri = new Uri(new Uri("http://api"), output.RequestUri); - Assert.Equal($"/foo?{(int)TestEnum.A}=value1{TestEnumUrlParameterFormatter.StringParameterSuffix}&{(int)TestEnum.B}=value2{TestEnumUrlParameterFormatter.StringParameterSuffix}", uri.PathAndQuery); + Assert.Equal( + $"/foo?{(int)TestEnum.A}=value1{TestEnumUrlParameterFormatter.StringParameterSuffix}&{(int)TestEnum.B}=value2{TestEnumUrlParameterFormatter.StringParameterSuffix}", + uri.PathAndQuery + ); } [Fact] public void ComplexQueryObjectWithDefaultKeyFormatterProducesCorrectQueryString() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary) + ); - var complexQuery = new ComplexQueryObject - { - TestAlias2 = "value1" - }; + var complexQuery = new ComplexQueryObject { TestAlias2 = "value1" }; var output = factory(new object[] { complexQuery }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -2853,14 +3826,16 @@ public void ComplexQueryObjectWithCustomKeyFormatterProducesCorrectQueryString() { var urlParameterKeyFormatter = new CamelCaseUrlParameterKeyFormatter(); - var refitSettings = new RefitSettings { UrlParameterKeyFormatter = urlParameterKeyFormatter }; - var fixture = new RequestBuilderImplementation(refitSettings); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary)); - - var complexQuery = new ComplexQueryObject + var refitSettings = new RefitSettings { - TestAlias2 = "value1" + UrlParameterKeyFormatter = urlParameterKeyFormatter }; + var fixture = new RequestBuilderImplementation(refitSettings); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary) + ); + + var complexQuery = new ComplexQueryObject { TestAlias2 = "value1" }; var output = factory(new object[] { complexQuery }); var uri = new Uri(new Uri("http://api"), output.RequestUri); @@ -2872,7 +3847,9 @@ public void ComplexQueryObjectWithCustomKeyFormatterProducesCorrectQueryString() public void ComplexQueryObjectWithAliasedDictionaryProducesCorrectQueryString() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary) + ); var complexQuery = new ComplexQueryObject { @@ -2886,14 +3863,19 @@ public void ComplexQueryObjectWithAliasedDictionaryProducesCorrectQueryString() var output = factory(new object[] { complexQuery }); var uri = new Uri(new Uri("http://api"), output.RequestUri); - Assert.Equal("/foo?test-dictionary-alias.A=value1&test-dictionary-alias.B=value2", uri.PathAndQuery); + Assert.Equal( + "/foo?test-dictionary-alias.A=value1&test-dictionary-alias.B=value2", + uri.PathAndQuery + ); } [Fact] public void ComplexQueryObjectWithDictionaryProducesCorrectQueryString() { var fixture = new RequestBuilderImplementation(); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary) + ); var complexQuery = new ComplexQueryObject { @@ -2916,7 +3898,9 @@ public void ComplexQueryObjectWithDictionaryAndCustomFormatterProducesCorrectQue var urlParameterFormatter = new TestEnumUrlParameterFormatter(); var refitSettings = new RefitSettings { UrlParameterFormatter = urlParameterFormatter }; var fixture = new RequestBuilderImplementation(refitSettings); - var factory = fixture.BuildRequestFactoryForMethod(nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary)); + var factory = fixture.BuildRequestFactoryForMethod( + nameof(IDummyHttpApi.ComplexQueryObjectWithDictionary) + ); var complexQuery = new ComplexQueryObject { @@ -2930,28 +3914,41 @@ public void ComplexQueryObjectWithDictionaryAndCustomFormatterProducesCorrectQue var output = factory(new object[] { complexQuery }); var uri = new Uri(new Uri("http://api"), output.RequestUri); - Assert.Equal($"/foo?TestDictionary.{(int)TestEnum.A}=value1{TestEnumUrlParameterFormatter.StringParameterSuffix}&TestDictionary.{(int)TestEnum.B}=value2{TestEnumUrlParameterFormatter.StringParameterSuffix}", uri.PathAndQuery); + Assert.Equal( + $"/foo?TestDictionary.{(int)TestEnum.A}=value1{TestEnumUrlParameterFormatter.StringParameterSuffix}&TestDictionary.{(int)TestEnum.B}=value2{TestEnumUrlParameterFormatter.StringParameterSuffix}", + uri.PathAndQuery + ); } } static class RequestBuilderTestExtensions { - public static Func BuildRequestFactoryForMethod(this IRequestBuilder builder, string methodName, string baseAddress = "http://api/") + public static Func BuildRequestFactoryForMethod( + this IRequestBuilder builder, + string methodName, + string baseAddress = "http://api/" + ) { var factory = builder.BuildRestResultFuncForMethod(methodName); var testHttpMessageHandler = new TestHttpMessageHandler(); - return paramList => { - var task = (Task)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri(baseAddress) }, paramList); + var task = (Task)factory( + new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri(baseAddress) }, + paramList + ); task.Wait(); return testHttpMessageHandler.RequestMessage; }; } - - public static Func RunRequest(this IRequestBuilder builder, string methodName, string returnContent = null, string baseAddress = "http://api/") + public static Func RunRequest( + this IRequestBuilder builder, + string methodName, + string returnContent = null, + string baseAddress = "http://api/" + ) { var factory = builder.BuildRestResultFuncForMethod(methodName); var testHttpMessageHandler = new TestHttpMessageHandler(); @@ -2962,15 +3959,15 @@ public static Func RunRequest(this IRequestBui return paramList => { - var task = (Task)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri(baseAddress) }, paramList); + var task = (Task)factory( + new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri(baseAddress) }, + paramList + ); try { task.Wait(); } - catch (AggregateException e) when (e.InnerException is TaskCanceledException) - { - - } + catch (AggregateException e) when (e.InnerException is TaskCanceledException) { } return testHttpMessageHandler; }; diff --git a/Refit.Tests/ResponseTests.cs b/Refit.Tests/ResponseTests.cs index 0b3136968..0b7149f2a 100644 --- a/Refit.Tests/ResponseTests.cs +++ b/Refit.Tests/ResponseTests.cs @@ -6,15 +6,15 @@ using System.Net.Http.Headers; using System.Text; using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading.Tasks; using Newtonsoft.Json; -using RichardSzalay.MockHttp; using Refit; using Refit.Buffers; +using RichardSzalay.MockHttp; // for the code gen using Xunit; using JsonSerializer = Newtonsoft.Json.JsonSerializer; -using System.Text.Json.Serialization; namespace Refit.Tests; @@ -113,9 +113,7 @@ public async Task ThrowsValidationException() }; expectedResponse.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/problem+json"); - mockHandler - .Expect(HttpMethod.Get, "http://api/aliasTest") - .Respond(req => expectedResponse); + mockHandler.Expect(HttpMethod.Get, "http://api/aliasTest").Respond(req => expectedResponse); var actualException = await Assert.ThrowsAsync( () => fixture.GetTestObject() @@ -197,13 +195,9 @@ public async Task WhenProblemDetailsResponseContainsExtensions_ShouldHydrateExte expectedResponse.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/problem+json"); - mockHandler - .Expect(HttpMethod.Get, "http://api/aliasTest") - .Respond(req => expectedResponse); + mockHandler.Expect(HttpMethod.Get, "http://api/aliasTest").Respond(req => expectedResponse); - mockHandler - .Expect(HttpMethod.Get, "http://api/soloyolo") - .Respond(req => expectedResponse); + mockHandler.Expect(HttpMethod.Get, "http://api/soloyolo").Respond(req => expectedResponse); var actualException = await Assert.ThrowsAsync( () => fixture.GetTestObject() @@ -241,9 +235,7 @@ public async Task WithNonSeekableStream_UsingSystemTextJsonContentSerializer() { var model = new TestAliasObject { - ShortNameForAlias = nameof( - WithNonSeekableStream_UsingSystemTextJsonContentSerializer - ), + ShortNameForAlias = nameof(WithNonSeekableStream_UsingSystemTextJsonContentSerializer), ShortNameForJsonProperty = nameof(TestAliasObject) }; @@ -281,14 +273,9 @@ public async Task WithNonSeekableStream_UsingSystemTextJsonContentSerializer() } }; - var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = httpContent - }; + var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = httpContent }; - expectedResponse.Content.Headers.ContentType = new MediaTypeHeaderValue( - "application/json" - ); + expectedResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); expectedResponse.StatusCode = HttpStatusCode.OK; localHandler @@ -316,13 +303,9 @@ public async Task BadRequestWithEmptyContent_ShouldReturnApiException() }; expectedResponse.Content.Headers.Clear(); - mockHandler - .Expect(HttpMethod.Get, "http://api/aliasTest") - .Respond(req => expectedResponse); + mockHandler.Expect(HttpMethod.Get, "http://api/aliasTest").Respond(req => expectedResponse); - var actualException = await Assert.ThrowsAsync( - () => fixture.GetTestObject() - ); + var actualException = await Assert.ThrowsAsync(() => fixture.GetTestObject()); Assert.NotNull(actualException.Content); Assert.Equal("Hello world", actualException.Content); @@ -389,9 +372,7 @@ public async Task ValidationApiException_HydratesBaseContent() expectedResponse.Content.Headers.ContentType = new MediaTypeHeaderValue( "application/problem+json" ); - mockHandler - .Expect(HttpMethod.Get, "http://api/aliasTest") - .Respond(req => expectedResponse); + mockHandler.Expect(HttpMethod.Get, "http://api/aliasTest").Respond(req => expectedResponse); var actualException = await Assert.ThrowsAsync( () => fixture.GetTestObject() @@ -410,13 +391,9 @@ public async Task WithHtmlResponse_ShouldReturnApiException() }; expectedResponse.Content.Headers.Clear(); - mockHandler - .Expect(HttpMethod.Get, "http://api/aliasTest") - .Respond(req => expectedResponse); + mockHandler.Expect(HttpMethod.Get, "http://api/aliasTest").Respond(req => expectedResponse); - var actualException = await Assert.ThrowsAsync( - () => fixture.GetTestObject() - ); + var actualException = await Assert.ThrowsAsync(() => fixture.GetTestObject()); Assert.IsType(actualException.InnerException); Assert.NotNull(actualException.Content); @@ -463,9 +440,7 @@ public async Task WithNonJsonResponseUsingNewtonsoftJsonContentSerializer_Should }; expectedResponse.Content.Headers.Clear(); - mockHandler - .Expect(HttpMethod.Get, "http://api/aliasTest") - .Respond(req => expectedResponse); + mockHandler.Expect(HttpMethod.Get, "http://api/aliasTest").Respond(req => expectedResponse); var actualException = await Assert.ThrowsAsync( () => newtonSoftFixture.GetTestObject() @@ -511,7 +486,9 @@ public sealed class ThrowOnGetLengthMemoryStream : MemoryStream { public bool CanGetLength { get; set; } - public override bool CanSeek { get => CanGetLength; } - public override long Length => - CanGetLength ? base.Length : throw new NotSupportedException(); + public override bool CanSeek + { + get => CanGetLength; + } + public override long Length => CanGetLength ? base.Length : throw new NotSupportedException(); } diff --git a/Refit.Tests/RestService.cs b/Refit.Tests/RestService.cs index d334059a4..3b130a9d1 100644 --- a/Refit.Tests/RestService.cs +++ b/Refit.Tests/RestService.cs @@ -9,12 +9,9 @@ using System.Text; using System.Threading; using System.Threading.Tasks; - using Newtonsoft.Json; using Refit; // InterfaceStubGenerator looks for this - using RichardSzalay.MockHttp; - using Xunit; namespace Refit.Tests; @@ -466,9 +463,7 @@ public async Task GetWithPathBoundObjectAndParameterParameterPrecedence() var mockHttp = new MockHttpMessageHandler(); mockHttp .Expect(HttpMethod.Get, "http://foo/foos/chooseMe/bar/barNone") - .WithExactQueryString( - new[] { new KeyValuePair("SomeProperty", "1") } - ) + .WithExactQueryString(new[] { new KeyValuePair("SomeProperty", "1") }) .Respond("application/json", "Ok"); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; @@ -941,10 +936,7 @@ public async Task HitTheGitHubUserApi() mockHttp .Expect(HttpMethod.Get, "https://api.github.com/users/octocat") - .Respond( - "application/json", - "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }" - ); + .Respond("application/json", "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }"); var fixture = RestService.For("https://api.github.com", settings); @@ -974,10 +966,7 @@ public async Task HitWithCamelCaseParameter() mockHttp .Expect(HttpMethod.Get, "https://api.github.com/users/octocat") - .Respond( - "application/json", - "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }" - ); + .Respond("application/json", "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }"); var fixture = RestService.For("https://api.github.com", settings); @@ -1162,16 +1151,11 @@ public async Task HitTheGitHubUserApiAsObservable() mockHttp .Expect(HttpMethod.Get, "https://api.github.com/users/octocat") - .Respond( - "application/json", - "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }" - ); + .Respond("application/json", "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }"); var fixture = RestService.For("https://api.github.com", settings); - var result = await fixture - .GetUserObservable("octocat") - .Timeout(TimeSpan.FromSeconds(10)); + var result = await fixture.GetUserObservable("octocat").Timeout(TimeSpan.FromSeconds(10)); Assert.Equal("octocat", result.Login); Assert.False(string.IsNullOrEmpty(result.AvatarUrl)); @@ -1197,10 +1181,7 @@ public async Task HitTheGitHubUserApiAsObservableAndSubscribeAfterTheFact() mockHttp .When(HttpMethod.Get, "https://api.github.com/users/octocat") - .Respond( - "application/json", - "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }" - ); + .Respond("application/json", "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }"); var fixture = RestService.For("https://api.github.com", settings); @@ -1323,9 +1304,7 @@ public async Task PostToRequestBin() var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; - mockHttp - .Expect(HttpMethod.Post, "http://httpbin.org/1h3a5jm1") - .Respond(HttpStatusCode.OK); + mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/1h3a5jm1").Respond(HttpStatusCode.OK); var fixture = RestService.For("http://httpbin.org/", settings); @@ -1400,9 +1379,7 @@ public async Task PostToRequestBinWithGenerics() var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; - mockHttp - .Expect(HttpMethod.Post, "http://httpbin.org/1h3a5jm1") - .Respond(HttpStatusCode.OK); + mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/1h3a5jm1").Respond(HttpStatusCode.OK); var fixture = RestService.For("http://httpbin.org/", settings); @@ -1412,9 +1389,7 @@ public async Task PostToRequestBinWithGenerics() mockHttp.ResetExpectations(); - mockHttp - .Expect(HttpMethod.Post, "http://httpbin.org/1h3a5jm1") - .Respond(HttpStatusCode.OK); + mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/1h3a5jm1").Respond(HttpStatusCode.OK); await fixture.PostGeneric("4"); @@ -1428,11 +1403,7 @@ public async Task PostWithVoidReturnBufferedBodyExpectContentLengthHeader() var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; - var postBody = new Dictionary - { - { "some", "body" }, - { "once", "told me" } - }; + var postBody = new Dictionary { { "some", "body" }, { "once", "told me" } }; mockHttp .Expect(HttpMethod.Post, "http://httpbin.org/foo") @@ -1453,11 +1424,7 @@ public async Task PostWithNonVoidReturnBufferedBodyExpectContentLengthHeader() var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; - var postBody = new Dictionary - { - { "some", "body" }, - { "once", "told me" } - }; + var postBody = new Dictionary { { "some", "body" }, { "once", "told me" } }; const string expectedResponse = "some response"; mockHttp @@ -1972,19 +1939,13 @@ public async Task InheritedInterfaceWithoutRefitInBaseMethodsTest() mockHttp .Expect(HttpMethod.Get, "https://httpbin.org/DoSomethingElse") - .Respond( - "application/json", - nameof(IImplementTheInterfaceAndUseRefit.DoSomethingElse) - ); + .Respond("application/json", nameof(IImplementTheInterfaceAndUseRefit.DoSomethingElse)); await fixture.DoSomethingElse(); mockHttp.VerifyNoOutstandingExpectation(); mockHttp .Expect(HttpMethod.Get, "https://httpbin.org/DoSomethingElse") - .Respond( - "application/json", - nameof(IImplementTheInterfaceAndUseRefit.DoSomethingElse) - ); + .Respond("application/json", nameof(IImplementTheInterfaceAndUseRefit.DoSomethingElse)); await ((IAmInterfaceEWithNoRefit)fixture).DoSomethingElse(); mockHttp.VerifyNoOutstandingExpectation(); @@ -2199,31 +2160,30 @@ public void NonGenericCreate() Assert.Equal(fixture.Client.BaseAddress.AbsoluteUri, expectedBaseAddress); } - [Fact] - public async Task TypeCollisionTest() - { - var mockHttp = new MockHttpMessageHandler(); + [Fact] + public async Task TypeCollisionTest() + { + var mockHttp = new MockHttpMessageHandler(); - var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp, }; + var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp, }; - const string Url = "https://httpbin.org/get"; + const string Url = "https://httpbin.org/get"; - mockHttp.Expect(HttpMethod.Get, Url).Respond("application/json", "{ }"); + mockHttp.Expect(HttpMethod.Get, Url).Respond("application/json", "{ }"); - var fixtureA = RestService.For(Url, settings); + var fixtureA = RestService.For(Url, settings); - var respA = await fixtureA.SomeARequest(); + var respA = await fixtureA.SomeARequest(); - mockHttp.Expect(HttpMethod.Get, Url) - .Respond("application/json", "{ }"); + mockHttp.Expect(HttpMethod.Get, Url).Respond("application/json", "{ }"); - var fixtureB = RestService.For(Url, settings); + var fixtureB = RestService.For(Url, settings); - var respB = await fixtureB.SomeBRequest(); + var respB = await fixtureB.SomeBRequest(); - Assert.IsType(respA); - Assert.IsType(respB); - } + Assert.IsType(respA); + Assert.IsType(respB); + } internal static Stream GetTestFileStream(string relativeFilePath) { @@ -2243,9 +2203,7 @@ internal static Stream GetTestFileStream(string relativeFilePath) // get resource stream var fullName = assembly .GetManifestResourceNames() - .FirstOrDefault( - name => name.EndsWith(relativeName, StringComparison.InvariantCulture) - ); + .FirstOrDefault(name => name.EndsWith(relativeName, StringComparison.InvariantCulture)); if (fullName == null) { throw new Exception( @@ -2264,48 +2222,42 @@ internal static Stream GetTestFileStream(string relativeFilePath) return stream; } - [Fact] - public async Task SameTypeNameInMultipleNamespacesTest() - { - var mockHttp = new MockHttpMessageHandler(); + [Fact] + public async Task SameTypeNameInMultipleNamespacesTest() + { + var mockHttp = new MockHttpMessageHandler(); - var settings = new RefitSettings - { - HttpMessageHandlerFactory = () => mockHttp, - }; + var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp, }; - const string Url = "https://httpbin.org/get"; + const string Url = "https://httpbin.org/get"; - mockHttp.Expect(HttpMethod.Get, Url + "/") - .Respond("application/json", "{ }"); + mockHttp.Expect(HttpMethod.Get, Url + "/").Respond("application/json", "{ }"); - var fixtureA = RestService.For(Url, settings); + var fixtureA = RestService.For(Url, settings); - var respA = await fixtureA.SomeRequest(); + var respA = await fixtureA.SomeRequest(); - mockHttp.Expect(HttpMethod.Get, Url + "/") - .Respond("application/json", "{ }"); + mockHttp.Expect(HttpMethod.Get, Url + "/").Respond("application/json", "{ }"); - var fixtureB = RestService.For(Url, settings); + var fixtureB = RestService.For(Url, settings); - var respB = await fixtureB.SomeRequest(); + var respB = await fixtureB.SomeRequest(); - mockHttp.Expect(HttpMethod.Get, Url + "/") - .Respond("application/json", "{ }"); + mockHttp.Expect(HttpMethod.Get, Url + "/").Respond("application/json", "{ }"); - var fixtureC = RestService.For(Url, settings); + var fixtureC = RestService.For(Url, settings); - var respC = await fixtureC.SomeRequest(); + var respC = await fixtureC.SomeRequest(); - Assert.IsType(respA); - Assert.IsType(respB); - Assert.IsType(respC); - } + Assert.IsType(respA); + Assert.IsType(respB); + Assert.IsType(respC); + } - public void AssertFirstLineContains(string expectedSubstring, string actualString) - { - var eolIndex = actualString.IndexOf('\n'); - var firstLine = eolIndex < 0 ? actualString : actualString.Substring(0, eolIndex); - Assert.Contains(expectedSubstring, firstLine); - } + public void AssertFirstLineContains(string expectedSubstring, string actualString) + { + var eolIndex = actualString.IndexOf('\n'); + var firstLine = eolIndex < 0 ? actualString : actualString.Substring(0, eolIndex); + Assert.Contains(expectedSubstring, firstLine); + } } diff --git a/Refit.Tests/SerializedContentTests.cs b/Refit.Tests/SerializedContentTests.cs index a4b190d70..cc024ee46 100644 --- a/Refit.Tests/SerializedContentTests.cs +++ b/Refit.Tests/SerializedContentTests.cs @@ -1,9 +1,9 @@ using System; using System.Net; using System.Net.Http; +using System.Threading; using System.Threading.Tasks; using Xunit; -using System.Threading; namespace Refit.Tests; @@ -18,8 +18,7 @@ public class SerializedContentTests public async Task WhenARequestRequiresABodyThenItDoesNotDeadlock(Type contentSerializerType) { if ( - Activator.CreateInstance(contentSerializerType) - is not IHttpContentSerializer serializer + Activator.CreateInstance(contentSerializerType) is not IHttpContentSerializer serializer ) { throw new ArgumentException( @@ -33,10 +32,7 @@ is not IHttpContentSerializer serializer new StringContent(await content.ReadAsStringAsync().ConfigureAwait(false)) }; - var settings = new RefitSettings(serializer) - { - HttpMessageHandlerFactory = () => handler - }; + var settings = new RefitSettings(serializer) { HttpMessageHandlerFactory = () => handler }; var fixture = RestService.For(BaseAddress, settings); @@ -53,8 +49,7 @@ is not IHttpContentSerializer serializer public async Task WhenARequestRequiresABodyThenItIsSerialized(Type contentSerializerType) { if ( - Activator.CreateInstance(contentSerializerType) - is not IHttpContentSerializer serializer + Activator.CreateInstance(contentSerializerType) is not IHttpContentSerializer serializer ) { throw new ArgumentException( @@ -89,10 +84,7 @@ await content.ReadAsStringAsync().ConfigureAwait(false) } }; - var settings = new RefitSettings(serializer) - { - HttpMessageHandlerFactory = () => handler - }; + var settings = new RefitSettings(serializer) { HttpMessageHandlerFactory = () => handler }; var fixture = RestService.For(BaseAddress, settings); @@ -150,9 +142,7 @@ public async Task StreamDeserialization_UsingSystemTextJsonContentSerializer() { var model = new TestAliasObject { - ShortNameForAlias = nameof( - StreamDeserialization_UsingSystemTextJsonContentSerializer - ), + ShortNameForAlias = nameof(StreamDeserialization_UsingSystemTextJsonContentSerializer), ShortNameForJsonProperty = nameof(TestAliasObject) }; @@ -172,9 +162,7 @@ public void StreamDeserialization_UsingSystemTextJsonContentSerializer_SetsCorre { var model = new TestAliasObject { - ShortNameForAlias = nameof( - StreamDeserialization_UsingSystemTextJsonContentSerializer - ), + ShortNameForAlias = nameof(StreamDeserialization_UsingSystemTextJsonContentSerializer), ShortNameForJsonProperty = nameof(TestAliasObject) }; diff --git a/Refit.Tests/TypeCollisionApiA.cs b/Refit.Tests/TypeCollisionApiA.cs index 119a8e9fd..e1fe2e8f0 100644 --- a/Refit.Tests/TypeCollisionApiA.cs +++ b/Refit.Tests/TypeCollisionApiA.cs @@ -1,7 +1,5 @@ using System.Threading.Tasks; - using CollisionA; - using Refit; // InterfaceStubGenerator looks for this namespace Refit.Tests; diff --git a/Refit.Tests/TypeCollisionApiB.cs b/Refit.Tests/TypeCollisionApiB.cs index e7407d317..715438f27 100644 --- a/Refit.Tests/TypeCollisionApiB.cs +++ b/Refit.Tests/TypeCollisionApiB.cs @@ -1,7 +1,5 @@ using System.Threading.Tasks; - using CollisionB; - using Refit; // InterfaceStubGenerator looks for this namespace Refit.Tests; diff --git a/Refit.Tests/Verifiers/CSharpIncrementalSourceGeneratorVerifier`1+Test.cs b/Refit.Tests/Verifiers/CSharpIncrementalSourceGeneratorVerifier`1+Test.cs index 4c35e0002..160f4869c 100644 --- a/Refit.Tests/Verifiers/CSharpIncrementalSourceGeneratorVerifier`1+Test.cs +++ b/Refit.Tests/Verifiers/CSharpIncrementalSourceGeneratorVerifier`1+Test.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Testing; diff --git a/Refit.Tests/Verifiers/CSharpSourceGeneratorVerifier`1+Test.cs b/Refit.Tests/Verifiers/CSharpSourceGeneratorVerifier`1+Test.cs index eefb94bcc..bd8790220 100644 --- a/Refit.Tests/Verifiers/CSharpSourceGeneratorVerifier`1+Test.cs +++ b/Refit.Tests/Verifiers/CSharpSourceGeneratorVerifier`1+Test.cs @@ -1,5 +1,4 @@ using System; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing; diff --git a/Refit.Tests/Verifiers/CSharpVerifierHelper.cs b/Refit.Tests/Verifiers/CSharpVerifierHelper.cs index f28f6cb67..05d49b038 100644 --- a/Refit.Tests/Verifiers/CSharpVerifierHelper.cs +++ b/Refit.Tests/Verifiers/CSharpVerifierHelper.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Immutable; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; diff --git a/Refit.Tests/XmlContentSerializerTests.cs b/Refit.Tests/XmlContentSerializerTests.cs index d9f257b7d..bc26cbd8e 100644 --- a/Refit.Tests/XmlContentSerializerTests.cs +++ b/Refit.Tests/XmlContentSerializerTests.cs @@ -43,8 +43,7 @@ public async Task ShouldSerializeToXml() document.LoadXml(await content.ReadAsStringAsync()); var root = - document[nameof(Dto)] - ?? throw new NullReferenceException("Root element was not found"); + document[nameof(Dto)] ?? throw new NullReferenceException("Root element was not found"); Assert.Equal( dto.CreatedOn, XmlConvert.ToDateTime( diff --git a/Refit/ApiException.cs b/Refit/ApiException.cs index 5330232f8..5db3d5c5d 100644 --- a/Refit/ApiException.cs +++ b/Refit/ApiException.cs @@ -134,8 +134,8 @@ protected ApiException( /// The response content deserialized as public async Task GetContentAsAsync() => HasContent - ? await RefitSettings.ContentSerializer - .FromHttpContentAsync(new StringContent(Content!)) + ? await RefitSettings + .ContentSerializer.FromHttpContentAsync(new StringContent(Content!)) .ConfigureAwait(false) : default; @@ -214,9 +214,10 @@ public static async Task Create( exception.Content = content; if ( - response.Content.Headers?.ContentType?.MediaType?.Equals( - "application/problem+json" - ) ?? false + response + .Content.Headers?.ContentType + ?.MediaType + ?.Equals("application/problem+json") ?? false ) { exception = ValidationApiException.Create(exception); diff --git a/Refit/ApiResponse.cs b/Refit/ApiResponse.cs index 9e2786c06..8df834cd6 100644 --- a/Refit/ApiResponse.cs +++ b/Refit/ApiResponse.cs @@ -42,9 +42,10 @@ public sealed class ApiResponse( T? content, RefitSettings settings, ApiException? error = null - ) : IApiResponse, IApiResponse + ) : IApiResponse, IApiResponse { - readonly HttpResponseMessage response = response ?? throw new ArgumentNullException(nameof(response)); + readonly HttpResponseMessage response = + response ?? throw new ArgumentNullException(nameof(response)); bool disposed; /// @@ -175,7 +176,11 @@ public interface IApiResponse : IApiResponseBase /// /// The object in case of unsuccessful response. /// - [SuppressMessage("Naming", "CA1716:Identifiers should not match keywords", Justification = "By Design")] + [SuppressMessage( + "Naming", + "CA1716:Identifiers should not match keywords", + Justification = "By Design" + )] ApiException? Error { get; } } @@ -202,7 +207,11 @@ public interface IApiResponse : IApiResponseBase /// /// The object in case of unsuccessful response. /// - [SuppressMessage("Naming", "CA1716:Identifiers should not match keywords", Justification = "By Design")] + [SuppressMessage( + "Naming", + "CA1716:Identifiers should not match keywords", + Justification = "By Design" + )] ApiException? Error { get; } } diff --git a/Refit/Attributes.cs b/Refit/Attributes.cs index b092ff20d..5552f3027 100644 --- a/Refit/Attributes.cs +++ b/Refit/Attributes.cs @@ -350,7 +350,6 @@ public sealed class HeadersAttribute(params string[] headers) : Attribute [AttributeUsage(AttributeTargets.Parameter)] public sealed class HeaderAttribute(string header) : Attribute { - /// /// Gets the header. /// diff --git a/Refit/CamelCaseUrlParameterKeyFormatter.cs b/Refit/CamelCaseUrlParameterKeyFormatter.cs index 52cfb39b9..9396c91e1 100644 --- a/Refit/CamelCaseUrlParameterKeyFormatter.cs +++ b/Refit/CamelCaseUrlParameterKeyFormatter.cs @@ -13,12 +13,15 @@ public string Format(string key) } #if NETCOREAPP - return string.Create(key.Length, key, (chars, name) => - { - name - .CopyTo(chars); - FixCasing(chars); - }); + return string.Create( + key.Length, + key, + (chars, name) => + { + name.CopyTo(chars); + FixCasing(chars); + } + ); #else char[] chars = key.ToCharArray(); FixCasing(chars); diff --git a/Refit/JsonContentSerializer.cs b/Refit/JsonContentSerializer.cs index e681107a0..9df5fafe2 100644 --- a/Refit/JsonContentSerializer.cs +++ b/Refit/JsonContentSerializer.cs @@ -47,6 +47,7 @@ public class JsonContentSerializer : IHttpContentSerializer /// The calculated field name. /// /// - public string GetFieldNameForProperty(PropertyInfo propertyInfo) => throw new NotImplementedException(); + public string GetFieldNameForProperty(PropertyInfo propertyInfo) => + throw new NotImplementedException(); } } diff --git a/Refit/MultipartItem.cs b/Refit/MultipartItem.cs index f0fad7ca4..03cab49a2 100644 --- a/Refit/MultipartItem.cs +++ b/Refit/MultipartItem.cs @@ -45,7 +45,8 @@ public MultipartItem(string fileName, string? contentType, string? name) /// /// The name of the file. /// - public string FileName { get; } = fileName ?? throw new ArgumentNullException(nameof(fileName)); + public string FileName { get; } = + fileName ?? throw new ArgumentNullException(nameof(fileName)); /// /// Converts to content. @@ -85,7 +86,7 @@ public class StreamPart( string fileName, string? contentType = null, string? name = null - ) : MultipartItem(fileName, contentType, name) + ) : MultipartItem(fileName, contentType, name) { /// /// Gets the value. @@ -121,9 +122,8 @@ public class ByteArrayPart( string fileName, string? contentType = null, string? name = null - ) : MultipartItem(fileName, contentType, name) + ) : MultipartItem(fileName, contentType, name) { - /// /// Gets the value. /// @@ -158,7 +158,7 @@ public class FileInfoPart( string fileName, string? contentType = null, string? name = null - ) : MultipartItem(fileName, contentType, name) + ) : MultipartItem(fileName, contentType, name) { /// /// Gets the value. diff --git a/Refit/PushStreamContent.cs b/Refit/PushStreamContent.cs index ac5f20787..e698df717 100644 --- a/Refit/PushStreamContent.cs +++ b/Refit/PushStreamContent.cs @@ -187,7 +187,8 @@ protected override void Dispose(bool disposing) [ExcludeFromCodeCoverage] abstract class DelegatingStream(Stream innerStream) : Stream { - protected Stream InnerStream { get; private set; } = innerStream ?? throw new ArgumentNullException(nameof(innerStream)); + protected Stream InnerStream { get; private set; } = + innerStream ?? throw new ArgumentNullException(nameof(innerStream)); public override bool CanRead { diff --git a/Refit/RefitSettings.cs b/Refit/RefitSettings.cs index 85706aa9e..1180ff177 100644 --- a/Refit/RefitSettings.cs +++ b/Refit/RefitSettings.cs @@ -37,10 +37,10 @@ public RefitSettings() public RefitSettings( IHttpContentSerializer contentSerializer, IUrlParameterFormatter? urlParameterFormatter, - IFormUrlEncodedParameterFormatter? formUrlEncodedParameterFormatter) + IFormUrlEncodedParameterFormatter? formUrlEncodedParameterFormatter + ) : this(contentSerializer, urlParameterFormatter, formUrlEncodedParameterFormatter, null) - { - } + { } /// /// Creates a new instance with the specified parameters @@ -53,19 +53,31 @@ public RefitSettings( IHttpContentSerializer contentSerializer, IUrlParameterFormatter? urlParameterFormatter = null, IFormUrlEncodedParameterFormatter? formUrlEncodedParameterFormatter = null, - IUrlParameterKeyFormatter? urlParameterKeyFormatter = null) + IUrlParameterKeyFormatter? urlParameterKeyFormatter = null + ) { - ContentSerializer = contentSerializer ?? throw new ArgumentNullException(nameof(contentSerializer), "The content serializer can't be null"); + ContentSerializer = + contentSerializer + ?? throw new ArgumentNullException( + nameof(contentSerializer), + "The content serializer can't be null" + ); UrlParameterFormatter = urlParameterFormatter ?? new DefaultUrlParameterFormatter(); - FormUrlEncodedParameterFormatter = formUrlEncodedParameterFormatter ?? new DefaultFormUrlEncodedParameterFormatter(); - UrlParameterKeyFormatter = urlParameterKeyFormatter ?? new DefaultUrlParameterKeyFormatter(); + FormUrlEncodedParameterFormatter = + formUrlEncodedParameterFormatter ?? new DefaultFormUrlEncodedParameterFormatter(); + UrlParameterKeyFormatter = + urlParameterKeyFormatter ?? new DefaultUrlParameterKeyFormatter(); ExceptionFactory = new DefaultApiExceptionFactory(this).CreateAsync; } /// /// Supply a function to provide the Authorization header. Does not work if you supply an HttpClient instance. /// - public Func>? AuthorizationHeaderValueGetter { get; set; } + public Func< + HttpRequestMessage, + CancellationToken, + Task + >? AuthorizationHeaderValueGetter { get; set; } /// /// Supply a custom inner HttpMessageHandler. Does not work if you supply an HttpClient instance. @@ -102,7 +114,8 @@ public RefitSettings( /// /// Sets the default collection format to use. (defaults to ) /// - public CollectionFormat CollectionFormat { get; set; } = CollectionFormat.RefitParameterFormatter; + public CollectionFormat CollectionFormat { get; set; } = + CollectionFormat.RefitParameterFormatter; /// /// Sets the default behavior when sending a request's body content. (defaults to false, request body is not streamed to the server) @@ -135,7 +148,10 @@ public interface IHttpContentSerializer /// HttpContent object to deserialize. /// CancellationToken to abort the deserialization. /// The deserialized object of type . - Task FromHttpContentAsync(HttpContent content, CancellationToken cancellationToken = default); + Task FromHttpContentAsync( + HttpContent content, + CancellationToken cancellationToken = default + ); /// /// Calculates what the field name should be for the given property. This may be affected by custom attributes the serializer understands @@ -205,7 +221,10 @@ public class DefaultUrlParameterKeyFormatter : IUrlParameterKeyFormatter /// public class DefaultUrlParameterFormatter : IUrlParameterFormatter { - static readonly ConcurrentDictionary> EnumMemberCache = new(); + static readonly ConcurrentDictionary< + Type, + ConcurrentDictionary + > EnumMemberCache = new(); /// /// Formats the specified parameter value. @@ -215,7 +234,11 @@ public class DefaultUrlParameterFormatter : IUrlParameterFormatter /// The type. /// /// attributeProvider - public virtual string? Format(object? parameterValue, ICustomAttributeProvider attributeProvider, Type type) + public virtual string? Format( + object? parameterValue, + ICustomAttributeProvider attributeProvider, + Type type + ) { if (attributeProvider is null) { @@ -223,9 +246,11 @@ public class DefaultUrlParameterFormatter : IUrlParameterFormatter } // See if we have a format - var formatString = attributeProvider.GetCustomAttributes(typeof(QueryAttribute), true) + var formatString = attributeProvider + .GetCustomAttributes(typeof(QueryAttribute), true) .OfType() - .FirstOrDefault()?.Format; + .FirstOrDefault() + ?.Format; EnumMemberAttribute? enummember = null; if (parameterValue != null) @@ -233,18 +258,28 @@ public class DefaultUrlParameterFormatter : IUrlParameterFormatter var parameterType = parameterValue.GetType(); if (parameterType.IsEnum) { - var cached = EnumMemberCache.GetOrAdd(parameterType, t => new ConcurrentDictionary()); - enummember = cached.GetOrAdd(parameterValue.ToString()!, val => parameterType.GetMember(val).First().GetCustomAttribute()); + var cached = EnumMemberCache.GetOrAdd( + parameterType, + t => new ConcurrentDictionary() + ); + enummember = cached.GetOrAdd( + parameterValue.ToString()!, + val => + parameterType + .GetMember(val) + .First() + .GetCustomAttribute() + ); } } return parameterValue == null - ? null - : string.Format(CultureInfo.InvariantCulture, - string.IsNullOrWhiteSpace(formatString) - ? "{0}" - : $"{{0:{formatString}}}", - enummember?.Value ?? parameterValue); + ? null + : string.Format( + CultureInfo.InvariantCulture, + string.IsNullOrWhiteSpace(formatString) ? "{0}" : $"{{0:{formatString}}}", + enummember?.Value ?? parameterValue + ); } } @@ -253,8 +288,10 @@ public class DefaultUrlParameterFormatter : IUrlParameterFormatter /// public class DefaultFormUrlEncodedParameterFormatter : IFormUrlEncodedParameterFormatter { - static readonly ConcurrentDictionary> EnumMemberCache - = new(); + static readonly ConcurrentDictionary< + Type, + ConcurrentDictionary + > EnumMemberCache = new(); /// /// Formats the specified parameter value. @@ -272,15 +309,25 @@ public class DefaultFormUrlEncodedParameterFormatter : IFormUrlEncodedParameterF EnumMemberAttribute? enummember = null; if (parameterType.GetTypeInfo().IsEnum) { - var cached = EnumMemberCache.GetOrAdd(parameterType, t => new ConcurrentDictionary()); - enummember = cached.GetOrAdd(parameterValue.ToString()!, val => parameterType.GetMember(val).First().GetCustomAttribute()); + var cached = EnumMemberCache.GetOrAdd( + parameterType, + t => new ConcurrentDictionary() + ); + enummember = cached.GetOrAdd( + parameterValue.ToString()!, + val => + parameterType + .GetMember(val) + .First() + .GetCustomAttribute() + ); } - return string.Format(CultureInfo.InvariantCulture, - string.IsNullOrWhiteSpace(formatString) - ? "{0}" - : $"{{0:{formatString}}}", - enummember?.Value ?? parameterValue); + return string.Format( + CultureInfo.InvariantCulture, + string.IsNullOrWhiteSpace(formatString) ? "{0}" : $"{{0:{formatString}}}", + enummember?.Value ?? parameterValue + ); } } @@ -308,12 +355,17 @@ public class DefaultApiExceptionFactory(RefitSettings refitSettings) } } - static async Task CreateExceptionAsync(HttpResponseMessage responseMessage, RefitSettings refitSettings) + static async Task CreateExceptionAsync( + HttpResponseMessage responseMessage, + RefitSettings refitSettings + ) { var requestMessage = responseMessage.RequestMessage!; var method = requestMessage.Method; - return await ApiException.Create(requestMessage, method, responseMessage, refitSettings).ConfigureAwait(false); + return await ApiException + .Create(requestMessage, method, responseMessage, refitSettings) + .ConfigureAwait(false); } } } diff --git a/Refit/RequestBuilder.cs b/Refit/RequestBuilder.cs index 8c2741387..aa06da38b 100644 --- a/Refit/RequestBuilder.cs +++ b/Refit/RequestBuilder.cs @@ -22,7 +22,7 @@ public interface IRequestBuilder } /// - /// + /// /// /// public interface IRequestBuilder : IRequestBuilder { } @@ -40,14 +40,16 @@ public static class RequestBuilder /// /// The settings. /// - public static IRequestBuilder ForType(RefitSettings? settings) => PlatformRequestBuilderFactory.Create(settings); + public static IRequestBuilder ForType(RefitSettings? settings) => + PlatformRequestBuilderFactory.Create(settings); /// /// Fors the type. /// /// /// - public static IRequestBuilder ForType() => PlatformRequestBuilderFactory.Create(null); + public static IRequestBuilder ForType() => + PlatformRequestBuilderFactory.Create(null); /// /// Fors the type. @@ -55,13 +57,15 @@ public static class RequestBuilder /// Type of the refit interface. /// The settings. /// - public static IRequestBuilder ForType(Type refitInterfaceType, RefitSettings? settings) => PlatformRequestBuilderFactory.Create(refitInterfaceType, settings); + public static IRequestBuilder ForType(Type refitInterfaceType, RefitSettings? settings) => + PlatformRequestBuilderFactory.Create(refitInterfaceType, settings); /// /// Fors the type. /// /// Type of the refit interface. /// - public static IRequestBuilder ForType(Type refitInterfaceType) => PlatformRequestBuilderFactory.Create(refitInterfaceType, null); + public static IRequestBuilder ForType(Type refitInterfaceType) => + PlatformRequestBuilderFactory.Create(refitInterfaceType, null); } } diff --git a/Refit/RequestBuilderImplementation.cs b/Refit/RequestBuilderImplementation.cs index d98ca577a..fab857a8c 100644 --- a/Refit/RequestBuilderImplementation.cs +++ b/Refit/RequestBuilderImplementation.cs @@ -8,30 +8,33 @@ namespace Refit { - class RequestBuilderImplementation(RefitSettings? refitSettings = null) : RequestBuilderImplementation(typeof(TApi), refitSettings), IRequestBuilder - { - } + class RequestBuilderImplementation(RefitSettings? refitSettings = null) + : RequestBuilderImplementation(typeof(TApi), refitSettings), + IRequestBuilder { } partial class RequestBuilderImplementation : IRequestBuilder { - static readonly HashSet BodylessMethods = - [ - HttpMethod.Get, - HttpMethod.Head - ]; + static readonly HashSet BodylessMethods = [HttpMethod.Get, HttpMethod.Head]; readonly Dictionary> interfaceHttpMethods; - readonly ConcurrentDictionary interfaceGenericHttpMethods; + readonly ConcurrentDictionary< + CloseGenericMethodKey, + RestMethodInfoInternal + > interfaceGenericHttpMethods; readonly IHttpContentSerializer serializer; readonly RefitSettings settings; public Type TargetType { get; } - public RequestBuilderImplementation(Type refitInterfaceType, RefitSettings? refitSettings = null) + public RequestBuilderImplementation( + Type refitInterfaceType, + RefitSettings? refitSettings = null + ) { var targetInterfaceInheritedInterfaces = refitInterfaceType.GetInterfaces(); settings = refitSettings ?? new RefitSettings(); serializer = settings.ContentSerializer; - interfaceGenericHttpMethods = new ConcurrentDictionary(); + interfaceGenericHttpMethods = + new ConcurrentDictionary(); if (refitInterfaceType == null || !refitInterfaceType.GetTypeInfo().IsInterface) { @@ -51,7 +54,10 @@ public RequestBuilderImplementation(Type refitInterfaceType, RefitSettings? refi interfaceHttpMethods = dict; } - void AddInterfaceHttpMethods(Type interfaceType, Dictionary> methods) + void AddInterfaceHttpMethods( + Type interfaceType, + Dictionary> methods + ) { // Consider public (the implicit visibility) and non-public abstract members of the interfaceType var methodInfos = interfaceType @@ -76,11 +82,17 @@ void AddInterfaceHttpMethods(Type interfaceType, Dictionary 1) { throw new ArgumentException( - $"MethodName exists more than once, '{nameof(parameterTypes)}' mut be defined"); + $"MethodName exists more than once, '{nameof(parameterTypes)}' mut be defined" + ); } return CloseGenericMethodIfNeeded(httpMethods[0], genericArgumentTypes); @@ -96,16 +109,22 @@ RestMethodInfoInternal FindMatchingRestMethodInfo(string key, Type[]? parameterT var isGeneric = genericArgumentTypes?.Length > 0; - var possibleMethodsCollection = httpMethods.Where(method => - method.MethodInfo.GetParameters().Length == parameterTypes.Length); + var possibleMethodsCollection = httpMethods.Where( + method => method.MethodInfo.GetParameters().Length == parameterTypes.Length + ); // If it's a generic method, add that filter if (isGeneric) - possibleMethodsCollection = possibleMethodsCollection.Where(method => - method.MethodInfo.IsGenericMethod && method.MethodInfo.GetGenericArguments().Length == - genericArgumentTypes!.Length); + possibleMethodsCollection = possibleMethodsCollection.Where( + method => + method.MethodInfo.IsGenericMethod + && method.MethodInfo.GetGenericArguments().Length + == genericArgumentTypes!.Length + ); else // exclude generic methods - possibleMethodsCollection = possibleMethodsCollection.Where(method => !method.MethodInfo.IsGenericMethod); + possibleMethodsCollection = possibleMethodsCollection.Where( + method => !method.MethodInfo.IsGenericMethod + ); var possibleMethods = possibleMethodsCollection.ToArray(); @@ -114,7 +133,8 @@ RestMethodInfoInternal FindMatchingRestMethodInfo(string key, Type[]? parameterT foreach (var method in possibleMethods) { - var match = method.MethodInfo.GetParameters() + var match = method + .MethodInfo.GetParameters() .Select(p => p.ParameterType) .SequenceEqual(parameterTypes); if (match) @@ -126,24 +146,44 @@ RestMethodInfoInternal FindMatchingRestMethodInfo(string key, Type[]? parameterT throw new Exception("No suitable Method found..."); } - RestMethodInfoInternal CloseGenericMethodIfNeeded(RestMethodInfoInternal restMethodInfo, Type[]? genericArgumentTypes) + RestMethodInfoInternal CloseGenericMethodIfNeeded( + RestMethodInfoInternal restMethodInfo, + Type[]? genericArgumentTypes + ) { if (genericArgumentTypes != null) { - return interfaceGenericHttpMethods.GetOrAdd(new CloseGenericMethodKey(restMethodInfo.MethodInfo, genericArgumentTypes), - _ => new RestMethodInfoInternal(restMethodInfo.Type, restMethodInfo.MethodInfo.MakeGenericMethod(genericArgumentTypes), restMethodInfo.RefitSettings)); + return interfaceGenericHttpMethods.GetOrAdd( + new CloseGenericMethodKey(restMethodInfo.MethodInfo, genericArgumentTypes), + _ => + new RestMethodInfoInternal( + restMethodInfo.Type, + restMethodInfo.MethodInfo.MakeGenericMethod(genericArgumentTypes), + restMethodInfo.RefitSettings + ) + ); } return restMethodInfo; } - public Func BuildRestResultFuncForMethod(string methodName, Type[]? parameterTypes = null, Type[]? genericArgumentTypes = null) + public Func BuildRestResultFuncForMethod( + string methodName, + Type[]? parameterTypes = null, + Type[]? genericArgumentTypes = null + ) { if (!interfaceHttpMethods.ContainsKey(methodName)) { - throw new ArgumentException("Method must be defined and have an HTTP Method attribute"); + throw new ArgumentException( + "Method must be defined and have an HTTP Method attribute" + ); } - var restMethod = FindMatchingRestMethodInfo(methodName, parameterTypes, genericArgumentTypes); + var restMethod = FindMatchingRestMethodInfo( + methodName, + parameterTypes, + genericArgumentTypes + ); if (restMethod.ReturnType == typeof(Task)) { return BuildVoidTaskFuncForMethod(restMethod); @@ -155,20 +195,43 @@ RestMethodInfoInternal CloseGenericMethodIfNeeded(RestMethodInfoInternal restMet // difficult to upcast Task to an arbitrary T, especially // if you need to AOT everything, so we need to reflectively // invoke buildTaskFuncForMethod. - var taskFuncMi = typeof(RequestBuilderImplementation).GetMethod(nameof(BuildTaskFuncForMethod), BindingFlags.NonPublic | BindingFlags.Instance); - var taskFunc = (MulticastDelegate?)(taskFuncMi!.MakeGenericMethod(restMethod.ReturnResultType, restMethod.DeserializedResultType)).Invoke(this, new[] { restMethod }); + var taskFuncMi = typeof(RequestBuilderImplementation).GetMethod( + nameof(BuildTaskFuncForMethod), + BindingFlags.NonPublic | BindingFlags.Instance + ); + var taskFunc = (MulticastDelegate?) + ( + taskFuncMi!.MakeGenericMethod( + restMethod.ReturnResultType, + restMethod.DeserializedResultType + ) + ).Invoke(this, new[] { restMethod }); return (client, args) => taskFunc!.DynamicInvoke(client, args); } // Same deal - var rxFuncMi = typeof(RequestBuilderImplementation).GetMethod(nameof(BuildRxFuncForMethod), BindingFlags.NonPublic | BindingFlags.Instance); - var rxFunc = (MulticastDelegate?)(rxFuncMi!.MakeGenericMethod(restMethod.ReturnResultType, restMethod.DeserializedResultType)).Invoke(this, new[] { restMethod }); + var rxFuncMi = typeof(RequestBuilderImplementation).GetMethod( + nameof(BuildRxFuncForMethod), + BindingFlags.NonPublic | BindingFlags.Instance + ); + var rxFunc = (MulticastDelegate?) + ( + rxFuncMi!.MakeGenericMethod( + restMethod.ReturnResultType, + restMethod.DeserializedResultType + ) + ).Invoke(this, new[] { restMethod }); return (client, args) => rxFunc!.DynamicInvoke(client, args); } - void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName, string parameterName, object itemValue) + void AddMultipartItem( + MultipartFormDataContent multiPartContent, + string fileName, + string parameterName, + object itemValue + ) { if (itemValue is HttpContent content) { @@ -178,7 +241,11 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName if (itemValue is MultipartItem multipartItem) { var httpContent = multipartItem.ToContent(); - multiPartContent.Add(httpContent, multipartItem.Name ?? parameterName, string.IsNullOrEmpty(multipartItem.FileName) ? fileName : multipartItem.FileName); + multiPartContent.Add( + httpContent, + multipartItem.Name ?? parameterName, + string.IsNullOrEmpty(multipartItem.FileName) ? fileName : multipartItem.FileName + ); return; } @@ -213,7 +280,10 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName Exception e; try { - multiPartContent.Add(settings.ContentSerializer.ToHttpContent(itemValue), parameterName); + multiPartContent.Add( + settings.ContentSerializer.ToHttpContent(itemValue), + parameterName + ); return; } catch (Exception ex) @@ -222,17 +292,30 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName e = ex; } - throw new ArgumentException($"Unexpected parameter type in a Multipart request. Parameter {fileName} is of type {itemValue.GetType().Name}, whereas allowed types are String, Stream, FileInfo, Byte array and anything that's JSON serializable", nameof(itemValue), e); + throw new ArgumentException( + $"Unexpected parameter type in a Multipart request. Parameter {fileName} is of type {itemValue.GetType().Name}, whereas allowed types are String, Stream, FileInfo, Byte array and anything that's JSON serializable", + nameof(itemValue), + e + ); } - Func> BuildCancellableTaskFuncForMethod(RestMethodInfoInternal restMethod) + Func> BuildCancellableTaskFuncForMethod< + T, + TBody + >(RestMethodInfoInternal restMethod) { return async (client, ct, paramList) => { if (client.BaseAddress == null) - throw new InvalidOperationException("BaseAddress must be set on the HttpClient instance"); - - var factory = BuildRequestFactoryForMethod(restMethod, client.BaseAddress.AbsolutePath, restMethod.CancellationToken != null); + throw new InvalidOperationException( + "BaseAddress must be set on the HttpClient instance" + ); + + var factory = BuildRequestFactoryForMethod( + restMethod, + client.BaseAddress.AbsolutePath, + restMethod.CancellationToken != null + ); var rq = factory(paramList); HttpResponseMessage? resp = null; HttpContent? content = null; @@ -244,7 +327,9 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName { await rq.Content!.LoadIntoBufferAsync().ConfigureAwait(false); } - resp = await client.SendAsync(rq, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + resp = await client + .SendAsync(rq, HttpCompletionOption.ResponseHeadersRead, ct) + .ConfigureAwait(false); content = resp.Content ?? new StringContent(string.Empty); Exception? e = null; disposeResponse = restMethod.ShouldDisposeResponse; @@ -261,17 +346,31 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName try { // Only attempt to deserialize content if no error present for backward-compatibility - body = e == null - ? await DeserializeContentAsync(resp, content, ct).ConfigureAwait(false) - : default; + body = + e == null + ? await DeserializeContentAsync(resp, content, ct) + .ConfigureAwait(false) + : default; } catch (Exception ex) { //if an error occured while attempting to deserialize return the wrapped ApiException - e = await ApiException.Create("An error occured deserializing the response.", resp.RequestMessage!, resp.RequestMessage!.Method, resp, settings, ex); + e = await ApiException.Create( + "An error occured deserializing the response.", + resp.RequestMessage!, + resp.RequestMessage!.Method, + resp, + settings, + ex + ); } - return ApiResponse.Create(resp, body, settings, e as ApiException); + return ApiResponse.Create( + resp, + body, + settings, + e as ApiException + ); } else if (e != null) { @@ -282,11 +381,19 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName { try { - return await DeserializeContentAsync(resp, content, ct).ConfigureAwait(false); + return await DeserializeContentAsync(resp, content, ct) + .ConfigureAwait(false); } catch (Exception ex) { - throw await ApiException.Create("An error occured deserializing the response.", resp.RequestMessage!, resp.RequestMessage!.Method, resp, settings, ex); + throw await ApiException.Create( + "An error occured deserializing the response.", + resp.RequestMessage!, + resp.RequestMessage!.Method, + resp, + settings, + ex + ); } } } @@ -304,7 +411,11 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName }; } - async Task DeserializeContentAsync(HttpResponseMessage resp, HttpContent content, CancellationToken cancellationToken) + async Task DeserializeContentAsync( + HttpResponseMessage resp, + HttpContent content, + CancellationToken cancellationToken + ) { T? result; if (typeof(T) == typeof(HttpResponseMessage)) @@ -320,12 +431,15 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName } else if (typeof(T) == typeof(Stream)) { - var stream = (object)await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + var stream = (object) + await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); result = (T)stream; } else if (typeof(T) == typeof(string)) { - using var stream = await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + using var stream = await content + .ReadAsStreamAsync(cancellationToken) + .ConfigureAwait(false); using var reader = new StreamReader(stream); var str = (object)await reader.ReadToEndAsync().ConfigureAwait(false); result = (T)str; @@ -346,7 +460,11 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName return result; } - List> BuildQueryMap(object? @object, string? delimiter = null, RestMethodParameterInfo? parameterInfo = null) + List> BuildQueryMap( + object? @object, + string? delimiter = null, + RestMethodParameterInfo? parameterInfo = null + ) { if (@object is IDictionary idictionary) { @@ -355,9 +473,12 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName var kvps = new List>(); - if (@object is null) return kvps; + if (@object is null) + return kvps; - var props = @object.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public) + var props = @object + .GetType() + .GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(p => p.CanRead && p.GetMethod?.IsPublic == true); foreach (var propertyInfo in props) @@ -384,13 +505,23 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName var queryAttribute = propertyInfo.GetCustomAttribute(); if (queryAttribute is { Format: not null }) { - obj = settings.FormUrlEncodedParameterFormatter.Format(obj, queryAttribute.Format); + obj = settings.FormUrlEncodedParameterFormatter.Format( + obj, + queryAttribute.Format + ); } // If obj is IEnumerable - format it accounting for Query attribute and CollectionFormat if (obj is not string && obj is IEnumerable ienu && obj is not IDictionary) { - foreach (var value in ParseEnumerableQueryParameterValue(ienu, propertyInfo, propertyInfo.PropertyType, queryAttribute)) + foreach ( + var value in ParseEnumerableQueryParameterValue( + ienu, + propertyInfo, + propertyInfo.PropertyType, + queryAttribute + ) + ) { kvps.Add(new KeyValuePair(key, value)); } @@ -409,7 +540,12 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName case IDictionary idict: foreach (var keyValuePair in BuildQueryMap(idict, delimiter)) { - kvps.Add(new KeyValuePair($"{key}{delimiter}{keyValuePair.Key}", keyValuePair.Value)); + kvps.Add( + new KeyValuePair( + $"{key}{delimiter}{keyValuePair.Key}", + keyValuePair.Value + ) + ); } break; @@ -417,7 +553,12 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName default: foreach (var keyValuePair in BuildQueryMap(obj, delimiter)) { - kvps.Add(new KeyValuePair($"{key}{delimiter}{keyValuePair.Key}", keyValuePair.Value)); + kvps.Add( + new KeyValuePair( + $"{key}{delimiter}{keyValuePair.Key}", + keyValuePair.Value + ) + ); } break; @@ -427,7 +568,10 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName return kvps; } - List> BuildQueryMap(IDictionary dictionary, string? delimiter = null) + List> BuildQueryMap( + IDictionary dictionary, + string? delimiter = null + ) { var kvps = new List>(); @@ -440,7 +584,7 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName var keyType = key.GetType(); var formattedKey = settings.UrlParameterFormatter.Format(key, keyType, keyType); - if(string.IsNullOrWhiteSpace(formattedKey)) // blank keys can't be put in the query string + if (string.IsNullOrWhiteSpace(formattedKey)) // blank keys can't be put in the query string { continue; } @@ -453,7 +597,12 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName { foreach (var keyValuePair in BuildQueryMap(obj, delimiter)) { - kvps.Add(new KeyValuePair($"{formattedKey}{delimiter}{keyValuePair.Key}", keyValuePair.Value)); + kvps.Add( + new KeyValuePair( + $"{formattedKey}{delimiter}{keyValuePair.Key}", + keyValuePair.Value + ) + ); } } } @@ -461,20 +610,23 @@ void AddMultipartItem(MultipartFormDataContent multiPartContent, string fileName return kvps; } - Func BuildRequestFactoryForMethod(RestMethodInfoInternal restMethod, string basePath, bool paramsContainsCancellationToken) + Func BuildRequestFactoryForMethod( + RestMethodInfoInternal restMethod, + string basePath, + bool paramsContainsCancellationToken + ) { return paramList => { // make sure we strip out any cancellation tokens if (paramsContainsCancellationToken) { - paramList = paramList.Where(o => o == null || o.GetType() != typeof(CancellationToken)).ToArray(); + paramList = paramList + .Where(o => o == null || o.GetType() != typeof(CancellationToken)) + .ToArray(); } - var ret = new HttpRequestMessage - { - Method = restMethod.HttpMethod - }; + var ret = new HttpRequestMessage { Method = restMethod.HttpMethod }; // set up multipart content MultipartFormDataContent? multiPartContent = null; @@ -484,7 +636,8 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn ret.Content = multiPartContent; } - var urlTarget = (basePath == "/" ? string.Empty : basePath) + restMethod.RelativePath; + var urlTarget = + (basePath == "/" ? string.Empty : basePath) + restMethod.RelativePath; var queryParamsToAdd = new List>(); var headersToAdd = new Dictionary(restMethod.Headers); var propertiesToAdd = new Dictionary(); @@ -506,11 +659,16 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn var propertyObject = propertyInfo.PropertyInfo.GetValue(param); urlTarget = Regex.Replace( urlTarget, - "{" + propertyInfo.Name + "}", - Uri.EscapeDataString(settings.UrlParameterFormatter.Format(propertyObject, - propertyInfo.PropertyInfo, - propertyInfo.PropertyInfo.PropertyType) ?? string.Empty), - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + "{" + propertyInfo.Name + "}", + Uri.EscapeDataString( + settings.UrlParameterFormatter.Format( + propertyObject, + propertyInfo.PropertyInfo, + propertyInfo.PropertyInfo.PropertyType + ) ?? string.Empty + ), + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); } //don't continue here as we want it to fall through so any parameters on this object not bound here get passed as query parameters } @@ -524,34 +682,48 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn var paramValue = (string)param; replacement = string.Join( "/", - paramValue.Split('/') - .Select(s => - Uri.EscapeDataString( - settings.UrlParameterFormatter.Format(s, restMethod.ParameterInfoMap[i], restMethod.ParameterInfoMap[i].ParameterType) ?? string.Empty - ) + paramValue + .Split('/') + .Select( + s => + Uri.EscapeDataString( + settings.UrlParameterFormatter.Format( + s, + restMethod.ParameterInfoMap[i], + restMethod.ParameterInfoMap[i].ParameterType + ) ?? string.Empty + ) ) ); } else { pattern = "{" + parameterMapValue.Name + "}"; - replacement = Uri.EscapeDataString(settings.UrlParameterFormatter - .Format(param, restMethod.ParameterInfoMap[i], restMethod.ParameterInfoMap[i].ParameterType) ?? string.Empty); + replacement = Uri.EscapeDataString( + settings.UrlParameterFormatter.Format( + param, + restMethod.ParameterInfoMap[i], + restMethod.ParameterInfoMap[i].ParameterType + ) ?? string.Empty + ); } urlTarget = Regex.Replace( urlTarget, pattern, replacement, - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); isParameterMappedToRequest = true; - } } // if marked as body, add to content - if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item3 == i) + if ( + restMethod.BodyParameterInfo != null + && restMethod.BodyParameterInfo.Item3 == i + ) { if (param is HttpContent httpContentParam) { @@ -562,8 +734,10 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn ret.Content = new StreamContent(streamParam); } // Default sends raw strings - else if (restMethod.BodyParameterInfo.Item1 == BodySerializationMethod.Default && - param is string stringParam) + else if ( + restMethod.BodyParameterInfo.Item1 == BodySerializationMethod.Default + && param is string stringParam + ) { ret.Content = new StringContent(stringParam); } @@ -572,7 +746,16 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn switch (restMethod.BodyParameterInfo.Item1) { case BodySerializationMethod.UrlEncoded: - ret.Content = param is string str ? (HttpContent)new StringContent(Uri.EscapeDataString(str), Encoding.UTF8, "application/x-www-form-urlencoded") : new FormUrlEncodedContent(new FormValueMultimap(param, settings)); + ret.Content = param is string str + ? (HttpContent) + new StringContent( + Uri.EscapeDataString(str), + Encoding.UTF8, + "application/x-www-form-urlencoded" + ) + : new FormUrlEncodedContent( + new FormValueMultimap(param, settings) + ); break; case BodySerializationMethod.Default: #pragma warning disable CS0618 // Type or member is obsolete @@ -590,9 +773,13 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn { using (stream) { - await content.CopyToAsync(stream).ConfigureAwait(false); + await content + .CopyToAsync(stream) + .ConfigureAwait(false); } - }, content.Headers.ContentType); + }, + content.Headers.ContentType + ); break; case true: ret.Content = content; @@ -616,7 +803,9 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn //if header collection, add to request headers if (restMethod.HeaderCollectionParameterMap.Contains(i)) { - var headerCollection = param as IDictionary ?? new Dictionary(); + var headerCollection = + param as IDictionary + ?? new Dictionary(); foreach (var header in headerCollection) { @@ -627,9 +816,13 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn } //if authorize, add to request headers with scheme - if (restMethod.AuthorizeParameterInfo != null && restMethod.AuthorizeParameterInfo.Item2 == i) + if ( + restMethod.AuthorizeParameterInfo != null + && restMethod.AuthorizeParameterInfo.Item2 == i + ) { - headersToAdd["Authorization"] = $"{restMethod.AuthorizeParameterInfo.Item1} {param}"; + headersToAdd["Authorization"] = + $"{restMethod.AuthorizeParameterInfo.Item1} {param}"; isParameterMappedToRequest = true; } @@ -641,28 +834,49 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn } // ignore nulls and already processed parameters - if (isParameterMappedToRequest || param == null) continue; + if (isParameterMappedToRequest || param == null) + continue; // for anything that fell through to here, if this is not a multipart method add the parameter to the query string // or if is an object bound to the path add any non-path bound properties to query string // or if it's an object with a query attribute - var queryAttribute = restMethod.ParameterInfoMap[i].GetCustomAttribute(); - if (!restMethod.IsMultipart || - restMethod.ParameterMap.ContainsKey(i) && restMethod.ParameterMap[i].IsObjectPropertyParameter || - queryAttribute != null + var queryAttribute = restMethod + .ParameterInfoMap[i] + .GetCustomAttribute(); + if ( + !restMethod.IsMultipart + || restMethod.ParameterMap.ContainsKey(i) + && restMethod.ParameterMap[i].IsObjectPropertyParameter + || queryAttribute != null ) { var attr = queryAttribute ?? new QueryAttribute(); if (DoNotConvertToQueryMap(param)) { - queryParamsToAdd.AddRange(ParseQueryParameter(param, restMethod.ParameterInfoMap[i], restMethod.QueryParameterMap[i], attr)); + queryParamsToAdd.AddRange( + ParseQueryParameter( + param, + restMethod.ParameterInfoMap[i], + restMethod.QueryParameterMap[i], + attr + ) + ); } else { foreach (var kvp in BuildQueryMap(param, attr.Delimiter, parameterInfo)) { - var path = !string.IsNullOrWhiteSpace(attr.Prefix) ? $"{attr.Prefix}{attr.Delimiter}{kvp.Key}" : kvp.Key; - queryParamsToAdd.AddRange(ParseQueryParameter(kvp.Value, restMethod.ParameterInfoMap[i], path, attr)); + var path = !string.IsNullOrWhiteSpace(attr.Prefix) + ? $"{attr.Prefix}{attr.Delimiter}{kvp.Key}" + : kvp.Key; + queryParamsToAdd.AddRange( + ParseQueryParameter( + kvp.Value, + restMethod.ParameterInfoMap[i], + path, + attr + ) + ); } } @@ -722,7 +936,7 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn // Add RefitSetting.HttpRequestMessageOptions to the HttpRequestMessage if (settings.HttpRequestMessageOptions != null) { - foreach(var p in settings.HttpRequestMessageOptions) + foreach (var p in settings.HttpRequestMessageOptions) { #if NET6_0_OR_GREATER ret.Options.Set(new HttpRequestOptionsKey(p.Key), p.Value); @@ -735,7 +949,10 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn foreach (var property in propertiesToAdd) { #if NET6_0_OR_GREATER - ret.Options.Set(new HttpRequestOptionsKey(property.Key), property.Value); + ret.Options.Set( + new HttpRequestOptionsKey(property.Key), + property.Value + ); #else ret.Properties[property.Key] = property.Value; #endif @@ -743,11 +960,20 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn // Always add the top-level type of the interface to the properties #if NET6_0_OR_GREATER - ret.Options.Set(new HttpRequestOptionsKey(HttpRequestMessageOptions.InterfaceType), TargetType); - ret.Options.Set(new HttpRequestOptionsKey(HttpRequestMessageOptions.RestMethodInfo), restMethod.ToRestMethodInfo()); + ret.Options.Set( + new HttpRequestOptionsKey(HttpRequestMessageOptions.InterfaceType), + TargetType + ); + ret.Options.Set( + new HttpRequestOptionsKey( + HttpRequestMessageOptions.RestMethodInfo + ), + restMethod.ToRestMethodInfo() + ); #else ret.Properties[HttpRequestMessageOptions.InterfaceType] = TargetType; - ret.Properties[HttpRequestMessageOptions.RestMethodInfo] = restMethod.ToRestMethodInfo(); + ret.Properties[HttpRequestMessageOptions.RestMethodInfo] = + restMethod.ToRestMethodInfo(); #endif // NB: The URI methods in .NET are dumb. Also, we do this @@ -759,14 +985,23 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn { if (!string.IsNullOrWhiteSpace(key)) { - queryParamsToAdd.Insert(0, new KeyValuePair(key, query[key])); + queryParamsToAdd.Insert( + 0, + new KeyValuePair(key, query[key]) + ); } } if (queryParamsToAdd.Count != 0) { - var pairs = queryParamsToAdd.Where(x => x.Key != null && x.Value != null) - .Select(x => Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value ?? string.Empty)); + var pairs = queryParamsToAdd + .Where(x => x.Key != null && x.Value != null) + .Select( + x => + Uri.EscapeDataString(x.Key) + + "=" + + Uri.EscapeDataString(x.Value ?? string.Empty) + ); uri.Query = string.Join("&", pairs); } else @@ -774,53 +1009,98 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn uri.Query = null; } - var uriFormat = restMethod.MethodInfo.GetCustomAttribute()?.UriFormat ?? UriFormat.UriEscaped; - ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, uriFormat), UriKind.Relative); + var uriFormat = + restMethod.MethodInfo.GetCustomAttribute()?.UriFormat + ?? UriFormat.UriEscaped; + ret.RequestUri = new Uri( + uri.Uri.GetComponents(UriComponents.PathAndQuery, uriFormat), + UriKind.Relative + ); return ret; }; } - IEnumerable> ParseQueryParameter(object? param, ParameterInfo parameterInfo, string queryPath, QueryAttribute queryAttribute) + IEnumerable> ParseQueryParameter( + object? param, + ParameterInfo parameterInfo, + string queryPath, + QueryAttribute queryAttribute + ) { if (param is not string && param is IEnumerable paramValues) { - foreach (var value in ParseEnumerableQueryParameterValue(paramValues, parameterInfo, parameterInfo.ParameterType, queryAttribute)) + foreach ( + var value in ParseEnumerableQueryParameterValue( + paramValues, + parameterInfo, + parameterInfo.ParameterType, + queryAttribute + ) + ) { yield return new KeyValuePair(queryPath, value); } } else { - yield return new KeyValuePair(queryPath, settings.UrlParameterFormatter.Format(param, parameterInfo, parameterInfo.ParameterType)); + yield return new KeyValuePair( + queryPath, + settings.UrlParameterFormatter.Format( + param, + parameterInfo, + parameterInfo.ParameterType + ) + ); } } - IEnumerable ParseEnumerableQueryParameterValue(IEnumerable paramValues, ICustomAttributeProvider customAttributeProvider, Type type, QueryAttribute? queryAttribute) + IEnumerable ParseEnumerableQueryParameterValue( + IEnumerable paramValues, + ICustomAttributeProvider customAttributeProvider, + Type type, + QueryAttribute? queryAttribute + ) { - var collectionFormat = queryAttribute != null && queryAttribute.IsCollectionFormatSpecified - ? queryAttribute.CollectionFormat - : settings.CollectionFormat; + var collectionFormat = + queryAttribute != null && queryAttribute.IsCollectionFormatSpecified + ? queryAttribute.CollectionFormat + : settings.CollectionFormat; switch (collectionFormat) { case CollectionFormat.Multi: foreach (var paramValue in paramValues) { - yield return settings.UrlParameterFormatter.Format(paramValue, customAttributeProvider, type); + yield return settings.UrlParameterFormatter.Format( + paramValue, + customAttributeProvider, + type + ); } break; default: - var delimiter = collectionFormat == CollectionFormat.Ssv ? " " - : collectionFormat == CollectionFormat.Tsv ? "\t" - : collectionFormat == CollectionFormat.Pipes ? "|" - : ","; + var delimiter = + collectionFormat == CollectionFormat.Ssv + ? " " + : collectionFormat == CollectionFormat.Tsv + ? "\t" + : collectionFormat == CollectionFormat.Pipes + ? "|" + : ","; // Missing a "default" clause was preventing the collection from serializing at all, as it was hitting "continue" thus causing an off-by-one error var formattedValues = paramValues .Cast() - .Select(v => settings.UrlParameterFormatter.Format(v, customAttributeProvider, type)); + .Select( + v => + settings.UrlParameterFormatter.Format( + v, + customAttributeProvider, + type + ) + ); yield return string.Join(delimiter, formattedValues); @@ -828,7 +1108,9 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn } } - Func> BuildRxFuncForMethod(RestMethodInfoInternal restMethod) + Func> BuildRxFuncForMethod( + RestMethodInfoInternal restMethod + ) { var taskFunc = BuildCancellableTaskFuncForMethod(restMethod); @@ -850,7 +1132,9 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn }; } - Func> BuildTaskFuncForMethod(RestMethodInfoInternal restMethod) + Func> BuildTaskFuncForMethod( + RestMethodInfoInternal restMethod + ) { var ret = BuildCancellableTaskFuncForMethod(restMethod); @@ -858,21 +1142,33 @@ Func BuildRequestFactoryForMethod(RestMethodInfoIn { if (restMethod.CancellationToken != null) { - return ret(client, paramList.OfType().FirstOrDefault(), paramList); + return ret( + client, + paramList.OfType().FirstOrDefault(), + paramList + ); } return ret(client, CancellationToken.None, paramList); }; } - Func BuildVoidTaskFuncForMethod(RestMethodInfoInternal restMethod) + Func BuildVoidTaskFuncForMethod( + RestMethodInfoInternal restMethod + ) { return async (client, paramList) => { if (client.BaseAddress == null) - throw new InvalidOperationException("BaseAddress must be set on the HttpClient instance"); - - var factory = BuildRequestFactoryForMethod(restMethod, client.BaseAddress.AbsolutePath, restMethod.CancellationToken != null); + throw new InvalidOperationException( + "BaseAddress must be set on the HttpClient instance" + ); + + var factory = BuildRequestFactoryForMethod( + restMethod, + client.BaseAddress.AbsolutePath, + restMethod.CancellationToken != null + ); var rq = factory(paramList); var ct = CancellationToken.None; @@ -897,7 +1193,10 @@ Func BuildVoidTaskFuncForMethod(RestMethodInfoIntern }; } - private static bool IsBodyBuffered(RestMethodInfoInternal restMethod, HttpRequestMessage? request) + private static bool IsBodyBuffered( + RestMethodInfoInternal restMethod, + HttpRequestMessage? request + ) { return (restMethod.BodyParameterInfo?.Item2 ?? false) && (request?.Content != null); } @@ -957,7 +1256,8 @@ static void SetHeader(HttpRequestMessage request, string name, string? value) request.Content.Headers.Remove(name); } - if (value == null) return; + if (value == null) + return; var added = request.Headers.TryAddWithoutValidation(name, value); diff --git a/Refit/RestMethodInfo.cs b/Refit/RestMethodInfo.cs index 63c0d9d69..3716cb0df 100644 --- a/Refit/RestMethodInfo.cs +++ b/Refit/RestMethodInfo.cs @@ -1,5 +1,5 @@ -using System.Net.Http; -using System.Diagnostics; +using System.Diagnostics; +using System.Net.Http; using System.Reflection; using System.Text.RegularExpressions; @@ -98,7 +98,9 @@ public RestMethodInfoInternal( Headers = ParseHeaders(methodInfo); HeaderParameterMap = BuildHeaderParameterMap(parameterList); - HeaderCollectionParameterMap = RestMethodInfoInternal.BuildHeaderCollectionParameterMap(parameterList); + HeaderCollectionParameterMap = RestMethodInfoInternal.BuildHeaderCollectionParameterMap( + parameterList + ); PropertyParameterMap = BuildRequestPropertyMap(parameterList); // get names for multipart attachments @@ -233,8 +235,8 @@ static Dictionary BuildRequestPropertyMap(List param static PropertyInfo[] GetParameterProperties(ParameterInfo parameter) { - return parameter.ParameterType - .GetProperties(BindingFlags.Public | BindingFlags.Instance) + return parameter + .ParameterType.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanRead && p.GetMethod?.IsPublic == true) .ToArray(); } @@ -303,9 +305,7 @@ List parameterInfo var parameterType = isRoundTripping ? ParameterType.RoundTripping : ParameterType.Normal; - var restMethodParameterInfo = new RestMethodParameterInfo( - name, -value) + var restMethodParameterInfo = new RestMethodParameterInfo(name, value) { Type = parameterType }; @@ -323,7 +323,10 @@ List parameterInfo #endif } //else if it's a property on a object parameter - else if (objectParamValidationDict.TryGetValue(name, out var value1) && !isRoundTripping) + else if ( + objectParamValidationDict.TryGetValue(name, out var value1) + && !isRoundTripping + ) { var property = value1; var parameterIndex = parameterInfo.IndexOf(property.Item1); @@ -542,8 +545,8 @@ HttpMethod method var inheritedAttributes = methodInfo.DeclaringType != null - ? methodInfo.DeclaringType - .GetInterfaces() + ? methodInfo + .DeclaringType.GetInterfaces() .SelectMany(i => i.GetTypeInfo().GetCustomAttributes(true)) .Reverse() : Array.Empty(); diff --git a/samples/Meow.Common/Middleware/HttpClientDiagnosticsHandler.cs b/samples/Meow.Common/Middleware/HttpClientDiagnosticsHandler.cs index b7653971e..477c15584 100644 --- a/samples/Meow.Common/Middleware/HttpClientDiagnosticsHandler.cs +++ b/samples/Meow.Common/Middleware/HttpClientDiagnosticsHandler.cs @@ -1,8 +1,8 @@ -using Serilog; -using System.Diagnostics; +using System.Diagnostics; using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using Serilog; namespace HttpClientDiagnostics { diff --git a/samples/Meow.Common/Services/CatsService.cs b/samples/Meow.Common/Services/CatsService.cs index 66da25105..f600b1d2d 100644 --- a/samples/Meow.Common/Services/CatsService.cs +++ b/samples/Meow.Common/Services/CatsService.cs @@ -1,11 +1,11 @@ -using HttpClientDiagnostics; -using Meow.Responses; -using Refit; -using System; +using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; +using HttpClientDiagnostics; +using Meow.Responses; +using Refit; namespace Meow { diff --git a/samples/Meow.Common/Services/ITheCatsAPI.cs b/samples/Meow.Common/Services/ITheCatsAPI.cs index 19af93de7..60100f344 100644 --- a/samples/Meow.Common/Services/ITheCatsAPI.cs +++ b/samples/Meow.Common/Services/ITheCatsAPI.cs @@ -1,9 +1,9 @@ -using Meow.Responses; -using Refit; -using System; +using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; +using Meow.Responses; +using Refit; namespace Meow { diff --git a/samples/Meow/Program.cs b/samples/Meow/Program.cs index f9cc0d943..fe2b565d5 100644 --- a/samples/Meow/Program.cs +++ b/samples/Meow/Program.cs @@ -1,6 +1,6 @@ -using Serilog; -using System; +using System; using System.Threading.Tasks; +using Serilog; namespace Meow { @@ -8,8 +8,8 @@ class Program { static async Task Main(string[] args) { - Log.Logger = new LoggerConfiguration().WriteTo - .Console() + Log.Logger = new LoggerConfiguration() + .WriteTo.Console() .MinimumLevel.Verbose() .CreateLogger();