-
Notifications
You must be signed in to change notification settings - Fork 753
Expand file tree
/
Copy pathPackageDownloadRunnerTests.cs
More file actions
604 lines (540 loc) · 22.2 KB
/
PackageDownloadRunnerTests.cs
File metadata and controls
604 lines (540 loc) · 22.2 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Test.Utility;
using Moq;
using NuGet.CommandLine.XPlat;
using NuGet.CommandLine.XPlat.Commands.Package;
using NuGet.CommandLine.XPlat.Commands.Package.PackageDownload;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Test.Utility;
using NuGet.Versioning;
using Xunit;
namespace NuGet.CommandLine.Xplat.Tests;
public class PackageDownloadRunnerTests
{
public static IEnumerable<object[]> PackageTestData()
{
// Basic stable explicit versions
yield return new object[]
{
new List<(string, string)>
{
("Contoso.Core", "1.0.0"),
("Contoso.Core", "1.1.0"),
("Contoso.Core", "2.0.0-beta")
}, // source packages
new List<(string, string)>
{
("Contoso.Core", "1.1.0"),
("Contoso.Core", "1.0.0"),
}, // argument packages
false, // enablePrerelease
"myOutput", // output directory subpath
new List<(string, string)>
{
("Contoso.Core", "1.1.0"),
("Contoso.Core", "1.0.0")
} // expected
};
// Basic stable explicit versions with different ids
yield return new object[]
{
new List<(string, string)>
{
("Contoso.Core", "1.0.0"),
("Contoso.Core.Utils", "1.1.0"),
("Contoso.Core", "2.0.0-beta")
}, // source packages
new List<(string, string)>
{
("Contoso.Core.Utils", "1.1.0"),
("Contoso.Core", "1.0.0"),
}, // argument packages
false, // enablePrerelease
"myOutput", // output directory subpath
new List<(string, string)>
{
("Contoso.Core.Utils", "1.1.0"),
("Contoso.Core", "1.0.0")
} // expected
};
// Mixed casing on the ID in the *download* argument
yield return new object[]
{
new List<(string, string)>
{
("Contoso.Core", "1.1.0")
}, // source packages
new List<(string, string)>
{
("contoso.core", "1.1.0")
}, // download argument
false, // enablePrerelease
"", // output directory subpath
new List<(string, string)>
{
("Contoso.Core", "1.1.0")
}, // expected
};
// prerelease with IncludePrerelease == true
yield return new object[]
{
new List<(string, string)>
{
("Contoso.Preview", "1.3.0"),
("Contoso.Preview", "2.0.0-beta.2")
}, // source packages
new List<(string, string)>
{
("Contoso.Preview", null),
}, // download argument
true, // enablePrerelease
"AnotherSubPath", // output directory subpath
new List<(string, string)>
{
("Contoso.Preview", "2.0.0-beta.2")
}, // expected
};
// chose stable with IncludePrerelease == false
yield return new object[]
{
new List<(string, string)>
{
("Contoso.Preview", "1.3.2"),
("Contoso.Preview", "1.3.0"),
("Contoso.Preview", "2.0.0-beta.2")
}, // source packages
new List<(string, string)>
{
("Contoso.Preview", null)
}, // download argument
false, // enablePrerelease
"SubPath", // output directory subpath
new List <(string, string) > {
("Contoso.Preview", "1.3.2")
} // expected
};
}
[Theory]
[MemberData(nameof(PackageTestData))]
public async Task RunAsync_ExplicitVersionFromLocalFolderSource_SucceedsAsync(
IReadOnlyList<(string, string)> sourcePackages,
IReadOnlyList<(string, string)> argumentPackages,
bool enablePrerelease,
string outputDirectorySubPath,
IReadOnlyList<(string, string)> expectedPackages)
{
// Arrange
using var context = new SimpleTestPathContext();
var sourceDir = context.PackageSource;
var outputDir = Path.Combine(context.WorkingDirectory, outputDirectorySubPath);
foreach (var (id, version) in sourcePackages)
{
await SimpleTestPackageUtility.CreateFullPackageAsync(sourceDir, id, version);
}
var logger = new Mock<ILoggerWithColor>(MockBehavior.Loose);
var settings = new Mock<ISettings>(MockBehavior.Loose);
List<PackageWithNuGetVersion> packages = [];
foreach (var (id, version) in argumentPackages)
{
packages.Add(new PackageWithNuGetVersion
{
Id = id,
NuGetVersion = version == null ? null : NuGetVersion.Parse(version)
});
}
var args = new PackageDownloadArgs()
{
Packages = packages,
OutputDirectory = outputDir,
IncludePrerelease = enablePrerelease,
};
// Act
var result = await PackageDownloadRunner.RunAsync(
args,
logger.Object,
[new(sourceDir)],
settings.Object,
CancellationToken.None);
// Assert
foreach (var (expectedId, expectedVersion) in expectedPackages)
{
result.Should().Be(PackageDownloadRunner.ExitCodeSuccess);
var installDir = Path.Combine(outputDir, expectedId.ToLowerInvariant(), expectedVersion);
Directory.Exists(installDir).Should().BeTrue();
Directory.EnumerateFiles(installDir, "*.nupkg").Any().Should().BeTrue();
File.Exists(Path.Combine(installDir, $"{expectedId.ToLowerInvariant()}.{expectedVersion}.nupkg")).Should().BeTrue();
}
}
[Fact]
public async Task RunAsync_NoVersion_PicksHighestAcrossMultipleSources()
{
// Arrange
using var contextA = new SimpleTestPathContext();
using var contextB = new SimpleTestPathContext();
var srcA = contextA.PackageSource;
var srcB = contextB.PackageSource;
var outputDir = contextA.WorkingDirectory;
var id = "Contoso.Toolkit";
await SimpleTestPackageUtility.CreateFullPackageAsync(srcA, id, "1.1.0");
await SimpleTestPackageUtility.CreateFullPackageAsync(srcB, id, "1.2.0");
var logger = new Mock<ILoggerWithColor>(MockBehavior.Loose);
var settings = new Mock<ISettings>(MockBehavior.Loose);
var args = new PackageDownloadArgs()
{
Packages = [new PackageWithNuGetVersion { Id = id, NuGetVersion = null }],
OutputDirectory = outputDir,
};
// Act
var result = await PackageDownloadRunner.RunAsync(
args,
logger.Object,
[new PackageSource(srcA), new PackageSource(srcB)],
settings.Object,
CancellationToken.None);
// Assert
result.Should().Be(PackageDownloadRunner.ExitCodeSuccess);
var chosen = Path.Combine(outputDir, id.ToLowerInvariant(), "1.2.0");
Directory.Exists(chosen).Should().BeTrue("should choose the highest version found across all sources");
File.Exists(Path.Combine(chosen, $"{id.ToLowerInvariant()}.1.2.0.nupkg")).Should().BeTrue();
}
public static IEnumerable<object[]> ShortCircuitsPackageData =>
[
// single package already installed
[
new []
{
("Contoso.Utils", "3.4.5") // source packages
},
new[]
{
new PackageWithNuGetVersion // argument packages
{
Id = "Contoso.Utils",
NuGetVersion = NuGetVersion.Parse("3.4.5")
}
},
new []
{
("Contoso.Utils", "3.4.5") // expected packages
}
],
// multiple packages already installed
[
new []
{
("Contoso.Utils", "3.4.5"), // source packages
("Contoso.Core", "3.0.5")
},
new []
{
new PackageWithNuGetVersion // argument packages
{
Id = "Contoso.Utils",
NuGetVersion = NuGetVersion.Parse("3.4.5")
},
new PackageWithNuGetVersion
{
Id = "Contoso.Core",
NuGetVersion = NuGetVersion.Parse("3.0.5")
}
},
new []
{
("Contoso.Utils", "3.4.5"), // expected packages
("Contoso.Core", "3.0.5")
}
],
// no version specified, but latest version already installed
[
new []
{
("Contoso.Utils", "3.4.5"), // source packages
("Contoso.Core", "3.0.5")
},
new []
{
new PackageWithNuGetVersion // argument packages
{
Id = "Contoso.Utils",
NuGetVersion = null
},
new PackageWithNuGetVersion
{
Id = "Contoso.Core",
NuGetVersion = null
}
},
new []
{
("Contoso.Utils", "3.4.5"), // expected packages
("Contoso.Core", "3.0.5")
}
]];
[Theory]
[MemberData(nameof(ShortCircuitsPackageData))]
internal async Task RunAsync_VersionAlreadyInstalled_ShortCircuitsAndSucceeds(
IReadOnlyList<(string, string)> sourcePackages,
PackageWithNuGetVersion[] packageDownloadArgs,
IReadOnlyList<(string, string)> expectedPackages)
{
// Arrange
using var context = new SimpleTestPathContext();
var sourceDir = context.PackageSource;
var outputDir = context.WorkingDirectory;
List<PackageWithNuGetVersion> packagesToInstall = [];
foreach (var (id, version) in sourcePackages)
{
await SimpleTestPackageUtility.CreateFullPackageAsync(sourceDir, id, version);
}
var logger = new Mock<ILoggerWithColor>(MockBehavior.Loose);
var settings = new Mock<ISettings>(MockBehavior.Loose);
// First run: install explicit version
var args1 = new PackageDownloadArgs()
{
Packages = packageDownloadArgs,
LogLevel = LogLevel.Verbose,
OutputDirectory = outputDir,
};
var first = await PackageDownloadRunner.RunAsync(
args1,
logger.Object,
[new PackageSource(sourceDir)],
settings.Object,
CancellationToken.None);
first.Should().Be(ExitCodes.Success);
// Second run: should short-circuit because already installed
var args2 = new PackageDownloadArgs()
{
Packages = packageDownloadArgs,
OutputDirectory = outputDir,
};
// Act
var second = await PackageDownloadRunner.RunAsync(
args2,
logger.Object,
[new PackageSource(sourceDir)],
settings.Object,
CancellationToken.None);
// Assert
foreach (var (id, version) in expectedPackages)
{
second.Should().Be(PackageDownloadRunner.ExitCodeSuccess);
var installDir = Path.Combine(outputDir, id.ToLowerInvariant(), version);
Directory.Exists(installDir).Should().BeTrue();
File.Exists(Path.Combine(installDir, $"{id.ToLowerInvariant()}.{version}.nupkg")).Should().BeTrue();
}
logger.Verify(l => l.LogMinimal(It.Is<string>(s => s.Contains("Skipping", StringComparison.OrdinalIgnoreCase))), Times.AtLeastOnce);
}
[Fact]
public async Task RunAsync_WhenAllowInsecureConnectionsFalse_RejectsHttpSource()
{
// Arrange
using var context = new SimpleTestPathContext();
var httpSource = "http://contoso/v3/index.json";
var logger = new Mock<ILoggerWithColor>(MockBehavior.Loose);
var settings = new Mock<ISettings>(MockBehavior.Loose);
var args = new PackageDownloadArgs()
{
Packages = [new PackageWithNuGetVersion { Id = "Contoso.Lib", NuGetVersion = null }],
};
// Act
var result = await PackageDownloadRunner.RunAsync(
args,
logger.Object,
[new PackageSource(httpSource)],
settings.Object,
CancellationToken.None);
// Assert
result.Should().Be(PackageDownloadRunner.ExitCodeError);
logger.Verify(l => l.LogError(It.Is<string>(s => s.Contains(httpSource, StringComparison.OrdinalIgnoreCase))), Times.AtLeastOnce);
}
[Fact]
public async Task RunAsync_PackageDoesNotExist_ReturnsError()
{
// Arrange
using var context = new SimpleTestPathContext();
var id = "Missing.Package";
var v = "9.9.9";
var logger = new Mock<ILoggerWithColor>(MockBehavior.Loose);
var settings = new Mock<ISettings>(MockBehavior.Loose);
var args = new PackageDownloadArgs()
{
Packages = [new PackageWithNuGetVersion { Id = id, NuGetVersion = NuGetVersion.Parse(v) }],
OutputDirectory = context.WorkingDirectory,
};
// Act
var result = await PackageDownloadRunner.RunAsync(
args,
logger.Object,
[new PackageSource(context.PackageSource)],
settings.Object,
CancellationToken.None);
// Assert
result.Should().Be(PackageDownloadRunner.ExitCodeError);
logger.Verify(l => l.LogError(It.IsAny<string>()), Times.AtLeastOnce);
File.Exists(Path.Combine(context.WorkingDirectory, $"{id.ToLowerInvariant()}.{v}.nupkg"))
.Should().BeFalse("Package does not exist in sources");
}
public static IEnumerable<object[]> Cases()
{
// Parameters:
// A-packages, B-packages, sourceMappings, sourcesArgs, downloadId, downloadVersion,
// allowInsecureConnections, expectSuccess, expectedInstalled
// --source specified, mapping ignored, package only in A -> success
yield return new object[]
{
new List<(string,string)> { ("Contoso.Lib", "1.0.0") }, // A
new List<(string,string)>(), // B
new List<(string,string)> { ("B", "Contoso.*") }, // mapping ignored
new List<string> { "A" }, // --source A
"Contoso.Lib", "1.0.0", // downloadId, downloadVersion
true, // allow insecure
true, // expect success
("Contoso.Lib", "1.0.0") // expectedInstalled
};
// no --source, mapping -> B, package only in B -> success
yield return new object[]
{
new List<(string,string)>(), // A
new List<(string,string)> { ("Contoso.Mapped", "2.0.0") }, // B
new List<(string,string)> { ("B", "Contoso.*") }, // mapping -> B
null, // no --source
"Contoso.Mapped", "2.0.0", // downloadId, downloadVersion
true, // allow insecure
true, // expect success
("Contoso.Mapped", "2.0.0") // expectedInstalled
};
// no --source, mapping -> A, package only in B -> fail
yield return new object[]
{
new List<(string,string)>(), // A
new List<(string,string)> { ("Contoso.Mapped", "2.0.0") },
new List<(string,string)> { ("A", "Contoso.*") }, // mapped to A
null,
"Contoso.Mapped", "2.0.0",
true,
false,
null!
};
// --source specified, no source mapping with an insecure source
yield return new object[]
{
new List<(string,string)> { ("Contoso.Lib", "1.0.0") }, // A
new List<(string,string)>(),
new List<(string,string)> { ("A", "Contoso.*") },
new List<string> { "A" }, // --source
"Contoso.Lib", "1.0.0",
false, // allow insecure connections false / not set to true
false,
null!
};
// no --source, mapping -> B, allow insecure not enabled -> fail
yield return new object[]
{
new List<(string,string)>(), // A
new List<(string,string)> { ("Contoso.Mapped", "1.0.0") },
new List<(string,string)> { ("B", "Contoso.*") },
null,
"Contoso.Mapped", "1.0.0",
false, // allow insecure connections false / not set to true
false,
null!
};
}
[Theory]
[MemberData(nameof(Cases))]
public async Task RunAsync_WithSourceMapping(
IReadOnlyList<(string id, string version)> sourceAPackages,
IReadOnlyList<(string id, string version)> sourceBPackages,
IReadOnlyList<(string source, string pattern)> sourceMappings,
IReadOnlyList<string> sourcesArgs,
string downloadId,
string downloadVersion,
bool allowInsecureConnections,
bool expectSuccess,
(string id, string version)? expectedInstalled)
{
// Arrange
using var context = new SimpleTestPathContext();
string srcADirectory = Path.Combine(context.PackageSource, "SourceA");
string srcBDirectory = Path.Combine(context.PackageSource, "SourceB");
using var serverA = new FileSystemBackedV3MockServer(srcADirectory);
using var serverB = new FileSystemBackedV3MockServer(srcBDirectory);
foreach (var (id, ver) in sourceAPackages)
{
await SimpleTestPackageUtility.CreateFullPackageAsync(srcADirectory, id, ver);
}
foreach (var (id, ver) in sourceBPackages)
{
await SimpleTestPackageUtility.CreateFullPackageAsync(srcBDirectory, id, ver);
}
serverA.Start();
serverB.Start();
// sources
context.Settings.AddSource("A", serverA.ServiceIndexUri);
context.Settings.AddSource("B", serverB.ServiceIndexUri);
// mapping
foreach (var (src, pattern) in sourceMappings)
{
context.Settings.AddPackageSourceMapping(src, pattern);
}
var settings = Settings.LoadSettingsGivenConfigPaths([context.Settings.ConfigPath]);
var packageSources = new List<PackageSource>
{
new(serverA.ServiceIndexUri, "A"),
new(serverB.ServiceIndexUri, "B")
};
// args
var args = new PackageDownloadArgs
{
Packages =
[
new PackageWithNuGetVersion
{
Id = downloadId,
NuGetVersion = downloadVersion is null ? null : NuGetVersion.Parse(downloadVersion)
}
],
OutputDirectory = context.WorkingDirectory,
AllowInsecureConnections = allowInsecureConnections,
Sources = sourcesArgs == null ? [] : sourcesArgs.ToList()
};
string capturedLogs = string.Empty;
var logger = new Mock<ILoggerWithColor>(MockBehavior.Loose);
logger
.Setup(l => l.LogError(It.IsAny<string>()))
.Callback<string>(msg => capturedLogs += msg + Environment.NewLine);
// Act
var exit = await PackageDownloadRunner.RunAsync(
args,
logger.Object,
packageSources,
settings,
CancellationToken.None);
serverA.Stop();
serverB.Stop();
// Assert
if (expectSuccess)
{
exit.Should().Be(PackageDownloadRunner.ExitCodeSuccess, because: capturedLogs);
expectedInstalled.Should().NotBeNull();
var (expId, expVer) = expectedInstalled!.Value;
var installDir = Path.Combine(context.WorkingDirectory, expId.ToLowerInvariant(), expVer);
Directory.Exists(installDir).Should().BeTrue();
File.Exists(Path.Combine(installDir, $"{expId.ToLowerInvariant()}.{expVer}.nupkg")).Should().BeTrue();
}
else
{
exit.Should().Be(PackageDownloadRunner.ExitCodeError);
}
}
}