Skip to content

Refactor a common TempDirectory test class #9370

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

Merged
merged 1 commit into from
May 17, 2025
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
17 changes: 0 additions & 17 deletions tests/Aspire.Hosting.Docker.Tests/DockerComposePublisherTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -299,23 +299,6 @@ public Task BuildImageAsync(IResource resource, CancellationToken cancellationTo
}
}

private sealed class TempDirectory : IDisposable
{
public TempDirectory()
{
Path = Directory.CreateTempSubdirectory(".aspire-compose").FullName;
}

public string Path { get; }
public void Dispose()
{
if (File.Exists(Path))
{
File.Delete(Path);
}
}
}

private sealed class TestProject : IProjectMetadata
{
public string ProjectPath => "another-path";
Expand Down
13 changes: 0 additions & 13 deletions tests/Aspire.Hosting.Kubernetes.Tests/KubernetesPublisherTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,19 +105,6 @@ await Verify(content, "yaml")
.UseHelixAwareDirectory();
}

public sealed class TempDirectory : IDisposable
{
public string Path { get; } = Directory.CreateTempSubdirectory(".aspire-kubernetes").FullName;

public void Dispose()
{
if (Directory.Exists(Path))
{
Directory.Delete(Path, recursive: true);
}
}
}

private sealed class TestProject : IProjectMetadata
{
public string ProjectPath => "another-path";
Expand Down
13 changes: 2 additions & 11 deletions tests/Aspire.Hosting.MySql.Tests/AddMySqlTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,8 @@ public void WithPhpMyAdminProducesValidServerConfigFile()
{
var builder = DistributedApplication.CreateBuilder();

var tempStorePath = Directory.CreateTempSubdirectory().FullName;
builder.Configuration["Aspire:Store:Path"] = tempStorePath;
using var tempStore = new TempDirectory();
builder.Configuration["Aspire:Store:Path"] = tempStore.Path;

var mysql1 = builder.AddMySql("mysql1").WithPhpMyAdmin(c => c.WithHostPort(8081));
var mysql2 = builder.AddMySql("mysql2").WithPhpMyAdmin(c => c.WithHostPort(8081));
Expand All @@ -286,15 +286,6 @@ public void WithPhpMyAdminProducesValidServerConfigFile()
Assert.True(match1.Success);
Match match2 = Regex.Match(fileContents, pattern2);
Assert.True(match2.Success);

try
{
Directory.Delete(tempStorePath, true);
}
catch
{
// Ignore.
}
}

[Fact]
Expand Down
13 changes: 2 additions & 11 deletions tests/Aspire.Hosting.MySql.Tests/MySqlFunctionalTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ public async Task MySql_WithPersistentLifetime_ReusesContainers(bool useMultiple
using var cts = new CancellationTokenSource(TestConstants.ExtraLongTimeoutTimeSpan * 2);

// Use the same path for both runs
var aspireStorePath = Directory.CreateTempSubdirectory().FullName;
using var aspireStore = new TempDirectory();

var before = await RunContainersAsync();
var after = await RunContainersAsync();
Expand All @@ -465,19 +465,10 @@ public async Task MySql_WithPersistentLifetime_ReusesContainers(bool useMultiple
Assert.All(after, Assert.NotNull);
Assert.Equal(before, after);

try
{
Directory.Delete(aspireStorePath, true);
}
catch
{
// Don't fail test if we can't clean the temporary folder
}

async Task<string?[]> RunContainersAsync()
{
using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper)
.WithTempAspireStore(aspireStorePath)
.WithTempAspireStore(aspireStore.Path)
.WithResourceCleanUp(false);

var passwordParameter = builder.AddParameter("pwd", "p@ssw0rd1", secret: true);
Expand Down
26 changes: 4 additions & 22 deletions tests/Aspire.Hosting.PostgreSQL.Tests/AddPostgresTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -455,8 +455,8 @@ public async Task WithPostgresProducesValidServersJsonFile()
{
var builder = DistributedApplication.CreateBuilder();

var tempStorePath = Directory.CreateTempSubdirectory().FullName;
builder.Configuration["Aspire:Store:Path"] = tempStorePath;
using var tempStore = new TempDirectory();
builder.Configuration["Aspire:Store:Path"] = tempStore.Path;

var username = builder.AddParameter("pg-user", "myuser");
var pg1 = builder.AddPostgres("mypostgres1").WithPgAdmin(pga => pga.WithHostPort(8081));
Expand Down Expand Up @@ -508,24 +508,15 @@ public async Task WithPostgresProducesValidServersJsonFile()
Assert.Equal("prefer", servers.GetProperty("2").GetProperty("SSLMode").GetString());
Assert.Equal("postgres", servers.GetProperty("2").GetProperty("MaintenanceDB").GetString());
Assert.Equal($"echo '{pg2.Resource.PasswordParameter.Value}'", servers.GetProperty("2").GetProperty("PasswordExecCommand").GetString());

try
{
Directory.Delete(tempStorePath, true);
}
catch
{
// Ignore.
}
}

[Fact]
public async Task WithPgwebProducesValidBookmarkFiles()
{
var builder = DistributedApplication.CreateBuilder();

var tempStorePath = Directory.CreateTempSubdirectory().FullName;
builder.Configuration["Aspire:Store:Path"] = tempStorePath;
using var tempStore = new TempDirectory();
builder.Configuration["Aspire:Store:Path"] = tempStore.Path;

var pg1 = builder.AddPostgres("mypostgres1").WithPgWeb(pga => pga.WithHostPort(8081));
var pg2 = builder.AddPostgres("mypostgres2").WithPgWeb(pga => pga.WithHostPort(8081));
Expand Down Expand Up @@ -574,15 +565,6 @@ public async Task WithPgwebProducesValidBookmarkFiles()
Assert.Equal(UnixFileMode.None, file.Mode);
Assert.Equal(CreatePgWebBookmarkfileContent(db2.Resource), file.Contents);
});

try
{
Directory.Delete(tempStorePath, true);
}
catch
{
// Ignore.
}
}

[Fact]
Expand Down
13 changes: 2 additions & 11 deletions tests/Aspire.Hosting.PostgreSQL.Tests/PostgresFunctionalTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ public async Task Postgres_WithPersistentLifetime_ReusesContainers()
var cts = new CancellationTokenSource(TimeSpan.FromMinutes(10));

// Use the same path for both runs
var aspireStorePath = Directory.CreateTempSubdirectory().FullName;
using var aspireStore = new TempDirectory();

var before = await RunContainersAsync();
var after = await RunContainersAsync();
Expand All @@ -455,19 +455,10 @@ public async Task Postgres_WithPersistentLifetime_ReusesContainers()
Assert.All(after, Assert.NotNull);
Assert.Equal(before, after);

try
{
Directory.Delete(aspireStorePath, true);
}
catch
{
// Don't fail test if we can't clean the temporary folder
}

async Task<string?[]> RunContainersAsync()
{
using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper)
.WithTempAspireStore(aspireStorePath)
.WithTempAspireStore(aspireStore.Path)
.WithResourceCleanUp(false);

var passwordParameter = builder.AddParameter("pwd", "p@ssword1", secret: true);
Expand Down
1 change: 1 addition & 0 deletions tests/Aspire.Hosting.Tests/Aspire.Hosting.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
<Compile Include="$(TestsSharedDir)Logging\*.cs" LinkBase="shared/Logging" />
<Compile Include="$(TestsSharedDir)ConsoleLogging\*.cs" LinkBase="shared" />
<Compile Include="$(TestsSharedDir)AsyncTestHelpers.cs" Link="shared/AsyncTestHelpers.cs" />
<Compile Include="$(TestsSharedDir)TempDirectory.cs" Link="shared/TempDirectory.cs" />
<Compile Include="$(TestsSharedDir)DistributedApplicationTestingBuilderExtensions.cs" Link="shared/DistributedApplicationTestingBuilderExtensions.cs" />
<Compile Include="$(RepoRoot)src\Aspire.Hosting.PostgreSQL\PostgresContainerImageTags.cs" />
<Compile Include="$(RepoRoot)src\Aspire.Hosting.Redis\RedisContainerImageTags.cs" />
Expand Down
90 changes: 42 additions & 48 deletions tests/Aspire.Hosting.Tests/MSBuildTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,12 @@ public class MSBuildTests
public void EnsureWarningsAreEmittedWhenProjectReferencingLibraries()
{
var repoRoot = MSBuildUtils.GetRepoRoot();
var tempDirectory = Directory.CreateTempSubdirectory("AspireHostingTests");
try
{
var libraryDirectory = Path.Combine(tempDirectory.FullName, "Library");
Directory.CreateDirectory(libraryDirectory);
using var tempDirectory = new TempDirectory();

var libraryDirectory = Path.Combine(tempDirectory.Path, "Library");
Directory.CreateDirectory(libraryDirectory);

File.WriteAllText(Path.Combine(libraryDirectory, "Library.csproj"), """
File.WriteAllText(Path.Combine(libraryDirectory, "Library.csproj"), """
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
Expand All @@ -34,18 +33,18 @@ public void EnsureWarningsAreEmittedWhenProjectReferencingLibraries()

</Project>
""");
File.WriteAllText(Path.Combine(libraryDirectory, "Class1.cs"), """
File.WriteAllText(Path.Combine(libraryDirectory, "Class1.cs"), """
namespace Library;

public class Class1
{
}
""");

var appHostDirectory = Path.Combine(tempDirectory.FullName, "AppHost");
Directory.CreateDirectory(appHostDirectory);
var appHostDirectory = Path.Combine(tempDirectory.Path, "AppHost");
Directory.CreateDirectory(appHostDirectory);

File.WriteAllText(Path.Combine(appHostDirectory, "AppHost.csproj"), $"""
File.WriteAllText(Path.Combine(appHostDirectory, "AppHost.csproj"), $"""
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
Expand All @@ -71,12 +70,12 @@ the Aspire.AppHost.SDK targets that will automatically add these references to p

</Project>
""");
File.WriteAllText(Path.Combine(appHostDirectory, "AppHost.cs"), """
File.WriteAllText(Path.Combine(appHostDirectory, "AppHost.cs"), """
var builder = DistributedApplication.CreateBuilder();
builder.Build().Run();
""");

File.WriteAllText(Path.Combine(appHostDirectory, "Directory.Build.props"), $"""
File.WriteAllText(Path.Combine(appHostDirectory, "Directory.Build.props"), $"""
<Project>
<PropertyGroup>
<SkipAspireWorkloadManifest>true</SkipAspireWorkloadManifest>
Expand All @@ -85,49 +84,44 @@ the Aspire.AppHost.SDK targets that will automatically add these references to p
<Import Project="{repoRoot}\src\Aspire.Hosting.AppHost\build\Aspire.Hosting.AppHost.props" />
</Project>
""");
File.WriteAllText(Path.Combine(appHostDirectory, "Directory.Build.targets"), $"""
File.WriteAllText(Path.Combine(appHostDirectory, "Directory.Build.targets"), $"""
<Project>
<Import Project="{repoRoot}\src\Aspire.Hosting.AppHost\build\Aspire.Hosting.AppHost.in.targets" />
<Import Project="{repoRoot}\src\Aspire.AppHost.Sdk\SDK\Sdk.in.targets" />
</Project>
""");

var output = new StringBuilder();
var outputDone = new ManualResetEvent(false);
using var process = new Process();
// set '-nodereuse:false -p:UseSharedCompilation=false' so the MSBuild and Roslyn server processes don't hang around, which may hang the test in CI
process.StartInfo = new ProcessStartInfo("dotnet", $"build -nodereuse:false -p:UseSharedCompilation=false")
var output = new StringBuilder();
var outputDone = new ManualResetEvent(false);
using var process = new Process();
// set '-nodereuse:false -p:UseSharedCompilation=false' so the MSBuild and Roslyn server processes don't hang around, which may hang the test in CI
process.StartInfo = new ProcessStartInfo("dotnet", $"build -nodereuse:false -p:UseSharedCompilation=false")
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = appHostDirectory
};
process.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = appHostDirectory
};
process.OutputDataReceived += (sender, e) =>
outputDone.Set();
}
else
{
if (e.Data == null)
{
outputDone.Set();
}
else
{
output.AppendLine(e.Data);
}
};
process.Start();
process.BeginOutputReadLine();

Assert.True(process.WaitForExit(milliseconds: 180_000), "dotnet build command timed out after 3 minutes.");
Assert.True(process.ExitCode == 0, $"Build failed: {Environment.NewLine}{output}");

Assert.True(outputDone.WaitOne(millisecondsTimeout: 60_000), "Timed out waiting for output to complete.");

// Ensure a warning is emitted when an AppHost references a Library project
Assert.Contains("warning ASPIRE004", output.ToString());
}
finally
{
tempDirectory.Delete(true);
}
output.AppendLine(e.Data);
}
};
process.Start();
process.BeginOutputReadLine();

Assert.True(process.WaitForExit(milliseconds: 180_000), "dotnet build command timed out after 3 minutes.");
Assert.True(process.ExitCode == 0, $"Build failed: {Environment.NewLine}{output}");

Assert.True(outputDone.WaitOne(millisecondsTimeout: 60_000), "Timed out waiting for output to complete.");

// Ensure a warning is emitted when an AppHost references a Library project
Assert.Contains("warning ASPIRE004", output.ToString());
}
}
Loading