-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathMSBuildTargetsTests.cs
More file actions
299 lines (255 loc) · 12.6 KB
/
Copy pathMSBuildTargetsTests.cs
File metadata and controls
299 lines (255 loc) · 12.6 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using Xunit;
namespace GitHub.Copilot.Test.Unit;
/// <summary>
/// Integration tests for the MSBuild targets shipped in
/// <c>dotnet/src/build/GitHub.Copilot.SDK.targets</c>. Each test creates a throwaway
/// project that imports the targets file directly and invokes <c>dotnet build</c> in
/// a subprocess so we exercise real MSBuild evaluation.
/// </summary>
/// <remarks>
/// These tests deliberately do not exercise the network-bound default download path; they
/// pin a fake <c>CopilotCliVersion</c> and supply a fake CLI binary via
/// <c>CopilotCliBinaryPath</c>. That is sufficient to cover the regression in issue
/// #921 ("preinstalled CLI is ignored and copy/register are skipped when
/// CopilotSkipCliDownload=true").
/// </remarks>
public class MSBuildTargetsTests
{
private static readonly string TargetsFilePath = FindTargetsFile();
private static readonly string BinaryName = OperatingSystem.IsWindows() ? "copilot.exe" : "copilot";
[Fact]
public async Task PreinstalledCliBinaryPath_IsHonored_DownloadSkipped_AndCopiedToOutput()
{
using var sandbox = MSBuildSandbox.Create();
var preinstalled = sandbox.WritePreinstalledBinary("fake-cli-contents");
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotCliBinaryPath"] = preinstalled,
});
Assert.True(result.Succeeded, result.FailureMessage());
// Download message must be absent because the download target was skipped.
Assert.DoesNotContain("Downloading Copilot CLI", result.StandardOutput, StringComparison.Ordinal);
// Binary must be placed at the canonical runtimes path so Client.cs can locate it.
var outputPath = sandbox.ExpectedOutputBinary();
Assert.True(File.Exists(outputPath), $"Expected CLI to be copied to '{outputPath}'.\n{result.FailureMessage()}");
Assert.Equal(File.ReadAllText(preinstalled), File.ReadAllText(outputPath));
}
[Fact]
public async Task PreinstalledCliBinaryPath_NormalizesNonStandardFileNameToCanonical()
{
using var sandbox = MSBuildSandbox.Create();
// Use an off-spec source filename to confirm the copy task renames it to copilot[.exe].
var preinstalled = sandbox.WritePreinstalledBinary("custom-named", fileName: "my-copilot-binary-v1.bin");
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotCliBinaryPath"] = preinstalled,
});
Assert.True(result.Succeeded, result.FailureMessage());
var outputPath = sandbox.ExpectedOutputBinary();
Assert.True(File.Exists(outputPath), $"Expected canonical binary at '{outputPath}'.\n{result.FailureMessage()}");
}
[Fact]
public async Task SkipCliDownload_WithoutBinaryPath_ProducesNoBinaryAndSucceeds()
{
using var sandbox = MSBuildSandbox.Create();
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotSkipCliDownload"] = "true",
});
Assert.True(result.Succeeded, result.FailureMessage());
// The runtimes folder may or may not be created by something else, but the binary
// itself must not exist.
Assert.False(File.Exists(sandbox.ExpectedOutputBinary()),
$"Expected no CLI binary in output when CopilotSkipCliDownload=true and no path supplied.\n{result.FailureMessage()}");
// Download must also have been skipped.
Assert.DoesNotContain("Downloading Copilot CLI", result.StandardOutput, StringComparison.Ordinal);
}
[Fact]
public async Task PreinstalledCliBinaryPath_WithSkipCliDownload_StillCopiesToOutput()
{
using var sandbox = MSBuildSandbox.Create();
var preinstalled = sandbox.WritePreinstalledBinary("fake-cli-contents");
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotCliBinaryPath"] = preinstalled,
["CopilotSkipCliDownload"] = "true",
});
Assert.True(result.Succeeded, result.FailureMessage());
Assert.True(File.Exists(sandbox.ExpectedOutputBinary()), result.FailureMessage());
}
[Fact]
public async Task PreinstalledCliBinaryPath_NonExistentFile_FailsWithActionableError()
{
using var sandbox = MSBuildSandbox.Create();
var nonexistent = Path.Combine(sandbox.ProjectDir, "does-not-exist", BinaryName);
var result = await sandbox.BuildAsync(new Dictionary<string, string>
{
["CopilotCliBinaryPath"] = nonexistent,
});
Assert.False(result.Succeeded, "Build should have failed when CopilotCliBinaryPath points at a missing file.");
Assert.Contains("Copilot CLI binary not found", result.StandardOutput, StringComparison.Ordinal);
Assert.Contains(nonexistent, result.StandardOutput, StringComparison.Ordinal);
}
private static string FindTargetsFile([CallerFilePath] string? thisFile = null)
{
// thisFile == <repo>/dotnet/test/Unit/MSBuildTargetsTests.cs
if (thisFile is not null && File.Exists(thisFile))
{
var candidate = Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(thisFile)!, "..", "..", "src", "build", "GitHub.Copilot.SDK.targets"));
if (File.Exists(candidate))
{
return candidate;
}
}
// Fall back to walking up from the test assembly location.
var dir = AppContext.BaseDirectory;
for (var i = 0; i < 8 && dir is not null; i++)
{
var candidate = Path.Combine(dir, "src", "build", "GitHub.Copilot.SDK.targets");
if (File.Exists(candidate))
{
return candidate;
}
dir = Path.GetDirectoryName(dir);
}
throw new InvalidOperationException(
"Could not locate GitHub.Copilot.SDK.targets relative to test assembly or source file.");
}
/// <summary>
/// A throwaway directory containing a minimal csproj that imports the SDK targets
/// file. Disposing removes the directory tree.
/// </summary>
private sealed class MSBuildSandbox : IDisposable
{
public string ProjectDir { get; }
private MSBuildSandbox(string projectDir)
{
ProjectDir = projectDir;
}
public static MSBuildSandbox Create()
{
var dir = Path.Combine(Path.GetTempPath(), "copilot-sdk-targets-test-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
// Minimal class library that imports the SDK targets with a pinned fake
// CopilotCliVersion so the targets do not need the generated props file.
var csproj = $"""
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<CopilotCliVersion>0.0.0-test</CopilotCliVersion>
<EnableDefaultCompileItems>true</EnableDefaultCompileItems>
</PropertyGroup>
<Import Project="{TargetsFilePath}" />
</Project>
""";
File.WriteAllText(Path.Combine(dir, "App.csproj"), csproj);
File.WriteAllText(Path.Combine(dir, "Stub.cs"), "namespace CopilotSdkTargetsTest { internal static class Stub { } }\n");
return new MSBuildSandbox(dir);
}
public string WritePreinstalledBinary(string contents, string? fileName = null)
{
var preinstallDir = Path.Combine(ProjectDir, "preinstall");
Directory.CreateDirectory(preinstallDir);
// Strip any path information from fileName so it cannot escape preinstallDir.
var safeFileName = string.IsNullOrEmpty(fileName) ? BinaryName : Path.GetFileName(fileName);
var path = Path.Combine(preinstallDir, safeFileName);
File.WriteAllText(path, contents);
return path;
}
public string ExpectedOutputBinary()
{
var rid = GetPortableRid();
return Path.Combine(ProjectDir, "bin", "Debug", "net8.0", "runtimes", rid, "native", BinaryName);
}
public async Task<BuildResult> BuildAsync(IDictionary<string, string> properties)
{
var args = new StringBuilder("build --nologo -clp:NoSummary");
foreach (var (key, value) in properties)
{
// Quote the value so paths with spaces are preserved.
args.Append(" /p:").Append(key).Append('=').Append('"').Append(value).Append('"');
}
var psi = new ProcessStartInfo("dotnet", args.ToString())
{
WorkingDirectory = ProjectDir,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
// Avoid inheriting the parent's MSBuildSDKsPath/RuntimeIdentifier from the
// running test host; the subprocess should resolve its own SDK and pick the
// RID that matches ExpectedOutputBinary().
psi.Environment.Remove("MSBuildSDKsPath");
psi.Environment.Remove("RuntimeIdentifier");
using var process = Process.Start(psi) ?? throw new InvalidOperationException("Failed to start dotnet build subprocess.");
// Drain both streams concurrently to avoid deadlocks on full pipe buffers.
var stdoutTask = process.StandardOutput.ReadToEndAsync();
var stderrTask = process.StandardError.ReadToEndAsync();
// Generous timeout: dotnet restore + build of an empty project on a slow CI
// worker can take ~60s the first time. We keep individual tests short by
// using minimal projects.
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
try
{
await process.WaitForExitAsync(cts.Token);
}
catch (OperationCanceledException)
{
try { process.Kill(entireProcessTree: true); }
catch (InvalidOperationException) { /* process already exited */ }
catch (NotSupportedException) { /* not supported on this platform */ }
catch (System.ComponentModel.Win32Exception) { /* kill failed; best effort */ }
throw new TimeoutException($"dotnet build did not complete within the timeout for args: {args}");
}
return new BuildResult(
ExitCode: process.ExitCode,
StandardOutput: await stdoutTask,
StandardError: await stderrTask,
CommandLine: $"dotnet {args}");
}
public void Dispose()
{
try { Directory.Delete(ProjectDir, recursive: true); }
catch (IOException) { /* cleanup is best effort */ }
catch (UnauthorizedAccessException) { /* cleanup is best effort */ }
}
private static string GetPortableRid()
{
if (OperatingSystem.IsWindows())
{
return System.Runtime.InteropServices.RuntimeInformation.OSArchitecture switch
{
System.Runtime.InteropServices.Architecture.Arm64 => "win-arm64",
_ => "win-x64",
};
}
if (OperatingSystem.IsMacOS())
{
return System.Runtime.InteropServices.RuntimeInformation.OSArchitecture switch
{
System.Runtime.InteropServices.Architecture.Arm64 => "osx-arm64",
_ => "osx-x64",
};
}
return System.Runtime.InteropServices.RuntimeInformation.OSArchitecture switch
{
System.Runtime.InteropServices.Architecture.Arm64 => "linux-arm64",
_ => "linux-x64",
};
}
}
private sealed record BuildResult(int ExitCode, string StandardOutput, string StandardError, string CommandLine)
{
public bool Succeeded => ExitCode == 0;
public string FailureMessage() =>
$"{CommandLine}\nExitCode: {ExitCode}\n--- STDOUT ---\n{StandardOutput}\n--- STDERR ---\n{StandardError}";
}
}