-
Notifications
You must be signed in to change notification settings - Fork 10.1k
/
AspNetProcess.cs
294 lines (255 loc) · 10.8 KB
/
AspNetProcess.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
// 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.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Threading.Tasks;
using AngleSharp.Dom.Html;
using AngleSharp.Parser.Html;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.Extensions.CommandLineUtils;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Playwright;
using Xunit;
using Xunit.Abstractions;
namespace Templates.Test.Helpers;
[DebuggerDisplay("{ToString(),nq}")]
public class AspNetProcess : IDisposable
{
private const string ListeningMessagePrefix = "Now listening on: ";
private readonly HttpClient _httpClient;
private readonly ITestOutputHelper _output;
private readonly DevelopmentCertificate _developmentCertificate;
internal readonly Uri ListeningUri;
internal ProcessEx Process { get; }
public AspNetProcess(
DevelopmentCertificate cert,
ITestOutputHelper output,
string workingDirectory,
string dllPath,
IDictionary<string, string> environmentVariables,
bool published,
bool hasListeningUri = true,
bool usePublishedAppHost = false,
ILogger logger = null)
{
_developmentCertificate = cert;
_output = output;
_httpClient = new HttpClient(new HttpClientHandler()
{
AllowAutoRedirect = true,
UseCookies = true,
CookieContainer = new CookieContainer(),
ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) => (certificate.Subject != "CN=localhost" && errors == SslPolicyErrors.None) || certificate?.Thumbprint == _developmentCertificate.CertificateThumbprint,
})
{
Timeout = TimeSpan.FromMinutes(2)
};
output.WriteLine("Running ASP.NET Core application...");
string process;
string arguments;
if (published)
{
if (usePublishedAppHost)
{
// When publishingu used the app host to run the app. This makes it easy to consistently run for regular and single-file publish
process = Path.ChangeExtension(dllPath, OperatingSystem.IsWindows() ? ".exe" : null);
arguments = null;
}
else
{
process = DotNetMuxer.MuxerPathOrDefault();
arguments = $"exec {dllPath}";
}
}
else
{
process = DotNetMuxer.MuxerPathOrDefault();
// When executing "dotnet run", the launch urls specified in the app's launchSettings.json have higher precedence
// than ambient environment variables. We specify the urls using command line arguments instead to allow us
// to continue binding to "port 0" and avoid test flakiness due to port conflicts.
arguments = $"run --no-build --urls \"{environmentVariables["ASPNETCORE_URLS"]}\"";
}
logger?.LogInformation($"AspNetProcess - process: {process} arguments: {arguments}");
var finalEnvironmentVariables = new Dictionary<string, string>(environmentVariables)
{
["ASPNETCORE_Kestrel__Certificates__Default__Path"] = _developmentCertificate.CertificatePath,
["ASPNETCORE_Kestrel__Certificates__Default__Password"] = _developmentCertificate.CertificatePassword,
};
Process = ProcessEx.Run(output, workingDirectory, process, arguments, envVars: finalEnvironmentVariables);
logger?.LogInformation("AspNetProcess - process started");
if (hasListeningUri)
{
logger?.LogInformation("AspNetProcess - Getting listening uri");
ListeningUri = ResolveListeningUrl(output);
logger?.LogInformation($"AspNetProcess - Got {ListeningUri}");
}
}
public async Task VisitInBrowserAsync(IPage page)
{
_output.WriteLine($"Opening browser at {ListeningUri}...");
await page.GotoAsync(ListeningUri.AbsoluteUri);
}
public async Task AssertPagesOk(IEnumerable<Page> pages)
{
foreach (var page in pages)
{
await AssertOk(page.Url);
await ContainsLinks(page);
}
}
public async Task ContainsLinks(Page page)
{
var response = await RetryHelper.RetryRequest(async () =>
{
var request = new HttpRequestMessage(
HttpMethod.Get,
new Uri(ListeningUri, page.Url));
return await _httpClient.SendAsync(request);
}, logger: NullLogger.Instance);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var parser = new HtmlParser();
var html = await parser.ParseAsync(await response.Content.ReadAsStreamAsync());
foreach (IHtmlLinkElement styleSheet in html.GetElementsByTagName("link"))
{
Assert.Equal("stylesheet", styleSheet.Relation);
// Workaround for https://github.com/dotnet/aspnetcore/issues/31030#issuecomment-811334450
// Cleans up incorrectly generated filename for scoped CSS files
var styleSheetHref = styleSheet.Href.Replace("_", string.Empty).Replace("about://", string.Empty);
await AssertOk(styleSheetHref);
}
foreach (var script in html.Scripts)
{
if (!string.IsNullOrEmpty(script.Source))
{
await AssertOk(script.Source);
}
}
Assert.True(html.Links.Length == page.Links.Count(), $"Expected {page.Url} to have {page.Links.Count()} links but it had {html.Links.Length}");
foreach ((var link, var expectedLink) in html.Links.Zip(page.Links, Tuple.Create))
{
IHtmlAnchorElement anchor = (IHtmlAnchorElement)link;
if (string.Equals(anchor.Protocol, "about:"))
{
Assert.True(anchor.PathName.EndsWith(expectedLink, StringComparison.Ordinal), $"Expected next link on {page.Url} to be {expectedLink} but it was {anchor.PathName}: {html.Source.Text}");
await AssertOk(anchor.PathName);
}
else
{
Assert.True(string.Equals(anchor.Href, expectedLink), $"Expected next link to be {expectedLink} but it was {anchor.Href}.");
var result = await RetryHelper.RetryRequest(async () =>
{
return await _httpClient.GetAsync(anchor.Href);
}, logger: NullLogger.Instance);
Assert.True(IsSuccessStatusCode(result), $"{anchor.Href} is a broken link!");
}
}
}
private Uri ResolveListeningUrl(ITestOutputHelper output)
{
// Wait until the app is accepting HTTP requests
output.WriteLine("Waiting until ASP.NET application is accepting connections...");
var listeningMessage = GetListeningMessage();
if (!string.IsNullOrEmpty(listeningMessage))
{
listeningMessage = listeningMessage.Trim();
// Verify we have a valid URL to make requests to
var listeningUrlString = listeningMessage.Substring(listeningMessage.IndexOf(
ListeningMessagePrefix, StringComparison.Ordinal) + ListeningMessagePrefix.Length);
output.WriteLine($"Detected that ASP.NET application is accepting connections on: {listeningUrlString}");
listeningUrlString = string.Concat(listeningUrlString.AsSpan(0, listeningUrlString.IndexOf(':')),
"://localhost",
listeningUrlString.AsSpan(listeningUrlString.LastIndexOf(':')));
output.WriteLine("Sending requests to " + listeningUrlString);
return new Uri(listeningUrlString, UriKind.Absolute);
}
else
{
return null;
}
}
private string GetListeningMessage()
{
var buffer = new List<string>();
try
{
foreach (var line in Process.OutputLinesAsEnumerable)
{
if (line != null)
{
buffer.Add(line);
if (line.Trim().Contains(ListeningMessagePrefix, StringComparison.Ordinal))
{
return line;
}
}
}
}
catch (OperationCanceledException)
{
}
throw new InvalidOperationException(@$"Couldn't find listening url:
{string.Join(Environment.NewLine, buffer)}");
}
private static bool IsSuccessStatusCode(HttpResponseMessage response)
{
return response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Redirect;
}
public Task AssertOk(string requestUrl)
=> AssertStatusCode(requestUrl, HttpStatusCode.OK);
public Task AssertNotFound(string requestUrl)
=> AssertStatusCode(requestUrl, HttpStatusCode.NotFound);
internal Task<HttpResponseMessage> SendRequest(string path) =>
RetryHelper.RetryRequest(() => _httpClient.GetAsync(new Uri(ListeningUri, path)), logger: NullLogger.Instance);
internal Task<HttpResponseMessage> SendRequest(Func<HttpRequestMessage> requestFactory)
=> RetryHelper.RetryRequest(() => _httpClient.SendAsync(requestFactory()), logger: NullLogger.Instance);
public async Task AssertStatusCode(string requestUrl, HttpStatusCode statusCode, string acceptContentType = null)
{
var response = await RetryHelper.RetryRequest(() =>
{
var request = new HttpRequestMessage(
HttpMethod.Get,
new Uri(ListeningUri, requestUrl));
if (!string.IsNullOrEmpty(acceptContentType))
{
request.Headers.Add("Accept", acceptContentType);
}
return _httpClient.SendAsync(request);
}, logger: NullLogger.Instance);
Assert.True(statusCode == response.StatusCode, $"Expected {requestUrl} to have status '{statusCode}' but it was '{response.StatusCode}'.");
}
public void Dispose()
{
_httpClient.Dispose();
Process.Dispose();
}
public override string ToString()
{
var result = "";
result += Process != null ? "Active: " : "Inactive";
if (Process != null)
{
if (!Process.HasExited)
{
result += $"(Listening on {ListeningUri.OriginalString}) PID: {Process.Id}";
}
else
{
result += "(Already finished)";
}
}
return result;
}
}
public class Page
{
public string Url { get; set; }
public IEnumerable<string> Links { get; set; }
}