This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
BasicTests.cs
380 lines (320 loc) · 14.2 KB
/
BasicTests.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.FunctionalTests
{
public class BasicTests : IClassFixture<MvcTestFixture<BasicWebSite.Startup>>
{
// Some tests require comparing the actual response body against an expected response baseline
// so they require a reference to the assembly on which the resources are located, in order to
// make the tests less verbose, we get a reference to the assembly with the resources and we
// use it on all the rest of the tests.
private static readonly Assembly _resourcesAssembly = typeof(BasicTests).GetTypeInfo().Assembly;
public BasicTests(MvcTestFixture<BasicWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory]
[InlineData("")]
[InlineData("Home")]
[InlineData("Home/Index")]
public async Task CanRender_ViewsWithLayout(string url)
{
// Arrange
var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
var outputFile = "compiler/resources/BasicWebSite.Home.Index.html";
var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
// Act
// The host is not important as everything runs in memory and tests are isolated from each other.
var response = await Client.GetAsync(url);
var responseContent = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);
#if GENERATE_BASELINES
ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
Assert.Equal(expectedContent, responseContent, ignoreLineEndingDifferences: true);
#endif
}
[Fact]
public async Task CanRender_SimpleViews()
{
// Arrange
var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
var outputFile = "compiler/resources/BasicWebSite.Home.PlainView.html";
var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
// Act
var response = await Client.GetAsync("http://localhost/Home/PlainView");
var responseContent = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);
#if GENERATE_BASELINES
ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
Assert.Equal(expectedContent, responseContent, ignoreLineEndingDifferences: true);
#endif
}
[Fact]
public async Task ViewWithAttributePrefix_RendersWithoutIgnoringPrefix()
{
// Arrange
var outputFile = "compiler/resources/BasicWebSite.Home.ViewWithPrefixedAttributeValue.html";
var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
// Act
var response = await Client.GetAsync("Home/ViewWithPrefixedAttributeValue");
var responseContent = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
#if GENERATE_BASELINES
ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
Assert.Equal(expectedContent, responseContent, ignoreLineEndingDifferences: true);
#endif
}
[Fact]
public async Task CanReturn_ResultsWithoutContent()
{
// Act
var response = await Client.GetAsync("Home/NoContentResult");
var responseContent = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
Assert.Null(response.Content.Headers.ContentType);
Assert.Equal(0, response.Content.Headers.ContentLength);
Assert.Equal(0, responseContent.Length);
}
[Fact]
public async Task ReturningTaskFromAction_ProducesEmptyResult()
{
// Act
var response = await Client.GetAsync("Home/ActionReturningTask");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("Hello, World!", Assert.Single(response.Headers.GetValues("Message")));
Assert.Empty(await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task ActionDescriptors_CreatedOncePerRequest()
{
// Arrange
var expectedContent = "1";
// Act and Assert
for (var i = 0; i < 3; i++)
{
var result = await Client.GetAsync("Monitor/CountActionDescriptorInvocations");
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
var responseContent = await result.Content.ReadAsStringAsync();
Assert.Equal(expectedContent, responseContent);
}
}
[Fact]
public async Task ActionWithRequireHttps_RedirectsToSecureUrl_ForNonHttpsGetRequests()
{
// Act
var response = await Client.GetAsync("Home/HttpsOnlyAction");
// Assert
Assert.Equal(HttpStatusCode.MovedPermanently, response.StatusCode);
Assert.NotNull(response.Headers.Location);
Assert.Equal("https://localhost/Home/HttpsOnlyAction", response.Headers.Location.ToString());
Assert.Equal(0, response.Content.Headers.ContentLength);
var responseBytes = await response.Content.ReadAsByteArrayAsync();
Assert.Equal(0, responseBytes.Length);
}
[Fact]
public async Task ActionWithRequireHttps_ReturnsBadRequestResponse_ForNonHttpsNonGetRequests()
{
// Act
var response = await Client.SendAsync(new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/Home/HttpsOnlyAction"));
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal(0, response.Content.Headers.ContentLength);
var responseBytes = await response.Content.ReadAsByteArrayAsync();
Assert.Equal(0, responseBytes.Length);
}
[Theory]
[InlineData("GET")]
[InlineData("POST")]
public async Task ActionWithRequireHttps_AllowsHttpsRequests(string method)
{
// Act
var response = await Client.SendAsync(new HttpRequestMessage(
new HttpMethod(method),
"https://localhost/Home/HttpsOnlyAction"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task JsonViewComponent_RendersJson()
{
// Arrange
var expectedBody = JsonConvert.SerializeObject(new BasicWebSite.Models.Person()
{
Id = 10,
Name = "John"
});
// Act
var response = await Client.GetAsync("Home/JsonTextInView");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType);
var actualBody = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, actualBody);
}
[Fact]
public async Task JsonHelper_RendersJson()
{
// Arrange
var json = JsonConvert.SerializeObject(new BasicWebSite.Models.Person()
{
Id = 9000,
Name = "John <b>Smith</b>"
});
var expectedBody = string.Format(
@"<script type=""text/javascript"">
var json = {0};
</script>",
json);
// Act
var response = await Client.GetAsync("Home/JsonHelperInView");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType);
var actualBody = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, actualBody, ignoreLineEndingDifferences: true);
}
[Fact]
public async Task JsonHelperWithSettings_RendersJson()
{
// Arrange
var json = JsonConvert.SerializeObject(new BasicWebSite.Models.Person()
{
Id = 9000,
Name = "John <b>Smith</b>"
}, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
var expectedBody = string.Format(
@"<script type=""text/javascript"">
var json = {0};
</script>",
json);
// Act
var response = await Client.GetAsync("Home/JsonHelperWithSettingsInView");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType);
var actualBody = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, actualBody, ignoreLineEndingDifferences: true);
}
public static IEnumerable<object[]> HtmlHelperLinkGenerationData
{
get
{
yield return new[] {
"ActionLink_ActionOnSameController",
@"<a href=""/Links/Details"">linktext</a>" };
yield return new[] {
"ActionLink_ActionOnOtherController",
@"<a href=""/Products/Details?print=true"">linktext</a>"
};
yield return new[] {
"ActionLink_SecurePage_ImplicitHostName",
@"<a href=""https://localhost/Products/Details?print=true"">linktext</a>"
};
yield return new[] {
"ActionLink_HostNameFragmentAttributes",
// note: attributes are alphabetically ordered
@"<a href=""https://www.contoso.com:9000/Products/Details?print=true#details"" p1=""p1-value"">linktext</a>"
};
yield return new[] {
"RouteLink_RestLinkToOtherController",
@"<a href=""/api/orders/10"">linktext</a>"
};
yield return new[] {
"RouteLink_SecureApi_ImplicitHostName",
@"<a href=""https://localhost/api/orders/10"">linktext</a>"
};
yield return new[] {
"RouteLink_HostNameFragmentAttributes",
@"<a href=""https://www.contoso.com:9000/api/orders/10?print=True#details"" p1=""p1-value"">linktext</a>"
};
}
}
[Theory]
[MemberData(nameof(HtmlHelperLinkGenerationData))]
public async Task HtmlHelperLinkGeneration(string viewName, string expectedLink)
{
// Act
var response = await Client.GetAsync("Links/Index?view=" + viewName);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var responseData = await response.Content.ReadAsStringAsync();
Assert.Contains(expectedLink, responseData, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task ConfigureMvc_AddsOptionsProperly()
{
// Act
var response = await Client.GetAsync("Home/GetApplicationDescription");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var responseData = await response.Content.ReadAsStringAsync();
Assert.Equal("This is a basic website.", responseData);
}
[Fact]
public async Task TypesWithoutControllerSuffix_DerivingFromTypesWithControllerSuffix_CanBeAccessed()
{
// Act
var response = await Client.GetStringAsync("appointments");
// Assert
Assert.Equal("2 appointments available.", response);
}
[Fact]
public async Task TypesMarkedAsNonAction_AreInaccessible()
{
// Act
var response = await Client.GetAsync("SqlData/TruncateAllDbRecords");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task ResourceFilter_CreatesSpecificInputAndOutputFormatters()
{
// Arrange
var input = "{\"fullName\":\"John Doe\"}";
// Act
var response = await Client.PostAsync(
"http://localhost/api/ActionUsingSpecificFormatters",
new StringContent(input, Encoding.UTF8, "application/json"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(input, await response.Content.ReadAsStringAsync());
// Make sure it does not affect other actions
//Arrange
input = "{\"FullName\":\"John Doe\"}";
// Act
response = await Client.PostAsync(
"http://localhost/api/ActionUsingGlobalFormatters",
new StringContent(input, Encoding.UTF8, "application/json"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(input, await response.Content.ReadAsStringAsync());
}
}
}