-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReferenceProtector.Tasks.TestBase.cs
More file actions
230 lines (193 loc) · 7.71 KB
/
ReferenceProtector.Tasks.TestBase.cs
File metadata and controls
230 lines (193 loc) · 7.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
using System.Diagnostics;
using Xunit;
namespace ReferenceProtector.Tasks.IntegrationTests;
/// <summary>
/// Base class for integration tests.
/// </summary>
public class TestBase : IDisposable
{
/// <summary>
/// Output helper for logging test output.
/// This is used to capture output during test execution, which can be useful for debugging.
/// </summary>
protected ITestOutputHelper Output { get; }
/// <summary>
/// Temporary directory for on-the-fly generated test projects.
/// </summary>
protected string TestDirectory { get; }
/// <summary>
/// Initializes a new instance of the <see cref="TestBase"/> class.
/// This constructor sets up the test environment by creating a unique directory for each test run.
/// It also creates necessary files like `dirs.proj`, `Directory.Build.props`, and `Directory.Build.targets` in the test directory.
/// The `ITestOutputHelper` is used to log messages during the test execution, which can be useful for debugging purposes.
/// The test directory is created with a unique identifier to avoid conflicts between different test runs.
/// </summary>
/// <param name="output">The output helper for logging test output.</param>
public TestBase(ITestOutputHelper output)
{
Output = output;
TestDirectory = SetupTestEnvironment();
}
internal string SetupTestEnvironment()
{
var identifier = Guid.NewGuid();
var testDirectory = Path.Combine(Directory.GetCurrentDirectory(), identifier.ToString());
// Create the test directory
{
Output.WriteLine($"Creating test directory: {testDirectory}");
Directory.CreateDirectory(testDirectory);
}
// Create the dirs.proj file
{
var dirsProjPath = Path.Combine(testDirectory, "dirs.proj");
Output.WriteLine($"Creating dirs.proj file: {dirsProjPath}");
File.WriteAllText(dirsProjPath, """
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build">
<ItemGroup>
<ProjectFiles Include="**\*.csproj" />
</ItemGroup>
<Target Name="Restore">
<MSBuild Projects="@(ProjectFiles)" Targets="Restore" />
</Target>
<Target Name="Build">
<MSBuild Projects="@(ProjectFiles)" />
</Target>
<Target Name="Rebuild">
<MSBuild Projects="@(ProjectFiles)" Targets="Rebuild" />
</Target>
<Target Name="Clean">
<MSBuild Projects="@(ProjectFiles)" Targets="Clean" />
</Target>
</Project>
""");
}
// Create an empty Directory.Packages.props to decouple from the repo's CPM settings
{
var packagesPropsPath = Path.Combine(testDirectory, "Directory.Packages.props");
Output.WriteLine($"Creating packages props file: {packagesPropsPath}");
File.WriteAllText(packagesPropsPath, """<Project />""");
}
// Create the build props file
{
var buildPropsPath = Path.Combine(testDirectory, "Directory.Build.props");
Output.WriteLine($"Creating build props file: {buildPropsPath}");
File.WriteAllText(buildPropsPath, """
<Project>
<Import Project="..\ReferenceProtector.props" />
<PropertyGroup>
<DisableTransitiveProjectReferences>false</DisableTransitiveProjectReferences>
</PropertyGroup>
</Project>
""");
}
// Create the build targets file
{
var buildTargetsPath = Path.Combine(testDirectory, "ReferenceProtector.Build.targets");
Output.WriteLine($"Creating build targets file: {buildTargetsPath}");
File.WriteAllText(Path.Combine(testDirectory, "Directory.Build.targets"), """
<Project>
<Import Project="..\ReferenceProtector.targets" />
</Project>
""");
}
return testDirectory;
}
internal void CreateProject(string projectName)
{
var projectPath = Path.Combine(TestDirectory, projectName);
// Ensure the project directory exists
{
Output.WriteLine($"Creating project directory: {projectPath}");
Directory.CreateDirectory(projectPath);
}
// Create the project file
{
Output.WriteLine($"Creating project: {projectName}.cs at {projectPath}");
File.WriteAllText(Path.Combine(projectPath, $"{projectName}.csproj"), """
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>
</Project>
""");
}
// Create a simple class file
{
Output.WriteLine($"Creating Class.cs in project: {projectName}");
File.WriteAllText(Path.Combine(projectPath, $"Class.cs"), $@"
namespace {projectName};
public class Class1
{{
}}
");
}
}
internal async Task AddProjectReference(string projectName, string referenceProjectName)
{
var projectPath = Path.Combine(TestDirectory, projectName, $"{projectName}.csproj");
var referencePath = Path.Combine(TestDirectory, referenceProjectName, $"{referenceProjectName}.csproj");
await RunDotnetCommandAsync(TestDirectory, $"add {projectPath} reference {referencePath}", TestContext.Current.CancellationToken);
}
internal async Task AddPackageReference(string projectName, string packageName)
{
var projectPath = Path.Combine(TestDirectory, projectName, $"{projectName}.csproj");
await RunDotnetCommandAsync(TestDirectory, $"add {projectPath} package {packageName}", TestContext.Current.CancellationToken);
}
internal async Task Build(string additionalArgs = "")
{
string buildArgs =
$"build dirs.proj " +
$"-m:1 -restore -nologo -nodeReuse:false -noAutoResponse " +
$"/p:Configuration=Debug " +
$"/p:ReferenceProtectorTaskAssembly={Path.Combine(Directory.GetCurrentDirectory(), "ReferenceProtector.Tasks.dll")} " +
$"/v:m" +
$" {additionalArgs}";
await RunDotnetCommandAsync(TestDirectory, buildArgs, TestContext.Current.CancellationToken);
}
internal List<string> GetGeneratedReferencesFiles()
{
var files = Directory.GetFiles(TestDirectory, "_ReferenceProtector_DeclaredReferences.tsv", SearchOption.AllDirectories);
return files.ToList();
}
private async Task RunDotnetCommandAsync(string workingDirectory, string args, CancellationToken ct)
{
Output.WriteLine($"Running dotnet with arguments: {args}");
var process = Process.Start(new ProcessStartInfo
{
FileName = "dotnet",
Arguments = args,
WorkingDirectory = workingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
});
Assert.NotNull(process);
Assert.False(process.HasExited);
string output = await process.StandardOutput.ReadToEndAsync(ct);
string error = await process.StandardError.ReadToEndAsync(ct);
await process.WaitForExitAsync(ct);
Output.WriteLine($"MSBuild Output: {output}");
Output.WriteLine($"MSBuild Error: {error}");
Assert.Equal(0, process.ExitCode);
}
/// <inheritdoc/>
public void Dispose()
{
Output.WriteLine("Disposing CollectAllReferencesIntegrationTests...");
// Clean up the test directory
if (Directory.Exists(TestDirectory))
{
try
{
Directory.Delete(TestDirectory, true);
Output.WriteLine($"Test Directory Deleted: {TestDirectory}");
}
catch (IOException ex)
{
Output.WriteLine($"Error deleting test directory: {ex.Message}");
}
}
}
}