diff --git a/test/Microsoft.NET.TestFramework/SdkTest.cs b/test/Microsoft.NET.TestFramework/SdkTest.cs index 57403ba29a0d..30c629d522c6 100644 --- a/test/Microsoft.NET.TestFramework/SdkTest.cs +++ b/test/Microsoft.NET.TestFramework/SdkTest.cs @@ -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() diff --git a/test/Microsoft.NET.TestFramework/TestAssetsManager.cs b/test/Microsoft.NET.TestFramework/TestAssetsManager.cs index 17a4fa411dab..db19220796fd 100644 --- a/test/Microsoft.NET.TestFramework/TestAssetsManager.cs +++ b/test/Microsoft.NET.TestFramework/TestAssetsManager.cs @@ -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; diff --git a/test/dotnet-watch.Tests/FileSetSerializerTests.cs b/test/dotnet-watch.Tests/FileSetSerializerTests.cs index 94c6b8577086..c83606535b93 100644 --- a/test/dotnet-watch.Tests/FileSetSerializerTests.cs +++ b/test/dotnet-watch.Tests/FileSetSerializerTests.cs @@ -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) @@ -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(); diff --git a/test/dotnet-watch.Tests/FileWatcherTests.cs b/test/dotnet-watch.Tests/FileWatcherTests.cs index ab12f6c40f45..9a3da7ca1420 100644 --- a/test/dotnet-watch.Tests/FileWatcherTests.cs +++ b/test/dotnet-watch.Tests/FileWatcherTests.cs @@ -1,13 +1,14 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable + 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, @@ -18,35 +19,47 @@ 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 barrierDir = Path.Combine(dir, ".barrier"); + var seenBarrier = false; var changedEv = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var filesChanged = new HashSet<(string path, ChangeKind kind)>(); - EventHandler<(string path, ChangeKind kind)> handler = null; + EventHandler<(string path, ChangeKind kind)>? handler = null; handler = (_, f) => { - if (filesChanged.Add(f)) + if (!seenBarrier) { - output.WriteLine($"Observed new {f.kind}: '{f.path}' ({filesChanged.Count} out of {expectedChanges.Length})"); + seenBarrier = f.kind == ChangeKind.Add && f.path == barrierDir; } else { - output.WriteLine($"Already seen {f.kind}: '{f.path}'"); - } + if (filesChanged.Add(f)) + { + Log.WriteLine($"Observed new {f.kind}: '{f.path}' ({filesChanged.Count} out of {expectedChanges.Length})"); + } + else + { + Log.WriteLine($"Already seen {f.kind}: '{f.path}'"); + } - if (filesChanged.Count == expectedChanges.Length) - { - watcher.EnableRaisingEvents = false; - watcher.OnFileChange -= handler; - changedEv.TrySetResult(); + if (filesChanged.Count == expectedChanges.Length) + { + watcher.EnableRaisingEvents = false; + watcher.OnFileChange -= handler; + changedEv.TrySetResult(); + } } }; watcher.OnFileChange += handler; watcher.EnableRaisingEvents = true; + // Create a barrier directory. Only start registering events once the barrier add event is received. + Directory.CreateDirectory(barrierDir); + if (usePolling) { // On Unix the file write time is in 1s increments; @@ -57,7 +70,7 @@ private async Task TestOperation( operation(); - await changedEv.Task.TimeoutAfter(DefaultTimeout); + await changedEv.Task.TimeoutAfter(s_defaultTimeout); AssertEx.SequenceEqual(expectedChanges, filesChanged.Order()); } @@ -66,7 +79,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"); @@ -91,7 +104,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"); @@ -122,7 +135,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); @@ -138,7 +151,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"); @@ -167,7 +180,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); @@ -190,7 +203,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); @@ -211,7 +224,7 @@ public async Task NoNotificationIfDisabled(bool usePolling) } File.WriteAllText(testFileFullPath, string.Empty); - await Assert.ThrowsAsync(() => changedEv.Task.TimeoutAfter(NegativeTimeout)); + await Assert.ThrowsAsync(() => changedEv.Task.TimeoutAfter(s_negativeTimeout)); } [Theory] @@ -219,7 +232,7 @@ public async Task NoNotificationIfDisabled(bool usePolling) [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)) { @@ -238,7 +251,7 @@ public async Task DisposedNoEvents(bool usePolling) } File.WriteAllText(testFileFullPath, string.Empty); - await Assert.ThrowsAsync(() => changedEv.Task.TimeoutAfter(NegativeTimeout)); + await Assert.ThrowsAsync(() => changedEv.Task.TimeoutAfter(s_negativeTimeout)); } [Theory] @@ -246,7 +259,7 @@ public async Task DisposedNoEvents(bool usePolling) [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); @@ -274,7 +287,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); @@ -294,7 +307,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)) @@ -321,7 +334,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 { @@ -334,7 +347,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); @@ -349,30 +362,8 @@ public async Task DeleteSubfolder(bool usePolling) await TestOperation( dir, - expectedChanges: usePolling ? - [ - (subdir, ChangeKind.Delete), - (f1, ChangeKind.Delete), - (f2, ChangeKind.Delete), - (f3, ChangeKind.Delete), - ] - : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? - [ - (subdir, ChangeKind.Add), - (subdir, ChangeKind.Delete), - (f1, ChangeKind.Update), - (f1, ChangeKind.Add), - (f1, ChangeKind.Delete), - (f2, ChangeKind.Update), - (f2, ChangeKind.Add), - (f2, ChangeKind.Delete), - (f3, ChangeKind.Update), - (f3, ChangeKind.Add), - (f3, ChangeKind.Delete), - ] - : RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? + expectedChanges: usePolling || !RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? [ - (subdir, ChangeKind.Update), (subdir, ChangeKind.Delete), (f1, ChangeKind.Delete), (f2, ChangeKind.Delete), @@ -380,6 +371,7 @@ await TestOperation( ] : [ + (subdir, ChangeKind.Update), (subdir, ChangeKind.Delete), (f1, ChangeKind.Delete), (f2, ChangeKind.Delete), diff --git a/test/dotnet-watch.Tests/HotReload/ApplyDeltaTests.cs b/test/dotnet-watch.Tests/HotReload/ApplyDeltaTests.cs index 275dab47e8f0..901798e007d2 100644 --- a/test/dotnet-watch.Tests/HotReload/ApplyDeltaTests.cs +++ b/test/dotnet-watch.Tests/HotReload/ApplyDeltaTests.cs @@ -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"); @@ -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"); @@ -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, []); @@ -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 = """ @@ -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"); @@ -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"); @@ -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"); @@ -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(); @@ -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 => @@ -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"); @@ -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"); @@ -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"); } @@ -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"); @@ -419,7 +419,7 @@ 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"); } @@ -427,7 +427,7 @@ public static void PrintDirectoryName([CallerFilePathAttribute] string filePath [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"); diff --git a/test/dotnet-watch.Tests/HotReload/CompilationHandlerTests.cs b/test/dotnet-watch.Tests/HotReload/CompilationHandlerTests.cs index 5720c24cc6cd..766f5a7d97e5 100644 --- a/test/dotnet-watch.Tests/HotReload/CompilationHandlerTests.cs +++ b/test/dotnet-watch.Tests/HotReload/CompilationHandlerTests.cs @@ -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( diff --git a/test/dotnet-watch.Tests/HotReload/RuntimeProcessLauncherTests.cs b/test/dotnet-watch.Tests/HotReload/RuntimeProcessLauncherTests.cs index c4ab7b0db357..b7331c379709 100644 --- a/test/dotnet-watch.Tests/HotReload/RuntimeProcessLauncherTests.cs +++ b/test/dotnet-watch.Tests/HotReload/RuntimeProcessLauncherTests.cs @@ -15,7 +15,7 @@ public enum TriggerEvent } private TestAsset CopyTestAsset(string assetName, params object[] testParameters) - => TestAssets.CopyTestAsset("WatchAppMultiProc", identifier: string.Join(";", testParameters)).WithSource(); + => _testAssetsManager.CopyTestAsset("WatchAppMultiProc", identifier: string.Join(";", testParameters)).WithSource(); private static async Task Launch(string projectPath, TestRuntimeProcessLauncher service, string workingDirectory, CancellationToken cancellationToken) { @@ -72,8 +72,8 @@ public async Task UpdateAndRudeEdit(TriggerEvent trigger) var libProject = Path.Combine(libDir, "Lib.csproj"); var libSource = Path.Combine(libDir, "Lib.cs"); - var console = new TestConsole(Logger); - var reporter = new TestReporter(Logger); + var console = new TestConsole(Log); + var reporter = new TestReporter(Log); var program = Program.TryCreate( TestOptions.GetCommandLineOptions(["--verbose", "--non-interactive", "--project", hostProject]), @@ -136,29 +136,29 @@ public async Task UpdateAndRudeEdit(TriggerEvent trigger) await launchCompletionB.Task; // let the host process start: - Log("Waiting for changes..."); + LogMessage("Waiting for changes..."); await waitingForChanges.WaitAsync(); - Log("Waiting for session started..."); + LogMessage("Waiting for session started..."); await sessionStarted.WaitAsync(); await MakeRudeEditChange(); - Log("Waiting for changed handled ..."); + LogMessage("Waiting for changed handled ..."); await changeHandled.WaitAsync(); // Wait for project baselines to be updated, so that we capture the new solution snapshot // and further changes are treated as another update. - Log("Waiting for baselines updated..."); + LogMessage("Waiting for baselines updated..."); await projectBaselinesUpdated.WaitAsync(); await MakeValidDependencyChange(); - Log("Waiting for changed handled ..."); + LogMessage("Waiting for changed handled ..."); await changeHandled.WaitAsync(); // clean up: - Log("Shutting down"); + LogMessage("Shutting down"); watchCancellationSource.Cancel(); try { @@ -215,10 +215,10 @@ public static void Common() } """); - Log("Waiting for updated output from project A ..."); + LogMessage("Waiting for updated output from project A ..."); await hasUpdateSourceA.Task; - Log("Waiting for updated output from project B ..."); + LogMessage("Waiting for updated output from project B ..."); await hasUpdateSourceB.Task; Assert.True(hasUpdateSourceA.Task.IsCompletedSuccessfully); @@ -244,7 +244,7 @@ async Task MakeRudeEditChange() [assembly: System.Reflection.AssemblyMetadata("TestAssemblyMetadata", "2")] """); - Log("Waiting for updated output from project A ..."); + LogMessage("Waiting for updated output from project A ..."); await hasUpdateSource.Task; Assert.True(hasUpdateSource.Task.IsCompletedSuccessfully); @@ -275,8 +275,8 @@ public async Task UpdateAppliedToNewProcesses(bool sharedOutput) var libProject = Path.Combine(libDir, "Lib.csproj"); var libSource = Path.Combine(libDir, "Lib.cs"); - var console = new TestConsole(Logger); - var reporter = new TestReporter(Logger); + var console = new TestConsole(Log); + var reporter = new TestReporter(Log); var program = Program.TryCreate( TestOptions.GetCommandLineOptions(["--verbose", "--non-interactive", "--project", hostProject]), @@ -325,7 +325,7 @@ public async Task UpdateAppliedToNewProcesses(bool sharedOutput) }; // let the host process start: - Log("Waiting for changes..."); + LogMessage("Waiting for changes..."); await waitingForChanges.WaitAsync(); // service should have been created before Hot Reload session started: @@ -346,27 +346,27 @@ public static void Common() } """); - Log("Waiting for updated output from A ..."); + LogMessage("Waiting for updated output from A ..."); await hasUpdateA.WaitAsync(); // Host and ServiceA received updates: - Log("Waiting for updates applied 1/2 ..."); + LogMessage("Waiting for updates applied 1/2 ..."); await updatesApplied.WaitAsync(); - Log("Waiting for updates applied 2/2 ..."); + LogMessage("Waiting for updates applied 2/2 ..."); await updatesApplied.WaitAsync(); await Launch(serviceProjectB, service, workingDirectory, watchCancellationSource.Token); // ServiceB received updates: - Log("Waiting for updates applied ..."); + LogMessage("Waiting for updates applied ..."); await updatesApplied.WaitAsync(); - Log("Waiting for updated output from B ..."); + LogMessage("Waiting for updated output from B ..."); await hasUpdateB.WaitAsync(); // clean up: - Log("Shutting down"); + LogMessage("Shutting down"); watchCancellationSource.Cancel(); try { @@ -397,8 +397,8 @@ public async Task HostRestart(UpdateLocation updateLocation) var libProject = Path.Combine(testAsset.Path, "Lib2", "Lib2.csproj"); var lib = Path.Combine(testAsset.Path, "Lib2", "Lib2.cs"); - var console = new TestConsole(Logger); - var reporter = new TestReporter(Logger); + var console = new TestConsole(Log); + var reporter = new TestReporter(Log); var program = Program.TryCreate( TestOptions.GetCommandLineOptions(["--verbose", "--project", hostProject]), @@ -445,7 +445,7 @@ public async Task HostRestart(UpdateLocation updateLocation) await Task.Delay(TimeSpan.FromSeconds(1)); // let the host process start: - Log("Waiting for changes..."); + LogMessage("Waiting for changes..."); await waitingForChanges.WaitAsync(); switch (updateLocation) @@ -464,7 +464,7 @@ public static void Print() """); // Host received Hot Reload updates: - Log("Waiting for change handled ..."); + LogMessage("Waiting for change handled ..."); await changeHandled.WaitAsync(); break; @@ -473,7 +473,7 @@ public static void Print() UpdateSourceFile(hostProgram, content => content.Replace("Waiting", "")); // Host received Hot Reload updates: - Log("Waiting for change handled ..."); + LogMessage("Waiting for change handled ..."); await changeHandled.WaitAsync(); break; @@ -482,17 +482,17 @@ public static void Print() UpdateSourceFile(hostProgram, content => content.Replace("Started", "")); // ⚠ ENC0118: Changing 'top-level code' might not have any effect until the application is restarted. Press "Ctrl + R" to restart. - Log("Waiting for restart needed ..."); + LogMessage("Waiting for restart needed ..."); await restartNeeded.WaitAsync(); console.PressKey(new ConsoleKeyInfo('R', ConsoleKey.R, shift: false, alt: false, control: true)); - Log("Waiting for restart requested ..."); + LogMessage("Waiting for restart requested ..."); await restartRequested.WaitAsync(); break; } - Log("Waiting updated output from Host ..."); + LogMessage("Waiting updated output from Host ..."); await hasUpdate.WaitAsync(); // clean up: @@ -518,8 +518,8 @@ public async Task RudeEditInProjectWithoutRunningProcess() var serviceSourceA2 = Path.Combine(serviceDirA, "A2.cs"); var serviceProjectA = Path.Combine(serviceDirA, "A.csproj"); - var console = new TestConsole(Logger); - var reporter = new TestReporter(Logger); + var console = new TestConsole(Log); + var reporter = new TestReporter(Log); var program = Program.TryCreate( TestOptions.GetCommandLineOptions(["--verbose", "--non-interactive", "--project", hostProject]), @@ -548,14 +548,14 @@ public async Task RudeEditInProjectWithoutRunningProcess() var sessionStarted = reporter.RegisterSemaphore(MessageDescriptor.HotReloadSessionStarted); // let the host process start: - Log("Waiting for changes..."); + LogMessage("Waiting for changes..."); await waitingForChanges.WaitAsync(); // service should have been created before Hot Reload session started: Assert.NotNull(service); var runningProject = await Launch(serviceProjectA, service, workingDirectory, watchCancellationSource.Token); - Log("Waiting for session started ..."); + LogMessage("Waiting for session started ..."); await sessionStarted.WaitAsync(); // Terminate the process: @@ -566,7 +566,7 @@ public async Task RudeEditInProjectWithoutRunningProcess() [assembly: System.Reflection.AssemblyMetadata("TestAssemblyMetadata", "2")] """); - Log("Waiting for change handled ..."); + LogMessage("Waiting for change handled ..."); await changeHandled.WaitAsync(); reporter.ProcessOutput.Contains("verbose ⌚ Rude edits detected but do not affect any running process"); diff --git a/test/dotnet-watch.Tests/LaunchSettingsProfileTest.cs b/test/dotnet-watch.Tests/LaunchSettingsProfileTest.cs index c520c36f330b..b785eed22ff9 100644 --- a/test/dotnet-watch.Tests/LaunchSettingsProfileTest.cs +++ b/test/dotnet-watch.Tests/LaunchSettingsProfileTest.cs @@ -3,21 +3,14 @@ namespace Microsoft.DotNet.Watch.UnitTests; -public class LaunchSettingsProfileTest +public class LaunchSettingsProfileTest(ITestOutputHelper output) : SdkTest(output) { - private readonly IReporter _reporter; - private readonly TestAssetsManager _testAssets; - - public LaunchSettingsProfileTest(ITestOutputHelper output) - { - _reporter = new TestReporter(output); - _testAssets = new TestAssetsManager(output); - } + private readonly IReporter _reporter = new TestReporter(output); [Fact] public void LoadsLaunchProfiles() { - var project = _testAssets.CreateTestProject(new TestProject("Project1") + var project = _testAssetsManager.CreateTestProject(new TestProject("Project1") { TargetFrameworks = ToolsetInfo.CurrentTargetFramework, }); diff --git a/test/dotnet-watch.Tests/MsBuildFileSetFactoryTest.cs b/test/dotnet-watch.Tests/MsBuildFileSetFactoryTest.cs index febeb098195a..149f7e45f692 100644 --- a/test/dotnet-watch.Tests/MsBuildFileSetFactoryTest.cs +++ b/test/dotnet-watch.Tests/MsBuildFileSetFactoryTest.cs @@ -5,10 +5,9 @@ namespace Microsoft.DotNet.Watch.UnitTests { - public class MsBuildFileSetFactoryTest(ITestOutputHelper output) + public class MsBuildFileSetFactoryTest(ITestOutputHelper output) : SdkTest(output) { private readonly TestReporter _reporter = new(output); - private readonly TestAssetsManager _testAssets = new(output); private string MuxerPath => TestContext.Current.ToolsetUnderTest.DotNetHostPath; @@ -24,7 +23,7 @@ private static IEnumerable Inspect(string rootDir, IReadOnlyDictionary @@ -192,7 +191,7 @@ public async Task IncludesContentFiles() [Fact] public async Task IncludesContentFilesFromRCL() { - var testDir = _testAssets.CreateTestDirectory(); + var testDir = _testAssetsManager.CreateTestDirectory(); WriteFile( testDir, Path.Combine("RCL1", "RCL1.csproj"), @@ -244,12 +243,12 @@ public async Task IncludesContentFilesFromRCL() [Fact] public async Task ProjectReferences_OneLevel() { - var project2 = _testAssets.CreateTestProject(new TestProject("Project2") + var project2 = _testAssetsManager.CreateTestProject(new TestProject("Project2") { TargetFrameworks = "netstandard2.0", }); - var project1 = _testAssets.CreateTestProject(new TestProject("Project1") + var project1 = _testAssetsManager.CreateTestProject(new TestProject("Project1") { TargetFrameworks = $"{ToolsetInfo.CurrentTargetFramework};net462", ReferencedProjects = { project2.TestProject, }, @@ -273,18 +272,18 @@ public async Task ProjectReferences_OneLevel() [Fact] public async Task TransitiveProjectReferences_TwoLevels() { - var project3 = _testAssets.CreateTestProject(new TestProject("Project3") + var project3 = _testAssetsManager.CreateTestProject(new TestProject("Project3") { TargetFrameworks = "netstandard2.0", }); - var project2 = _testAssets.CreateTestProject(new TestProject("Project2") + var project2 = _testAssetsManager.CreateTestProject(new TestProject("Project2") { TargetFrameworks = "netstandard2.0", ReferencedProjects = { project3.TestProject }, }); - var project1 = _testAssets.CreateTestProject(new TestProject("Project1") + var project1 = _testAssetsManager.CreateTestProject(new TestProject("Project1") { TargetFrameworks = $"{ToolsetInfo.CurrentTargetFramework};net462", ReferencedProjects = { project2.TestProject }, @@ -320,7 +319,7 @@ public async Task ProjectReferences_Graph() // G->E // W->U // Y->B,F,Z - var testDirectory = _testAssets.CopyTestAsset("ProjectReferences_Graph") + var testDirectory = _testAssetsManager.CopyTestAsset("ProjectReferences_Graph") .WithSource() .Path; var projectA = Path.Combine(testDirectory, "A", "A.csproj"); @@ -373,12 +372,12 @@ public async Task ProjectReferences_Graph() [Fact] public async Task MsbuildOutput() { - var project2 = _testAssets.CreateTestProject(new TestProject("Project2") + var project2 = _testAssetsManager.CreateTestProject(new TestProject("Project2") { TargetFrameworks = "netstandard2.1", }); - var project1 = _testAssets.CreateTestProject(new TestProject("Project1") + var project1 = _testAssetsManager.CreateTestProject(new TestProject("Project1") { TargetFrameworks = $"net462", ReferencedProjects = { project2.TestProject, }, diff --git a/test/dotnet-watch.Tests/Watch/BrowserLaunchTests.cs b/test/dotnet-watch.Tests/Watch/BrowserLaunchTests.cs index fc55382456ac..7bfd6d01fd37 100644 --- a/test/dotnet-watch.Tests/Watch/BrowserLaunchTests.cs +++ b/test/dotnet-watch.Tests/Watch/BrowserLaunchTests.cs @@ -15,7 +15,7 @@ public BrowserLaunchTests(ITestOutputHelper logger) [Fact] public async Task LaunchesBrowserOnStart() { - var testAsset = TestAssets.CopyTestAsset(AppName) + var testAsset = _testAssetsManager.CopyTestAsset(AppName) .WithSource(); App.Start(testAsset, [], testFlags: TestFlags.MockBrowser); @@ -33,7 +33,7 @@ public async Task LaunchesBrowserOnStart() [Fact] public async Task UsesBrowserSpecifiedInEnvironment() { - var testAsset = TestAssets.CopyTestAsset(AppName) + var testAsset = _testAssetsManager.CopyTestAsset(AppName) .WithSource(); App.EnvironmentVariables.Add("DOTNET_WATCH_BROWSER_PATH", "mycustombrowser.bat"); diff --git a/test/dotnet-watch.Tests/Watch/DotNetWatcherTests.cs b/test/dotnet-watch.Tests/Watch/DotNetWatcherTests.cs index d011b12fcd1e..7f27d3256319 100644 --- a/test/dotnet-watch.Tests/Watch/DotNetWatcherTests.cs +++ b/test/dotnet-watch.Tests/Watch/DotNetWatcherTests.cs @@ -19,7 +19,7 @@ public async Task RunsWithDotnetWatchEnvVariable() { Assert.True(string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DOTNET_WATCH")), "DOTNET_WATCH cannot be set already when this test is running"); - var testAsset = TestAssets.CopyTestAsset(AppName) + var testAsset = _testAssetsManager.CopyTestAsset(AppName) .WithSource(); App.Start(testAsset, []); @@ -32,7 +32,7 @@ public async Task RunsWithDotnetLaunchProfileEnvVariableWhenNotExplicitlySpecifi { Assert.True(string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DOTNET_LAUNCH_PROFILE")), "DOTNET_LAUNCH_PROFILE cannot be set already when this test is running"); - var testAsset = TestAssets.CopyTestAsset(AppName, identifier: hotReload.ToString()) + var testAsset = _testAssetsManager.CopyTestAsset(AppName, identifier: hotReload.ToString()) .WithSource(); if (!hotReload) @@ -50,7 +50,7 @@ public async Task RunsWithDotnetLaunchProfileEnvVariableWhenExplicitlySpecified( { Assert.True(string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DOTNET_LAUNCH_PROFILE")), "DOTNET_LAUNCH_PROFILE cannot be set already when this test is running"); - var testAsset = TestAssets.CopyTestAsset(AppName, identifier: hotReload.ToString()) + var testAsset = _testAssetsManager.CopyTestAsset(AppName, identifier: hotReload.ToString()) .WithSource(); if (!hotReload) @@ -70,7 +70,7 @@ public async Task RunsWithDotnetLaunchProfileEnvVariableWhenExplicitlySpecifiedB { Assert.True(string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DOTNET_LAUNCH_PROFILE")), "DOTNET_LAUNCH_PROFILE cannot be set already when this test is running"); - var testAsset = TestAssets.CopyTestAsset(AppName, identifier: hotReload.ToString()) + var testAsset = _testAssetsManager.CopyTestAsset(AppName, identifier: hotReload.ToString()) .WithSource(); if (!hotReload) @@ -85,7 +85,7 @@ public async Task RunsWithDotnetLaunchProfileEnvVariableWhenExplicitlySpecifiedB [Fact] public async Task RunsWithIterationEnvVariable() { - var testAsset = TestAssets.CopyTestAsset(AppName) + var testAsset = _testAssetsManager.CopyTestAsset(AppName) .WithSource(); App.Start(testAsset, []); @@ -111,7 +111,7 @@ public async Task RunsWithIterationEnvVariable() [Fact] public async Task Run_WithHotReloadEnabled_ReadsLaunchSettings() { - var testAsset = TestAssets.CopyTestAsset("WatchAppWithLaunchSettings") + var testAsset = _testAssetsManager.CopyTestAsset("WatchAppWithLaunchSettings") .WithSource(); App.Start(testAsset, []); @@ -122,7 +122,7 @@ public async Task Run_WithHotReloadEnabled_ReadsLaunchSettings() [Fact] public async Task Run_WithHotReloadEnabled_ReadsLaunchSettings_WhenUsingProjectOption() { - var testAsset = TestAssets.CopyTestAsset("WatchAppWithLaunchSettings") + var testAsset = _testAssetsManager.CopyTestAsset("WatchAppWithLaunchSettings") .WithSource(); var directoryInfo = new DirectoryInfo(testAsset.Path); @@ -139,7 +139,7 @@ public async Task Run_WithHotReloadEnabled_ReadsLaunchSettings_WhenUsingProjectO [CoreMSBuildOnlyFact(Skip = "https://github.com/dotnet/sdk/issues/29047")] public async Task Run_WithHotReloadEnabled_DoesNotReadConsoleIn_InNonInteractiveMode() { - var testAsset = TestAssets.CopyTestAsset("WatchAppWithLaunchSettings") + var testAsset = _testAssetsManager.CopyTestAsset("WatchAppWithLaunchSettings") .WithSource(); App.EnvironmentVariables.Add("READ_INPUT", "true"); diff --git a/test/dotnet-watch.Tests/Watch/GlobbingAppTests.cs b/test/dotnet-watch.Tests/Watch/GlobbingAppTests.cs index 48ff617568cc..282cc62ac595 100644 --- a/test/dotnet-watch.Tests/Watch/GlobbingAppTests.cs +++ b/test/dotnet-watch.Tests/Watch/GlobbingAppTests.cs @@ -17,7 +17,7 @@ public GlobbingAppTests(ITestOutputHelper logger) [InlineData(false)] public async Task ChangeCompiledFile(bool usePollingWatcher) { - var testAsset = TestAssets.CopyTestAsset(AppName, identifier: usePollingWatcher.ToString()) + var testAsset = _testAssetsManager.CopyTestAsset(AppName, identifier: usePollingWatcher.ToString()) .WithSource(); App.UsePollingWatcher = usePollingWatcher; @@ -37,7 +37,7 @@ public async Task ChangeCompiledFile(bool usePollingWatcher) [Fact(Skip = "https://github.com/dotnet/sdk/issues/42921")] public async Task DeleteCompiledFile() { - var testAsset = TestAssets.CopyTestAsset(AppName) + var testAsset = _testAssetsManager.CopyTestAsset(AppName) .WithSource(); App.Start(testAsset, ["--no-hot-reload"]); @@ -54,7 +54,7 @@ public async Task DeleteCompiledFile() [Fact(Skip = "https://github.com/dotnet/sdk/issues/42921")] public async Task DeleteSourceFolder() { - var testAsset = TestAssets.CopyTestAsset(AppName) + var testAsset = _testAssetsManager.CopyTestAsset(AppName) .WithSource(); App.Start(testAsset, ["--no-hot-reload"]); @@ -71,7 +71,7 @@ public async Task DeleteSourceFolder() [Fact(Skip = "https://github.com/dotnet/sdk/issues/42921")] public async Task RenameCompiledFile() { - var testAsset = TestAssets.CopyTestAsset(AppName) + var testAsset = _testAssetsManager.CopyTestAsset(AppName) .WithSource(); App.Start(testAsset, ["--no-hot-reload"]); @@ -88,7 +88,7 @@ public async Task RenameCompiledFile() [Fact(Skip = "https://github.com/dotnet/sdk/issues/42921")] public async Task ChangeExcludedFile() { - var testAsset = TestAssets.CopyTestAsset(AppName) + var testAsset = _testAssetsManager.CopyTestAsset(AppName) .WithSource(); App.Start(testAsset, ["--no-hot-reload"]); @@ -106,7 +106,7 @@ public async Task ChangeExcludedFile() [Fact] public async Task ListsFiles() { - var testAsset = TestAssets.CopyTestAsset(AppName) + var testAsset = _testAssetsManager.CopyTestAsset(AppName) .WithSource(); App.DotnetWatchArgs.Clear(); diff --git a/test/dotnet-watch.Tests/Watch/NoDepsAppTests.cs b/test/dotnet-watch.Tests/Watch/NoDepsAppTests.cs index 9614366519d9..1ffefc9d3593 100644 --- a/test/dotnet-watch.Tests/Watch/NoDepsAppTests.cs +++ b/test/dotnet-watch.Tests/Watch/NoDepsAppTests.cs @@ -10,7 +10,7 @@ public class NoDepsAppTests(ITestOutputHelper logger) : DotNetWatchTestBase(logg [Fact(Skip = "https://github.com/dotnet/sdk/issues/42921")] public async Task RestartProcessOnFileChange() { - var testAsset = TestAssets.CopyTestAsset(AppName) + var testAsset = _testAssetsManager.CopyTestAsset(AppName) .WithSource(); App.Start(testAsset, ["--no-hot-reload", "--no-exit"]); @@ -28,7 +28,7 @@ public async Task RestartProcessOnFileChange() [Fact(Skip = "https://github.com/dotnet/sdk/issues/42921")] public async Task RestartProcessThatTerminatesAfterFileChange() { - var testAsset = TestAssets.CopyTestAsset(AppName) + var testAsset = _testAssetsManager.CopyTestAsset(AppName) .WithSource(); App.Start(testAsset, []); diff --git a/test/dotnet-watch.Tests/Watch/ProgramTests.cs b/test/dotnet-watch.Tests/Watch/ProgramTests.cs index 8fc4f2d20d55..b1be97350bde 100644 --- a/test/dotnet-watch.Tests/Watch/ProgramTests.cs +++ b/test/dotnet-watch.Tests/Watch/ProgramTests.cs @@ -8,11 +8,11 @@ public class ProgramTests(ITestOutputHelper logger) : DotNetWatchTestBase(logger [Fact] public async Task ConsoleCancelKey() { - var testAsset = TestAssets.CopyTestAsset("WatchKitchenSink") + var testAsset = _testAssetsManager.CopyTestAsset("WatchKitchenSink") .WithSource(); - var console = new TestConsole(Logger); - var reporter = new TestReporter(Logger); + var console = new TestConsole(Log); + var reporter = new TestReporter(Log); var watching = reporter.RegisterSemaphore(MessageDescriptor.WatchingWithHotReload); var shutdownRequested = reporter.RegisterSemaphore(MessageDescriptor.ShutdownRequested); @@ -53,7 +53,7 @@ public async Task ConsoleCancelKey() [InlineData(new[] { "abc" }, "abc")] public async Task Arguments(string[] arguments, string expectedApplicationArgs) { - var testAsset = TestAssets.CopyTestAsset("WatchHotReloadApp", identifier: string.Join(",", arguments)) + var testAsset = _testAssetsManager.CopyTestAsset("WatchHotReloadApp", identifier: string.Join(",", arguments)) .WithSource(); App.Start(testAsset, arguments); @@ -70,7 +70,7 @@ public async Task Arguments(string[] arguments, string expectedApplicationArgs) [InlineData(new[] { "-lp", "P1" }, "Argument Specified in Props")] public async Task Arguments_HostArguments(string[] arguments, string expectedApplicationArgs) { - var testAsset = TestAssets.CopyTestAsset("WatchHotReloadAppCustomHost", identifier: string.Join(",", arguments)) + var testAsset = _testAssetsManager.CopyTestAsset("WatchHotReloadAppCustomHost", identifier: string.Join(",", arguments)) .WithSource(); App.Start(testAsset, arguments); @@ -81,7 +81,7 @@ public async Task Arguments_HostArguments(string[] arguments, string expectedApp [Fact] public async Task RunArguments_NoHotReload() { - var testAsset = TestAssets.CopyTestAsset("WatchHotReloadAppMultiTfm") + var testAsset = _testAssetsManager.CopyTestAsset("WatchHotReloadAppMultiTfm") .WithSource(); App.DotnetWatchArgs.Clear(); @@ -115,7 +115,7 @@ public async Task RunArguments_NoHotReload() [Fact] public async Task RunArguments_HotReload() { - var testAsset = TestAssets.CopyTestAsset("WatchHotReloadAppMultiTfm") + var testAsset = _testAssetsManager.CopyTestAsset("WatchHotReloadAppMultiTfm") .WithSource(); App.DotnetWatchArgs.Clear(); @@ -148,7 +148,7 @@ public async Task RunArguments_HotReload() [InlineData("P and Q and \"R\"", "argPQR")] public async Task ArgumentsFromLaunchSettings_Watch(string profileName, string expectedArgs) { - var testAsset = TestAssets.CopyTestAsset("WatchAppWithLaunchSettings", identifier: profileName) + var testAsset = _testAssetsManager.CopyTestAsset("WatchAppWithLaunchSettings", identifier: profileName) .WithSource(); App.Start(testAsset, arguments: new[] @@ -170,7 +170,7 @@ public async Task ArgumentsFromLaunchSettings_Watch(string profileName, string e [InlineData("P and Q and \"R\"", "argPQR")] public async Task ArgumentsFromLaunchSettings_HotReload(string profileName, string expectedArgs) { - var testAsset = TestAssets.CopyTestAsset("WatchAppWithLaunchSettings", identifier: profileName) + var testAsset = _testAssetsManager.CopyTestAsset("WatchAppWithLaunchSettings", identifier: profileName) .WithSource(); App.Start(testAsset, arguments: new[] @@ -188,7 +188,7 @@ public async Task ArgumentsFromLaunchSettings_HotReload(string profileName, stri [Fact] public async Task TestCommand() { - var testAsset = TestAssets.CopyTestAsset("XunitCore") + var testAsset = _testAssetsManager.CopyTestAsset("XunitCore") .WithSource(); App.Start(testAsset, ["--verbose", "test", "--list-tests", "/p:VSTestUseMSBuildOutput=false"]); @@ -213,7 +213,7 @@ public async Task TestCommand() [Fact] public async Task TestCommand_MultiTargeting() { - var testAsset = TestAssets.CopyTestAsset("XunitMulti") + var testAsset = _testAssetsManager.CopyTestAsset("XunitMulti") .WithSource(); App.Start(testAsset, ["--verbose", "test", "--framework", ToolsetInfo.CurrentTargetFramework, "--list-tests", "/p:VSTestUseMSBuildOutput=false"]); @@ -225,7 +225,7 @@ public async Task TestCommand_MultiTargeting() [Fact] public async Task BuildCommand() { - var testAsset = TestAssets.CopyTestAsset("WatchNoDepsApp") + var testAsset = _testAssetsManager.CopyTestAsset("WatchNoDepsApp") .WithSource(); App.Start(testAsset, ["--verbose", "--property", "TestProperty=123", "build", "/t:TestTarget"]); @@ -243,7 +243,7 @@ public async Task BuildCommand() [Fact] public async Task MSBuildCommand() { - var testAsset = TestAssets.CopyTestAsset("WatchNoDepsApp") + var testAsset = _testAssetsManager.CopyTestAsset("WatchNoDepsApp") .WithSource(); App.Start(testAsset, ["--verbose", "/p:TestProperty=123", "msbuild", "/t:TestTarget"]); @@ -261,7 +261,7 @@ public async Task MSBuildCommand() [Fact] public async Task PackCommand() { - var testAsset = TestAssets.CopyTestAsset("WatchNoDepsApp") + var testAsset = _testAssetsManager.CopyTestAsset("WatchNoDepsApp") .WithSource(); App.Start(testAsset, ["--verbose", "pack", "-c", "Release"]); @@ -281,7 +281,7 @@ public async Task PackCommand() [Fact] public async Task PublishCommand() { - var testAsset = TestAssets.CopyTestAsset("WatchNoDepsApp") + var testAsset = _testAssetsManager.CopyTestAsset("WatchNoDepsApp") .WithSource(); App.Start(testAsset, ["--verbose", "publish", "-c", "Release"]); @@ -300,7 +300,7 @@ public async Task PublishCommand() [Fact] public async Task FormatCommand() { - var testAsset = TestAssets.CopyTestAsset("WatchNoDepsApp") + var testAsset = _testAssetsManager.CopyTestAsset("WatchNoDepsApp") .WithSource(); App.DotnetWatchArgs.Clear(); @@ -318,7 +318,7 @@ public async Task FormatCommand() [Fact] public async Task ProjectGraphLoadFailure() { - var testAsset = TestAssets + var testAsset = _testAssetsManager .CopyTestAsset("WatchAppWithProjectDeps") .WithSource() .WithProjectChanges((path, proj) => diff --git a/test/dotnet-watch.Tests/Watch/Utilities/DotNetWatchTestBase.cs b/test/dotnet-watch.Tests/Watch/Utilities/DotNetWatchTestBase.cs index 4650141560af..dd169ba5c523 100644 --- a/test/dotnet-watch.Tests/Watch/Utilities/DotNetWatchTestBase.cs +++ b/test/dotnet-watch.Tests/Watch/Utilities/DotNetWatchTestBase.cs @@ -6,43 +6,39 @@ namespace Microsoft.DotNet.Watch.UnitTests; /// /// Base class for all tests that create dotnet watch process. /// -public abstract class DotNetWatchTestBase : IDisposable +public abstract class DotNetWatchTestBase : SdkTest, IDisposable { - internal TestAssetsManager TestAssets { get; } internal WatchableApp App { get; } - public DotNetWatchTestBase(ITestOutputHelper logger) + public DotNetWatchTestBase(ITestOutputHelper output) + : base(new DebugTestOutputLogger(output)) { - var debugLogger = new DebugTestOutputLogger(logger); - App = new WatchableApp(debugLogger); - TestAssets = new TestAssetsManager(debugLogger); + App = new WatchableApp(Log); // disposes the test class if the test execution is cancelled: AppDomain.CurrentDomain.ProcessExit += (_, _) => Dispose(); } - public DebugTestOutputLogger Logger => (DebugTestOutputLogger)App.Logger; + public void Dispose() + { + App.Dispose(); + } - public void Log(string message) - => Logger.WriteLine($"[TEST] {message}"); + public void LogMessage(string message) + => Log.WriteLine($"[TEST] {message}"); public void UpdateSourceFile(string path, string text) { File.WriteAllText(path, text, Encoding.UTF8); - Log($"File '{path}' updated ({HotReloadDotNetWatcher.FormatTimestamp(File.GetLastWriteTimeUtc(path))})."); + LogMessage($"File '{path}' updated ({HotReloadDotNetWatcher.FormatTimestamp(File.GetLastWriteTimeUtc(path))})."); } public void UpdateSourceFile(string path, Func contentTransform) { File.WriteAllText(path, contentTransform(File.ReadAllText(path, Encoding.UTF8)), Encoding.UTF8); - Log($"File '{path}' updated."); + LogMessage($"File '{path}' updated."); } public void UpdateSourceFile(string path) => UpdateSourceFile(path, content => content); - - public void Dispose() - { - App.Dispose(); - } } diff --git a/test/dotnet.Tests/dotnet-msbuild/GivenDotnetRunInvocation.cs b/test/dotnet.Tests/dotnet-msbuild/GivenDotnetRunInvocation.cs index 17518f66c2bc..eaa757c477c4 100644 --- a/test/dotnet.Tests/dotnet-msbuild/GivenDotnetRunInvocation.cs +++ b/test/dotnet.Tests/dotnet-msbuild/GivenDotnetRunInvocation.cs @@ -6,15 +6,8 @@ namespace Microsoft.DotNet.Cli.MSBuild.Tests { [Collection(TestConstants.UsesStaticTelemetryState)] - public class GivenDotnetRunInvocation : IClassFixture + public class GivenDotnetRunInvocation(ITestOutputHelper log) : SdkTest(log), IClassFixture { - public ITestOutputHelper Log { get; } - - public GivenDotnetRunInvocation(ITestOutputHelper log) - { - Log = log; - } - [Theory] [InlineData(new string[] { "-p:prop1=true" }, new string[] { "--property:prop1=true" })] [InlineData(new string[] { "--property:prop1=true" }, new string[] { "--property:prop1=true" })] @@ -29,9 +22,8 @@ public void MsbuildInvocationIsCorrect(string[] args, string[] expectedArgs) string[] constantRestoreArgs = ["-nologo", "-verbosity:quiet"]; string[] fullExpectedArgs = constantRestoreArgs.Concat(expectedArgs).ToArray(); - var tam = new TestAssetsManager(Log); var oldWorkingDirectory = Directory.GetCurrentDirectory(); - var newWorkingDir = tam.CopyTestAsset("HelloWorld", identifier: $"{nameof(MsbuildInvocationIsCorrect)}_{args.GetHashCode()}_{expectedArgs.GetHashCode()}").WithSource().Path; + var newWorkingDir = _testAssetsManager.CopyTestAsset("HelloWorld", identifier: $"{nameof(MsbuildInvocationIsCorrect)}_{args.GetHashCode()}_{expectedArgs.GetHashCode()}").WithSource().Path; try { Directory.SetCurrentDirectory(newWorkingDir);