Skip to content

Commit

Permalink
Do not create custom instances of TestAssetsManager in tests, use Sdk…
Browse files Browse the repository at this point in the history
…Test base instead
  • Loading branch information
tmat committed Nov 24, 2024
1 parent ed355b0 commit a73c47d
Show file tree
Hide file tree
Showing 16 changed files with 147 additions and 167 deletions.
2 changes: 2 additions & 0 deletions test/Microsoft.NET.TestFramework/SdkTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ public abstract class SdkTest
protected SdkTest(ITestOutputHelper log)
{
Log = log;
#pragma warning disable CS0618 // The only allowed caller of TestAssetsManager constructor.
_testAssetsManager = new TestAssetsManager(log);
#pragma warning restore CS0618
}

protected static void WaitForUtcNowToAdvance()
Expand Down
1 change: 1 addition & 0 deletions test/Microsoft.NET.TestFramework/TestAssetsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public class TestAssetsManager

protected ITestOutputHelper Log { get; }

[Obsolete($"Use instance provided by {nameof(SdkTest)}.")]
public TestAssetsManager(ITestOutputHelper log)
{
var testAssetsDirectory = TestContext.Current.TestAssetsDirectory;
Expand Down
6 changes: 2 additions & 4 deletions test/dotnet-watch.Tests/FileSetSerializerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@

namespace Microsoft.DotNet.Watch.UnitTests;

public class FileSetSerializerTests(ITestOutputHelper output)
public class FileSetSerializerTests(ITestOutputHelper output) : SdkTest(output)
{
private readonly TestAssetsManager _testAssetManager = new (output);

private static string Serialize(MSBuildFileSetResult fileSetResult, Stream stream)
{
foreach (var item in fileSetResult.Projects.Values)
Expand Down Expand Up @@ -102,7 +100,7 @@ public async Task Roundtrip()
[Fact]
public async Task Task()
{
var dir = _testAssetManager.CreateTestDirectory().Path;
var dir = _testAssetsManager.CreateTestDirectory().Path;
var outputPath = Path.Combine(dir, "output.txt");

var engine = new MockBuildEngine();
Expand Down
43 changes: 21 additions & 22 deletions test/dotnet-watch.Tests/FileWatcherTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@

namespace Microsoft.DotNet.Watch.UnitTests
{
public class FileWatcherTests(ITestOutputHelper output)
public class FileWatcherTests(ITestOutputHelper output) : SdkTest(output)
{
private readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(60);
private readonly TimeSpan NegativeTimeout = TimeSpan.FromSeconds(5);
private readonly TestAssetsManager _testAssetManager = new TestAssetsManager(output);
private static readonly TimeSpan s_defaultTimeout = TimeSpan.FromSeconds(60);
private static readonly TimeSpan s_negativeTimeout = TimeSpan.FromSeconds(5);

private async Task TestOperation(
string dir,
Expand All @@ -18,7 +17,7 @@ private async Task TestOperation(
using var watcher = FileWatcherFactory.CreateWatcher(dir, usePolling);
if (watcher is EventBasedDirectoryWatcher dotnetWatcher)
{
dotnetWatcher.Logger = m => output.WriteLine(m);
dotnetWatcher.Logger = m => Log.WriteLine(m);
}

var changedEv = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
Expand All @@ -29,11 +28,11 @@ private async Task TestOperation(
{
if (filesChanged.Add(f))
{
output.WriteLine($"Observed new {f.kind}: '{f.path}' ({filesChanged.Count} out of {expectedChanges.Length})");
Log.WriteLine($"Observed new {f.kind}: '{f.path}' ({filesChanged.Count} out of {expectedChanges.Length})");
}
else
{
output.WriteLine($"Already seen {f.kind}: '{f.path}'");
Log.WriteLine($"Already seen {f.kind}: '{f.path}'");
}
if (filesChanged.Count == expectedChanges.Length)
Expand All @@ -57,7 +56,7 @@ private async Task TestOperation(

operation();

await changedEv.Task.TimeoutAfter(DefaultTimeout);
await changedEv.Task.TimeoutAfter(s_defaultTimeout);
AssertEx.SequenceEqual(expectedChanges, filesChanged.Order());
}

Expand All @@ -66,7 +65,7 @@ private async Task TestOperation(
[InlineData(false)]
public async Task NewFile(bool usePolling)
{
var dir = _testAssetManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;
var dir = _testAssetsManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;

var testFileFullPath = Path.Combine(dir, "foo");

Expand All @@ -91,7 +90,7 @@ await TestOperation(
[InlineData(false)]
public async Task NewFileInNewDirectory(bool usePolling)
{
var dir = _testAssetManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;
var dir = _testAssetsManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;

var newDir = Path.Combine(dir, "Dir");
var newFile = Path.Combine(newDir, "foo");
Expand Down Expand Up @@ -122,7 +121,7 @@ await TestOperation(
[InlineData(false)]
public async Task ChangeFile(bool usePolling)
{
var dir = _testAssetManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;
var dir = _testAssetsManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;

var testFileFullPath = Path.Combine(dir, "foo");
File.WriteAllText(testFileFullPath, string.Empty);
Expand All @@ -138,7 +137,7 @@ await TestOperation(
[CombinatorialData]
public async Task MoveFile(bool usePolling)
{
var dir = _testAssetManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;
var dir = _testAssetsManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;
var srcFile = Path.Combine(dir, "foo");
var dstFile = Path.Combine(dir, "foo2");

Expand Down Expand Up @@ -167,7 +166,7 @@ await TestOperation(
[Fact]
public async Task FileInSubdirectory()
{
var dir = _testAssetManager.CreateTestDirectory().Path;
var dir = _testAssetsManager.CreateTestDirectory().Path;
var subdir = Path.Combine(dir, "subdir");
Directory.CreateDirectory(subdir);
Expand All @@ -190,7 +189,7 @@ await TestOperation(
[InlineData(false)]
public async Task NoNotificationIfDisabled(bool usePolling)
{
var dir = _testAssetManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;
var dir = _testAssetsManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;
using var watcher = FileWatcherFactory.CreateWatcher(dir, usePolling);
Expand All @@ -211,15 +210,15 @@ public async Task NoNotificationIfDisabled(bool usePolling)
}
File.WriteAllText(testFileFullPath, string.Empty);
await Assert.ThrowsAsync<TimeoutException>(() => changedEv.Task.TimeoutAfter(NegativeTimeout));
await Assert.ThrowsAsync<TimeoutException>(() => changedEv.Task.TimeoutAfter(s_negativeTimeout));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task DisposedNoEvents(bool usePolling)
{
var dir = _testAssetManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;
var dir = _testAssetsManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;
var changedEv = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using (var watcher = FileWatcherFactory.CreateWatcher(dir, usePolling))
{
Expand All @@ -238,15 +237,15 @@ public async Task DisposedNoEvents(bool usePolling)
}
File.WriteAllText(testFileFullPath, string.Empty);
await Assert.ThrowsAsync<TimeoutException>(() => changedEv.Task.TimeoutAfter(NegativeTimeout));
await Assert.ThrowsAsync<TimeoutException>(() => changedEv.Task.TimeoutAfter(s_negativeTimeout));
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task MultipleFiles(bool usePolling)
{
var dir = _testAssetManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;
var dir = _testAssetsManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;

File.WriteAllText(Path.Combine(dir, "foo1"), string.Empty);
File.WriteAllText(Path.Combine(dir, "foo2"), string.Empty);
Expand Down Expand Up @@ -274,7 +273,7 @@ await TestOperation(
[InlineData(false)]
public async Task MultipleTriggers(bool usePolling)
{
var dir = _testAssetManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;
var dir = _testAssetsManager.CreateTestDirectory(identifier: usePolling.ToString()).Path;

using var watcher = FileWatcherFactory.CreateWatcher(dir, usePolling);

Expand All @@ -294,7 +293,7 @@ private async Task AssertFileChangeRaisesEvent(string directory, IDirectoryWatch
var expectedPath = Path.Combine(directory, Path.GetRandomFileName());
EventHandler<(string, ChangeKind)> handler = (_, f) =>
{
output.WriteLine("File changed: " + f);
Log.WriteLine("File changed: " + f);
try
{
if (string.Equals(f.Item1, expectedPath, StringComparison.OrdinalIgnoreCase))
Expand All @@ -321,7 +320,7 @@ private async Task AssertFileChangeRaisesEvent(string directory, IDirectoryWatch
// watcher will not detect the change
await Task.Delay(1000);
File.AppendAllText(expectedPath, " ");
await changedEv.Task.TimeoutAfter(DefaultTimeout);
await changedEv.Task.TimeoutAfter(s_defaultTimeout);
}
finally
{
Expand All @@ -334,7 +333,7 @@ private async Task AssertFileChangeRaisesEvent(string directory, IDirectoryWatch
[InlineData(false)]
public async Task DeleteSubfolder(bool usePolling)
{
var dir = _testAssetManager.CreateTestDirectory(usePolling.ToString()).Path;
var dir = _testAssetsManager.CreateTestDirectory(usePolling.ToString()).Path;

var subdir = Path.Combine(dir, "subdir");
Directory.CreateDirectory(subdir);
Expand Down
36 changes: 18 additions & 18 deletions test/dotnet-watch.Tests/HotReload/ApplyDeltaTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ public class ApplyDeltaTests(ITestOutputHelper logger) : DotNetWatchTestBase(log
[Fact]
public async Task AddSourceFile()
{
Logger.WriteLine("AddSourceFile started");
LogMessage("AddSourceFile started");

var testAsset = TestAssets.CopyTestAsset("WatchAppWithProjectDeps")
var testAsset = _testAssetsManager.CopyTestAsset("WatchAppWithProjectDeps")
.WithSource();

var dependencyDir = Path.Combine(testAsset.Path, "Dependency");
Expand Down Expand Up @@ -43,7 +43,7 @@ public static void Print()
[Fact]
public async Task ChangeFileInDependency()
{
var testAsset = TestAssets.CopyTestAsset("WatchAppWithProjectDeps")
var testAsset = _testAssetsManager.CopyTestAsset("WatchAppWithProjectDeps")
.WithSource();

var dependencyDir = Path.Combine(testAsset.Path, "Dependency");
Expand All @@ -68,7 +68,7 @@ public static void Print()
[Fact]
public async Task ChangeFileInFSharpProject()
{
var testAsset = TestAssets.CopyTestAsset("FSharpTestAppSimple")
var testAsset = _testAssetsManager.CopyTestAsset("FSharpTestAppSimple")
.WithSource();

App.Start(testAsset, []);
Expand All @@ -83,7 +83,7 @@ public async Task ChangeFileInFSharpProject()
[Fact]
public async Task ChangeFileInFSharpProjectWithLoop()
{
var testAsset = TestAssets.CopyTestAsset("FSharpTestAppSimple")
var testAsset = _testAssetsManager.CopyTestAsset("FSharpTestAppSimple")
.WithSource();

var source = """
Expand Down Expand Up @@ -123,7 +123,7 @@ open System.Threading
[CoreMSBuildOnlyFact]
public async Task HandleTypeLoadFailure()
{
var testAsset = TestAssets.CopyTestAsset("WatchAppTypeLoadFailure")
var testAsset = _testAssetsManager.CopyTestAsset("WatchAppTypeLoadFailure")
.WithSource();

App.Start(testAsset, [], "App");
Expand Down Expand Up @@ -153,7 +153,7 @@ public static void Print()
[Fact]
public async Task MetadataUpdateHandler_NoActions()
{
var testAsset = TestAssets.CopyTestAsset("WatchHotReloadApp")
var testAsset = _testAssetsManager.CopyTestAsset("WatchHotReloadApp")
.WithSource();

var sourcePath = Path.Combine(testAsset.Path, "Program.cs");
Expand Down Expand Up @@ -186,7 +186,7 @@ await App.WaitUntilOutputContains(
[CombinatorialData]
public async Task MetadataUpdateHandler_Exception(bool verbose)
{
var testAsset = TestAssets.CopyTestAsset("WatchHotReloadApp", identifier: verbose.ToString())
var testAsset = _testAssetsManager.CopyTestAsset("WatchHotReloadApp", identifier: verbose.ToString())
.WithSource();

var sourcePath = Path.Combine(testAsset.Path, "Program.cs");
Expand Down Expand Up @@ -234,7 +234,7 @@ class AppUpdateHandler
[Fact]
public async Task BlazorWasm()
{
var testAsset = TestAssets.CopyTestAsset("WatchBlazorWasm")
var testAsset = _testAssetsManager.CopyTestAsset("WatchBlazorWasm")
.WithSource();

var port = TestOptions.GetTestPort();
Expand All @@ -261,7 +261,7 @@ public async Task BlazorWasm()
[Fact]
public async Task BlazorWasm_MSBuildWarning()
{
var testAsset = TestAssets
var testAsset = _testAssetsManager
.CopyTestAsset("WatchBlazorWasm")
.WithSource()
.WithProjectChanges(proj =>
Expand All @@ -284,7 +284,7 @@ public async Task BlazorWasm_MSBuildWarning()
[CoreMSBuildOnlyFact]
public async Task HandleMissingAssemblyFailure()
{
var testAsset = TestAssets.CopyTestAsset("WatchAppMissingAssemblyFailure")
var testAsset = _testAssetsManager.CopyTestAsset("WatchAppMissingAssemblyFailure")
.WithSource();

App.Start(testAsset, [], "App");
Expand Down Expand Up @@ -322,9 +322,9 @@ public static void Print()
[InlineData(false)]
public async Task RenameSourceFile(bool useMove)
{
Logger.WriteLine("RenameSourceFile started");
LogMessage("RenameSourceFile started");

var testAsset = TestAssets.CopyTestAsset("WatchAppWithProjectDeps")
var testAsset = _testAssetsManager.CopyTestAsset("WatchAppWithProjectDeps")
.WithSource();

var dependencyDir = Path.Combine(testAsset.Path, "Dependency");
Expand Down Expand Up @@ -364,7 +364,7 @@ public static void PrintFileName([CallerFilePathAttribute] string filePath = nul
File.WriteAllText(newFilePath, source);
}

Logger.WriteLine($"Renamed '{oldFilePath}' to '{newFilePath}'.");
LogMessage($"Renamed '{oldFilePath}' to '{newFilePath}'.");

await App.AssertOutputLineStartsWith("> Renamed.cs");
}
Expand All @@ -374,9 +374,9 @@ public static void PrintFileName([CallerFilePathAttribute] string filePath = nul
[InlineData(false)]
public async Task RenameDirectory(bool useMove)
{
Logger.WriteLine("RenameSourceFile started");
LogMessage("RenameSourceFile started");

var testAsset = TestAssets.CopyTestAsset("WatchAppWithProjectDeps")
var testAsset = _testAssetsManager.CopyTestAsset("WatchAppWithProjectDeps")
.WithSource();

var dependencyDir = Path.Combine(testAsset.Path, "Dependency");
Expand Down Expand Up @@ -419,15 +419,15 @@ public static void PrintDirectoryName([CallerFilePathAttribute] string filePath
File.WriteAllText(Path.Combine(newSubdir, "Foo.cs"), source);
}

Logger.WriteLine($"Renamed '{oldSubdir}' to '{newSubdir}'.");
LogMessage($"Renamed '{oldSubdir}' to '{newSubdir}'.");

await App.AssertOutputLineStartsWith("> NewSubdir");
}

[Fact]
public async Task Aspire()
{
var testAsset = TestAssets.CopyTestAsset("WatchAspire")
var testAsset = _testAssetsManager.CopyTestAsset("WatchAspire")
.WithSource();

var serviceSourcePath = Path.Combine(testAsset.Path, "WatchAspire.ApiService", "Program.cs");
Expand Down
4 changes: 2 additions & 2 deletions test/dotnet-watch.Tests/HotReload/CompilationHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ public class CompilationHandlerTests(ITestOutputHelper logger) : DotNetWatchTest
[Fact]
public async Task ReferenceOutputAssembly_False()
{
var testAsset = TestAssets.CopyTestAsset("WatchAppMultiProc")
var testAsset = _testAssetsManager.CopyTestAsset("WatchAppMultiProc")
.WithSource();

var workingDirectory = testAsset.Path;
var hostDir = Path.Combine(testAsset.Path, "Host");
var hostProject = Path.Combine(hostDir, "Host.csproj");

var reporter = new TestReporter(Logger);
var reporter = new TestReporter(Log);
var options = TestOptions.GetProjectOptions(["--project", hostProject]);

var factory = new MSBuildFileSetFactory(
Expand Down
Loading

0 comments on commit a73c47d

Please sign in to comment.