Skip to content

Commit

Permalink
Add more logging to WaitForStartAsync and check for success status code
Browse files Browse the repository at this point in the history
  • Loading branch information
Muhammad Rehan Saeed committed Dec 6, 2019
1 parent d799fde commit dc014b0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 20 deletions.
2 changes: 1 addition & 1 deletion Source/Boxed.DotnetNewTest/Boxed.DotnetNewTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
</PropertyGroup>

<PropertyGroup Label="Package">
<VersionPrefix>3.1.1</VersionPrefix>
<VersionPrefix>3.1.2</VersionPrefix>
<Authors>Muhammad Rehan Saeed (RehanSaeed.com)</Authors>
<Product>ASP.NET Core Dotnet New Test Boxed</Product>
<Description>ASP.NET Core test framework for dotnet new project templates.</Description>
Expand Down
56 changes: 37 additions & 19 deletions Source/Boxed.DotnetNewTest/ProjectExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ public static class ProjectExtensions
/// </summary>
/// <param name="project">The project.</param>
/// <param name="projectRelativeDirectoryPath">The project relative directory path.</param>
/// <param name="relativeUrl">The relative URL to call to test if the app has started or not.</param>
/// <param name="action">The action to perform while the project is running.</param>
/// <param name="noRestore">Whether to restore the project.</param>
/// <param name="validateCertificate">Validate the project certificate.</param>
Expand All @@ -126,6 +127,7 @@ public static class ProjectExtensions
public static async Task DotnetRunAsync(
this Project project,
string projectRelativeDirectoryPath,
Uri relativeUrl,
Func<HttpClient, Task> action,
bool? noRestore = true,
Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> validateCertificate = null,
Expand All @@ -148,18 +150,18 @@ public static class ProjectExtensions
}

var httpPort = PortHelper.GetFreeTcpPort();
var httpUrl = $"http://localhost:{httpPort}";
var httpUrl = new Uri($"http://localhost:{httpPort}");

var projectFilePath = Path.Combine(project.DirectoryPath, projectRelativeDirectoryPath);
var dotnetRun = await DotnetRunInternalAsync(projectFilePath, noRestore, timeout, showShellWindow, httpUrl)
var dotnetRun = await DotnetRunInternalAsync(projectFilePath, relativeUrl, noRestore, timeout, showShellWindow, httpUrl)
.ConfigureAwait(false);

var httpClientHandler = new HttpClientHandler()
{
AllowAutoRedirect = false,
ServerCertificateCustomValidationCallback = validateCertificate ?? DefaultValidateCertificate,
};
var httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(httpUrl) };
var httpClient = new HttpClient(httpClientHandler) { BaseAddress = httpUrl };

try
{
Expand All @@ -178,6 +180,7 @@ public static class ProjectExtensions
/// </summary>
/// <param name="project">The project.</param>
/// <param name="projectRelativeDirectoryPath">The project relative directory path.</param>
/// <param name="relativeUrl">The relative URL to call to test if the app has started or not.</param>
/// <param name="action">The action to perform while the project is running.</param>
/// <param name="noRestore">Whether to restore the project.</param>
/// <param name="validateCertificate">Validate the project certificate.</param>
Expand All @@ -187,6 +190,7 @@ public static class ProjectExtensions
public static async Task DotnetRunAsync(
this Project project,
string projectRelativeDirectoryPath,
Uri relativeUrl,
Func<HttpClient, HttpClient, Task> action,
bool? noRestore = true,
Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> validateCertificate = null,
Expand All @@ -210,20 +214,20 @@ public static class ProjectExtensions

var httpPort = PortHelper.GetFreeTcpPort();
var httpsPort = PortHelper.GetFreeTcpPort();
var httpUrl = $"http://localhost:{httpPort}";
var httpsUrl = $"https://localhost:{httpsPort}";
var httpUrl = new Uri($"http://localhost:{httpPort}");
var httpsUrl = new Uri($"https://localhost:{httpsPort}");

var projectFilePath = Path.Combine(project.DirectoryPath, projectRelativeDirectoryPath);
var dotnetRun = await DotnetRunInternalAsync(projectFilePath, noRestore, timeout, showShellWindow, httpUrl, httpsUrl)
var dotnetRun = await DotnetRunInternalAsync(projectFilePath, relativeUrl, noRestore, timeout, showShellWindow, httpUrl, httpsUrl)
.ConfigureAwait(false);

var httpClientHandler = new HttpClientHandler()
{
AllowAutoRedirect = false,
ServerCertificateCustomValidationCallback = validateCertificate ?? DefaultValidateCertificate,
};
var httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(httpUrl) };
var httpsClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(httpsUrl) };
var httpClient = new HttpClient(httpClientHandler) { BaseAddress = httpUrl };
var httpsClient = new HttpClient(httpClientHandler) { BaseAddress = httpsUrl };

