diff options
Diffstat (limited to 'src/Http/Routing/test/UnitTests/Builder')
5 files changed, 1364 insertions, 1369 deletions
diff --git a/src/Http/Routing/test/UnitTests/Builder/EndpointRoutingApplicationBuilderExtensionsTest.cs b/src/Http/Routing/test/UnitTests/Builder/EndpointRoutingApplicationBuilderExtensionsTest.cs index ec9c88e9e1..79f597390e 100644 --- a/src/Http/Routing/test/UnitTests/Builder/EndpointRoutingApplicationBuilderExtensionsTest.cs +++ b/src/Http/Routing/test/UnitTests/Builder/EndpointRoutingApplicationBuilderExtensionsTest.cs @@ -16,357 +16,356 @@ using Microsoft.Extensions.Options; using Moq; using Xunit; -namespace Microsoft.AspNetCore.Builder +namespace Microsoft.AspNetCore.Builder; + +public class EndpointRoutingApplicationBuilderExtensionsTest { - public class EndpointRoutingApplicationBuilderExtensionsTest + [Fact] + public void UseRouting_ServicesNotRegistered_Throws() { - [Fact] - public void UseRouting_ServicesNotRegistered_Throws() - { - // Arrange - var app = new ApplicationBuilder(Mock.Of<IServiceProvider>()); - - // Act - var ex = Assert.Throws<InvalidOperationException>(() => app.UseRouting()); - - // Assert - Assert.Equal( - "Unable to find the required services. " + - "Please add all the required services by calling 'IServiceCollection.AddRouting' " + - "inside the call to 'ConfigureServices(...)' in the application startup code.", - ex.Message); - } - - [Fact] - public void UseEndpoint_ServicesNotRegistered_Throws() - { - // Arrange - var app = new ApplicationBuilder(Mock.Of<IServiceProvider>()); - - // Act - var ex = Assert.Throws<InvalidOperationException>(() => app.UseEndpoints(endpoints => { })); - - // Assert - Assert.Equal( - "Unable to find the required services. " + - "Please add all the required services by calling 'IServiceCollection.AddRouting' " + - "inside the call to 'ConfigureServices(...)' in the application startup code.", - ex.Message); - } - - [Fact] - public async Task UseRouting_ServicesRegistered_NoMatch_DoesNotSetFeature() - { - // Arrange - var services = CreateServices(); - - var app = new ApplicationBuilder(services); - - app.UseRouting(); + // Arrange + var app = new ApplicationBuilder(Mock.Of<IServiceProvider>()); + + // Act + var ex = Assert.Throws<InvalidOperationException>(() => app.UseRouting()); + + // Assert + Assert.Equal( + "Unable to find the required services. " + + "Please add all the required services by calling 'IServiceCollection.AddRouting' " + + "inside the call to 'ConfigureServices(...)' in the application startup code.", + ex.Message); + } - var appFunc = app.Build(); - var httpContext = new DefaultHttpContext(); + [Fact] + public void UseEndpoint_ServicesNotRegistered_Throws() + { + // Arrange + var app = new ApplicationBuilder(Mock.Of<IServiceProvider>()); + + // Act + var ex = Assert.Throws<InvalidOperationException>(() => app.UseEndpoints(endpoints => { })); + + // Assert + Assert.Equal( + "Unable to find the required services. " + + "Please add all the required services by calling 'IServiceCollection.AddRouting' " + + "inside the call to 'ConfigureServices(...)' in the application startup code.", + ex.Message); + } - // Act - await appFunc(httpContext); + [Fact] + public async Task UseRouting_ServicesRegistered_NoMatch_DoesNotSetFeature() + { + // Arrange + var services = CreateServices(); - // Assert - Assert.Null(httpContext.Features.Get<IEndpointFeature>()); - } + var app = new ApplicationBuilder(services); - [Fact] - public async Task UseRouting_ServicesRegistered_Match_DoesNotSetsFeature() - { - // Arrange - var endpoint = new RouteEndpoint( - TestConstants.EmptyRequestDelegate, - RoutePatternFactory.Parse("{*p}"), - 0, - EndpointMetadataCollection.Empty, - "Test"); + app.UseRouting(); - var services = CreateServices(); + var appFunc = app.Build(); + var httpContext = new DefaultHttpContext(); - var app = new ApplicationBuilder(services); + // Act + await appFunc(httpContext); - app.UseRouting(); + // Assert + Assert.Null(httpContext.Features.Get<IEndpointFeature>()); + } - app.UseEndpoints(endpoints => - { - endpoints.DataSources.Add(new DefaultEndpointDataSource(endpoint)); - }); + [Fact] + public async Task UseRouting_ServicesRegistered_Match_DoesNotSetsFeature() + { + // Arrange + var endpoint = new RouteEndpoint( + TestConstants.EmptyRequestDelegate, + RoutePatternFactory.Parse("{*p}"), + 0, + EndpointMetadataCollection.Empty, + "Test"); - var appFunc = app.Build(); - var httpContext = new DefaultHttpContext(); + var services = CreateServices(); - // Act - await appFunc(httpContext); + var app = new ApplicationBuilder(services); - // Assert - var feature = httpContext.Features.Get<IEndpointFeature>(); - Assert.NotNull(feature); - Assert.Same(endpoint, httpContext.GetEndpoint()); - } + app.UseRouting(); - [Fact] - public void UseEndpoint_WithoutEndpointRoutingMiddleware_Throws() + app.UseEndpoints(endpoints => { - // Arrange - var services = CreateServices(); + endpoints.DataSources.Add(new DefaultEndpointDataSource(endpoint)); + }); - var app = new ApplicationBuilder(services); + var appFunc = app.Build(); + var httpContext = new DefaultHttpContext(); - // Act - var ex = Assert.Throws<InvalidOperationException>(() => app.UseEndpoints(endpoints => { })); + // Act + await appFunc(httpContext); - // Assert - Assert.Equal( - "EndpointRoutingMiddleware matches endpoints setup by EndpointMiddleware and so must be added to the request " + - "execution pipeline before EndpointMiddleware. " + - "Please add EndpointRoutingMiddleware by calling 'IApplicationBuilder.UseRouting' " + - "inside the call to 'Configure(...)' in the application startup code.", - ex.Message); - } + // Assert + var feature = httpContext.Features.Get<IEndpointFeature>(); + Assert.NotNull(feature); + Assert.Same(endpoint, httpContext.GetEndpoint()); + } - [Fact] - public void UseEndpoint_WithApplicationBuilderMismatch_Throws() - { - // Arrange - var services = CreateServices(); + [Fact] + public void UseEndpoint_WithoutEndpointRoutingMiddleware_Throws() + { + // Arrange + var services = CreateServices(); - var app = new ApplicationBuilder(services); + var app = new ApplicationBuilder(services); - app.UseRouting(); + // Act + var ex = Assert.Throws<InvalidOperationException>(() => app.UseEndpoints(endpoints => { })); - // Act - var ex = Assert.Throws<InvalidOperationException>(() => app.Map("/Test", b => b.UseEndpoints(endpoints => { }))); + // Assert + Assert.Equal( + "EndpointRoutingMiddleware matches endpoints setup by EndpointMiddleware and so must be added to the request " + + "execution pipeline before EndpointMiddleware. " + + "Please add EndpointRoutingMiddleware by calling 'IApplicationBuilder.UseRouting' " + + "inside the call to 'Configure(...)' in the application startup code.", + ex.Message); + } - // Assert - Assert.Equal( - "The EndpointRoutingMiddleware and EndpointMiddleware must be added to the same IApplicationBuilder instance. " + - "To use Endpoint Routing with 'Map(...)', make sure to call 'IApplicationBuilder.UseRouting' before " + - "'IApplicationBuilder.UseEndpoints' for each branch of the middleware pipeline.", - ex.Message); - } + [Fact] + public void UseEndpoint_WithApplicationBuilderMismatch_Throws() + { + // Arrange + var services = CreateServices(); - [Fact] - public async Task UseEndpoint_ServicesRegisteredAndEndpointRoutingRegistered_NoMatch_DoesNotSetFeature() - { - // Arrange - var services = CreateServices(); + var app = new ApplicationBuilder(services); - var app = new ApplicationBuilder(services); + app.UseRouting(); - app.UseRouting(); - app.UseEndpoints(endpoints => { }); + // Act + var ex = Assert.Throws<InvalidOperationException>(() => app.Map("/Test", b => b.UseEndpoints(endpoints => { }))); - var appFunc = app.Build(); - var httpContext = new DefaultHttpContext(); + // Assert + Assert.Equal( + "The EndpointRoutingMiddleware and EndpointMiddleware must be added to the same IApplicationBuilder instance. " + + "To use Endpoint Routing with 'Map(...)', make sure to call 'IApplicationBuilder.UseRouting' before " + + "'IApplicationBuilder.UseEndpoints' for each branch of the middleware pipeline.", + ex.Message); + } - // Act - await appFunc(httpContext); + [Fact] + public async Task UseEndpoint_ServicesRegisteredAndEndpointRoutingRegistered_NoMatch_DoesNotSetFeature() + { + // Arrange + var services = CreateServices(); - // Assert - Assert.Null(httpContext.Features.Get<IEndpointFeature>()); - } + var app = new ApplicationBuilder(services); - [Fact] - public void UseEndpoints_CallWithBuilder_SetsEndpointDataSource() - { - // Arrange - var matcherEndpointDataSources = new List<EndpointDataSource>(); - var matcherFactoryMock = new Mock<MatcherFactory>(); - matcherFactoryMock - .Setup(m => m.CreateMatcher(It.IsAny<EndpointDataSource>())) - .Callback((EndpointDataSource arg) => - { - matcherEndpointDataSources.Add(arg); - }) - .Returns(new TestMatcher(false)); - - var services = CreateServices(matcherFactoryMock.Object); - - var app = new ApplicationBuilder(services); - - // Act - app.UseRouting(); - app.UseEndpoints(builder => - { - builder.Map("/1", d => null).WithDisplayName("Test endpoint 1"); - builder.Map("/2", d => null).WithDisplayName("Test endpoint 2"); - }); + app.UseRouting(); + app.UseEndpoints(endpoints => { }); - app.UseRouting(); - app.UseEndpoints(builder => - { - builder.Map("/3", d => null).WithDisplayName("Test endpoint 3"); - builder.Map("/4", d => null).WithDisplayName("Test endpoint 4"); - }); + var appFunc = app.Build(); + var httpContext = new DefaultHttpContext(); - // This triggers the middleware to be created and the matcher factory to be called - // with the datasource we want to test - var requestDelegate = app.Build(); - requestDelegate(new DefaultHttpContext()); + // Act + await appFunc(httpContext); - // Assert - Assert.Equal(2, matcherEndpointDataSources.Count); + // Assert + Assert.Null(httpContext.Features.Get<IEndpointFeature>()); + } - // each UseRouter has its own data source collection - Assert.Collection(matcherEndpointDataSources[0].Endpoints, - e => Assert.Equal("Test endpoint 1", e.DisplayName), - e => Assert.Equal("Test endpoint 2", e.DisplayName)); + [Fact] + public void UseEndpoints_CallWithBuilder_SetsEndpointDataSource() + { + // Arrange + var matcherEndpointDataSources = new List<EndpointDataSource>(); + var matcherFactoryMock = new Mock<MatcherFactory>(); + matcherFactoryMock + .Setup(m => m.CreateMatcher(It.IsAny<EndpointDataSource>())) + .Callback((EndpointDataSource arg) => + { + matcherEndpointDataSources.Add(arg); + }) + .Returns(new TestMatcher(false)); - Assert.Collection(matcherEndpointDataSources[1].Endpoints, - e => Assert.Equal("Test endpoint 3", e.DisplayName), - e => Assert.Equal("Test endpoint 4", e.DisplayName)); + var services = CreateServices(matcherFactoryMock.Object); - var compositeEndpointBuilder = services.GetRequiredService<EndpointDataSource>(); + var app = new ApplicationBuilder(services); - // Global collection has all endpoints - Assert.Collection(compositeEndpointBuilder.Endpoints, - e => Assert.Equal("Test endpoint 1", e.DisplayName), - e => Assert.Equal("Test endpoint 2", e.DisplayName), - e => Assert.Equal("Test endpoint 3", e.DisplayName), - e => Assert.Equal("Test endpoint 4", e.DisplayName)); - } + // Act + app.UseRouting(); + app.UseEndpoints(builder => + { + builder.Map("/1", d => null).WithDisplayName("Test endpoint 1"); + builder.Map("/2", d => null).WithDisplayName("Test endpoint 2"); + }); - // Verifies that it's possible to use endpoints and map together. - [Fact] - public void UseEndpoints_CallWithBuilder_SetsEndpointDataSource_WithMap() + app.UseRouting(); + app.UseEndpoints(builder => { - // Arrange - var matcherEndpointDataSources = new List<EndpointDataSource>(); - var matcherFactoryMock = new Mock<MatcherFactory>(); - matcherFactoryMock - .Setup(m => m.CreateMatcher(It.IsAny<EndpointDataSource>())) - .Callback((EndpointDataSource arg) => - { - matcherEndpointDataSources.Add(arg); - }) - .Returns(new TestMatcher(false)); + builder.Map("/3", d => null).WithDisplayName("Test endpoint 3"); + builder.Map("/4", d => null).WithDisplayName("Test endpoint 4"); + }); + + // This triggers the middleware to be created and the matcher factory to be called + // with the datasource we want to test + var requestDelegate = app.Build(); + requestDelegate(new DefaultHttpContext()); + + // Assert + Assert.Equal(2, matcherEndpointDataSources.Count); + + // each UseRouter has its own data source collection + Assert.Collection(matcherEndpointDataSources[0].Endpoints, + e => Assert.Equal("Test endpoint 1", e.DisplayName), + e => Assert.Equal("Test endpoint 2", e.DisplayName)); + + Assert.Collection(matcherEndpointDataSources[1].Endpoints, + e => Assert.Equal("Test endpoint 3", e.DisplayName), + e => Assert.Equal("Test endpoint 4", e.DisplayName)); + + var compositeEndpointBuilder = services.GetRequiredService<EndpointDataSource>(); + + // Global collection has all endpoints + Assert.Collection(compositeEndpointBuilder.Endpoints, + e => Assert.Equal("Test endpoint 1", e.DisplayName), + e => Assert.Equal("Test endpoint 2", e.DisplayName), + e => Assert.Equal("Test endpoint 3", e.DisplayName), + e => Assert.Equal("Test endpoint 4", e.DisplayName)); + } - var services = CreateServices(matcherFactoryMock.Object); + // Verifies that it's possible to use endpoints and map together. + [Fact] + public void UseEndpoints_CallWithBuilder_SetsEndpointDataSource_WithMap() + { + // Arrange + var matcherEndpointDataSources = new List<EndpointDataSource>(); + var matcherFactoryMock = new Mock<MatcherFactory>(); + matcherFactoryMock + .Setup(m => m.CreateMatcher(It.IsAny<EndpointDataSource>())) + .Callback((EndpointDataSource arg) => + { + matcherEndpointDataSources.Add(arg); + }) + .Returns(new TestMatcher(false)); - var app = new ApplicationBuilder(services); + var services = CreateServices(matcherFactoryMock.Object); - // Act - app.UseRouting(); + var app = new ApplicationBuilder(services); - app.Map("/foo", b => - { - b.UseRouting(); - b.UseEndpoints(builder => - { - builder.Map("/1", d => null).WithDisplayName("Test endpoint 1"); - builder.Map("/2", d => null).WithDisplayName("Test endpoint 2"); - }); - }); + // Act + app.UseRouting(); - app.UseEndpoints(builder => + app.Map("/foo", b => + { + b.UseRouting(); + b.UseEndpoints(builder => { - builder.Map("/3", d => null).WithDisplayName("Test endpoint 3"); - builder.Map("/4", d => null).WithDisplayName("Test endpoint 4"); + builder.Map("/1", d => null).WithDisplayName("Test endpoint 1"); + builder.Map("/2", d => null).WithDisplayName("Test endpoint 2"); }); + }); - // This triggers the middleware to be created and the matcher factory to be called - // with the datasource we want to test - var requestDelegate = app.Build(); - requestDelegate(new DefaultHttpContext()); - requestDelegate(new DefaultHttpContext() { Request = { Path = "/Foo", }, }); - - // Assert - Assert.Equal(2, matcherEndpointDataSources.Count); + app.UseEndpoints(builder => + { + builder.Map("/3", d => null).WithDisplayName("Test endpoint 3"); + builder.Map("/4", d => null).WithDisplayName("Test endpoint 4"); + }); + + // This triggers the middleware to be created and the matcher factory to be called + // with the datasource we want to test + var requestDelegate = app.Build(); + requestDelegate(new DefaultHttpContext()); + requestDelegate(new DefaultHttpContext() { Request = { Path = "/Foo", }, }); + + // Assert + Assert.Equal(2, matcherEndpointDataSources.Count); + + // Each UseRouter has its own data source + Assert.Collection(matcherEndpointDataSources[1].Endpoints, // app.UseRouter + e => Assert.Equal("Test endpoint 1", e.DisplayName), + e => Assert.Equal("Test endpoint 2", e.DisplayName)); + + Assert.Collection(matcherEndpointDataSources[0].Endpoints, // b.UseRouter + e => Assert.Equal("Test endpoint 3", e.DisplayName), + e => Assert.Equal("Test endpoint 4", e.DisplayName)); + + var compositeEndpointBuilder = services.GetRequiredService<EndpointDataSource>(); + + // Global middleware has all endpoints + Assert.Collection(compositeEndpointBuilder.Endpoints, + e => Assert.Equal("Test endpoint 1", e.DisplayName), + e => Assert.Equal("Test endpoint 2", e.DisplayName), + e => Assert.Equal("Test endpoint 3", e.DisplayName), + e => Assert.Equal("Test endpoint 4", e.DisplayName)); + } - // Each UseRouter has its own data source - Assert.Collection(matcherEndpointDataSources[1].Endpoints, // app.UseRouter - e => Assert.Equal("Test endpoint 1", e.DisplayName), - e => Assert.Equal("Test endpoint 2", e.DisplayName)); + [Fact] + public void UseEndpoints_WithGlobalEndpointRouteBuilderHasRoutes() + { + // Arrange + var services = CreateServices(); - Assert.Collection(matcherEndpointDataSources[0].Endpoints, // b.UseRouter - e => Assert.Equal("Test endpoint 3", e.DisplayName), - e => Assert.Equal("Test endpoint 4", e.DisplayName)); + var app = new ApplicationBuilder(services); - var compositeEndpointBuilder = services.GetRequiredService<EndpointDataSource>(); + var mockRouteBuilder = new Mock<IEndpointRouteBuilder>(); + mockRouteBuilder.Setup(m => m.DataSources).Returns(new List<EndpointDataSource>()); - // Global middleware has all endpoints - Assert.Collection(compositeEndpointBuilder.Endpoints, - e => Assert.Equal("Test endpoint 1", e.DisplayName), - e => Assert.Equal("Test endpoint 2", e.DisplayName), - e => Assert.Equal("Test endpoint 3", e.DisplayName), - e => Assert.Equal("Test endpoint 4", e.DisplayName)); - } + var routeBuilder = mockRouteBuilder.Object; + app.Properties.Add("__GlobalEndpointRouteBuilder", routeBuilder); + app.UseRouting(); - [Fact] - public void UseEndpoints_WithGlobalEndpointRouteBuilderHasRoutes() + app.UseEndpoints(endpoints => { - // Arrange - var services = CreateServices(); + endpoints.Map("/1", d => Task.CompletedTask).WithDisplayName("Test endpoint 1"); + }); - var app = new ApplicationBuilder(services); + var requestDelegate = app.Build(); - var mockRouteBuilder = new Mock<IEndpointRouteBuilder>(); - mockRouteBuilder.Setup(m => m.DataSources).Returns(new List<EndpointDataSource>()); + var endpointDataSource = Assert.Single(mockRouteBuilder.Object.DataSources); + Assert.Collection(endpointDataSource.Endpoints, + e => Assert.Equal("Test endpoint 1", e.DisplayName)); - var routeBuilder = mockRouteBuilder.Object; - app.Properties.Add("__GlobalEndpointRouteBuilder", routeBuilder); - app.UseRouting(); - - app.UseEndpoints(endpoints => - { - endpoints.Map("/1", d => Task.CompletedTask).WithDisplayName("Test endpoint 1"); - }); - - var requestDelegate = app.Build(); + var routeOptions = app.ApplicationServices.GetRequiredService<IOptions<RouteOptions>>(); + Assert.Equal(mockRouteBuilder.Object.DataSources, routeOptions.Value.EndpointDataSources); + } - var endpointDataSource = Assert.Single(mockRouteBuilder.Object.DataSources); - Assert.Collection(endpointDataSource.Endpoints, - e => Assert.Equal("Test endpoint 1", e.DisplayName)); + [Fact] + public void UseRouting_SetsEndpointRouteBuilder_IfGlobalOneExists() + { + // Arrange + var services = CreateServices(); - var routeOptions = app.ApplicationServices.GetRequiredService<IOptions<RouteOptions>>(); - Assert.Equal(mockRouteBuilder.Object.DataSources, routeOptions.Value.EndpointDataSources); - } + var app = new ApplicationBuilder(services); - [Fact] - public void UseRouting_SetsEndpointRouteBuilder_IfGlobalOneExists() - { - // Arrange - var services = CreateServices(); + var routeBuilder = new Mock<IEndpointRouteBuilder>().Object; + app.Properties.Add("__GlobalEndpointRouteBuilder", routeBuilder); + app.UseRouting(); - var app = new ApplicationBuilder(services); + Assert.True(app.Properties.TryGetValue("__EndpointRouteBuilder", out var local)); + Assert.True(app.Properties.TryGetValue("__GlobalEndpointRouteBuilder", out var global)); + Assert.Same(local, global); + } - var routeBuilder = new Mock<IEndpointRouteBuilder>().Object; - app.Properties.Add("__GlobalEndpointRouteBuilder", routeBuilder); - app.UseRouting(); + private IServiceProvider CreateServices() + { + return CreateServices(matcherFactory: null); + } - Assert.True(app.Properties.TryGetValue("__EndpointRouteBuilder", out var local)); - Assert.True(app.Properties.TryGetValue("__GlobalEndpointRouteBuilder", out var global)); - Assert.Same(local, global); - } + private IServiceProvider CreateServices(MatcherFactory matcherFactory) + { + var services = new ServiceCollection(); - private IServiceProvider CreateServices() + if (matcherFactory != null) { - return CreateServices(matcherFactory: null); + services.AddSingleton<MatcherFactory>(matcherFactory); } - private IServiceProvider CreateServices(MatcherFactory matcherFactory) - { - var services = new ServiceCollection(); + services.AddLogging(); + services.AddOptions(); + services.AddRouting(); + var listener = new DiagnosticListener("Microsoft.AspNetCore"); + services.AddSingleton(listener); + services.AddSingleton<DiagnosticSource>(listener); - if (matcherFactory != null) - { - services.AddSingleton<MatcherFactory>(matcherFactory); - } - - services.AddLogging(); - services.AddOptions(); - services.AddRouting(); - var listener = new DiagnosticListener("Microsoft.AspNetCore"); - services.AddSingleton(listener); - services.AddSingleton<DiagnosticSource>(listener); + var serviceProvder = services.BuildServiceProvider(); - var serviceProvder = services.BuildServiceProvider(); - - return serviceProvder; - } + return serviceProvder; } } diff --git a/src/Http/Routing/test/UnitTests/Builder/RequestDelegateEndpointRouteBuilderExtensionsTest.cs b/src/Http/Routing/test/UnitTests/Builder/RequestDelegateEndpointRouteBuilderExtensionsTest.cs index f9079850ea..40aae08767 100644 --- a/src/Http/Routing/test/UnitTests/Builder/RequestDelegateEndpointRouteBuilderExtensionsTest.cs +++ b/src/Http/Routing/test/UnitTests/Builder/RequestDelegateEndpointRouteBuilderExtensionsTest.cs @@ -12,215 +12,214 @@ using Microsoft.AspNetCore.Routing.Patterns; using Moq; using Xunit; -namespace Microsoft.AspNetCore.Builder +namespace Microsoft.AspNetCore.Builder; + +public class RequestDelegateEndpointRouteBuilderExtensionsTest { - public class RequestDelegateEndpointRouteBuilderExtensionsTest + private ModelEndpointDataSource GetBuilderEndpointDataSource(IEndpointRouteBuilder endpointRouteBuilder) { - private ModelEndpointDataSource GetBuilderEndpointDataSource(IEndpointRouteBuilder endpointRouteBuilder) - { - return Assert.IsType<ModelEndpointDataSource>(Assert.Single(endpointRouteBuilder.DataSources)); - } + return Assert.IsType<ModelEndpointDataSource>(Assert.Single(endpointRouteBuilder.DataSources)); + } - private RouteEndpointBuilder GetRouteEndpointBuilder(IEndpointRouteBuilder endpointRouteBuilder) - { - return Assert.IsType<RouteEndpointBuilder>(Assert.Single(GetBuilderEndpointDataSource(endpointRouteBuilder).EndpointBuilders)); - } + private RouteEndpointBuilder GetRouteEndpointBuilder(IEndpointRouteBuilder endpointRouteBuilder) + { + return Assert.IsType<RouteEndpointBuilder>(Assert.Single(GetBuilderEndpointDataSource(endpointRouteBuilder).EndpointBuilders)); + } - public static object[][] MapMethods + public static object[][] MapMethods + { + get { - get - { - IEndpointConventionBuilder MapGet(IEndpointRouteBuilder routes, string template, RequestDelegate action) => - routes.MapGet(template, action); + IEndpointConventionBuilder MapGet(IEndpointRouteBuilder routes, string template, RequestDelegate action) => + routes.MapGet(template, action); - IEndpointConventionBuilder MapPost(IEndpointRouteBuilder routes, string template, RequestDelegate action) => - routes.MapPost(template, action); + IEndpointConventionBuilder MapPost(IEndpointRouteBuilder routes, string template, RequestDelegate action) => + routes.MapPost(template, action); - IEndpointConventionBuilder MapPut(IEndpointRouteBuilder routes, string template, RequestDelegate action) => - routes.MapPut(template, action); + IEndpointConventionBuilder MapPut(IEndpointRouteBuilder routes, string template, RequestDelegate action) => + routes.MapPut(template, action); - IEndpointConventionBuilder MapDelete(IEndpointRouteBuilder routes, string template, RequestDelegate action) => - routes.MapDelete(template, action); + IEndpointConventionBuilder MapDelete(IEndpointRouteBuilder routes, string template, RequestDelegate action) => + routes.MapDelete(template, action); - IEndpointConventionBuilder Map(IEndpointRouteBuilder routes, string template, RequestDelegate action) => - routes.Map(template, action); + IEndpointConventionBuilder Map(IEndpointRouteBuilder routes, string template, RequestDelegate action) => + routes.Map(template, action); - return new object[][] - { + return new object[][] + { new object[] { (Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder>)MapGet }, new object[] { (Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder>)MapPost }, new object[] { (Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder>)MapPut }, new object[] { (Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder>)MapDelete }, new object[] { (Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder>)Map }, - }; - } + }; } + } - [Fact] - public void MapEndpoint_StringPattern_BuildsEndpoint() - { - // Arrange - var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); - RequestDelegate requestDelegate = (d) => null; + [Fact] + public void MapEndpoint_StringPattern_BuildsEndpoint() + { + // Arrange + var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); + RequestDelegate requestDelegate = (d) => null; - // Act - var endpointBuilder = builder.Map("/", requestDelegate); + // Act + var endpointBuilder = builder.Map("/", requestDelegate); - // Assert - var endpointBuilder1 = GetRouteEndpointBuilder(builder); + // Assert + var endpointBuilder1 = GetRouteEndpointBuilder(builder); - Assert.Equal(requestDelegate, endpointBuilder1.RequestDelegate); - Assert.Equal("/", endpointBuilder1.DisplayName); - Assert.Equal("/", endpointBuilder1.RoutePattern.RawText); - } + Assert.Equal(requestDelegate, endpointBuilder1.RequestDelegate); + Assert.Equal("/", endpointBuilder1.DisplayName); + Assert.Equal("/", endpointBuilder1.RoutePattern.RawText); + } - [Fact] - public void MapEndpoint_TypedPattern_BuildsEndpoint() - { - // Arrange - var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); - RequestDelegate requestDelegate = (d) => null; + [Fact] + public void MapEndpoint_TypedPattern_BuildsEndpoint() + { + // Arrange + var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); + RequestDelegate requestDelegate = (d) => null; - // Act - var endpointBuilder = builder.Map(RoutePatternFactory.Parse("/"), requestDelegate); + // Act + var endpointBuilder = builder.Map(RoutePatternFactory.Parse("/"), requestDelegate); - // Assert - var endpointBuilder1 = GetRouteEndpointBuilder(builder); + // Assert + var endpointBuilder1 = GetRouteEndpointBuilder(builder); - Assert.Equal(requestDelegate, endpointBuilder1.RequestDelegate); - Assert.Equal("/", endpointBuilder1.DisplayName); - Assert.Equal("/", endpointBuilder1.RoutePattern.RawText); - } + Assert.Equal(requestDelegate, endpointBuilder1.RequestDelegate); + Assert.Equal("/", endpointBuilder1.DisplayName); + Assert.Equal("/", endpointBuilder1.RoutePattern.RawText); + } - [Fact] - public void MapEndpoint_AttributesCollectedAsMetadata() - { - // Arrange - var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); - - // Act - var endpointBuilder = builder.Map(RoutePatternFactory.Parse("/"), Handle); - - // Assert - var endpointBuilder1 = GetRouteEndpointBuilder(builder); - Assert.Equal("/", endpointBuilder1.RoutePattern.RawText); - Assert.Equal(2, endpointBuilder1.Metadata.Count); - Assert.IsType<Attribute1>(endpointBuilder1.Metadata[0]); - Assert.IsType<Attribute2>(endpointBuilder1.Metadata[1]); - } + [Fact] + public void MapEndpoint_AttributesCollectedAsMetadata() + { + // Arrange + var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); + + // Act + var endpointBuilder = builder.Map(RoutePatternFactory.Parse("/"), Handle); + + // Assert + var endpointBuilder1 = GetRouteEndpointBuilder(builder); + Assert.Equal("/", endpointBuilder1.RoutePattern.RawText); + Assert.Equal(2, endpointBuilder1.Metadata.Count); + Assert.IsType<Attribute1>(endpointBuilder1.Metadata[0]); + Assert.IsType<Attribute2>(endpointBuilder1.Metadata[1]); + } - [Fact] - public void MapEndpoint_GeneratedDelegateWorks() - { - // Arrange - var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); + [Fact] + public void MapEndpoint_GeneratedDelegateWorks() + { + // Arrange + var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); - Expression<RequestDelegate> handler = context => Task.CompletedTask; + Expression<RequestDelegate> handler = context => Task.CompletedTask; - // Act - var endpointBuilder = builder.Map(RoutePatternFactory.Parse("/"), handler.Compile()); + // Act + var endpointBuilder = builder.Map(RoutePatternFactory.Parse("/"), handler.Compile()); - // Assert - var endpointBuilder1 = GetRouteEndpointBuilder(builder); - Assert.Equal("/", endpointBuilder1.RoutePattern.RawText); - } + // Assert + var endpointBuilder1 = GetRouteEndpointBuilder(builder); + Assert.Equal("/", endpointBuilder1.RoutePattern.RawText); + } - [Fact] - public void MapEndpoint_PrecedenceOfMetadata_BuilderMetadataReturned() - { - // Arrange - var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); + [Fact] + public void MapEndpoint_PrecedenceOfMetadata_BuilderMetadataReturned() + { + // Arrange + var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); - // Act - var endpointBuilder = builder.MapMethods("/", new[] { "METHOD" }, HandleHttpMetdata); - endpointBuilder.WithMetadata(new HttpMethodMetadata(new[] { "BUILDER" })); + // Act + var endpointBuilder = builder.MapMethods("/", new[] { "METHOD" }, HandleHttpMetdata); + endpointBuilder.WithMetadata(new HttpMethodMetadata(new[] { "BUILDER" })); - // Assert - var dataSource = Assert.Single(builder.DataSources); - var endpoint = Assert.Single(dataSource.Endpoints); + // Assert + var dataSource = Assert.Single(builder.DataSources); + var endpoint = Assert.Single(dataSource.Endpoints); - Assert.Equal(3, endpoint.Metadata.Count); - Assert.Equal("ATTRIBUTE", GetMethod(endpoint.Metadata[0])); - Assert.Equal("METHOD", GetMethod(endpoint.Metadata[1])); - Assert.Equal("BUILDER", GetMethod(endpoint.Metadata[2])); + Assert.Equal(3, endpoint.Metadata.Count); + Assert.Equal("ATTRIBUTE", GetMethod(endpoint.Metadata[0])); + Assert.Equal("METHOD", GetMethod(endpoint.Metadata[1])); + Assert.Equal("BUILDER", GetMethod(endpoint.Metadata[2])); - Assert.Equal("BUILDER", endpoint.Metadata.GetMetadata<IHttpMethodMetadata>().HttpMethods.Single()); + Assert.Equal("BUILDER", endpoint.Metadata.GetMetadata<IHttpMethodMetadata>().HttpMethods.Single()); - string GetMethod(object metadata) - { - var httpMethodMetadata = Assert.IsAssignableFrom<IHttpMethodMetadata>(metadata); - return Assert.Single(httpMethodMetadata.HttpMethods); - } - } - - [Theory] - [MemberData(nameof(MapMethods))] - public void Map_EndpointMetadataNotDuplicated(Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder> map) + string GetMethod(object metadata) { - // Arrange - var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); + var httpMethodMetadata = Assert.IsAssignableFrom<IHttpMethodMetadata>(metadata); + return Assert.Single(httpMethodMetadata.HttpMethods); + } + } - // Act - var endpointBuilder = map(builder, "/", context => Task.CompletedTask).WithMetadata(new EndpointNameMetadata("MapMe")); + [Theory] + [MemberData(nameof(MapMethods))] + public void Map_EndpointMetadataNotDuplicated(Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder> map) + { + // Arrange + var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); - // Assert - var ds = GetBuilderEndpointDataSource(builder); + // Act + var endpointBuilder = map(builder, "/", context => Task.CompletedTask).WithMetadata(new EndpointNameMetadata("MapMe")); - _ = ds.Endpoints; - _ = ds.Endpoints; - _ = ds.Endpoints; + // Assert + var ds = GetBuilderEndpointDataSource(builder); - Assert.Single(ds.Endpoints); - var endpoint = ds.Endpoints.Single(); + _ = ds.Endpoints; + _ = ds.Endpoints; + _ = ds.Endpoints; - Assert.Single(endpoint.Metadata.GetOrderedMetadata<IEndpointNameMetadata>()); - } + Assert.Single(ds.Endpoints); + var endpoint = ds.Endpoints.Single(); - [Theory] - [MemberData(nameof(MapMethods))] - public void AddingMetadataAfterBuildingEndpointThrows(Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder> map) - { - // Arrange - var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); + Assert.Single(endpoint.Metadata.GetOrderedMetadata<IEndpointNameMetadata>()); + } - // Act - var endpointBuilder = map(builder, "/", context => Task.CompletedTask).WithMetadata(new EndpointNameMetadata("MapMe")); + [Theory] + [MemberData(nameof(MapMethods))] + public void AddingMetadataAfterBuildingEndpointThrows(Func<IEndpointRouteBuilder, string, RequestDelegate, IEndpointConventionBuilder> map) + { + // Arrange + var builder = new DefaultEndpointRouteBuilder(Mock.Of<IApplicationBuilder>()); - // Assert - var ds = GetBuilderEndpointDataSource(builder); + // Act + var endpointBuilder = map(builder, "/", context => Task.CompletedTask).WithMetadata(new EndpointNameMetadata("MapMe")); - var endpoint = Assert.Single(ds.Endpoints); + // Assert + var ds = GetBuilderEndpointDataSource(builder); - Assert.Single(endpoint.Metadata.GetOrderedMetadata<IEndpointNameMetadata>()); + var endpoint = Assert.Single(ds.Endpoints); - Assert.Throws<InvalidOperationException>(() => endpointBuilder.WithMetadata(new RouteNameMetadata("Foo"))); - } + Assert.Single(endpoint.Metadata.GetOrderedMetadata<IEndpointNameMetadata>()); - [Attribute1] - [Attribute2] - private static Task Handle(HttpContext context) => Task.CompletedTask; + Assert.Throws<InvalidOperationException>(() => endpointBuilder.WithMetadata(new RouteNameMetadata("Foo"))); + } - [HttpMethod("ATTRIBUTE")] - private static Task HandleHttpMetdata(HttpContext context) => Task.CompletedTask; + [Attribute1] + [Attribute2] + private static Task Handle(HttpContext context) => Task.CompletedTask; - private class HttpMethodAttribute : Attribute, IHttpMethodMetadata - { - public bool AcceptCorsPreflight => false; + [HttpMethod("ATTRIBUTE")] + private static Task HandleHttpMetdata(HttpContext context) => Task.CompletedTask; - public IReadOnlyList<string> HttpMethods { get; } + private class HttpMethodAttribute : Attribute, IHttpMethodMetadata + { + public bool AcceptCorsPreflight => false; - public HttpMethodAttribute(params string[] httpMethods) - { - HttpMethods = httpMethods; - } - } + public IReadOnlyList<string> HttpMethods { get; } - private class Attribute1 : Attribute + public HttpMethodAttribute(params string[] httpMethods) { + HttpMethods = httpMethods; } + } - private class Attribute2 : Attribute - { - } + private class Attribute1 : Attribute + { + } + + private class Attribute2 : Attribute + { } } diff --git a/src/Http/Routing/test/UnitTests/Builder/RouteHandlerEndpointRouteBuilderExtensionsTest.cs b/src/Http/Routing/test/UnitTests/Builder/RouteHandlerEndpointRouteBuilderExtensionsTest.cs index e485e0b3fd..e942596cba 100644 --- a/src/Http/Routing/test/UnitTests/Builder/RouteHandlerEndpointRouteBuilderExtensionsTest.cs +++ b/src/Http/Routing/test/UnitTests/Builder/RouteHandlerEndpointRouteBuilderExtensionsTest.cs @@ -10,224 +10,224 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; -namespace Microsoft.AspNetCore.Builder +namespace Microsoft.AspNetCore.Builder; + +public class RouteHandlerEndpointRouteBuilderExtensionsTest { - public class RouteHandlerEndpointRouteBuilderExtensionsTest + private ModelEndpointDataSource GetBuilderEndpointDataSource(IEndpointRouteBuilder endpointRouteBuilder) { - private ModelEndpointDataSource GetBuilderEndpointDataSource(IEndpointRouteBuilder endpointRouteBuilder) - { - return Assert.IsType<ModelEndpointDataSource>(Assert.Single(endpointRouteBuilder.DataSources)); - } + return Assert.IsType<ModelEndpointDataSource>(Assert.Single(endpointRouteBuilder.DataSources)); + } - private RouteEndpointBuilder GetRouteEndpointBuilder(IEndpointRouteBuilder endpointRouteBuilder) - { - return Assert.IsType<RouteEndpointBuilder>(Assert.Single(GetBuilderEndpointDataSource(endpointRouteBuilder).EndpointBuilders)); - } + private RouteEndpointBuilder GetRouteEndpointBuilder(IEndpointRouteBuilder endpointRouteBuilder) + { + return Assert.IsType<RouteEndpointBuilder>(Assert.Single(GetBuilderEndpointDataSource(endpointRouteBuilder).EndpointBuilders)); + } - public static object?[]?[] MapMethods + public static object?[]?[] MapMethods + { + get { - get - { - IEndpointConventionBuilder MapGet(IEndpointRouteBuilder routes, string template, Delegate action) => - routes.MapGet(template, action); + IEndpointConventionBuilder MapGet(IEndpointRouteBuilder routes, string template, Delegate action) => + routes.MapGet(template, action); - IEndpointConventionBuilder MapPost(IEndpointRouteBuilder routes, string template, Delegate action) => - routes.MapPost(template, action); + IEndpointConventionBuilder MapPost(IEndpointRouteBuilder routes, string template, Delegate action) => + routes.MapPost(template, action); - IEndpointConventionBuilder MapPut(IEndpointRouteBuilder routes, string template, Delegate action) => - routes.MapPut(template, action); + IEndpointConventionBuilder MapPut(IEndpointRouteBuilder routes, string template, Delegate action) => + routes.MapPut(template, action); - IEndpointConventionBuilder MapDelete(IEndpointRouteBuilder routes, string template, Delegate action) => - routes.MapDelete(template, action); + IEndpointConventionBuilder MapDelete(IEndpointRouteBuilder routes, string template, Delegate action) => + routes.MapDelete(template, action); - IEndpointConventionBuilder MapPatch(IEndpointRouteBuilder routes, string template, Delegate action) => - routes.MapPatch(template, action); + IEndpointConventionBuilder MapPatch(IEndpointRouteBuilder routes, string template, Delegate action) => + routes.MapPatch(template, action); - IEndpointConventionBuilder Map(IEndpointRouteBuilder routes, string template, Delegate action) => - routes.Map(template, action); + IEndpointConventionBuilder Map(IEndpointRouteBuilder routes, string template, Delegate action) => + routes.Map(template, action); - return new object?[]?[] - { + return new object?[]?[] + { new object?[] { (Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder>)MapGet, "GET" }, new object?[] { (Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder>)MapPost, "POST" }, new object?[] { (Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder>)MapPut, "PUT" }, new object?[] { (Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder>)MapDelete, "DELETE" }, new object?[] { (Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder>)MapPatch, "PATCH" }, new object?[] { (Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder>)Map, null }, - }; - } + }; } + } - [Fact] - public void MapEndpoint_PrecedenceOfMetadata_BuilderMetadataReturned() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + [Fact] + public void MapEndpoint_PrecedenceOfMetadata_BuilderMetadataReturned() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - [HttpMethod("ATTRIBUTE")] - void TestAction() - { - } + [HttpMethod("ATTRIBUTE")] + void TestAction() + { + } - var endpointBuilder = builder.MapMethods("/", new[] { "METHOD" }, (Action)TestAction); - endpointBuilder.WithMetadata(new HttpMethodMetadata(new[] { "BUILDER" })); + var endpointBuilder = builder.MapMethods("/", new[] { "METHOD" }, (Action)TestAction); + endpointBuilder.WithMetadata(new HttpMethodMetadata(new[] { "BUILDER" })); - var dataSource = Assert.Single(builder.DataSources); - var endpoint = Assert.Single(dataSource.Endpoints); + var dataSource = Assert.Single(builder.DataSources); + var endpoint = Assert.Single(dataSource.Endpoints); - var metadataArray = endpoint.Metadata.OfType<IHttpMethodMetadata>().ToArray(); + var metadataArray = endpoint.Metadata.OfType<IHttpMethodMetadata>().ToArray(); - static string GetMethod(IHttpMethodMetadata metadata) => Assert.Single(metadata.HttpMethods); + static string GetMethod(IHttpMethodMetadata metadata) => Assert.Single(metadata.HttpMethods); - Assert.Equal(3, metadataArray.Length); - Assert.Equal("ATTRIBUTE", GetMethod(metadataArray[0])); - Assert.Equal("METHOD", GetMethod(metadataArray[1])); - Assert.Equal("BUILDER", GetMethod(metadataArray[2])); + Assert.Equal(3, metadataArray.Length); + Assert.Equal("ATTRIBUTE", GetMethod(metadataArray[0])); + Assert.Equal("METHOD", GetMethod(metadataArray[1])); + Assert.Equal("BUILDER", GetMethod(metadataArray[2])); - Assert.Equal("BUILDER", endpoint.Metadata.GetMetadata<IHttpMethodMetadata>()!.HttpMethods.Single()); - } + Assert.Equal("BUILDER", endpoint.Metadata.GetMetadata<IHttpMethodMetadata>()!.HttpMethods.Single()); + } - [Fact] - public void MapGet_BuildsEndpointWithCorrectMethod() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapGet("/", () => { }); + [Fact] + public void MapGet_BuildsEndpointWithCorrectMethod() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapGet("/", () => { }); - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("GET", method); + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("GET", method); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - [Fact] - public void MapPatch_BuildsEndpointWithCorrectMethod() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapPatch("/", () => { }); + [Fact] + public void MapPatch_BuildsEndpointWithCorrectMethod() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapPatch("/", () => { }); - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("PATCH", method); + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("PATCH", method); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: PATCH /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: PATCH /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - [Fact] - public async Task MapGetWithRouteParameter_BuildsEndpointWithRouteSpecificBinding() + [Fact] + public async Task MapGetWithRouteParameter_BuildsEndpointWithRouteSpecificBinding() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapGet("/{id}", (int? id, HttpContext httpContext) => { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapGet("/{id}", (int? id, HttpContext httpContext) => + if (id is not null) { - if (id is not null) - { - httpContext.Items["input"] = id; - } - }); + httpContext.Items["input"] = id; + } + }); - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("GET", method); + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("GET", method); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: GET /{id}", routeEndpointBuilder.DisplayName); - Assert.Equal("/{id}", routeEndpointBuilder.RoutePattern.RawText); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: GET /{id}", routeEndpointBuilder.DisplayName); + Assert.Equal("/{id}", routeEndpointBuilder.RoutePattern.RawText); - // Assert that we don't fallback to the query string - var httpContext = new DefaultHttpContext(); + // Assert that we don't fallback to the query string + var httpContext = new DefaultHttpContext(); - httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues> - { - ["id"] = "42" - }); + httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues> + { + ["id"] = "42" + }); - await endpoint.RequestDelegate!(httpContext); + await endpoint.RequestDelegate!(httpContext); - Assert.Null(httpContext.Items["input"]); - } + Assert.Null(httpContext.Items["input"]); + } - [Fact] - public async Task MapGetWithoutRouteParameter_BuildsEndpointWithQuerySpecificBinding() + [Fact] + public async Task MapGetWithoutRouteParameter_BuildsEndpointWithQuerySpecificBinding() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapGet("/", (int? id, HttpContext httpContext) => { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapGet("/", (int? id, HttpContext httpContext) => + if (id is not null) { - if (id is not null) - { - httpContext.Items["input"] = id; - } - }); + httpContext.Items["input"] = id; + } + }); - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("GET", method); + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("GET", method); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - // Assert that we don't fallback to the route values - var httpContext = new DefaultHttpContext(); + // Assert that we don't fallback to the route values + var httpContext = new DefaultHttpContext(); - httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues>() - { - ["id"] = "41" - }); - httpContext.Request.RouteValues = new(); - httpContext.Request.RouteValues["id"] = "42"; + httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues>() + { + ["id"] = "41" + }); + httpContext.Request.RouteValues = new(); + httpContext.Request.RouteValues["id"] = "42"; - await endpoint.RequestDelegate!(httpContext); + await endpoint.RequestDelegate!(httpContext); - Assert.Equal(41, httpContext.Items["input"]); - } + Assert.Equal(41, httpContext.Items["input"]); + } - [Fact] - public void MapGet_ThrowsWithImplicitFromBody() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - var ex = Assert.Throws<InvalidOperationException>(() => builder.MapGet("/", (Todo todo) => { })); - Assert.Contains("Body was inferred but the method does not allow inferred body parameters.", ex.Message); - Assert.Contains("Did you mean to register the \"Body (Inferred)\" parameter(s) as a Service or apply the [FromService] or [FromBody] attribute?", ex.Message); - } + [Fact] + public void MapGet_ThrowsWithImplicitFromBody() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + var ex = Assert.Throws<InvalidOperationException>(() => builder.MapGet("/", (Todo todo) => { })); + Assert.Contains("Body was inferred but the method does not allow inferred body parameters.", ex.Message); + Assert.Contains("Did you mean to register the \"Body (Inferred)\" parameter(s) as a Service or apply the [FromService] or [FromBody] attribute?", ex.Message); + } - [Fact] - public void MapDelete_ThrowsWithImplicitFromBody() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - var ex = Assert.Throws<InvalidOperationException>(() => builder.MapDelete("/", (Todo todo) => { })); - Assert.Contains("Body was inferred but the method does not allow inferred body parameters.", ex.Message); - Assert.Contains("Did you mean to register the \"Body (Inferred)\" parameter(s) as a Service or apply the [FromService] or [FromBody] attribute?", ex.Message); - } + [Fact] + public void MapDelete_ThrowsWithImplicitFromBody() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + var ex = Assert.Throws<InvalidOperationException>(() => builder.MapDelete("/", (Todo todo) => { })); + Assert.Contains("Body was inferred but the method does not allow inferred body parameters.", ex.Message); + Assert.Contains("Did you mean to register the \"Body (Inferred)\" parameter(s) as a Service or apply the [FromService] or [FromBody] attribute?", ex.Message); + } - public static object[][] NonImplicitFromBodyMethods + public static object[][] NonImplicitFromBodyMethods + { + get { - get + return new[] { - return new[] - { new[] { HttpMethods.Delete }, new[] { HttpMethods.Connect }, new[] { HttpMethods.Trace }, @@ -235,699 +235,698 @@ namespace Microsoft.AspNetCore.Builder new[] { HttpMethods.Head }, new[] { HttpMethods.Options }, }; - } - } - - [Theory] - [MemberData(nameof(NonImplicitFromBodyMethods))] - public void MapVerb_ThrowsWithImplicitFromBody(string method) - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - var ex = Assert.Throws<InvalidOperationException>(() => builder.MapMethods("/", new[] { method }, (Todo todo) => { })); - Assert.Contains("Body was inferred but the method does not allow inferred body parameters.", ex.Message); - Assert.Contains("Did you mean to register the \"Body (Inferred)\" parameter(s) as a Service or apply the [FromService] or [FromBody] attribute?", ex.Message); } + } - [Fact] - public void MapGet_ImplicitFromService() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); - _ = builder.MapGet("/", (TodoService todo) => { }); + [Theory] + [MemberData(nameof(NonImplicitFromBodyMethods))] + public void MapVerb_ThrowsWithImplicitFromBody(string method) + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + var ex = Assert.Throws<InvalidOperationException>(() => builder.MapMethods("/", new[] { method }, (Todo todo) => { })); + Assert.Contains("Body was inferred but the method does not allow inferred body parameters.", ex.Message); + Assert.Contains("Did you mean to register the \"Body (Inferred)\" parameter(s) as a Service or apply the [FromService] or [FromBody] attribute?", ex.Message); + } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void MapGet_ImplicitFromService() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); + _ = builder.MapGet("/", (TodoService todo) => { }); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("GET", method); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("GET", method); - [Fact] - public void MapDelete_ImplicitFromService() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); - _ = builder.MapDelete("/", (TodoService todo) => { }); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void MapDelete_ImplicitFromService() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); + _ = builder.MapDelete("/", (TodoService todo) => { }); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("DELETE", method); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: DELETE /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("DELETE", method); - [Fact] - public void MapPatch_ImplicitFromService() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); - _ = builder.MapPatch("/", (TodoService todo) => { }); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: DELETE /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void MapPatch_ImplicitFromService() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); + _ = builder.MapPatch("/", (TodoService todo) => { }); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("PATCH", method); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: PATCH /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("PATCH", method); - [AttributeUsage(AttributeTargets.Parameter)] - private class TestFromServiceAttribute : Attribute, IFromServiceMetadata - { } + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: PATCH /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - [Fact] - public void MapGet_ExplicitFromService() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); - _ = builder.MapGet("/", ([TestFromServiceAttribute] TodoService todo) => { }); + [AttributeUsage(AttributeTargets.Parameter)] + private class TestFromServiceAttribute : Attribute, IFromServiceMetadata + { } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void MapGet_ExplicitFromService() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); + _ = builder.MapGet("/", ([TestFromServiceAttribute] TodoService todo) => { }); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("GET", method); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("GET", method); - [Fact] - public void MapDelete_ExplicitFromService() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); - _ = builder.MapDelete("/", ([TestFromServiceAttribute] TodoService todo) => { }); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void MapDelete_ExplicitFromService() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); + _ = builder.MapDelete("/", ([TestFromServiceAttribute] TodoService todo) => { }); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("DELETE", method); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: DELETE /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("DELETE", method); - [Fact] - public void MapPatch_ExplicitFromService() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); - _ = builder.MapPatch("/", ([TestFromServiceAttribute] TodoService todo) => { }); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: DELETE /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void MapPatch_ExplicitFromService() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().AddSingleton<TodoService>().BuildServiceProvider())); + _ = builder.MapPatch("/", ([TestFromServiceAttribute] TodoService todo) => { }); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("PATCH", method); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: PATCH /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("PATCH", method); - [AttributeUsage(AttributeTargets.Parameter)] - private class TestFromBodyAttribute : Attribute, IFromBodyMetadata - { } + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: PATCH /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - [Fact] - public void MapGet_ExplicitFromBody_BuildsEndpointWithCorrectMethod() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapGet("/", ([TestFromBody] Todo todo) => { }); + [AttributeUsage(AttributeTargets.Parameter)] + private class TestFromBodyAttribute : Attribute, IFromBodyMetadata + { } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void MapGet_ExplicitFromBody_BuildsEndpointWithCorrectMethod() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapGet("/", ([TestFromBody] Todo todo) => { }); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("GET", method); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("GET", method); - [Fact] - public void MapDelete_ExplicitFromBody_BuildsEndpointWithCorrectMethod() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapDelete("/", ([TestFromBody] Todo todo) => { }); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void MapDelete_ExplicitFromBody_BuildsEndpointWithCorrectMethod() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapDelete("/", ([TestFromBody] Todo todo) => { }); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("DELETE", method); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: DELETE /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("DELETE", method); - [Fact] - public void MapPatch_ExplicitFromBody_BuildsEndpointWithCorrectMethod() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapPatch("/", ([TestFromBody] Todo todo) => { }); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: DELETE /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void MapPatch_ExplicitFromBody_BuildsEndpointWithCorrectMethod() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapPatch("/", ([TestFromBody] Todo todo) => { }); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("PATCH", method); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: PATCH /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("PATCH", method); - [Theory] - [MemberData(nameof(MapMethods))] - public void MapVerbDoesNotDuplicateMetadata(Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder> map, string expectedMethod) - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: PATCH /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - map(builder, "/{ID}", () => { }).WithName("Foo"); + [Theory] + [MemberData(nameof(MapMethods))] + public void MapVerbDoesNotDuplicateMetadata(Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder> map, string expectedMethod) + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - var dataSource = GetBuilderEndpointDataSource(builder); + map(builder, "/{ID}", () => { }).WithName("Foo"); - // Access endpoints a couple of times to make sure it gets built - _ = dataSource.Endpoints; - _ = dataSource.Endpoints; - _ = dataSource.Endpoints; + var dataSource = GetBuilderEndpointDataSource(builder); - var endpoint = Assert.Single(dataSource.Endpoints); + // Access endpoints a couple of times to make sure it gets built + _ = dataSource.Endpoints; + _ = dataSource.Endpoints; + _ = dataSource.Endpoints; - var endpointNameMetadata = Assert.Single(endpoint.Metadata.GetOrderedMetadata<IEndpointNameMetadata>()); - var routeNameMetadata = Assert.Single(endpoint.Metadata.GetOrderedMetadata<IRouteNameMetadata>()); - Assert.Equal("Foo", endpointNameMetadata.EndpointName); - Assert.Equal("Foo", routeNameMetadata.RouteName); + var endpoint = Assert.Single(dataSource.Endpoints); - if (expectedMethod is not null) - { - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal(expectedMethod, method); - } - } + var endpointNameMetadata = Assert.Single(endpoint.Metadata.GetOrderedMetadata<IEndpointNameMetadata>()); + var routeNameMetadata = Assert.Single(endpoint.Metadata.GetOrderedMetadata<IRouteNameMetadata>()); + Assert.Equal("Foo", endpointNameMetadata.EndpointName); + Assert.Equal("Foo", routeNameMetadata.RouteName); - [Theory] - [MemberData(nameof(MapMethods))] - public void AddingMetadataAfterBuildingEndpointThrows(Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder> map, string expectedMethod) + if (expectedMethod is not null) { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - - var endpointBuilder = map(builder, "/{ID}", () => { }); + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal(expectedMethod, method); + } + } - var dataSource = GetBuilderEndpointDataSource(builder); + [Theory] + [MemberData(nameof(MapMethods))] + public void AddingMetadataAfterBuildingEndpointThrows(Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder> map, string expectedMethod) + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - var endpoint = Assert.Single(dataSource.Endpoints); + var endpointBuilder = map(builder, "/{ID}", () => { }); - if (expectedMethod is not null) - { - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal(expectedMethod, method); - } + var dataSource = GetBuilderEndpointDataSource(builder); - Assert.Throws<InvalidOperationException>(() => endpointBuilder.WithMetadata(new RouteNameMetadata("Foo"))); - } + var endpoint = Assert.Single(dataSource.Endpoints); - [Theory] - [MemberData(nameof(MapMethods))] - public async Task MapVerbWithExplicitRouteParameterIsCaseInsensitive(Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder> map, string expectedMethod) + if (expectedMethod is not null) { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - - map(builder, "/{ID}", ([FromRoute] int? id, HttpContext httpContext) => - { - if (id is not null) - { - httpContext.Items["input"] = id; - } - }); + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal(expectedMethod, method); + } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + Assert.Throws<InvalidOperationException>(() => endpointBuilder.WithMetadata(new RouteNameMetadata("Foo"))); + } - if (expectedMethod is not null) - { - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal(expectedMethod, method); - } + [Theory] + [MemberData(nameof(MapMethods))] + public async Task MapVerbWithExplicitRouteParameterIsCaseInsensitive(Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder> map, string expectedMethod) + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - if (expectedMethod is not null) + map(builder, "/{ID}", ([FromRoute] int? id, HttpContext httpContext) => + { + if (id is not null) { - Assert.Equal($"HTTP: {expectedMethod} /{{ID}}", routeEndpointBuilder.DisplayName); + httpContext.Items["input"] = id; } - Assert.Equal($"/{{ID}}", routeEndpointBuilder.RoutePattern.RawText); + }); - var httpContext = new DefaultHttpContext(); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - httpContext.Request.RouteValues["id"] = "13"; - - await endpoint.RequestDelegate!(httpContext); - - Assert.Equal(13, httpContext.Items["input"]); + if (expectedMethod is not null) + { + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal(expectedMethod, method); } - [Theory] - [MemberData(nameof(MapMethods))] - public async Task MapVerbWithRouteParameterDoesNotFallbackToQuery(Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder> map, string expectedMethod) + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + if (expectedMethod is not null) { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + Assert.Equal($"HTTP: {expectedMethod} /{{ID}}", routeEndpointBuilder.DisplayName); + } + Assert.Equal($"/{{ID}}", routeEndpointBuilder.RoutePattern.RawText); - map(builder, "/{ID}", (int? id, HttpContext httpContext) => - { - if (id is not null) - { - httpContext.Items["input"] = id; - } - }); - - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); - if (expectedMethod is not null) - { - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal(expectedMethod, method); - } + var httpContext = new DefaultHttpContext(); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - if (expectedMethod is not null) - { - Assert.Equal($"HTTP: {expectedMethod} /{{ID}}", routeEndpointBuilder.DisplayName); - } - Assert.Equal($"/{{ID}}", routeEndpointBuilder.RoutePattern.RawText); + httpContext.Request.RouteValues["id"] = "13"; - // Assert that we don't fallback to the query string - var httpContext = new DefaultHttpContext(); + await endpoint.RequestDelegate!(httpContext); - httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues> - { - ["id"] = "42" - }); + Assert.Equal(13, httpContext.Items["input"]); + } - await endpoint.RequestDelegate!(httpContext); + [Theory] + [MemberData(nameof(MapMethods))] + public async Task MapVerbWithRouteParameterDoesNotFallbackToQuery(Func<IEndpointRouteBuilder, string, Delegate, IEndpointConventionBuilder> map, string expectedMethod) + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - Assert.Null(httpContext.Items["input"]); - } + map(builder, "/{ID}", (int? id, HttpContext httpContext) => + { + if (id is not null) + { + httpContext.Items["input"] = id; + } + }); - [Fact] - public void MapGetWithRouteParameter_ThrowsIfRouteParameterDoesNotExist() + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); + if (expectedMethod is not null) { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - var ex = Assert.Throws<InvalidOperationException>(() => builder.MapGet("/", ([FromRoute] int id) => { })); - Assert.Equal("'id' is not a route parameter.", ex.Message); + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal(expectedMethod, method); } - [Fact] - public async Task MapGetWithNamedFromRouteParameter_UsesFromRouteName() + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + if (expectedMethod is not null) { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapGet("/{value}", ([FromRoute(Name = "value")] int id, HttpContext httpContext) => - { - httpContext.Items["value"] = id; - }); + Assert.Equal($"HTTP: {expectedMethod} /{{ID}}", routeEndpointBuilder.DisplayName); + } + Assert.Equal($"/{{ID}}", routeEndpointBuilder.RoutePattern.RawText); - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + // Assert that we don't fallback to the query string + var httpContext = new DefaultHttpContext(); - // Assert that we don't fallback to the query string - var httpContext = new DefaultHttpContext(); + httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues> + { + ["id"] = "42" + }); - httpContext.Request.RouteValues["value"] = "42"; + await endpoint.RequestDelegate!(httpContext); - await endpoint.RequestDelegate!(httpContext); + Assert.Null(httpContext.Items["input"]); + } - Assert.Equal(42, httpContext.Items["value"]); - } + [Fact] + public void MapGetWithRouteParameter_ThrowsIfRouteParameterDoesNotExist() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + var ex = Assert.Throws<InvalidOperationException>(() => builder.MapGet("/", ([FromRoute] int id) => { })); + Assert.Equal("'id' is not a route parameter.", ex.Message); + } - [Fact] - public async Task MapGetWithNamedFromRouteParameter_FailsForParameterName() + [Fact] + public async Task MapGetWithNamedFromRouteParameter_UsesFromRouteName() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapGet("/{value}", ([FromRoute(Name = "value")] int id, HttpContext httpContext) => { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapGet("/{value}", ([FromRoute(Name = "value")] int id, HttpContext httpContext) => - { - httpContext.Items["value"] = id; - }); + httpContext.Items["value"] = id; + }); - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - // Assert that we don't fallback to the query string - var httpContext = new DefaultHttpContext(); - httpContext.RequestServices = new ServiceCollection().AddLogging().BuildServiceProvider(); + // Assert that we don't fallback to the query string + var httpContext = new DefaultHttpContext(); - httpContext.Request.RouteValues["id"] = "42"; + httpContext.Request.RouteValues["value"] = "42"; - await endpoint.RequestDelegate!(httpContext); + await endpoint.RequestDelegate!(httpContext); - Assert.Null(httpContext.Items["value"]); - Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode); - } + Assert.Equal(42, httpContext.Items["value"]); + } - [Fact] - public void MapGetWithNamedFromRouteParameter_ThrowsForMismatchedPattern() + [Fact] + public async Task MapGetWithNamedFromRouteParameter_FailsForParameterName() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapGet("/{value}", ([FromRoute(Name = "value")] int id, HttpContext httpContext) => { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - var ex = Assert.Throws<InvalidOperationException>(() =>builder.MapGet("/{id}", ([FromRoute(Name = "value")] int id, HttpContext httpContext) => { })); - Assert.Equal("'value' is not a route parameter.", ex.Message); - } + httpContext.Items["value"] = id; + }); - [Fact] - public void MapPost_BuildsEndpointWithCorrectMethod() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapPost("/", () => { }); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + // Assert that we don't fallback to the query string + var httpContext = new DefaultHttpContext(); + httpContext.RequestServices = new ServiceCollection().AddLogging().BuildServiceProvider(); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("POST", method); + httpContext.Request.RouteValues["id"] = "42"; - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: POST /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + await endpoint.RequestDelegate!(httpContext); - [Fact] - public void MapPost_BuildsEndpointWithCorrectEndpointMetadata() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapPost("/", [TestConsumesAttribute(typeof(Todo), "application/xml")] (Todo todo) => { }); + Assert.Null(httpContext.Items["value"]); + Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode); + } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void MapGetWithNamedFromRouteParameter_ThrowsForMismatchedPattern() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + var ex = Assert.Throws<InvalidOperationException>(() => builder.MapGet("/{id}", ([FromRoute(Name = "value")] int id, HttpContext httpContext) => { })); + Assert.Equal("'value' is not a route parameter.", ex.Message); + } - var endpointMetadata = endpoint.Metadata.GetMetadata<IAcceptsMetadata>(); + [Fact] + public void MapPost_BuildsEndpointWithCorrectMethod() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapPost("/", () => { }); - Assert.NotNull(endpointMetadata); - Assert.False(endpointMetadata!.IsOptional); - Assert.Equal(typeof(Todo), endpointMetadata.RequestType); - Assert.Equal(new[] { "application/xml" }, endpointMetadata.ContentTypes); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - } + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("POST", method); - [Fact] - public void MapPut_BuildsEndpointWithCorrectMethod() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapPut("/", () => { }); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: POST /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void MapPost_BuildsEndpointWithCorrectEndpointMetadata() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapPost("/", [TestConsumesAttribute(typeof(Todo), "application/xml")] (Todo todo) => { }); - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("PUT", method); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: PUT /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var endpointMetadata = endpoint.Metadata.GetMetadata<IAcceptsMetadata>(); - [Fact] - public void MapDelete_BuildsEndpointWithCorrectMethod() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapDelete("/", () => { }); + Assert.NotNull(endpointMetadata); + Assert.False(endpointMetadata!.IsOptional); + Assert.Equal(typeof(Todo), endpointMetadata.RequestType); + Assert.Equal(new[] { "application/xml" }, endpointMetadata.ContentTypes); - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + } - var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); - Assert.NotNull(methodMetadata); - var method = Assert.Single(methodMetadata!.HttpMethods); - Assert.Equal("DELETE", method); + [Fact] + public void MapPut_BuildsEndpointWithCorrectMethod() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapPut("/", () => { }); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("HTTP: DELETE /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - } + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - [Fact] - public void MapFallback_BuildsEndpointWithLowestRouteOrder() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapFallback("/", () => { }); + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("PUT", method); - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: PUT /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("Fallback /", routeEndpointBuilder.DisplayName); - Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); - Assert.Equal(int.MaxValue, routeEndpointBuilder.Order); - } + [Fact] + public void MapDelete_BuildsEndpointWithCorrectMethod() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapDelete("/", () => { }); - [Fact] - public void MapFallbackWithoutPath_BuildsEndpointWithLowestRouteOrder() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapFallback(() => { }); - - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); - - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Equal("Fallback {*path:nonfile}", routeEndpointBuilder.DisplayName); - Assert.Equal("{*path:nonfile}", routeEndpointBuilder.RoutePattern.RawText); - Assert.Single(routeEndpointBuilder.RoutePattern.Parameters); - Assert.True(routeEndpointBuilder.RoutePattern.Parameters[0].IsCatchAll); - Assert.Equal(int.MaxValue, routeEndpointBuilder.Order); - } + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - [Fact] - public void WithTags_CanSetTagsForEndpoint() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - string GetString() => "Foo"; - _ = builder.MapDelete("/", GetString).WithTags("Some", "Test", "Tags"); + var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); + Assert.NotNull(methodMetadata); + var method = Assert.Single(methodMetadata!.HttpMethods); + Assert.Equal("DELETE", method); - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("HTTP: DELETE /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + } - var tagsMetadata = endpoint.Metadata.GetMetadata<ITagsMetadata>(); - Assert.Equal(new[] { "Some", "Test", "Tags" }, tagsMetadata?.Tags); - } + [Fact] + public void MapFallback_BuildsEndpointWithLowestRouteOrder() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapFallback("/", () => { }); - [Fact] - public void MapMethod_DoesNotEndpointNameForMethodGroupByDefault() - { - string GetString() => "Foo"; - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); - _ = builder.MapDelete("/", GetString); - - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); - - var endpointName = endpoint.Metadata.GetMetadata<IEndpointNameMetadata>(); - var routeName = endpoint.Metadata.GetMetadata<IRouteNameMetadata>(); - var routeEndpointBuilder = GetRouteEndpointBuilder(builder); - Assert.Null(endpointName); - Assert.Null(routeName); - Assert.Equal("HTTP: DELETE / => GetString", routeEndpointBuilder.DisplayName); - } + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task MapMethod_FlowsThrowOnBadHttpRequest(bool throwOnBadRequest) - { - var serviceProvider = new EmptyServiceProvider(); - serviceProvider.RouteHandlerOptions.ThrowOnBadRequest = throwOnBadRequest; + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("Fallback /", routeEndpointBuilder.DisplayName); + Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); + Assert.Equal(int.MaxValue, routeEndpointBuilder.Order); + } - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(serviceProvider)); - _ = builder.Map("/{id}", (int id) => { }); + [Fact] + public void MapFallbackWithoutPath_BuildsEndpointWithLowestRouteOrder() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapFallback(() => { }); + + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); + + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Equal("Fallback {*path:nonfile}", routeEndpointBuilder.DisplayName); + Assert.Equal("{*path:nonfile}", routeEndpointBuilder.RoutePattern.RawText); + Assert.Single(routeEndpointBuilder.RoutePattern.Parameters); + Assert.True(routeEndpointBuilder.RoutePattern.Parameters[0].IsCatchAll); + Assert.Equal(int.MaxValue, routeEndpointBuilder.Order); + } - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + [Fact] + public void WithTags_CanSetTagsForEndpoint() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + string GetString() => "Foo"; + _ = builder.MapDelete("/", GetString).WithTags("Some", "Test", "Tags"); - var httpContext = new DefaultHttpContext(); - httpContext.RequestServices = new ServiceCollection().AddLogging().BuildServiceProvider(); - httpContext.Request.RouteValues["id"] = "invalid!"; + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - if (throwOnBadRequest) - { - var ex = await Assert.ThrowsAsync<BadHttpRequestException>(() => endpoint.RequestDelegate!(httpContext)); - Assert.Equal(400, ex.StatusCode); - } - else - { - await endpoint.RequestDelegate!(httpContext); - Assert.Equal(400, httpContext.Response.StatusCode); - } - } + var tagsMetadata = endpoint.Metadata.GetMetadata<ITagsMetadata>(); + Assert.Equal(new[] { "Some", "Test", "Tags" }, tagsMetadata?.Tags); + } - [Fact] - public async Task MapMethod_DefaultsToNotThrowOnBadHttpRequestIfItCannotResolveRouteHandlerOptions() - { - var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().BuildServiceProvider())); + [Fact] + public void MapMethod_DoesNotEndpointNameForMethodGroupByDefault() + { + string GetString() => "Foo"; + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); + _ = builder.MapDelete("/", GetString); + + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); + + var endpointName = endpoint.Metadata.GetMetadata<IEndpointNameMetadata>(); + var routeName = endpoint.Metadata.GetMetadata<IRouteNameMetadata>(); + var routeEndpointBuilder = GetRouteEndpointBuilder(builder); + Assert.Null(endpointName); + Assert.Null(routeName); + Assert.Equal("HTTP: DELETE / => GetString", routeEndpointBuilder.DisplayName); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task MapMethod_FlowsThrowOnBadHttpRequest(bool throwOnBadRequest) + { + var serviceProvider = new EmptyServiceProvider(); + serviceProvider.RouteHandlerOptions.ThrowOnBadRequest = throwOnBadRequest; - _ = builder.Map("/{id}", (int id) => { }); + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(serviceProvider)); + _ = builder.Map("/{id}", (int id) => { }); - var dataSource = GetBuilderEndpointDataSource(builder); - // Trigger Endpoint build by calling getter. - var endpoint = Assert.Single(dataSource.Endpoints); + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); - var httpContext = new DefaultHttpContext(); - httpContext.RequestServices = new ServiceCollection().AddLogging().BuildServiceProvider(); - httpContext.Request.RouteValues["id"] = "invalid!"; + var httpContext = new DefaultHttpContext(); + httpContext.RequestServices = new ServiceCollection().AddLogging().BuildServiceProvider(); + httpContext.Request.RouteValues["id"] = "invalid!"; + if (throwOnBadRequest) + { + var ex = await Assert.ThrowsAsync<BadHttpRequestException>(() => endpoint.RequestDelegate!(httpContext)); + Assert.Equal(400, ex.StatusCode); + } + else + { await endpoint.RequestDelegate!(httpContext); Assert.Equal(400, httpContext.Response.StatusCode); } + } - class FromRoute : Attribute, IFromRouteMetadata - { - public string? Name { get; set; } - } + [Fact] + public async Task MapMethod_DefaultsToNotThrowOnBadHttpRequestIfItCannotResolveRouteHandlerOptions() + { + var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().BuildServiceProvider())); + + _ = builder.Map("/{id}", (int id) => { }); + + var dataSource = GetBuilderEndpointDataSource(builder); + // Trigger Endpoint build by calling getter. + var endpoint = Assert.Single(dataSource.Endpoints); + + var httpContext = new DefaultHttpContext(); + httpContext.RequestServices = new ServiceCollection().AddLogging().BuildServiceProvider(); + httpContext.Request.RouteValues["id"] = "invalid!"; - class TestConsumesAttribute : Attribute, IAcceptsMetadata + await endpoint.RequestDelegate!(httpContext); + Assert.Equal(400, httpContext.Response.StatusCode); + } + + class FromRoute : Attribute, IFromRouteMetadata + { + public string? Name { get; set; } + } + + class TestConsumesAttribute : Attribute, IAcceptsMetadata + { + public TestConsumesAttribute(Type requestType, string contentType, params string[] otherContentTypes) { - public TestConsumesAttribute(Type requestType, string contentType, params string[] otherContentTypes) + if (contentType == null) { - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } + throw new ArgumentNullException(nameof(contentType)); + } - var contentTypes = new List<string>() + var contentTypes = new List<string>() { contentType }; - for (var i = 0; i < otherContentTypes.Length; i++) - { - contentTypes.Add(otherContentTypes[i]); - } - - _requestType = requestType; - _contentTypes = contentTypes; + for (var i = 0; i < otherContentTypes.Length; i++) + { + contentTypes.Add(otherContentTypes[i]); } - IReadOnlyList<string> IAcceptsMetadata.ContentTypes => _contentTypes; - Type? IAcceptsMetadata.RequestType => _requestType; + _requestType = requestType; + _contentTypes = contentTypes; + } - bool IAcceptsMetadata.IsOptional => false; + IReadOnlyList<string> IAcceptsMetadata.ContentTypes => _contentTypes; + Type? IAcceptsMetadata.RequestType => _requestType; - Type? _requestType; + bool IAcceptsMetadata.IsOptional => false; - List<string> _contentTypes = new(); - } + Type? _requestType; - class Todo - { + List<string> _contentTypes = new(); + } - } + class Todo + { - // Here to more easily disambiguate when ToDo is - // intended to be validated as an implicit service in tests - class TodoService - { + } - } + // Here to more easily disambiguate when ToDo is + // intended to be validated as an implicit service in tests + class TodoService + { - private class HttpMethodAttribute : Attribute, IHttpMethodMetadata - { - public bool AcceptCorsPreflight => false; + } - public IReadOnlyList<string> HttpMethods { get; } + private class HttpMethodAttribute : Attribute, IHttpMethodMetadata + { + public bool AcceptCorsPreflight => false; - public HttpMethodAttribute(params string[] httpMethods) - { - HttpMethods = httpMethods; - } + public IReadOnlyList<string> HttpMethods { get; } + + public HttpMethodAttribute(params string[] httpMethods) + { + HttpMethods = httpMethods; } + } + + private class EmptyServiceProvider : IServiceScope, IServiceProvider, IServiceScopeFactory + { + public IServiceProvider ServiceProvider => this; - private class EmptyServiceProvider : IServiceScope, IServiceProvider, IServiceScopeFactory + public RouteHandlerOptions RouteHandlerOptions { get; set; } = new RouteHandlerOptions(); + + public IServiceScope CreateScope() { - public IServiceProvider ServiceProvider => this; + return this; + } - public RouteHandlerOptions RouteHandlerOptions { get; set; } = new RouteHandlerOptions(); + public void Dispose() + { + } - public IServiceScope CreateScope() + public object? GetService(Type serviceType) + { + if (serviceType == typeof(IServiceScopeFactory)) { return this; } - - public void Dispose() + else if (serviceType == typeof(IOptions<RouteHandlerOptions>)) { + return Options.Create(RouteHandlerOptions); } - public object? GetService(Type serviceType) - { - if (serviceType == typeof(IServiceScopeFactory)) - { - return this; - } - else if (serviceType == typeof(IOptions<RouteHandlerOptions>)) - { - return Options.Create(RouteHandlerOptions); - } - - return null; - } + return null; } } } diff --git a/src/Http/Routing/test/UnitTests/Builder/RoutingBuilderExtensionsTest.cs b/src/Http/Routing/test/UnitTests/Builder/RoutingBuilderExtensionsTest.cs index 5d8299a442..e6f2b9673b 100644 --- a/src/Http/Routing/test/UnitTests/Builder/RoutingBuilderExtensionsTest.cs +++ b/src/Http/Routing/test/UnitTests/Builder/RoutingBuilderExtensionsTest.cs @@ -9,128 +9,127 @@ using Microsoft.Extensions.DependencyInjection; using Moq; using Xunit; -namespace Microsoft.AspNetCore.Builder +namespace Microsoft.AspNetCore.Builder; + +public class RoutingBuilderExtensionsTest { - public class RoutingBuilderExtensionsTest + [Fact] + public void UseRouter_ThrowsInvalidOperationException_IfRoutingMarkerServiceIsNotRegistered() { - [Fact] - public void UseRouter_ThrowsInvalidOperationException_IfRoutingMarkerServiceIsNotRegistered() - { - // Arrange - var applicationBuilderMock = new Mock<IApplicationBuilder>(); - applicationBuilderMock - .Setup(s => s.ApplicationServices) - .Returns(Mock.Of<IServiceProvider>()); - - var router = Mock.Of<IRouter>(); - - // Act & Assert - var exception = Assert.Throws<InvalidOperationException>( - () => applicationBuilderMock.Object.UseRouter(router)); - - Assert.Equal( - "Unable to find the required services. Please add all the required services by calling " + - "'IServiceCollection.AddRouting' inside the call to 'ConfigureServices(...)'" + - " in the application startup code.", - exception.Message); - } - - [Fact] - public void UseRouter_IRouter_ThrowsWithoutCallingAddRouting() - { - // Arrange - var app = new ApplicationBuilder(Mock.Of<IServiceProvider>()); - - // Act - var ex = Assert.Throws<InvalidOperationException>(() => app.UseRouter(Mock.Of<IRouter>())); - - // Assert - Assert.Equal( - "Unable to find the required services. " + - "Please add all the required services by calling 'IServiceCollection.AddRouting' " + - "inside the call to 'ConfigureServices(...)' in the application startup code.", - ex.Message); - } - - [Fact] - public void UseRouter_Action_ThrowsWithoutCallingAddRouting() - { - // Arrange - var app = new ApplicationBuilder(Mock.Of<IServiceProvider>()); - - // Act - var ex = Assert.Throws<InvalidOperationException>(() => app.UseRouter(b => { })); - - // Assert - Assert.Equal( - "Unable to find the required services. " + - "Please add all the required services by calling 'IServiceCollection.AddRouting' " + - "inside the call to 'ConfigureServices(...)' in the application startup code.", - ex.Message); - } - - [Fact] - public async Task UseRouter_IRouter_CallsRoute() - { - // Arrange - var services = CreateServices(); - - var app = new ApplicationBuilder(services); + // Arrange + var applicationBuilderMock = new Mock<IApplicationBuilder>(); + applicationBuilderMock + .Setup(s => s.ApplicationServices) + .Returns(Mock.Of<IServiceProvider>()); + + var router = Mock.Of<IRouter>(); + + // Act & Assert + var exception = Assert.Throws<InvalidOperationException>( + () => applicationBuilderMock.Object.UseRouter(router)); + + Assert.Equal( + "Unable to find the required services. Please add all the required services by calling " + + "'IServiceCollection.AddRouting' inside the call to 'ConfigureServices(...)'" + + " in the application startup code.", + exception.Message); + } - var router = new Mock<IRouter>(MockBehavior.Strict); - router - .Setup(r => r.RouteAsync(It.IsAny<RouteContext>())) - .Returns(Task.CompletedTask) - .Verifiable(); + [Fact] + public void UseRouter_IRouter_ThrowsWithoutCallingAddRouting() + { + // Arrange + var app = new ApplicationBuilder(Mock.Of<IServiceProvider>()); + + // Act + var ex = Assert.Throws<InvalidOperationException>(() => app.UseRouter(Mock.Of<IRouter>())); + + // Assert + Assert.Equal( + "Unable to find the required services. " + + "Please add all the required services by calling 'IServiceCollection.AddRouting' " + + "inside the call to 'ConfigureServices(...)' in the application startup code.", + ex.Message); + } - app.UseRouter(router.Object); + [Fact] + public void UseRouter_Action_ThrowsWithoutCallingAddRouting() + { + // Arrange + var app = new ApplicationBuilder(Mock.Of<IServiceProvider>()); + + // Act + var ex = Assert.Throws<InvalidOperationException>(() => app.UseRouter(b => { })); + + // Assert + Assert.Equal( + "Unable to find the required services. " + + "Please add all the required services by calling 'IServiceCollection.AddRouting' " + + "inside the call to 'ConfigureServices(...)' in the application startup code.", + ex.Message); + } - var appFunc = app.Build(); + [Fact] + public async Task UseRouter_IRouter_CallsRoute() + { + // Arrange + var services = CreateServices(); - // Act - await appFunc(new DefaultHttpContext()); + var app = new ApplicationBuilder(services); - // Assert - router.Verify(); - } + var router = new Mock<IRouter>(MockBehavior.Strict); + router + .Setup(r => r.RouteAsync(It.IsAny<RouteContext>())) + .Returns(Task.CompletedTask) + .Verifiable(); - [Fact] - public async Task UseRouter_Action_CallsRoute() - { - // Arrange - var services = CreateServices(); + app.UseRouter(router.Object); - var app = new ApplicationBuilder(services); + var appFunc = app.Build(); - var router = new Mock<IRouter>(MockBehavior.Strict); - router - .Setup(r => r.RouteAsync(It.IsAny<RouteContext>())) - .Returns(Task.CompletedTask) - .Verifiable(); + // Act + await appFunc(new DefaultHttpContext()); - app.UseRouter(b => - { - b.Routes.Add(router.Object); - }); + // Assert + router.Verify(); + } - var appFunc = app.Build(); + [Fact] + public async Task UseRouter_Action_CallsRoute() + { + // Arrange + var services = CreateServices(); - // Act - await appFunc(new DefaultHttpContext()); + var app = new ApplicationBuilder(services); - // Assert - router.Verify(); - } + var router = new Mock<IRouter>(MockBehavior.Strict); + router + .Setup(r => r.RouteAsync(It.IsAny<RouteContext>())) + .Returns(Task.CompletedTask) + .Verifiable(); - private IServiceProvider CreateServices() + app.UseRouter(b => { - var services = new ServiceCollection(); + b.Routes.Add(router.Object); + }); + + var appFunc = app.Build(); + + // Act + await appFunc(new DefaultHttpContext()); + + // Assert + router.Verify(); + } + + private IServiceProvider CreateServices() + { + var services = new ServiceCollection(); - services.AddLogging(); - services.AddOptions(); - services.AddRouting(); + services.AddLogging(); + services.AddOptions(); + services.AddRouting(); - return services.BuildServiceProvider(); - } + return services.BuildServiceProvider(); } } diff --git a/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs b/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs index 013e2a55ad..2082cc74ba 100644 --- a/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs +++ b/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs @@ -7,179 +7,178 @@ using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Patterns; using Xunit; -namespace Microsoft.AspNetCore.Builder +namespace Microsoft.AspNetCore.Builder; + +public class RoutingEndpointConventionBuilderExtensionsTest { - public class RoutingEndpointConventionBuilderExtensionsTest + [Fact] + public void RequireHost_AddsHostMetadata() { - [Fact] - public void RequireHost_AddsHostMetadata() - { - // Arrange - var builder = CreateBuilder(); + // Arrange + var builder = CreateBuilder(); - // Act - builder.RequireHost("www.example.com", "example.com"); + // Act + builder.RequireHost("www.example.com", "example.com"); - // Assert - var endpoint = builder.Build(); + // Assert + var endpoint = builder.Build(); - var metadata = endpoint.Metadata.GetMetadata<IHostMetadata>(); - Assert.NotNull(metadata); - Assert.Equal(new[] { "www.example.com", "example.com" }, metadata.Hosts); - } + var metadata = endpoint.Metadata.GetMetadata<IHostMetadata>(); + Assert.NotNull(metadata); + Assert.Equal(new[] { "www.example.com", "example.com" }, metadata.Hosts); + } - [Fact] - public void RequireHost_ChainedCall_ReturnedBuilderIsDerivedType() - { - // Arrange - var builder = CreateBuilder(); + [Fact] + public void RequireHost_ChainedCall_ReturnedBuilderIsDerivedType() + { + // Arrange + var builder = CreateBuilder(); - // Act - var chainedBuilder = builder.RequireHost("test"); + // Act + var chainedBuilder = builder.RequireHost("test"); - // Assert - Assert.True(chainedBuilder.TestProperty); - } + // Assert + Assert.True(chainedBuilder.TestProperty); + } - [Fact] - public void WithDisplayName_String_SetsDisplayName() - { - // Arrange - var builder = CreateBuilder(); + [Fact] + public void WithDisplayName_String_SetsDisplayName() + { + // Arrange + var builder = CreateBuilder(); - // Act - builder.WithDisplayName("test"); + // Act + builder.WithDisplayName("test"); - // Assert - var endpoint = builder.Build(); - Assert.Equal("test", endpoint.DisplayName); - } + // Assert + var endpoint = builder.Build(); + Assert.Equal("test", endpoint.DisplayName); + } - [Fact] - public void WithDisplayName_ChainedCall_ReturnedBuilderIsDerivedType() - { - // Arrange - var builder = CreateBuilder(); + [Fact] + public void WithDisplayName_ChainedCall_ReturnedBuilderIsDerivedType() + { + // Arrange + var builder = CreateBuilder(); - // Act - var chainedBuilder = builder.WithDisplayName("test"); + // Act + var chainedBuilder = builder.WithDisplayName("test"); - // Assert - Assert.True(chainedBuilder.TestProperty); - } + // Assert + Assert.True(chainedBuilder.TestProperty); + } - [Fact] - public void WithDisplayName_Func_SetsDisplayName() - { - // Arrange - var builder = CreateBuilder(); + [Fact] + public void WithDisplayName_Func_SetsDisplayName() + { + // Arrange + var builder = CreateBuilder(); - // Act - builder.WithDisplayName(b => "test"); + // Act + builder.WithDisplayName(b => "test"); - // Assert - var endpoint = builder.Build(); - Assert.Equal("test", endpoint.DisplayName); - } + // Assert + var endpoint = builder.Build(); + Assert.Equal("test", endpoint.DisplayName); + } - [Fact] - public void WithMetadata_AddsMetadata() - { - // Arrange - var builder = CreateBuilder(); + [Fact] + public void WithMetadata_AddsMetadata() + { + // Arrange + var builder = CreateBuilder(); - // Act - builder.WithMetadata("test", new HostAttribute("www.example.com", "example.com")); + // Act + builder.WithMetadata("test", new HostAttribute("www.example.com", "example.com")); - // Assert - var endpoint = builder.Build(); + // Assert + var endpoint = builder.Build(); - var hosts = endpoint.Metadata.GetMetadata<IHostMetadata>(); - Assert.NotNull(hosts); - Assert.Equal(new[] { "www.example.com", "example.com" }, hosts.Hosts); + var hosts = endpoint.Metadata.GetMetadata<IHostMetadata>(); + Assert.NotNull(hosts); + Assert.Equal(new[] { "www.example.com", "example.com" }, hosts.Hosts); - var @string = endpoint.Metadata.GetMetadata<string>(); - Assert.Equal("test", @string); - } + var @string = endpoint.Metadata.GetMetadata<string>(); + Assert.Equal("test", @string); + } - [Fact] - public void WithMetadata_ChainedCall_ReturnedBuilderIsDerivedType() - { - // Arrange - var builder = CreateBuilder(); + [Fact] + public void WithMetadata_ChainedCall_ReturnedBuilderIsDerivedType() + { + // Arrange + var builder = CreateBuilder(); - // Act - var chainedBuilder = builder.WithMetadata("test"); + // Act + var chainedBuilder = builder.WithMetadata("test"); - // Assert - Assert.True(chainedBuilder.TestProperty); - } + // Assert + Assert.True(chainedBuilder.TestProperty); + } - [Fact] - public void WithName_SetsEndpointName() - { - // Arrange - var name = "SomeEndpointName"; - var builder = CreateBuilder(); + [Fact] + public void WithName_SetsEndpointName() + { + // Arrange + var name = "SomeEndpointName"; + var builder = CreateBuilder(); - // Act - builder.WithName(name); + // Act + builder.WithName(name); - // Assert - var endpoint = builder.Build(); + // Assert + var endpoint = builder.Build(); - var endpointName = endpoint.Metadata.GetMetadata<IEndpointNameMetadata>(); - Assert.Equal(name, endpointName.EndpointName); + var endpointName = endpoint.Metadata.GetMetadata<IEndpointNameMetadata>(); + Assert.Equal(name, endpointName.EndpointName); - var routeName = endpoint.Metadata.GetMetadata<IRouteNameMetadata>(); - Assert.Equal(name, routeName.RouteName); - } + var routeName = endpoint.Metadata.GetMetadata<IRouteNameMetadata>(); + Assert.Equal(name, routeName.RouteName); + } - [Fact] - public void WithGroupName_SetsEndpointGroupName() - { - // Arrange - var builder = CreateBuilder(); + [Fact] + public void WithGroupName_SetsEndpointGroupName() + { + // Arrange + var builder = CreateBuilder(); - // Act - builder.WithGroupName("SomeEndpointGroupName"); + // Act + builder.WithGroupName("SomeEndpointGroupName"); - // Assert - var endpoint = builder.Build(); + // Assert + var endpoint = builder.Build(); - var endpointGroupName = endpoint.Metadata.GetMetadata<IEndpointGroupNameMetadata>(); - Assert.Equal("SomeEndpointGroupName", endpointGroupName.EndpointGroupName); - } + var endpointGroupName = endpoint.Metadata.GetMetadata<IEndpointGroupNameMetadata>(); + Assert.Equal("SomeEndpointGroupName", endpointGroupName.EndpointGroupName); + } - private TestEndpointConventionBuilder CreateBuilder() + private TestEndpointConventionBuilder CreateBuilder() + { + var conventionBuilder = new DefaultEndpointConventionBuilder(new RouteEndpointBuilder( + TestConstants.EmptyRequestDelegate, + RoutePatternFactory.Parse("/test"), + order: 0)); + + return new TestEndpointConventionBuilder(conventionBuilder); + } + + private class TestEndpointConventionBuilder : IEndpointConventionBuilder + { + private readonly DefaultEndpointConventionBuilder _endpointConventionBuilder; + public bool TestProperty { get; } = true; + + public TestEndpointConventionBuilder(DefaultEndpointConventionBuilder endpointConventionBuilder) { - var conventionBuilder = new DefaultEndpointConventionBuilder(new RouteEndpointBuilder( - TestConstants.EmptyRequestDelegate, - RoutePatternFactory.Parse("/test"), - order: 0)); + _endpointConventionBuilder = endpointConventionBuilder; + } - return new TestEndpointConventionBuilder(conventionBuilder); + public void Add(Action<EndpointBuilder> convention) + { + _endpointConventionBuilder.Add(convention); } - private class TestEndpointConventionBuilder : IEndpointConventionBuilder + public Endpoint Build() { - private readonly DefaultEndpointConventionBuilder _endpointConventionBuilder; - public bool TestProperty { get; } = true; - - public TestEndpointConventionBuilder(DefaultEndpointConventionBuilder endpointConventionBuilder) - { - _endpointConventionBuilder = endpointConventionBuilder; - } - - public void Add(Action<EndpointBuilder> convention) - { - _endpointConventionBuilder.Add(convention); - } - - public Endpoint Build() - { - return _endpointConventionBuilder.Build(); - } + return _endpointConventionBuilder.Build(); } } } |