Welcome to mirror list, hosted at ThFree Co, Russian Federation.

EndpointRoutingApplicationBuilderExtensionsTest.cs « Builder « UnitTests « test « Routing « Http « src - github.com/dotnet/aspnetcore.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 79f597390e1aca29dfbf5e668af795435f60080c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Matching;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.AspNetCore.Routing.TestObjects;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;

namespace Microsoft.AspNetCore.Builder;

public class EndpointRoutingApplicationBuilderExtensionsTest
{
    [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();

        var appFunc = app.Build();
        var httpContext = new DefaultHttpContext();

        // Act
        await appFunc(httpContext);

        // Assert
        Assert.Null(httpContext.Features.Get<IEndpointFeature>());
    }

    [Fact]
    public async Task UseRouting_ServicesRegistered_Match_DoesNotSetsFeature()
    {
        // Arrange
        var endpoint = new RouteEndpoint(
           TestConstants.EmptyRequestDelegate,
           RoutePatternFactory.Parse("{*p}"),
           0,
           EndpointMetadataCollection.Empty,
           "Test");

        var services = CreateServices();

        var app = new ApplicationBuilder(services);

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.DataSources.Add(new DefaultEndpointDataSource(endpoint));
        });

        var appFunc = app.Build();
        var httpContext = new DefaultHttpContext();

        // Act
        await appFunc(httpContext);

        // Assert
        var feature = httpContext.Features.Get<IEndpointFeature>();
        Assert.NotNull(feature);
        Assert.Same(endpoint, httpContext.GetEndpoint());
    }

    [Fact]
    public void UseEndpoint_WithoutEndpointRoutingMiddleware_Throws()
    {
        // Arrange
        var services = CreateServices();

        var app = new ApplicationBuilder(services);

        // Act
        var ex = Assert.Throws<InvalidOperationException>(() => app.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);
    }

    [Fact]
    public void UseEndpoint_WithApplicationBuilderMismatch_Throws()
    {
        // Arrange
        var services = CreateServices();

        var app = new ApplicationBuilder(services);

        app.UseRouting();

        // Act
        var ex = Assert.Throws<InvalidOperationException>(() => app.Map("/Test", b => b.UseEndpoints(endpoints => { })));

        // 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 async Task UseEndpoint_ServicesRegisteredAndEndpointRoutingRegistered_NoMatch_DoesNotSetFeature()
    {
        // Arrange
        var services = CreateServices();

        var app = new ApplicationBuilder(services);

        app.UseRouting();
        app.UseEndpoints(endpoints => { });

        var appFunc = app.Build();
        var httpContext = new DefaultHttpContext();

        // Act
        await appFunc(httpContext);

        // Assert
        Assert.Null(httpContext.Features.Get<IEndpointFeature>());
    }

    [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(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());

        // 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));
    }

    // 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 services = CreateServices(matcherFactoryMock.Object);

        var app = new ApplicationBuilder(services);

        // Act
        app.UseRouting();

        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");
            });
        });

        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));
    }

    [Fact]
    public void UseEndpoints_WithGlobalEndpointRouteBuilderHasRoutes()
    {
        // Arrange
        var services = CreateServices();

        var app = new ApplicationBuilder(services);

        var mockRouteBuilder = new Mock<IEndpointRouteBuilder>();
        mockRouteBuilder.Setup(m => m.DataSources).Returns(new List<EndpointDataSource>());

        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 endpointDataSource = Assert.Single(mockRouteBuilder.Object.DataSources);
        Assert.Collection(endpointDataSource.Endpoints,
            e => Assert.Equal("Test endpoint 1", e.DisplayName));

        var routeOptions = app.ApplicationServices.GetRequiredService<IOptions<RouteOptions>>();
        Assert.Equal(mockRouteBuilder.Object.DataSources, routeOptions.Value.EndpointDataSources);
    }

    [Fact]
    public void UseRouting_SetsEndpointRouteBuilder_IfGlobalOneExists()
    {
        // Arrange
        var services = CreateServices();

        var app = new ApplicationBuilder(services);

        var routeBuilder = new Mock<IEndpointRouteBuilder>().Object;
        app.Properties.Add("__GlobalEndpointRouteBuilder", routeBuilder);
        app.UseRouting();

        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()
    {
        return CreateServices(matcherFactory: null);
    }

    private IServiceProvider CreateServices(MatcherFactory matcherFactory)
    {
        var services = new ServiceCollection();

        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();

        return serviceProvder;
    }
}