Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing Chap 20 flaky tests #565

Merged
merged 2 commits into from
Oct 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 19 additions & 78 deletions src/Chapter20.Tests/BaseProgramTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@

namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Tests;

abstract public class BaseProgramTests
public abstract class BaseProgramTests
{
[NotNull]
static public ProgramWrapper? ProgramWrapper { get; set; }
public static ProgramWrapper? ProgramWrapper { get; set; }

protected abstract string DefaultUrl { get; }

[NotNull]
public TestContext? TestContext { get; set; }

[TestInitializeAttribute]
[TestInitialize]
public void TestInitialize()
{
Assert.IsNotNull(TestContext);
Expand All @@ -29,7 +29,7 @@ public void TestInitialize()
[TestMethod]
[DataRow("IntelliTect", @"[1-9]\d*")]
[DataRow("Text Snippet That Does Not Exist On The Page", @"0")]
public void Main_FindText_VerifyOccurenceCount(string findText, string countPattern)
public void Main_FindText_VerifyOccurrenceCount(string findText, string countPattern)
{
string url = DefaultUrl;
string expected =
Expand All @@ -41,10 +41,7 @@ public void Main_FindText_VerifyOccurenceCount(string findText, string countPatt
Regex.Escape(url)
}'\.\s+";
string actual = IntelliTect.TestTools.Console.ConsoleAssert.Execute("",
() =>
{
ProgramWrapper.Main(new string[] { findText }).Wait();
});
() => ProgramWrapper.Main(new string[] { findText }).Wait());

Regex regex = new(expected);
Assert.IsTrue(regex.Match(actual).Success,
Expand Down Expand Up @@ -110,78 +107,22 @@ protected static void AssertAggregateExceptionType(string messagePrefix, Aggrega
});
}

[TestMethod]
[ExpectedException(typeof(System.ArgumentNullException))]
public async Task Main_GivenNullUri_ThrowException()
{
try
{
await ProgramWrapper.Main(new string[] { "irrelevant", null! });
Assert.Fail("Expected exception was not thrown.");
}
catch (AggregateException exception)
{
if (exception.InnerExceptions.Count != 1)
{
throw new InvalidOperationException("Unexpected scenario with there being more than one inner exception.");
}
exception.Handle(innerException =>
{
// Rethrowing rather than using
// if condition on the type
ExceptionDispatchInfo.Capture(
innerException!).Throw();

return true;
});
}
}
protected static HttpClient GetMockedHttpClient()
=> new HttpClient(new MockHttpClientHandler());
}

[TestMethod]
[DataRow("Bad Uri", "Could not find file *")]
[DataRow("https://bad uri", "The filename, directory name, or volume label syntax is incorrect. *", "Could not find a part of the path*", "Could not find a part of the path*")]
[DataRow("https://thisisanotherbadurlthatpresumablyldoesnotexist.notexist", "No such host is known.*", "nodename nor servname provided, or not known*", "Name or service not known*")]
[ExpectedException(typeof(WebException))]
public async Task Main_GivenBadUri_ThrowException(string uri, string defaultMessagePrefix, string? messagePrefixOSX = null, string? messagePrefixLinux = null)
file class MockHttpClientHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
messagePrefixOSX ??= defaultMessagePrefix;
messagePrefixLinux ??= defaultMessagePrefix;

try
{
await ProgramWrapper.Main(new string[] { "irrelevant", uri });
Assert.Fail("Expected exception was not thrown.");
}
catch (Exception exception)
HttpResponseMessage response = new(HttpStatusCode.OK)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
AssertMainException(defaultMessagePrefix, exception);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
AssertMainException(messagePrefixOSX, exception);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
AssertMainException(messagePrefixLinux, exception);
}
if (exception is AggregateException aggregateException)
{
// InnerException expected to be WebException.
exception = aggregateException.Flatten();
aggregateException.Handle(innerException =>
{
// Rethrowing rather than using
// if condition on the type
ExceptionDispatchInfo.Capture(
innerException)
.Throw();
return true;
});
}
// WebException expected
else throw;
}
Content = new StringContent($"""
Test Data From {GetType().Namespace}.{nameof(MockHttpClientHandler)}
Request Uri: {request.RequestUri},
The tests search for the word "IntelliTect" so that is can count the number of times it appears on the page.
""")
};
return Task.FromResult(response);
}
}
1 change: 1 addition & 0 deletions src/Chapter20.Tests/Listing20.01.Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public class ProgramTests : BaseProgramTests
[ClassInitialize]
static public void ClassInitialize(TestContext _)
{
Program.HttpClient = GetMockedHttpClient();
ProgramWrapper = new ProgramWrapper(
(args) =>
Task.Run(() => Program.Main(args)));
Expand Down
1 change: 1 addition & 0 deletions src/Chapter20.Tests/Listing20.02.Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public class ProgramTests : BaseProgramTests
[ClassInitialize]
public static void ClassInitialize(TestContext _)
{
Program.HttpClient = GetMockedHttpClient();
ProgramWrapper = new ProgramWrapper(
(args) =>
Task.Run(() => Program.Main(args)));
Expand Down
1 change: 1 addition & 0 deletions src/Chapter20.Tests/Listing20.03.Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public class ProgramTests : BaseProgramTests
[ClassInitialize]
public static void ClassInitialize(TestContext _)
{
Program.HttpClient = GetMockedHttpClient();
ProgramWrapper = new ProgramWrapper(
(args) =>
Task.Run(() => Program.Main(args)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_01;

public static class Program
{
public static HttpClient HttpClient { get; set; } = new();
public const string DefaultUrl = "https://IntelliTect.com";

public static void Main(string[] args)
Expand All @@ -28,9 +29,8 @@ public static void Main(string[] args)
$"Searching for '{findText}' at URL '{url}'.");

Console.WriteLine("Downloading...");
using WebClient webClient = new();
byte[] downloadData =
webClient.DownloadData(url);
HttpClient.GetByteArrayAsync(url).Result;

Console.WriteLine("Searching...");
int textOccurrenceCount = CountOccurrences(
Expand Down
4 changes: 2 additions & 2 deletions src/Chapter20/Listing20.02.AsynchronousWebRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_02;

public static class Program
{
public static HttpClient HttpClient { get; set; } = new();
public const string DefaultUrl = "https://IntelliTect.com";

public static void Main(string[] args)
Expand All @@ -29,9 +30,8 @@ public static void Main(string[] args)
Console.WriteLine(
$"Searching for '{findText}' at URL '{url}'.");

using WebClient webClient = new();
Console.Write("Downloading...");
Task task = webClient.DownloadDataTaskAsync(url)
Task task = HttpClient.GetByteArrayAsync(url)
.ContinueWith(antecedent =>
{
byte[] downloadData = antecedent.Result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_03;
#region INCLUDE
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

public static class Program
{
public static HttpClient HttpClient { get; set; } = new();
public const string DefaultUrl = "https://IntelliTect.com";

public static async Task Main(string[] args)
Expand All @@ -28,9 +28,8 @@ public static async Task Main(string[] args)
Console.WriteLine(
$"Searching for '{findText}' at URL '{url}'.");

using WebClient webClient = new();
Task<byte[]> taskDownload =
webClient.DownloadDataTaskAsync(url);
HttpClient.GetByteArrayAsync(url);

Console.Write("Downloading...");
while (!taskDownload.Wait(100))
Expand Down
Loading