generated from codebeltnet/dotnet-new-classlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiVersionReaderTest.cs
364 lines (328 loc) · 18.7 KB
/
ApiVersionReaderTest.cs
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
using System.Net;
using System.Net.Http;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Codebelt.Extensions.Asp.Versioning.Assets;
using Codebelt.Extensions.AspNetCore.Mvc.Formatters.Text.Yaml;
using Codebelt.Extensions.Xunit;
using Codebelt.Extensions.Xunit.Hosting.AspNetCore;
using Cuemon;
using Cuemon.AspNetCore.Http;
using Cuemon.Diagnostics;
using Cuemon.Extensions.AspNetCore.Diagnostics;
using Cuemon.Extensions.AspNetCore.Mvc.Filters;
using Cuemon.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json;
using Cuemon.Extensions.AspNetCore.Mvc.Formatters.Text.Json;
using Cuemon.Extensions.AspNetCore.Mvc.Formatters.Xml;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
using YamlDotNet.Serialization.NamingConventions;
namespace Codebelt.Extensions.Asp.Versioning
{
public class ApiVersionReaderTest : Test
{
public ApiVersionReaderTest(ITestOutputHelper output) : base(output)
{
}
[Fact]
public async Task GetRequest_ShouldReturnOkay_AsWeAreFilteringAwayInvalidAcceptHeaders()
{
using (var app = WebHostTestFactory.Create(services =>
{
services.AddControllers().AddApplicationPart(typeof(FakeController).Assembly)
.AddJsonFormatters();
services.AddRestfulApiVersioning();
}, app =>
{
app.UseRouting();
app.UseEndpoints(routes => { routes.MapControllers(); });
}))
{
var client = app.Host.GetTestClient();
client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9,application/json;v=1.0");
var sut = await client.GetAsync("/fake/");
TestOutput.WriteLine(sut.Content.Headers.ContentType.ToString());
TestOutput.WriteLine(await sut.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, sut.StatusCode);
Assert.Equal(HttpMethod.Get, sut.RequestMessage.Method);
Assert.EndsWith("application/json; charset=utf-8; v=1.0", sut.Content.Headers.ContentType.ToString());
Assert.Equal(@"""Unit Test""", await sut.Content.ReadAsStringAsync(), ignoreLineEndingDifferences: true);
}
}
[Fact]
public async Task GetRequest_ShouldFailWitNotAcceptable_AsWeAreSpecifyingV2_WhenOnlyV1Exists()
{
using (var app = WebHostTestFactory.Create(services =>
{
services.AddControllers().AddApplicationPart(typeof(FakeController).Assembly);
services.AddRestfulApiVersioning();
}, app =>
{
app.UseFaultDescriptorExceptionHandler();
app.UseRestfulApiVersioning();
app.UseRouting();
app.UseEndpoints(routes => { routes.MapControllers(); });
}))
{
var client = app.Host.GetTestClient();
client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9,application/json;v=2.0");
var sut = await client.GetAsync("/fake/");
var stringResult = await sut.Content.ReadAsStringAsync();
TestOutput.WriteLine(stringResult);
Assert.Equal(HttpStatusCode.NotAcceptable, sut.StatusCode);
Assert.Equal(HttpMethod.Get, sut.RequestMessage.Method);
Assert.Equal("The HTTP resource that matches the request URI 'http://localhost/fake/' does not support the API version '2.0'.", stringResult, ignoreLineEndingDifferences: true);
}
}
[Fact]
public async Task PostRequest_ShouldFailWitUnsupportedMediaType_AsWeAreSpecifyingV2_WhenOnlyV1Exists()
{
using (var app = WebHostTestFactory.Create(services =>
{
services.AddControllers().AddApplicationPart(typeof(FakeController).Assembly);
services.AddRestfulApiVersioning();
}, app =>
{
app.UseFaultDescriptorExceptionHandler();
app.UseRestfulApiVersioning();
app.UseRouting();
app.UseEndpoints(routes => { routes.MapControllers(); });
}))
{
var client = app.Host.GetTestClient();
client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9,application/json;v=2.0");
var sut = await client.PostAsync("/fake/", new StringContent(Generate.RandomString(100)));
var stringResult = await sut.Content.ReadAsStringAsync();
TestOutput.WriteLine(stringResult);
Assert.Equal(HttpStatusCode.UnsupportedMediaType, sut.StatusCode);
Assert.Equal(HttpMethod.Post, sut.RequestMessage.Method);
Assert.Equal("The HTTP resource that matches the request URI 'http://localhost/fake/' does not support the API version '2.0'.", stringResult, ignoreLineEndingDifferences: true);
}
}
[Theory]
[InlineData("application/json")]
[InlineData("text/json")]
public async Task GetRequest_ShouldFailWithBadRequestFormattedAsJsonResponse_As_d3_IsAnUnknownVersion_CorrectlySetOnJsonAccept(string jsonAccept)
{
using (var app = WebHostTestFactory.Create(services =>
{
services.AddFaultDescriptorOptions();
services.AddControllers(o => o.Filters.AddFaultDescriptor())
.AddApplicationPart(typeof(FakeController).Assembly)
.AddJsonFormatters(o => o.Settings.Encoder = JavaScriptEncoder.Default);
services.AddHttpContextAccessor();
services.AddRestfulApiVersioning();
}, app =>
{
app.UseFaultDescriptorExceptionHandler();
app.UseRestfulApiVersioning();
app.UseRouting();
app.UseEndpoints(routes => { routes.MapControllers(); });
}))
{
var client = app.Host.GetTestClient();
client.DefaultRequestHeaders.Add("Accept", $"text/html,application/xhtml+xml,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9,{jsonAccept};q=10.0;v=d3");
var sut = await client.GetAsync("/fake/throw");
TestOutput.WriteLine(await sut.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.BadRequest, sut.StatusCode);
Assert.Equal(HttpMethod.Get, sut.RequestMessage.Method);
Assert.EndsWith(jsonAccept, sut.Content.Headers.ContentType.ToString());
Assert.True(Match(@"{
""error"": {
""instance"": ""http://localhost/fake/throw"",
""status"": 400,
""code"": ""BadRequest"",
""message"": ""The HTTP resource that matches the request URI \u0027http://localhost/fake/throw\u0027 does not support the API version \u0027d3\u0027.""
},
""traceId"": ""*""
}".ReplaceLineEndings(), (await sut.Content.ReadAsStringAsync()).ReplaceLineEndings()));
}
}
[Theory]
[InlineData("application/xml")]
[InlineData("text/xml")]
public async Task GetRequest_ShouldFailWithBadRequestFormattedAsXmlResponse_As_d3_IsAnUnknownVersion_CorrectlySetOnXmlAccept(string xmlAccept)
{
using (var app = WebHostTestFactory.Create(services =>
{
services.AddFaultDescriptorOptions();
services.AddControllers(o => o.Filters.AddFaultDescriptor())
.AddApplicationPart(typeof(FakeController).Assembly)
.AddJsonFormatters(o => o.Settings.Encoder = JavaScriptEncoder.Default)
.AddXmlFormatters();
services.AddHttpContextAccessor();
services.AddRestfulApiVersioning();
}, app =>
{
app.UseFaultDescriptorExceptionHandler();
app.UseRestfulApiVersioning();
app.UseRouting();
app.UseEndpoints(routes => { routes.MapControllers(); });
}))
{
var client = app.Host.GetTestClient();
client.DefaultRequestHeaders.Add("Accept", $"application/json,text/html,application/xhtml+xml,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9,{xmlAccept};q=10.0;v=d3");
var sut = await client.GetAsync("/fake/throw");
TestOutput.WriteLine(await sut.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.BadRequest, sut.StatusCode);
Assert.Equal(HttpMethod.Get, sut.RequestMessage.Method);
Assert.EndsWith(xmlAccept, sut.Content.Headers.ContentType.ToString());
Assert.True(Match(@"<?xml version=""1.0"" encoding=""utf-8""?><HttpExceptionDescriptor><Error><Instance>http://localhost/fake/throw</Instance><Status>400</Status><Code>BadRequest</Code><Message>The HTTP resource that matches the request URI 'http://localhost/fake/throw' does not support the API version 'd3'.</Message></Error><TraceId>*</TraceId></HttpExceptionDescriptor>", await sut.Content.ReadAsStringAsync()));
}
}
[Theory]
[InlineData("text/plain")]
[InlineData("text/yaml")]
[InlineData("application/yaml")]
[InlineData("*/*")]
public async Task GetRequest_ShouldFailWithBadRequestFormattedAsXmlResponse_As_d3_IsAnUnknownVersion_CorrectlySetOnYamlAccept(string yamlAccept)
{
using (var app = WebHostTestFactory.Create(services =>
{
services.AddFaultDescriptorOptions();
services.AddControllers(o => o.Filters.AddFaultDescriptor())
.AddApplicationPart(typeof(FakeController).Assembly)
.AddJsonFormatters()
.AddXmlFormatters()
.AddYamlFormatters(o => o.Settings.NamingConvention = PascalCaseNamingConvention.Instance);
services.AddHttpContextAccessor();
services.AddRestfulApiVersioning();
}, app =>
{
app.UseFaultDescriptorExceptionHandler();
app.UseRestfulApiVersioning();
app.UseRouting();
app.UseEndpoints(routes => { routes.MapControllers(); });
}))
{
var client = app.Host.GetTestClient();
client.DefaultRequestHeaders.Add("Accept", $"application/json,text/html,application/xhtml+xml,image/avif,image/webp,image/apng,application/signed-exchange;v=b3;q=0.9,{yamlAccept};q=10.0;v=d3");
var sut = await client.GetAsync("/fake/throw");
TestOutput.WriteLine(await sut.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.BadRequest, sut.StatusCode);
Assert.Equal(HttpMethod.Get, sut.RequestMessage.Method);
Assert.EndsWith(yamlAccept, sut.Content.Headers.ContentType.ToString());
Assert.True(Match("""
Error:
Instance: http://localhost/fake/throw
Status: 400
Code: BadRequest
Message: The HTTP resource that matches the request URI 'http://localhost/fake/throw' does not support the API version 'd3'.
TraceId: *
""".ReplaceLineEndings(), await sut.Content.ReadAsStringAsync(), o => o.ThrowOnNoMatch = true));
}
}
[Theory]
[InlineData("application/json")]
[InlineData("text/json")]
public async Task GetRequest_ShouldFailWithBadRequestFormattedAsNewtonsoftJsonResponse_As_d3_IsAnUnknownVersion_CorrectlySetOnJsonAccept(string jsonAccept)
{
using (var app = WebHostTestFactory.Create(services =>
{
services.AddFaultDescriptorOptions(o => o.SensitivityDetails = FaultSensitivityDetails.Evidence);
services.AddControllers(o => o.Filters.AddFaultDescriptor())
.AddApplicationPart(typeof(FakeController).Assembly)
.AddNewtonsoftJsonFormatters(o => o.SensitivityDetails = FaultSensitivityDetails.Evidence);
services.AddHttpContextAccessor();
services.AddRestfulApiVersioning();
}, app =>
{
app.UseFaultDescriptorExceptionHandler();
app.UseRestfulApiVersioning();
app.UseRouting();
app.UseEndpoints(routes => { routes.MapControllers(); });
}))
{
var client = app.Host.GetTestClient();
client.DefaultRequestHeaders.Add("Accept", $"text/html,application/xhtml+xml,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9,{jsonAccept};q=10.0;v=d3");
var sut = await client.GetAsync("/fake/throw");
TestOutput.WriteLine(await sut.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.BadRequest, sut.StatusCode);
Assert.Equal(HttpMethod.Get, sut.RequestMessage.Method);
Assert.EndsWith(jsonAccept, sut.Content.Headers.ContentType.ToString());
Assert.True(Match($$"""
{
"error": {
"instance": "http://localhost/fake/throw",
"status": 400,
"code": "BadRequest",
"message": "The HTTP resource that matches the request URI 'http://localhost/fake/throw' does not support the API version 'd3'."
},
"evidence": {
"request": {
"location": "http://localhost/fake/throw",
"method": "GET",
"headers": {
"accept": [
"text/html",
"application/xhtml+xml",
"image/avif",
"image/webp",
"image/apng",
"*/*; q=0.8",
"application/signed-exchange; v=b3; q=0.9",
"{{jsonAccept}}; q=10.0; v=d3"
],
"host": "localhost"
},
"query": [],
"cookies": [],
"body": ""
}
},
"traceId": "*"
}
""".ReplaceLineEndings(), (await sut.Content.ReadAsStringAsync()).ReplaceLineEndings()));
}
}
[Fact]
public async Task GetRequest_ShouldThrowNotAcceptableException_As_2dot0_IsAnUnknownVersion()
{
using (var app = WebHostTestFactory.Create(services =>
{
services.AddControllers()
.AddApplicationPart(typeof(FakeController).Assembly);
services.AddRestfulApiVersioning();
}, app =>
{
app.UseRestfulApiVersioning();
app.UseRouting();
app.UseEndpoints(routes =>
{
routes.MapControllers();
});
}))
{
var client = app.Host.GetTestClient();
client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9,application/xml;v=2.0");
await Assert.ThrowsAsync<NotAcceptableException>(() => client.GetAsync("/fake/"));
}
}
[Fact]
public async Task PostRequest_ShouldThrowUnsupportedMediaTypeException_As_2dot0_IsAnUnknownVersion()
{
using (var app = WebHostTestFactory.Create(services =>
{
services.AddControllers()
.AddApplicationPart(typeof(FakeController).Assembly);
services.AddRestfulApiVersioning();
}, app =>
{
app.UseRestfulApiVersioning();
app.UseRouting();
app.UseEndpoints(routes =>
{
routes.MapControllers();
});
}))
{
var client = app.Host.GetTestClient();
client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9,application/xml;v=2.0");
await Assert.ThrowsAsync<UnsupportedMediaTypeException>(() => client.PostAsync("/fake/", new StringContent(Generate.RandomString(100))));
}
}
}
}