Skip to content

Commit 6cbb289

Browse files
authored
Refactor a common TempDirectory test class (#9370)
DockerComposePublisherTests was using File.Exists and File.Delete, which don't work for directories.
1 parent ef5ab9a commit 6cbb289

File tree

10 files changed

+78
-152
lines changed

10 files changed

+78
-152
lines changed

tests/Aspire.Hosting.Docker.Tests/DockerComposePublisherTests.cs

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -299,23 +299,6 @@ public Task BuildImageAsync(IResource resource, CancellationToken cancellationTo
299299
}
300300
}
301301

302-
private sealed class TempDirectory : IDisposable
303-
{
304-
public TempDirectory()
305-
{
306-
Path = Directory.CreateTempSubdirectory(".aspire-compose").FullName;
307-
}
308-
309-
public string Path { get; }
310-
public void Dispose()
311-
{
312-
if (File.Exists(Path))
313-
{
314-
File.Delete(Path);
315-
}
316-
}
317-
}
318-
319302
private sealed class TestProject : IProjectMetadata
320303
{
321304
public string ProjectPath => "another-path";

tests/Aspire.Hosting.Kubernetes.Tests/KubernetesPublisherTests.cs

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -105,19 +105,6 @@ await Verify(content, "yaml")
105105
.UseHelixAwareDirectory();
106106
}
107107

108-
public sealed class TempDirectory : IDisposable
109-
{
110-
public string Path { get; } = Directory.CreateTempSubdirectory(".aspire-kubernetes").FullName;
111-
112-
public void Dispose()
113-
{
114-
if (Directory.Exists(Path))
115-
{
116-
Directory.Delete(Path, recursive: true);
117-
}
118-
}
119-
}
120-
121108
private sealed class TestProject : IProjectMetadata
122109
{
123110
public string ProjectPath => "another-path";

tests/Aspire.Hosting.MySql.Tests/AddMySqlTests.cs

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -258,8 +258,8 @@ public void WithPhpMyAdminProducesValidServerConfigFile()
258258
{
259259
var builder = DistributedApplication.CreateBuilder();
260260

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

264264
var mysql1 = builder.AddMySql("mysql1").WithPhpMyAdmin(c => c.WithHostPort(8081));
265265
var mysql2 = builder.AddMySql("mysql2").WithPhpMyAdmin(c => c.WithHostPort(8081));
@@ -286,15 +286,6 @@ public void WithPhpMyAdminProducesValidServerConfigFile()
286286
Assert.True(match1.Success);
287287
Match match2 = Regex.Match(fileContents, pattern2);
288288
Assert.True(match2.Success);
289-
290-
try
291-
{
292-
Directory.Delete(tempStorePath, true);
293-
}
294-
catch
295-
{
296-
// Ignore.
297-
}
298289
}
299290

300291
[Fact]

tests/Aspire.Hosting.MySql.Tests/MySqlFunctionalTests.cs

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -456,7 +456,7 @@ public async Task MySql_WithPersistentLifetime_ReusesContainers(bool useMultiple
456456
using var cts = new CancellationTokenSource(TestConstants.ExtraLongTimeoutTimeSpan * 2);
457457

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

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

468-
try
469-
{
470-
Directory.Delete(aspireStorePath, true);
471-
}
472-
catch
473-
{
474-
// Don't fail test if we can't clean the temporary folder
475-
}
476-
477468
async Task<string?[]> RunContainersAsync()
478469
{
479470
using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper)
480-
.WithTempAspireStore(aspireStorePath)
471+
.WithTempAspireStore(aspireStore.Path)
481472
.WithResourceCleanUp(false);
482473

483474
var passwordParameter = builder.AddParameter("pwd", "p@ssw0rd1", secret: true);

tests/Aspire.Hosting.PostgreSQL.Tests/AddPostgresTests.cs

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -455,8 +455,8 @@ public async Task WithPostgresProducesValidServersJsonFile()
455455
{
456456
var builder = DistributedApplication.CreateBuilder();
457457

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

461461
var username = builder.AddParameter("pg-user", "myuser");
462462
var pg1 = builder.AddPostgres("mypostgres1").WithPgAdmin(pga => pga.WithHostPort(8081));
@@ -508,24 +508,15 @@ public async Task WithPostgresProducesValidServersJsonFile()
508508
Assert.Equal("prefer", servers.GetProperty("2").GetProperty("SSLMode").GetString());
509509
Assert.Equal("postgres", servers.GetProperty("2").GetProperty("MaintenanceDB").GetString());
510510
Assert.Equal($"echo '{pg2.Resource.PasswordParameter.Value}'", servers.GetProperty("2").GetProperty("PasswordExecCommand").GetString());
511-
512-
try
513-
{
514-
Directory.Delete(tempStorePath, true);
515-
}
516-
catch
517-
{
518-
// Ignore.
519-
}
520511
}
521512

522513
[Fact]
523514
public async Task WithPgwebProducesValidBookmarkFiles()
524515
{
525516
var builder = DistributedApplication.CreateBuilder();
526517

527-
var tempStorePath = Directory.CreateTempSubdirectory().FullName;
528-
builder.Configuration["Aspire:Store:Path"] = tempStorePath;
518+
using var tempStore = new TempDirectory();
519+
builder.Configuration["Aspire:Store:Path"] = tempStore.Path;
529520

530521
var pg1 = builder.AddPostgres("mypostgres1").WithPgWeb(pga => pga.WithHostPort(8081));
531522
var pg2 = builder.AddPostgres("mypostgres2").WithPgWeb(pga => pga.WithHostPort(8081));
@@ -574,15 +565,6 @@ public async Task WithPgwebProducesValidBookmarkFiles()
574565
Assert.Equal(UnixFileMode.None, file.Mode);
575566
Assert.Equal(CreatePgWebBookmarkfileContent(db2.Resource), file.Contents);
576567
});
577-
578-
try
579-
{
580-
Directory.Delete(tempStorePath, true);
581-
}
582-
catch
583-
{
584-
// Ignore.
585-
}
586568
}
587569