try
{
Expand Down Expand Up @@ -302,16 +306,17 @@ public static class ProjectExtensions

private static async Task<IAsyncDisposable> DotnetRunInternalAsync(
string directoryPath,
Uri relativeUrl,
bool? noRestore,
TimeSpan? timeout,
bool showShellWindow,
params string[] urls)
params Uri[] urls)
{
#pragma warning disable CA2000 // Dispose objects before losing scope. Object disposed below.
var cancellationTokenSource = new CancellationTokenSource();
#pragma warning restore CA2000 // Dispose objects before losing scope. Object disposed below.
var noRestoreArgument = noRestore is null ? null : "--no-restore";
var urlsParameter = string.Join(";", urls);
var urlsParameter = string.Join(";", urls.Select(x => x.ToString()));
var task = AssertStartAsync(
directoryPath,
"dotnet",
Expand All @@ -321,7 +326,7 @@ public static class ProjectExtensions

try
{
await WaitForStartAsync(urls.First(), timeout ?? TimeSpan.FromMinutes(1)).ConfigureAwait(false);
await WaitForStartAsync(urls.First(), relativeUrl, timeout ?? TimeSpan.FromMinutes(1)).ConfigureAwait(false);
}
catch
{
Expand Down Expand Up @@ -355,36 +360,49 @@ async static ValueTask Dispose(CancellationTokenSource cancellationTokenSource,
}
}

private static async Task WaitForStartAsync(string url, TimeSpan timeout)
private static async Task WaitForStartAsync(Uri baseUrl, Uri relativeUrl, TimeSpan timeout)
{
const int intervalMilliseconds = 100;

var url = new Uri(baseUrl, relativeUrl);
TestLogger.WriteLine($"Waiting for app at {url} to start and return success status code.");

using (var cancellationTokenSource = new CancellationTokenSource(timeout))
using (var httpClientHandler = new HttpClientHandler()
{
AllowAutoRedirect = false,
ServerCertificateCustomValidationCallback = DefaultValidateCertificate,
})
using (var httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(url) })
using (var httpClient = new HttpClient(httpClientHandler) { BaseAddress = baseUrl })
{
while (true)
{
if (cancellationTokenSource.Token.IsCancellationRequested)
{
throw new TimeoutException(
$"Timed out after waiting {timeout} for application to start using dotnet run.");
var message = $"Timed out after waiting {timeout} for app at {url} to start using dotnet run.";
TestLogger.WriteLine(message);
throw new TimeoutException(message);
}

try
{
await httpClient.GetAsync(new Uri("/", UriKind.Relative)).ConfigureAwait(false);
return;
var response = await httpClient.GetAsync(relativeUrl).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
TestLogger.WriteLine($"App at {url} has started and returned success status code '{response.StatusCode}'.");
return;
}
else
{
TestLogger.WriteLine($"Waiting for app at {url} to start, error status code received '{response.StatusCode}'...");
}
}
catch (HttpRequestException exception)
when (IsApiDownException(exception))
{
await Task.Delay(intervalMilliseconds).ConfigureAwait(false);
TestLogger.WriteLine($"Waiting for app at {url} to start, app is not reachable...");
}

await Task.Delay(intervalMilliseconds).ConfigureAwait(false);
}
}
}
Expand Down

0 comments on commit dc014b0

Please sign in to comment.