588570
[Fact]

tests/Aspire.Hosting.PostgreSQL.Tests/PostgresFunctionalTests.cs

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ public async Task Postgres_WithPersistentLifetime_ReusesContainers()
446446
var cts = new CancellationTokenSource(TimeSpan.FromMinutes(10));
447447

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

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

458-
try
459-
{
460-
Directory.Delete(aspireStorePath, true);
461-
}
462-
catch
463-
{
464-
// Don't fail test if we can't clean the temporary folder
465-
}
466-
467458
async Task<string?[]> RunContainersAsync()
468459
{
469460
using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper)
470-
.WithTempAspireStore(aspireStorePath)
461+
.WithTempAspireStore(aspireStore.Path)
471462
.WithResourceCleanUp(false);
472463

473464
var passwordParameter = builder.AddParameter("pwd", "p@ssword1", secret: true);

tests/Aspire.Hosting.Tests/Aspire.Hosting.Tests.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
<Compile Include="$(TestsSharedDir)Logging\*.cs" LinkBase="shared/Logging" />
3434
<Compile Include="$(TestsSharedDir)ConsoleLogging\*.cs" LinkBase="shared" />
3535
<Compile Include="$(TestsSharedDir)AsyncTestHelpers.cs" Link="shared/AsyncTestHelpers.cs" />
36+
<Compile Include="$(TestsSharedDir)TempDirectory.cs" Link="shared/TempDirectory.cs" />
3637
<Compile Include="$(TestsSharedDir)DistributedApplicationTestingBuilderExtensions.cs" Link="shared/DistributedApplicationTestingBuilderExtensions.cs" />
3738
<Compile Include="$(RepoRoot)src\Aspire.Hosting.PostgreSQL\PostgresContainerImageTags.cs" />
3839
<Compile Include="$(RepoRoot)src\Aspire.Hosting.Redis\RedisContainerImageTags.cs" />

tests/Aspire.Hosting.Tests/MSBuildTests.cs

Lines changed: 42 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,12 @@ public class MSBuildTests
1717
public void EnsureWarningsAreEmittedWhenProjectReferencingLibraries()
1818
{
1919
var repoRoot = MSBuildUtils.GetRepoRoot();
20-
var tempDirectory = Directory.CreateTempSubdirectory("AspireHostingTests");
21-
try
22-
{
23-
var libraryDirectory = Path.Combine(tempDirectory.FullName, "Library");
24-
Directory.CreateDirectory(libraryDirectory);
20+
using var tempDirectory = new TempDirectory();
21+
22+
var libraryDirectory = Path.Combine(tempDirectory.Path, "Library");
23+
Directory.CreateDirectory(libraryDirectory);
2524

26-
File.WriteAllText(Path.Combine(libraryDirectory, "Library.csproj"), """
25+
File.WriteAllText(Path.Combine(libraryDirectory, "Library.csproj"), """
2726
<Project Sdk="Microsoft.NET.Sdk">
2827
2928
<PropertyGroup>
@@ -34,18 +33,18 @@ public void EnsureWarningsAreEmittedWhenProjectReferencingLibraries()
3433
3534
</Project>
3635
""");
37-
File.WriteAllText(Path.Combine(libraryDirectory, "Class1.cs"), """
36+
File.WriteAllText(Path.Combine(libraryDirectory, "Class1.cs"), """
3837
namespace Library;
3938
4039
public class Class1
4140
{
4241
}
4342
""");
4443

45-
var appHostDirectory = Path.Combine(tempDirectory.FullName, "AppHost");
46-
Directory.CreateDirectory(appHostDirectory);
44+
var appHostDirectory = Path.Combine(tempDirectory.Path, "AppHost");
45+
Directory.CreateDirectory(appHostDirectory);
4746

48-
File.WriteAllText(Path.Combine(appHostDirectory, "AppHost.csproj"), $"""
47+
File.WriteAllText(Path.Combine(appHostDirectory, "AppHost.csproj"), $"""
4948
<Project Sdk="Microsoft.NET.Sdk">
5049
5150
<PropertyGroup>
@@ -71,12 +70,12 @@ the Aspire.AppHost.SDK targets that will automatically add these references to p
7170
7271
</Project>
7372
""");
74-
File.WriteAllText(Path.Combine(appHostDirectory, "AppHost.cs"), """
73+
File.WriteAllText(Path.Combine(appHostDirectory, "AppHost.cs"), """
7574
var builder = DistributedApplication.CreateBuilder();
7675
builder.Build().Run();
7776
""");
7877

79-
File.WriteAllText(Path.Combine(appHostDirectory, "Directory.Build.props"), $"""
78+
File.WriteAllText(Path.Combine(appHostDirectory, "Directory.Build.props"), $"""
8079
<Project>
8180
<PropertyGroup>
8281
<SkipAspireWorkloadManifest>true</SkipAspireWorkloadManifest>
@@ -85,49 +84,44 @@ the Aspire.AppHost.SDK targets that will automatically add these references to p
8584
<Import Project="{repoRoot}\src\Aspire.Hosting.AppHost\build\Aspire.Hosting.AppHost.props" />
8685
</Project>
8786
""");
88-
File.WriteAllText(Path.Combine(appHostDirectory, "Directory.Build.targets"), $"""
87+
File.WriteAllText(Path.Combine(appHostDirectory, "Directory.Build.targets"), $"""
8988
<Project>
9089
<Import Project="{repoRoot}\src\Aspire.Hosting.AppHost\build\Aspire.Hosting.AppHost.in.targets" />
9190
<Import Project="{repoRoot}\src\Aspire.AppHost.Sdk\SDK\Sdk.in.targets" />
9291
</Project>
9392
""");
9493

95-
var output = new StringBuilder();
96-
var outputDone = new ManualResetEvent(false);
97-
using var process = new Process();
98-
// set '-nodereuse:false -p:UseSharedCompilation=false' so the MSBuild and Roslyn server processes don't hang around, which may hang the test in CI
99-
process.StartInfo = new ProcessStartInfo("dotnet", $"build -nodereuse:false -p:UseSharedCompilation=false")
94+
var output = new StringBuilder();
95+
var outputDone = new ManualResetEvent(false);
96+
using var process = new Process();
97+
// set '-nodereuse:false -p:UseSharedCompilation=false' so the MSBuild and Roslyn server processes don't hang around, which may hang the test in CI
98+
process.StartInfo = new ProcessStartInfo("dotnet", $"build -nodereuse:false -p:UseSharedCompilation=false")
99+
{
100+
RedirectStandardOutput = true,
101+
UseShellExecute = false,
102+
CreateNoWindow = true,
103+
WorkingDirectory = appHostDirectory
104+
};
105+
process.OutputDataReceived += (sender, e) =>
106+
{
107+
if (e.Data == null)
100108
{
101-
RedirectStandardOutput = true,
102-
UseShellExecute = false,
103-
CreateNoWindow = true,
104-
WorkingDirectory = appHostDirectory
105-
};
106-
process.OutputDataReceived += (sender, e) =>
109+
outputDone.Set();
110+
}
111+
else
107112
{
108-
if (e.Data == null)
109-
{
110-
outputDone.Set();
111-
}
112-
else
113-
{
114-
output.AppendLine(e.Data);
115-
}
116-
};
117-
process.Start();
118-
process.BeginOutputReadLine();
119-
120-
Assert.True(process.WaitForExit(milliseconds: 180_000), "dotnet build command timed out after 3 minutes.");
121-
Assert.True(process.ExitCode == 0, $"Build failed: {Environment.NewLine}{output}");
122-
123-
Assert.True(outputDone.WaitOne(millisecondsTimeout: 60_000), "Timed out waiting for output to complete.");
124-
125-
// Ensure a warning is emitted when an AppHost references a Library project
126-
Assert.Contains("warning ASPIRE004", output.ToString());
127-
}
128-
finally
129-
{
130-
tempDirectory.Delete(true);
131-
}
113+
output.AppendLine(e.Data);
114+
}
115+
};
116+
process.Start();
117+
process.BeginOutputReadLine();
118+
119+
Assert.True(process.WaitForExit(milliseconds: 180_000), "dotnet build command timed out after 3 minutes.");
120+
Assert.True(process.ExitCode == 0, $"Build failed: {Environment.NewLine}{output}");
121+
122+
Assert.True(outputDone.WaitOne(millisecondsTimeout: 60_000), "Timed out waiting for output to complete.");
123+
124+
// Ensure a warning is emitted when an AppHost references a Library project
125+
Assert.Contains("warning ASPIRE004", output.ToString());
132126
}
133127
}

0 commit comments

Comments
 (0)