public void Directory_Name_Contains_NinjaTurtles() { using (var testDirectory = new TestDirectory()) { StringAssert.Contains("NinjaTurtles", testDirectory.FullName); } }
public FileSystemIntegrationTester() { _testDirectory = new TestDirectory(); _testDirectory.ChangeDirectory(); _fileSystem = new FileSystem(); _basePath = Path.GetTempPath(); }
public void Constructor_Creates_Directory_And_Returns_In_FullName_Property() { using (var testDirectory = new TestDirectory()) { Assert.IsTrue(Directory.Exists(testDirectory.FullName)); } }
public void ConstructTestDirectoryWithNullFileSystem() { // Execute var directory = new TestDirectory(a_fileSystem: null, a_path: "\\"); // Assert Assert.AreEqual("\\", directory.Path); Assert.IsNotNull(directory.FileSystem); }
public void Dispose_Logs_Removal_Of_Directory() { string path; using (var testDirectory = new TestDirectory()) { path = testDirectory.FullName; } string expectedMessage = string.Format("DEBUG|Deleting folder \"{0}\".|", path); AssertLogContains(expectedMessage); }
public void CopyInWithNotExistingDirectory() { // Setup var fileSystem = new TestFileSystem(); var directory = fileSystem.StageDirectory(@"\directory"); var other = new TestDirectory(fileSystem, @"\other"); // Execute DirectoryHelpers.CopyIn(directory, other); }
public void CopyInOnNotExistingDirectory() { // Setup var fileSystem = new TestFileSystem(); var directory = new TestDirectory(@"\directory"); var file = fileSystem.StageFile(@"\file1.dat"); // Execute directory.CopyIn(file); }
public void Constructor_Logs_Created_Directory() { string path; using (var testDirectory = new TestDirectory()) { path = testDirectory.FullName; } string expectedMessage = string.Format("DEBUG|Creating folder \"{0}\".|", path); AssertLogContains(expectedMessage); }
public void ConstructTestDirectory() { // Setup var fileSystem = new TestFileSystem(); // Execute var directory = new TestDirectory(fileSystem, "\\"); // Assert Assert.AreEqual("\\", directory.Path); Assert.AreSame(fileSystem, directory.FileSystem); }
public FileSetTester() { _testDirectory = new TestDirectory(); _testDirectory.ChangeDirectory(); if (Directory.Exists("target")) { Directory.Delete("target", true); } Directory.CreateDirectory("target"); theFileSet = new FileSet(); }
public void Constructor_Copies_Non_Empty_Source_Directory() { string tempFolder = Path.GetTempPath(); string sourceFolder = Path.Combine(tempFolder, Guid.NewGuid().ToString("N")); string fileName = string.Format("{0:N}.txt", Guid.NewGuid()); Directory.CreateDirectory(sourceFolder); File.WriteAllText(Path.Combine(sourceFolder, fileName), "Ninja"); using (var testDirectory = new TestDirectory(sourceFolder)) { Assert.IsTrue(File.Exists(Path.Combine(testDirectory.FullName, fileName))); } Directory.Delete(sourceFolder, true); }
/// <summary> /// Runs the tests specified from the test assembly, found within the /// test directory identified in the provided /// <see cref="MutantMetaData" /> instance. /// <remarks> /// This method won't be called /// from a user's testing code, it is called internally by /// NinjaTurtles, and is only exposed publicly to allow for a new /// implementation to be provided as an extension to NinjaTurtles. /// </remarks> /// </summary> /// <param name="testDirectory"> /// The <see cref="TestDirectory" /> containing the test image. /// </param> /// <param name="testAssemblyLocation"> /// The file name (with or without path) of the unit test assembly. /// </param> /// <param name="testsToRun"> /// A list of qualified unit test names. /// </param> /// <returns> /// A <see cref="Process" /> instance to run the unit test runner. /// </returns> public override Process GetRunnerProcess(TestDirectory testDirectory, string testAssemblyLocation, IEnumerable<string> testsToRun) { IDictionary<string, IList<string>> testsByFixture = new Dictionary<string, IList<string>>(); foreach (var test in testsToRun) { int position = test.LastIndexOf("."); string fixture = test.Substring(0, position); string member = test.Substring(position + 1); if (!testsByFixture.ContainsKey(fixture)) { testsByFixture.Add(fixture, new List<string>()); } testsByFixture[fixture].Add(member); } string filter = string.Join(" or ", testsByFixture.Select( kv => string.Format("(Type: {0} and Member: {1})", kv.Key, string.Join(", ", kv.Value)))); string originalTestAssemblyLocation = testAssemblyLocation; testAssemblyLocation = Path.Combine(testDirectory.FullName, Path.GetFileName(testAssemblyLocation)); string arguments = string.Format("\"{0}\" {{0}}f:\"{1}\" {{0}}r:IsolatedProcess {{0}}sr", testAssemblyLocation, filter); var searchPath = new List<string>(); string solutionFolder = GetBestGuessSolutionFolder(originalTestAssemblyLocation); if (!string.IsNullOrEmpty(solutionFolder)) { DirectoryInfo gallioFolder = new DirectoryInfo(solutionFolder) .GetDirectories("packages").Single() .GetDirectories( "GallioBundle*").FirstOrDefault(); if (gallioFolder != null) { searchPath.Add(Path.Combine(gallioFolder.FullName, "bin")); } } string programFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); searchPath.Add(Path.Combine(programFilesFolder, "Gallio\\bin")); string programFilesX86Folder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); if (!string.IsNullOrEmpty(programFilesX86Folder)) { searchPath.Add(Path.Combine(programFilesX86Folder, "Gallio\\bin")); } return ConsoleProcessFactory.CreateProcess("Gallio.Echo.exe", arguments, searchPath); }
public void Dispose_Logs_Exception_When_Folder_Is_Locked() { string path; FileStream fileStream; using (var testDirectory = new TestDirectory()) { path = testDirectory.FullName; string fileName = Path.Combine(path, "locked.txt"); fileStream = File.OpenWrite(fileName); } fileStream.Dispose(); Directory.Delete(path, true); string expectedMessage = string.Format("ERROR|Failed to delete folder \"{0}\".|System.IO.IOException", path); AssertLogContains(expectedMessage, true); }
/// <summary> /// Runs the tests specified from the test assembly, found within the /// test directory identified in the provided /// <see cref="MutantMetaData" /> instance. /// <remarks> /// This method won't be called /// from a user's testing code, it is called internally by /// NinjaTurtles, and is only exposed publicly to allow for a new /// implementation to be provided as an extension to NinjaTurtles. /// </remarks> /// </summary> /// <param name="testDirectory"> /// The <see cref="TestDirectory" /> containing the test image. /// </param> /// <param name="testAssemblyLocation"> /// The file name (with or without path) of the unit test assembly. /// </param> /// <param name="testsToRun"> /// A list of qualified unit test names. /// </param> /// <returns> /// A <see cref="Process" /> instance to run the unit test runner. /// </returns> public override Process GetRunnerProcess(TestDirectory testDirectory, string testAssemblyLocation, IEnumerable<string> testsToRun) { testAssemblyLocation = Path.Combine(testDirectory.FullName, Path.GetFileName(testAssemblyLocation)); string testArguments = string.Join(" ", testsToRun.Select(t => string.Format("/test:\"{0}\"", t))); string arguments = string.Format("/testcontainer:\"{0}\" {1}", testAssemblyLocation, testArguments); var searchPath = new List<string>(); string programFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); string programFilesX86Folder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); AddSearchPathsForVisualStudioVersions(searchPath, programFilesFolder); if (!string.IsNullOrEmpty(programFilesX86Folder)) { AddSearchPathsForVisualStudioVersions(searchPath, programFilesX86Folder); } return ConsoleProcessFactory.CreateProcess("MSTest.exe", arguments, searchPath); }
public void GetDirectoryPathForNotExistingChild() { // Setup var fileSystem = new TestFileSystem(); fileSystem.StageDirectory(@"x:\mydirectory\directory1"); fileSystem.StageDirectory(@"x:\mydirectory\directory2\child"); fileSystem.StageFile(@"x:\mydirectory\directory3\file.rgb", new TestFileInstance()); var directory = new TestDirectory(fileSystem, @"x:\mydirectory"); // Execute var result = directory.DirectoryPath("Directory4"); // Assert Assert.AreEqual(@"x:\mydirectory\Directory4", result); }
public void GetChildDirectories() { // Setup var fileSystem = new TestFileSystem(); fileSystem.StageDirectory(@"x:\mydirectory\directory1"); fileSystem.StageDirectory(@"x:\mydirectory\directory2\child"); fileSystem.StageFile(@"x:\mydirectory\directory3\file.rgb", new TestFileInstance()); var directory = new TestDirectory(fileSystem, @"x:\mydirectory"); // Execute var result = directory.Directories(); // Assert Assert.AreEqual(3, result.Count()); }
public void GetChildFilesBySearchPattern() { // Setup var fileSystem = new TestFileSystem(); fileSystem.StageFile(@"x:\mydirectory\file1.dat", new TestFileInstance()); fileSystem.StageFile(@"x:\mydirectory\file2.css", new TestFileInstance()); fileSystem.StageFile(@"x:\mydirectory\file3.dat", new TestFileInstance()); fileSystem.StageFile(@"x:\mydirectory\otherdirectory\file4.dat", new TestFileInstance()); var directory = new TestDirectory(fileSystem, @"x:\mydirectory"); // Execute var filePaths = directory.Files("*.css"); // Assert Assert.AreEqual(1, filePaths.Count()); }
public async Task UWPRestore_BlankUWPApp() { // Arrange var sources = new List <PackageSource>(); sources.Add(new PackageSource("https://api.nuget.org/v3/index.json")); using (var packagesDir = TestDirectory.Create()) using (var projectDir = TestDirectory.Create()) using (var cacheContext = new SourceCacheContext()) { var configJson = JObject.Parse(@"{ ""dependencies"": { ""Microsoft.NETCore.UniversalWindowsPlatform"": ""5.0.0"" }, ""frameworks"": { ""uap10.0"": {} }, ""runtimes"": { ""win10-arm"": {}, ""win10-arm-aot"": {}, ""win10-x86"": {}, ""win10-x86-aot"": {}, ""win10-x64"": {}, ""win10-x64-aot"": {} } }"); var specPath = Path.Combine(projectDir, "TestProject", "project.json"); var spec = JsonPackageSpecReader.GetPackageSpec(configJson.ToString(), "TestProject", specPath).EnsureProjectJsonRestoreMetadata(); var logger = new TestLogger(); var request = new TestRestoreRequest(spec, sources, packagesDir, cacheContext, logger); request.LockFilePath = Path.Combine(projectDir, "project.lock.json"); var lockFileFormat = new LockFileFormat(); var command = new RestoreCommand(request); var expectedStream = GetResource("NuGet.Commands.FuncTest.compiler.resources.uwpBlankAppV2.json"); JObject expectedJson = null; using (var reader = new StreamReader(expectedStream)) { expectedJson = JObject.Parse(reader.ReadToEnd()); } // Act var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); var lockFileJson = JObject.Parse(File.ReadAllText(request.LockFilePath)); RemovePackageFolders(lockFileJson); RemoveRestoreSection(lockFileJson); // Assert Assert.True(result.Success); Assert.Equal(0, result.CompatibilityCheckResults.Sum(checkResult => checkResult.Issues.Count)); Assert.Equal(0, logger.Errors); Assert.Equal(0, logger.Warnings); Assert.Equal(118, result.GetAllInstalled().Count); Assert.Equal(expectedJson.ToString(), lockFileJson.ToString()); } }
public async Task RestoreCommand_WhenSwitchingBetweenLowercaseSettings_LockFileAlwaysRespectsLatestSetting(bool isLowercase) { // Arrange using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var sourceDir = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var projectDir = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); sourceDir.Create(); projectDir.Create(); var resolverA = new VersionFolderPathResolver(packagesDir.FullName, !isLowercase); var resolverB = new VersionFolderPathResolver(packagesDir.FullName, isLowercase); var sources = new List <string>(); sources.Add(sourceDir.FullName); var projectJson = @" { ""frameworks"": { ""netstandard1.0"": { ""dependencies"": { ""PackageA"": ""1.0.0-Beta"" } } } }"; File.WriteAllText(Path.Combine(projectDir.FullName, "project.json"), projectJson); var specPath = Path.Combine(projectDir.FullName, "project.json"); var spec = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath); var logger = new TestLogger(); var lockFilePath = Path.Combine(projectDir.FullName, "project.lock.json"); var lockFileFormat = new LockFileFormat(); var packageId = "PackageA"; var packageVersion = "1.0.0-Beta"; var packageAContext = new SimpleTestPackageContext(packageId, packageVersion); packageAContext.AddFile("lib/netstandard1.0/a.dll"); SimpleTestPackageUtility.CreateFullPackage(sourceDir.FullName, packageAContext); // Act // Execute the first restore with the opposite lowercase setting. var requestA = new TestRestoreRequest( spec, sources.Select(x => Repository.Factory.GetCoreV3(x)), packagesDir.FullName, Enumerable.Empty <string>(), logger) { LockFilePath = lockFilePath, IsLowercasePackagesDirectory = !isLowercase }; var commandA = new RestoreCommand(requestA); var resultA = await commandA.ExecuteAsync(); await resultA.CommitAsync(logger, CancellationToken.None); // Execute the second restore with the request lowercase setting. var requestB = new TestRestoreRequest( spec, sources.Select(x => Repository.Factory.GetCoreV3(x)), packagesDir.FullName, Enumerable.Empty <string>(), logger) { LockFilePath = lockFilePath, IsLowercasePackagesDirectory = isLowercase, ExistingLockFile = lockFileFormat.Read(lockFilePath) }; var commandB = new RestoreCommand(requestB); var resultB = await commandB.ExecuteAsync(); await resultB.CommitAsync(logger, CancellationToken.None); // Assert // Commands should have succeeded. Assert.True(resultA.Success); Assert.True(resultB.Success); // The lock file library path should match the requested case. var libraryA = resultA .LockFile .Libraries .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion); Assert.NotNull(libraryA); Assert.Equal( PathUtility.GetPathWithForwardSlashes(resolverA.GetPackageDirectory(packageId, libraryA.Version)), libraryA.Path); Assert.True(File.Exists(resolverA.GetPackageFilePath(packageId, libraryA.Version))); var libraryB = resultB .LockFile .Libraries .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion); Assert.NotNull(libraryB); Assert.Equal( PathUtility.GetPathWithForwardSlashes(resolverB.GetPackageDirectory(packageId, libraryB.Version)), libraryB.Path); Assert.True(File.Exists(resolverB.GetPackageFilePath(packageId, libraryB.Version))); // The lock file on disk should match the second restore's library. var diskLockFile = lockFileFormat.Read(lockFilePath); var lockFileLibrary = diskLockFile .Libraries .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion); Assert.NotNull(lockFileLibrary); Assert.Equal( PathUtility.GetPathWithForwardSlashes(resolverB.GetPackageDirectory(packageId, libraryB.Version)), libraryB.Path); Assert.Equal(libraryB, lockFileLibrary); } }
public void GetIsEmptyOnNotExistingDirectory() { // Setup var fileSystem = new TestFileSystem(); var directory = new TestDirectory(fileSystem, "\\directory\\does\\not\\exist"); // Execute var result = directory.IsEmpty; // Assert Assert.IsFalse(result); }
public TestSolutionManager(bool foo) { _testDirectory = TestDirectory.Create(); SolutionDirectory = _testDirectory; }
public VsSolutionRestoreServiceTests() { _testDirectory = TestDirectory.Create(); }
public async Task ClientPolicies_WithSignerInTrustedSignersListAsync(SigningTestType signature, SignaturePlacement trustedSigner, string validationMode) { // Arrange using (var dir = TestDirectory.Create()) using (var authorCertificate = new X509Certificate2(_testFixture.TrustedTestCertificate.Source.Cert)) using (var repoCertificate = new X509Certificate2(_trustedRepoTestCert.Source.Cert)) { var authorCertificateFingerprintString = SignatureTestUtility.GetFingerprint(authorCertificate, HashAlgorithmName.SHA256); var repoCertificateFingerprintString = SignatureTestUtility.GetFingerprint(repoCertificate, HashAlgorithmName.SHA256); var signedPackagePath = await CreateSignedPackageAsync(dir, signature, authorCertificate, repoCertificate); var trustedSignerString = ""; if (signature == SigningTestType.Author || (signature == SigningTestType.RepositoryCountersigned && trustedSigner == SignaturePlacement.PrimarySignature)) { trustedSignerString = $@"<author name=""author1""><certificate fingerprint=""{authorCertificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" /></author>"; } else { trustedSignerString = $@"<repository name=""repo1"" serviceIndex=""https://api.v3serviceIndex.test/json""><certificate fingerprint=""{repoCertificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" /></repository>"; } var config = $@" <configuration> <config> <add key=""signatureValidationMode"" value=""{validationMode}"" /> </config> <trustedSigners> {trustedSignerString} </trustedSigners> </configuration>"; var nugetConfigPath = "NuGet.Config"; SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, dir, config); // Act and Assert var settings = new Settings(dir); var clientPolicyContext = ClientPolicyContext.GetClientPolicy(settings, NullLogger.Instance); var trustProviders = new[] { new AllowListVerificationProvider(clientPolicyContext.AllowList, requireNonEmptyAllowList: clientPolicyContext.Policy == SignatureValidationMode.Require) }; var verifier = new PackageSignatureVerifier(trustProviders); using (var packageReader = new PackageArchiveReader(signedPackagePath)) { // Act var result = await verifier.VerifySignaturesAsync(packageReader, clientPolicyContext.VerifierSettings, CancellationToken.None); var resultsWithWarnings = result.Results.Where(r => r.GetWarningIssues().Any()); var resultsWithErrors = result.Results.Where(r => r.GetErrorIssues().Any()); var totalWarningIssues = resultsWithWarnings.SelectMany(r => r.GetWarningIssues()); var totalErrorIssues = resultsWithErrors.SelectMany(r => r.GetErrorIssues()); // Assert result.IsValid.Should().BeTrue(); totalWarningIssues.Count().Should().Be(0); totalErrorIssues.Count().Should().Be(0); } } }
public async Task FallbackFolderRestore_VerifyMissingFallbackFolderFailsAsync() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.3"": { ""dependencies"": { ""packageA"": ""1.0.0"", ""packageB"": ""1.0.0"" } } } }"; using (var workingDir = TestDirectory.Create()) { var fallbackFolder = new DirectoryInfo(Path.Combine(workingDir, "fallbackFolder")); var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest( spec1, sources, packagesDir.FullName, new List <string>() { fallbackFolder.FullName }, logger) { LockFilePath = Path.Combine(project1.FullName, "project.lock.json") }; var packageBContext = new SimpleTestPackageContext() { Id = "packageB", Version = "1.0.0" }; var packageAContext = new SimpleTestPackageContext() { Id = "packageA", Version = "1.0.0" }; await SimpleTestPackageUtility.CreatePackagesAsync( packageSource.FullName, packageAContext, packageBContext); // Act & Assert var command = new RestoreCommand(request); await Assert.ThrowsAsync <FatalProtocolException>(async() => await command.ExecuteAsync()); } }
public async Task Resources_AppearInLockFileWithAppropriateLocaleValue() { // Arrange var logger = new TestLogger(); var framework = "net46"; using (var workingDir = TestDirectory.Create()) { var repository = Path.Combine(workingDir, "repository"); Directory.CreateDirectory(repository); var projectDir = Path.Combine(workingDir, "project"); Directory.CreateDirectory(projectDir); var packagesDir = Path.Combine(workingDir, "packages"); Directory.CreateDirectory(packagesDir); var file = new FileInfo(Path.Combine(repository, "packageA.1.0.0.nupkg")); using (var zip = new ZipArchive(File.Create(file.FullName), ZipArchiveMode.Create)) { zip.AddEntry("lib/net46/MyPackage.dll", new byte[] { 0 }); zip.AddEntry("lib/net46/en-US/MyPackage.resources.dll", new byte[] { 0 }); zip.AddEntry("lib/net46/en-CA/MyPackage.resources.dll", new byte[] { 0 }); zip.AddEntry("lib/net46/fr-CA/MyPackage.resources.dll", new byte[] { 0 }); zip.AddEntry("packageA.nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2013/01/nuspec.xsd""> <metadata> <id>packageA</id> <version>1.0.0</version> <title /> <contentFiles> <files include=""**/*.*"" copyToOutput=""TRUE"" flatten=""true"" /> </contentFiles> </metadata> </package>", Encoding.UTF8); } var sources = new List <PackageSource>(); sources.Add(new PackageSource(repository)); var configJson = JObject.Parse(@"{ ""dependencies"": { ""packageA"": ""1.0.0"" }, ""frameworks"": { ""_FRAMEWORK_"": {} } }".Replace("_FRAMEWORK_", framework)); var specPath = Path.Combine(projectDir, "TestProject", "project.json"); var spec = JsonPackageSpecReader.GetPackageSpec(configJson.ToString(), "TestProject", specPath); var request = new TestRestoreRequest(spec, sources, packagesDir, logger); request.LockFilePath = Path.Combine(projectDir, "project.lock.json"); var command = new RestoreCommand(request); // Act var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); // Assert var target = result.LockFile.GetTarget(NuGetFramework.Parse(framework), null); var lib = target.Libraries.Single(); var resourceAssemblies = lib.ResourceAssemblies; AssertResourceAssembly(resourceAssemblies, "lib/net46/en-US/MyPackage.resources.dll", "en-US"); AssertResourceAssembly(resourceAssemblies, "lib/net46/en-CA/MyPackage.resources.dll", "en-CA"); AssertResourceAssembly(resourceAssemblies, "lib/net46/fr-CA/MyPackage.resources.dll", "fr-CA"); } }
public async Task FallbackFolderRestore_NoPackagesFoundInFallbackAsync() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.3"": { ""dependencies"": { ""packageA"": ""1.0.0"", ""packageB"": ""1.0.0"" } } } }"; using (var workingDir = TestDirectory.Create()) { var fallbackFolder = new DirectoryInfo(Path.Combine(workingDir, "fallbackFolder")); var fallbackFolder2 = new DirectoryInfo(Path.Combine(workingDir, "fallbackFolder2")); var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packageSource.Create(); project1.Create(); fallbackFolder.Create(); fallbackFolder2.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest( spec1, sources, packagesDir.FullName, new List <string>() { fallbackFolder.FullName, fallbackFolder2.FullName }, logger) { LockFilePath = Path.Combine(project1.FullName, "project.lock.json") }; var packageBContext = new SimpleTestPackageContext() { Id = "packageB", Version = "1.0.0" }; var packageAContext = new SimpleTestPackageContext() { Id = "packageA", Version = "1.0.0" }; await SimpleTestPackageUtility.CreatePackagesAsync( packageSource.FullName, packageAContext, packageBContext); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); // Assert Assert.True(result.Success); Assert.Equal(2, lockFile.Libraries.Count); Assert.Equal(2, result.GetAllInstalled().Count); Assert.Equal(2, Directory.GetDirectories(packagesDir.FullName).Length); Assert.Equal(3, lockFile.PackageFolders.Count); Assert.Equal(packagesDir.FullName, lockFile.PackageFolders[0].Path); Assert.Equal(fallbackFolder.FullName, lockFile.PackageFolders[1].Path); Assert.Equal(fallbackFolder2.FullName, lockFile.PackageFolders[2].Path); } }
public async Task CreatePathContextAsync_FromAssetsFile() { // Arrange using (var testDirectory = TestDirectory.Create()) { var userPackageFolder = Path.Combine(testDirectory.Path, "packagesA"); Directory.CreateDirectory(userPackageFolder); var fallbackPackageFolder = Path.Combine(testDirectory.Path, "packagesB"); Directory.CreateDirectory(fallbackPackageFolder); await SimpleTestPackageUtility.CreateFolderFeedV3Async( userPackageFolder, new PackageIdentity("Foo", NuGetVersion.Parse("1.0.1"))); await SimpleTestPackageUtility.CreateFolderFeedV3Async( fallbackPackageFolder, new PackageIdentity("Bar", NuGetVersion.Parse("1.0.2"))); var target = new VsPathContextProvider( Mock.Of <ISettings>(), Mock.Of <IVsSolutionManager>(), Mock.Of <ILogger>(), getLockFileOrNullAsync: _ => { var lockFile = new LockFile { PackageFolders = new[] { new LockFileItem(userPackageFolder), new LockFileItem(fallbackPackageFolder) }, Libraries = new[] { new LockFileLibrary { Type = LibraryType.Package, Name = "Foo", Version = NuGetVersion.Parse("1.0.1") }, new LockFileLibrary { Type = LibraryType.Package, Name = "Bar", Version = NuGetVersion.Parse("1.0.2") } } }; return(Task.FromResult(lockFile)); }); var project = Mock.Of <BuildIntegratedNuGetProject>(); // Act var actual = await target.CreatePathContextAsync(project, CancellationToken.None); // Assert Assert.NotNull(actual); Assert.Equal(userPackageFolder, actual.UserPackageFolder); Assert.Equal( new[] { fallbackPackageFolder }, actual.FallbackPackageFolders.Cast <string>().ToArray()); string actualPackageDirectory = null; var packageRootA = Path.Combine(userPackageFolder, "Foo", "1.0.1"); var assetFileA = Path.Combine(packageRootA, "lib", "net40", "a.dll"); Assert.True(actual.TryResolvePackageAsset(assetFileA, out actualPackageDirectory)); Assert.Equal(packageRootA, actualPackageDirectory, ignoreCase: true); var packageRootB = Path.Combine(fallbackPackageFolder, "Bar", "1.0.2"); var assetFileB = Path.Combine(packageRootB, "lib", "net46", "b.dll"); Assert.True(actual.TryResolvePackageAsset(assetFileB, out actualPackageDirectory)); Assert.Equal(packageRootB, actualPackageDirectory, ignoreCase: true); } }
public PreinstalledRepositoryProviderTests() { _testDirectory = TestDirectory.Create(); }
public void GetExistsOnExistingFile() { // Setup var path = "\\directory\\does\\exist"; var fileSystem = new TestFileSystem(); fileSystem.StageDirectory(path); var directory = new TestDirectory(fileSystem, path); // Execute var result = directory.Exists; // Assert Assert.IsTrue(result); }
public async Task UWPRestore_BlankUWPAppV1() { // Arrange var sources = new List <PackageSource>(); sources.Add(new PackageSource("https://api.nuget.org/v3/index.json")); using (var packagesDir = TestDirectory.Create()) using (var projectDir = TestDirectory.Create()) { var configJson = JObject.Parse(@"{ ""dependencies"": { ""Microsoft.NETCore.UniversalWindowsPlatform"": ""5.0.0"" }, ""frameworks"": { ""uap10.0"": {} }, ""runtimes"": { ""win10-arm"": {}, ""win10-arm-aot"": {}, ""win10-x86"": {}, ""win10-x86-aot"": {}, ""win10-x64"": {}, ""win10-x64-aot"": {} } }"); var specPath = Path.Combine(projectDir, "TestProject", "project.json"); var spec = JsonPackageSpecReader.GetPackageSpec(configJson.ToString(), "TestProject", specPath); var logger = new TestLogger(); var request = new TestRestoreRequest(spec, sources, packagesDir, logger); request.LockFilePath = Path.Combine(projectDir, "project.lock.json"); // Set the lock file version to v1 to force a downgrade request.LockFileVersion = 1; var lockFileFormat = new LockFileFormat(); var command = new RestoreCommand(request); var expectedStream = GetResource("NuGet.Commands.FuncTest.compiler.resources.uwpBlankAppV1.json"); JObject expectedJson = null; using (var reader = new StreamReader(expectedStream)) { expectedJson = JObject.Parse(reader.ReadToEnd()); } // Act var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); var lockFileJson = JObject.Parse(File.OpenText(request.LockFilePath).ReadToEnd()); RemovePackageFolders(lockFileJson); // Assert Assert.True(result.Success); Assert.Equal(0, result.CompatibilityCheckResults.Sum(checkResult => checkResult.Issues.Count)); Assert.Equal(0, logger.Errors); Assert.Equal(0, logger.Warnings); Assert.Equal(118, result.GetAllInstalled().Count); // TODO: skipping comparing assets file since NuGet.org is doing repo sign for all the existing // packages which is changing the sha512 in the assets file which fails the comparison. // We should enable it once all the packages are repo signed. // tracking issue# https://github.com/NuGet/Home/issues/7361 //Assert.Equal(expectedJson.ToString(), lockFileJson.ToString()); } }
public void GetFileByNameWithNull() { // Setup var fileSystem = new TestFileSystem(); var directory = new TestDirectory(fileSystem, @"x:\mydirectory"); // Execute directory.File(a_name: null); }
public void GetMSBuildSdkVersions_ReloadsGlobalJson_WhenGlobalJsonChanges() { var expectedVersions = new Dictionary <string, string> { { "Sdk1", "1.0.0" }, { "Sdk2", "2.0.0" }, }; using (var testDirectory = TestDirectory.Create()) { var expectedGlobalJsonReaderPath = WriteGlobalJson(testDirectory, expectedVersions); var context = new MockSdkResolverContext(testDirectory); var globalJsonReader = new GlobalJsonReader(); Dictionary <string, int> globalJsonReadCountByPath = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase); globalJsonReader.FileRead += (_, globalJsonPath) => { if (globalJsonReadCountByPath.ContainsKey(globalJsonPath)) { globalJsonReadCountByPath[globalJsonPath]++; } else { globalJsonReadCountByPath[globalJsonPath] = 1; } }; globalJsonReader.GetMSBuildSdkVersions(context).Should().Equal(expectedVersions); globalJsonReadCountByPath.ContainsKey(expectedGlobalJsonReaderPath).Should().BeTrue(); globalJsonReadCountByPath[expectedGlobalJsonReaderPath].Should().Be(1); Parallel.For(0, Environment.ProcessorCount * 2, _ => { globalJsonReader.GetMSBuildSdkVersions(context).Should().Equal(expectedVersions); }); globalJsonReadCountByPath.ContainsKey(expectedGlobalJsonReaderPath).Should().BeTrue(); globalJsonReadCountByPath[expectedGlobalJsonReaderPath].Should().Be(1); expectedVersions["Sdk1"] = "2.0.0;"; string path = WriteGlobalJson(testDirectory, expectedVersions); File.SetLastWriteTime(path, DateTime.Now.AddMinutes(1)); Parallel.For(0, Environment.ProcessorCount * 2, _ => { globalJsonReader.GetMSBuildSdkVersions(context).Should().Equal(expectedVersions); }); globalJsonReadCountByPath.ContainsKey(expectedGlobalJsonReaderPath).Should().BeTrue(); globalJsonReadCountByPath[expectedGlobalJsonReaderPath].Should().Be(2); } }
public async Task BuildIntegratedRestoreUtility_RestoreToRelativePathGlobalPackagesFolder() { // Arrange var projectName = "testproj"; using (var rootFolder = TestDirectory.Create()) using (var configFolder = TestDirectory.Create()) using (var solutionFolderParent = TestDirectory.Create()) { var projectFolder = new DirectoryInfo(Path.Combine(rootFolder, projectName)); projectFolder.Create(); var projectConfig = new FileInfo(Path.Combine(projectFolder.FullName, "project.json")); var msbuildProjectPath = new FileInfo(Path.Combine(projectFolder.FullName, $"{projectName}.csproj")); File.WriteAllText(projectConfig.FullName, BuildIntegrationTestUtility.ProjectJsonWithPackage); var sources = new List <SourceRepository> { Repository.Factory.GetVisualStudio("https://www.nuget.org/api/v2/") }; var projectTargetFramework = NuGetFramework.Parse("uap10.0"); var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext()); var project = new ProjectJsonNuGetProject(projectConfig.FullName, msbuildProjectPath.FullName); var configContents = @"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <config> <add key=""globalPackagesFolder"" value=""..\NuGetPackages"" /> </config> <packageSources> <add key=""nuget.org.v2"" value=""https://www.nuget.org/api/v2/"" /> </packageSources> </configuration>"; var configSubFolder = Path.Combine(configFolder, "sub"); Directory.CreateDirectory(configSubFolder); File.WriteAllText(Path.Combine(configFolder, "sub", "nuget.config"), configContents); var settings = new Configuration.Settings(configSubFolder); var solutionFolder = new DirectoryInfo(Path.Combine(solutionFolderParent, "solutionFolder")); solutionFolder.Create(); var solutionManager = new TestSolutionManager(false); solutionManager.NuGetProjects.Add(project); var testLogger = new TestLogger(); var restoreContext = new DependencyGraphCacheContext(testLogger, settings); // Act await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, new RestoreCommandProvidersCache(), (c) => { }, sources, false, await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext), testLogger, CancellationToken.None); // Assert Assert.True(File.Exists(Path.Combine(projectFolder.FullName, "project.lock.json"))); var packagesFolder = Path.Combine(configFolder, "NuGetPackages"); Assert.True(Directory.Exists(packagesFolder)); Assert.True(File.Exists(Path.Combine( packagesFolder, "EntityFramework", "5.0.0", "EntityFramework.5.0.0.nupkg"))); Assert.True(testLogger.Errors == 0, testLogger.ShowErrors()); } }
public DirectoryInfo GetProgramFilesDirectory(ProgramFiles programFiles) => TestDirectory.GetDirectory($"ProgramFiles{programFiles}");
public async Task RestoreCommand_VerifyRuntimeSpecificAssetsAreNotIncludedForCompile_RuntimeAndRef() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.5"": { ""dependencies"": { ""packageA"": ""1.0.0"" } } }, ""runtimes"": { ""win7-x64"": {} } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); var packageAContext = new SimpleTestPackageContext("packageA"); packageAContext.AddFile("ref/netstandard1.5/a.dll"); packageAContext.AddFile("runtimes/win7-x64/lib/netstandard1.5/a.dll"); SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageAContext); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); var targetLib = lockFile.GetTarget(NuGetFramework.Parse("netstandard1.5"), "win7-x64") .Libraries .Single(library => library.Name == "packageA"); // Assert Assert.True(result.Success); Assert.Equal("ref/netstandard1.5/a.dll", targetLib.CompileTimeAssemblies.Single()); Assert.Equal("runtimes/win7-x64/lib/netstandard1.5/a.dll", targetLib.RuntimeAssemblies.Single()); } }
public async Task GetInstallActionsAsync_WithProjectReferenceProject_WhenUpdatingPackage_ReturnsCorrectActions() { const string projectName = "a"; string projectId = Guid.NewGuid().ToString(); var projectSystemCache = new ProjectSystemCache(); using (TestDirectory testDirectory = TestDirectory.Create()) { var packageV1 = new SimpleTestPackageContext(packageId: "b", version: "1.0.0"); var packageV2 = new SimpleTestPackageContext(packageV1.Id, version: "2.0.0"); string packageSourceDirectoryPath = Path.Combine(testDirectory, "packageSource"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( packageSourceDirectoryPath, PackageSaveMode.Defaultv3, packageV1, packageV2); var packageSource = new PackageSource(packageSourceDirectoryPath); var packageSources = new List <PackageSource>() { packageSource }; Initialize(packageSources); string projectFullPath = Path.Combine(testDirectory.Path, $"{projectName}.csproj"); var unconfiguredProject = new Mock <UnconfiguredProject>(); var configuredProject = new Mock <ConfiguredProject>(); var projectServices = new Mock <ConfiguredProjectServices>(); var packageReferencesService = new Mock <IPackageReferencesService>(); var result = new Mock <IUnresolvedPackageReference>(); unconfiguredProject.Setup(x => x.GetSuggestedConfiguredProjectAsync()) .ReturnsAsync(configuredProject.Object); configuredProject.SetupGet(x => x.Services) .Returns(projectServices.Object); projectServices.SetupGet(x => x.PackageReferences) .Returns(packageReferencesService.Object); packageReferencesService.Setup(x => x.AddAsync(It.IsNotNull <string>(), It.IsNotNull <string>())) .ReturnsAsync(new AddReferenceResult <IUnresolvedPackageReference>(result.Object, added: true)); var nuGetProjectServices = new Mock <INuGetProjectServices>(); nuGetProjectServices.SetupGet(x => x.ScriptService) .Returns(Mock.Of <IProjectScriptHostService>()); var project = new CpsPackageReferenceProject( projectName: projectName, projectUniqueName: projectFullPath, projectFullPath: projectFullPath, projectSystemCache, unconfiguredProject.Object, nuGetProjectServices.Object, projectId); PackageSpec packageSpec = CreatePackageSpec( project.ProjectName, Path.Combine(testDirectory, "package.spec")); DependencyGraphSpec projectRestoreInfo = ProjectJsonTestHelpers.GetDGSpecFromPackageSpecs(packageSpec); projectRestoreInfo.AddProject(packageSpec); var projectNames = new ProjectNames( fullName: projectFullPath, uniqueName: projectFullPath, shortName: projectName, customUniqueName: projectName, projectId: projectId); projectSystemCache.AddProjectRestoreInfo(projectNames, projectRestoreInfo, Array.Empty <IAssetsLogMessage>()); _solutionManager.NuGetProjects.Add(project); string[] projectIds = new[] { projectId }; string[] packageSourceNames = new[] { packageSource.Name }; await PerformOperationAsync(async (projectManager) => { IReadOnlyList <ProjectAction> actions = await projectManager.GetInstallActionsAsync( projectIds, packageV1.Identity, VersionConstraints.None, includePrelease: true, DependencyBehavior.Lowest, packageSourceNames, CancellationToken.None); Assert.NotEmpty(actions); Assert.Equal(1, actions.Count); ProjectAction action = actions[0]; Assert.Equal(packageV1.Identity, action.PackageIdentity); Assert.Equal(NuGetProjectActionType.Install, action.ProjectActionType); Assert.Equal(projectId, action.ProjectId); Assert.Equal(1, action.ImplicitActions.Count); ImplicitProjectAction implicitAction = action.ImplicitActions[0]; Assert.Equal(packageV1.Identity, implicitAction.PackageIdentity); Assert.Equal(NuGetProjectActionType.Install, implicitAction.ProjectActionType); await projectManager.ExecuteActionsAsync(actions, CancellationToken.None); }); await PerformOperationAsync(async (projectManager) => { IReadOnlyList <ProjectAction> actions = await projectManager.GetInstallActionsAsync( projectIds, packageV2.Identity, VersionConstraints.None, includePrelease: true, DependencyBehavior.Lowest, packageSourceNames, CancellationToken.None); Assert.NotEmpty(actions); Assert.Equal(1, actions.Count); ProjectAction action = actions[0]; Assert.Equal(packageV2.Identity, action.PackageIdentity); Assert.Equal(NuGetProjectActionType.Install, action.ProjectActionType); Assert.Equal(projectId, action.ProjectId); Assert.Equal(2, action.ImplicitActions.Count); ImplicitProjectAction implicitAction = action.ImplicitActions[0]; Assert.Equal(packageV1.Identity, implicitAction.PackageIdentity); Assert.Equal(NuGetProjectActionType.Uninstall, implicitAction.ProjectActionType); implicitAction = action.ImplicitActions[1]; Assert.Equal(packageV2.Identity, implicitAction.PackageIdentity); Assert.Equal(NuGetProjectActionType.Install, implicitAction.ProjectActionType); }); } }
public async Task RestoreCommand_ReferenceWithSameNameDifferentCasing() { // Arrange var sources = new List <PackageSource>(); // Both TxMs reference packageA, but they are different types. // Verify that the reference does not show up under libraries. var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.3"": { ""dependencies"": { ""packageA"": ""4.0.0"" } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "PROJECT1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "PROJECT1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); var aContext = new SimpleTestPackageContext() { Id = "packageA", Version = "4.0.0" }; aContext.Dependencies.Add(new SimpleTestPackageContext("proJect1")); SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, "projeCt1", "4.0.0"); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); // Assert // Verify no stack overflows from circular dependencies Assert.False(result.Success); } }
public async Task GetInstallActionsAsync_WithPackagesConfigProject_WhenUpdatingPackage_ReturnsCorrectActions() { const string projectName = "a"; string projectId = Guid.NewGuid().ToString(); using (TestDirectory testDirectory = TestDirectory.Create()) { var packageV1 = new SimpleTestPackageContext(packageId: "b", version: "1.0.0"); var packageV2 = new SimpleTestPackageContext(packageV1.Id, version: "2.0.0"); string packageSourceDirectoryPath = Path.Combine(testDirectory, "packageSource"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( packageSourceDirectoryPath, PackageSaveMode.Defaultv3, packageV1, packageV2); var packageSource = new PackageSource(packageSourceDirectoryPath); var packageSources = new List <PackageSource>() { packageSource }; Initialize(packageSources); string projectFullPath = Path.Combine(testDirectory.Path, $"{projectName}.csproj"); NuGetFramework targetFramework = NuGetFramework.Parse("net46"); var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(targetFramework, new TestNuGetProjectContext()); var project = new TestMSBuildNuGetProject(msBuildNuGetProjectSystem, testDirectory.Path, projectFullPath, projectId); _solutionManager.NuGetProjects.Add(project); string[] projectIds = new[] { projectId }; string[] packageSourceNames = new[] { packageSource.Name }; await PerformOperationAsync(async (projectManager) => { IReadOnlyList <ProjectAction> actions = await projectManager.GetInstallActionsAsync( projectIds, packageV1.Identity, VersionConstraints.None, includePrelease: true, DependencyBehavior.Lowest, packageSourceNames, CancellationToken.None); Assert.NotEmpty(actions); Assert.Equal(1, actions.Count); ProjectAction action = actions[0]; Assert.Equal(packageV1.Identity, action.PackageIdentity); Assert.Equal(NuGetProjectActionType.Install, action.ProjectActionType); Assert.Equal(projectId, action.ProjectId); Assert.Empty(action.ImplicitActions); await projectManager.ExecuteActionsAsync(actions, CancellationToken.None); }); await PerformOperationAsync(async (projectManager) => { IReadOnlyList <ProjectAction> actions = await projectManager.GetInstallActionsAsync( projectIds, packageV2.Identity, VersionConstraints.None, includePrelease: true, DependencyBehavior.Lowest, packageSourceNames, CancellationToken.None); Assert.NotEmpty(actions); Assert.Equal(2, actions.Count); ProjectAction action = actions[0]; Assert.Equal(packageV1.Identity, action.PackageIdentity); Assert.Equal(NuGetProjectActionType.Uninstall, action.ProjectActionType); Assert.Equal(projectId, action.ProjectId); action = actions[1]; Assert.Equal(packageV2.Identity, action.PackageIdentity); Assert.Equal(NuGetProjectActionType.Install, action.ProjectActionType); Assert.Equal(projectId, action.ProjectId); }); } }
public void DeleteNotExistingDirectory() { // Setup var fileSystem = new TestFileSystem(); var directory = new TestDirectory(fileSystem, "\\this\\is\\a\\directory"); // Execute directory.Delete(); }
public async Task PackagePath_NotNull() { // Prepare var solutionManager = Mock.Of <INuGetSolutionManagerService>(); var uiContext = new Mock <INuGetUIContext>(); uiContext.Setup(x => x.SolutionManagerService) .Returns(solutionManager); var searchService = new Mock <INuGetSearchService>(MockBehavior.Strict); var packageSearchMetadata = new PackageSearchMetadataBuilder.ClonedPackageSearchMetadata() { Identity = new PackageIdentity("NuGet.org", new NuGetVersion("1.0")), PrefixReserved = true, PackagePath = "somesillypath", }; var packageSearchMetadataContextInfo = new List <PackageSearchMetadataContextInfo>() { PackageSearchMetadataContextInfo.Create(packageSearchMetadata) }; var searchResult = new SearchResultContextInfo(packageSearchMetadataContextInfo, new Dictionary <string, LoadingStatus> { { "Search", LoadingStatus.Loading } }, false); searchService.Setup(x => x.SearchAsync( It.IsAny <IReadOnlyCollection <IProjectContextInfo> >(), It.IsAny <IReadOnlyCollection <PackageSourceContextInfo> >(), It.IsAny <IReadOnlyCollection <string> >(), It.IsAny <string>(), It.IsAny <SearchFilter>(), It.IsAny <NuGet.VisualStudio.Internal.Contracts.ItemFilter>(), It.IsAny <bool>(), It.IsAny <CancellationToken>())) .Returns(new ValueTask <SearchResultContextInfo>(searchResult)); var packageFileService = new Mock <INuGetPackageFileService>(); uiContext.Setup(x => x.ServiceBroker) .Returns(Mock.Of <IServiceBroker>()); using (var localFeedDir = TestDirectory.Create()) // local feed { // create test package var pkgId = new PackageIdentity("nuget.lpsm.test", new NuGetVersion(0, 0, 1)); var pkg = new SimpleTestPackageContext(pkgId.Id, pkgId.Version.ToNormalizedString()); await SimpleTestPackageUtility.CreatePackagesAsync(localFeedDir.Path, pkg); // local test source var localUri = new Uri(localFeedDir.Path, UriKind.Absolute); var localSource = new PackageSource(localUri.ToString(), "LocalSource"); var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] { localSource }); var repositories = sourceRepositoryProvider.GetRepositories(); var context = new PackageLoadContext(isSolution: false, uiContext.Object); var packageFeed = new MultiSourcePackageFeed(repositories, logger: null, telemetryService: null); var loader = await PackageItemLoader.CreateAsync( Mock.Of <IServiceBroker>(), context, new List <PackageSourceContextInfo> { PackageSourceContextInfo.Create(localSource) }, NuGet.VisualStudio.Internal.Contracts.ItemFilter.All, searchService.Object, packageFileService.Object, TestSearchTerm); // Act await loader.LoadNextAsync(progress : null, CancellationToken.None); var results = loader.GetCurrent(); // Assert Assert.Single(results); Assert.NotNull(results.First().PackagePath); } }
public void GetProjectRestoreMetadataFrameworkInfos_WhenProjectReferenceSpecified_UsesFrameworkFromTargetFrameworkInformation() { using (var testDirectory = TestDirectory.Create()) { var projectA = new MockMSBuildProject(Path.Combine(testDirectory, "ProjectA", "ProjectA.csproj")); var projectB = new MockMSBuildProject(Path.Combine(testDirectory, "ProjectB", "ProjectB.csproj")); var net45Alias = "net45"; var netstandard20Alias = "netstandard2.0"; var projects = new Dictionary <string, IMSBuildProject> { [net45Alias] = new MockMSBuildProject(testDirectory) { Items = new Dictionary <string, IList <IMSBuildItem> > { ["ProjectReference"] = new List <IMSBuildItem> { new MSBuildItem(@"ProjectA\ProjectA.csproj", new Dictionary <string, string> { ["FullPath"] = projectA.FullPath }), new MSBuildItem(@"ProjectB\ProjectB.csproj", new Dictionary <string, string> { ["FullPath"] = projectB.FullPath }), } } }, [netstandard20Alias] = new MockMSBuildProject(testDirectory) { Items = new Dictionary <string, IList <IMSBuildItem> > { ["ProjectReference"] = new List <IMSBuildItem> { new MSBuildItem(@"ProjectA\ProjectA.csproj", new Dictionary <string, string> { ["FullPath"] = projectA.FullPath }), } } } }; var targetFrameworkInfos = new List <TargetFrameworkInformation>(); targetFrameworkInfos.Add(new TargetFrameworkInformation { TargetAlias = net45Alias, FrameworkName = FrameworkConstants.CommonFrameworks.Net45 }); targetFrameworkInfos.Add(new TargetFrameworkInformation { TargetAlias = netstandard20Alias, FrameworkName = FrameworkConstants.CommonFrameworks.NetStandard20 }); var actual = MSBuildStaticGraphRestore.GetProjectRestoreMetadataFrameworkInfos(targetFrameworkInfos, projects); actual.ShouldBeEquivalentTo(new[] { new ProjectRestoreMetadataFrameworkInfo(FrameworkConstants.CommonFrameworks.Net45) { TargetAlias = net45Alias, ProjectReferences = new List <ProjectRestoreReference> { new ProjectRestoreReference { ProjectPath = projectA.FullPath, ProjectUniqueName = projectA.FullPath }, new ProjectRestoreReference { ProjectPath = projectB.FullPath, ProjectUniqueName = projectB.FullPath } } }, new ProjectRestoreMetadataFrameworkInfo(FrameworkConstants.CommonFrameworks.NetStandard20) { TargetAlias = netstandard20Alias, ProjectReferences = new List <ProjectRestoreReference> { new ProjectRestoreReference { ProjectPath = projectA.FullPath, ProjectUniqueName = projectA.FullPath } } } }); } }
public void GetNotExistingChildDirectoryByName() { // Setup var fileSystem = new TestFileSystem(); fileSystem.StageDirectory(@"x:\mydirectory\directory1"); fileSystem.StageDirectory(@"x:\mydirectory\directory2\child"); fileSystem.StageFile(@"x:\mydirectory\directory3\file.rgb", new TestFileInstance()); var directory = new TestDirectory(fileSystem, @"x:\mydirectory"); // Execute var result = directory.Directory("Directory4"); // Assert Assert.AreEqual("Directory4", result.Name); Assert.IsFalse(result.Exists); }
public void GetChildFilesWithNullSearchPattern() { // Setup var fileSystem = new TestFileSystem(); var directory = new TestDirectory(fileSystem, @"x:\mydirectory"); // Execute directory.Files(a_pattern: null); }
private PackageReaderTest(PackageFolderReader reader, TestDirectory directory) { Reader = reader; _directory = directory; RootDirectoryPath = directory.Path; }
public void GetDirectoryWithNullName() { // Setup var fileSystem = new TestFileSystem(); var directory = new TestDirectory(fileSystem, @"x:\mydirectory"); // Execute var result = directory.Directory(a_name: null); }
// This method duplicates a lot of logic from the CLI in order to test generating deps files for tools in the SDK repo private CommandResult GenerateDepsAndRunTool(TestProject toolProject, [CallerMemberName] string callingMethod = "") { DeleteFolder(Path.Combine(TestContext.Current.NuGetCachePath, toolProject.Name.ToLowerInvariant())); DeleteFolder(Path.Combine(TestContext.Current.NuGetCachePath, ".tools", toolProject.Name.ToLowerInvariant())); var toolProjectInstance = _testAssetsManager.CreateTestProject(toolProject, callingMethod, identifier: toolProject.Name); NuGetConfigWriter.Write(toolProjectInstance.TestRoot, NuGetConfigWriter.DotnetCoreMyGetFeed); toolProjectInstance.Restore(Log, toolProject.Name, "/v:n"); var packCommand = new PackCommand(Log, Path.Combine(toolProjectInstance.TestRoot, toolProject.Name)); packCommand.Execute() .Should() .Pass(); string nupkgPath = Path.Combine(packCommand.ProjectRootPath, "bin", "Debug"); TestProject toolReferencer = new TestProject() { Name = "ToolReferencer", IsSdkProject = true, TargetFrameworks = "netcoreapp2.0" }; var toolReferencerInstance = _testAssetsManager.CreateTestProject(toolReferencer, callingMethod, identifier: toolReferencer.Name) .WithProjectChanges(project => { var ns = project.Root.Name.Namespace; var itemGroup = new XElement(ns + "ItemGroup"); project.Root.Add(itemGroup); itemGroup.Add(new XElement(ns + "DotNetCliToolReference", new XAttribute("Include", toolProject.Name), new XAttribute("Version", "1.0.0"))); }); List <string> sources = new List <string>() { NuGetConfigWriter.DotnetCoreMyGetFeed }; sources.Add(nupkgPath); NuGetConfigWriter.Write(toolReferencerInstance.TestRoot, sources); var restoreCommand = toolReferencerInstance.GetRestoreCommand(Log, toolReferencer.Name); restoreCommand.Execute("/v:n").Should().Pass(); string toolAssetsFilePath = Path.Combine(TestContext.Current.NuGetCachePath, ".tools", toolProject.Name.ToLowerInvariant(), "1.0.0", toolProject.TargetFrameworks, "project.assets.json"); var toolAssetsFile = new LockFileFormat().Read(toolAssetsFilePath); var args = new List <string>(); string currentToolsetSdksPath; if (TestContext.Current.ToolsetUnderTest.SdksPath == null) { // We don't have an overridden path to the SDKs, so figure out which version of the SDK we're using and // calculate the path based on that var command = new DotnetCommand(Log, "--version"); var testDirectory = TestDirectory.Create(Path.Combine(TestContext.Current.TestExecutionDirectory, "sdkversion")); command.WorkingDirectory = testDirectory.Path; var result = command.Execute(); result.Should().Pass(); var sdkVersion = result.StdOut.Trim(); string dotnetDir = Path.GetDirectoryName(TestContext.Current.ToolsetUnderTest.DotNetHostPath); currentToolsetSdksPath = Path.Combine(dotnetDir, "sdk", sdkVersion, "Sdks"); } else { currentToolsetSdksPath = TestContext.Current.ToolsetUnderTest.SdksPath; } string generateDepsProjectDirectoryPath = Path.Combine(currentToolsetSdksPath, "Microsoft.NET.Sdk", "targets", "GenerateDeps"); string generateDepsProjectFileName = "GenerateDeps.proj"; args.Add($"/p:ProjectAssetsFile=\"{toolAssetsFilePath}\""); args.Add($"/p:ToolName={toolProject.Name}"); string depsFilePath = Path.Combine(Path.GetDirectoryName(toolAssetsFilePath), toolProject.Name + ".deps.json"); args.Add($"/p:ProjectDepsFilePath={depsFilePath}"); var toolTargetFramework = toolAssetsFile.Targets.First().TargetFramework.GetShortFolderName(); args.Add($"/p:TargetFramework={toolProject.TargetFrameworks}"); // Look for the .props file in the Microsoft.NETCore.App package, until NuGet // generates .props and .targets files for tool restores (https://github.com/NuGet/Home/issues/5037) var platformLibrary = toolAssetsFile.Targets .Single() .Libraries .FirstOrDefault(e => e.Name.Equals("Microsoft.NETCore.App", StringComparison.OrdinalIgnoreCase)); if (platformLibrary != null) { string buildRelativePath = platformLibrary.Build.FirstOrDefault()?.Path; var platformLibraryPath = GetPackageDirectory(toolAssetsFile, platformLibrary); if (platformLibraryPath != null && buildRelativePath != null) { // Get rid of "_._" filename buildRelativePath = Path.GetDirectoryName(buildRelativePath); string platformLibraryBuildFolderPath = Path.Combine(platformLibraryPath, buildRelativePath); var platformLibraryPropsFile = Directory.GetFiles(platformLibraryBuildFolderPath, "*.props").FirstOrDefault(); if (platformLibraryPropsFile != null) { args.Add($"/p:AdditionalImport={platformLibraryPropsFile}"); } } } args.Add("/v:n"); var generateDepsCommand = new MSBuildCommand(Log, "BuildDepsJson", generateDepsProjectDirectoryPath, generateDepsProjectFileName); generateDepsCommand.Execute(args.ToArray()) .Should() .Pass(); new DirectoryInfo(generateDepsProjectDirectoryPath) .Should() .OnlyHaveFiles(new[] { generateDepsProjectFileName }); var toolLibrary = toolAssetsFile.Targets .Single() .Libraries.FirstOrDefault( l => StringComparer.OrdinalIgnoreCase.Equals(l.Name, toolProject.Name)); var toolAssembly = toolLibrary?.RuntimeAssemblies .FirstOrDefault(r => Path.GetFileNameWithoutExtension(r.Path) == toolProject.Name); var toolPackageDirectory = GetPackageDirectory(toolAssetsFile, toolLibrary); var toolAssemblyPath = Path.Combine( toolPackageDirectory, toolAssembly.Path); var dotnetArgs = new List <string>(); dotnetArgs.Add("exec"); dotnetArgs.Add("--depsfile"); dotnetArgs.Add(depsFilePath); foreach (var packageFolder in GetNormalizedPackageFolders(toolAssetsFile)) { dotnetArgs.Add("--additionalprobingpath"); dotnetArgs.Add(packageFolder); } dotnetArgs.Add(Path.GetFullPath(toolAssemblyPath)); var toolCommandSpec = new SdkCommandSpec() { FileName = TestContext.Current.ToolsetUnderTest.DotNetHostPath, Arguments = dotnetArgs }; TestContext.Current.AddTestEnvironmentVariables(toolCommandSpec); ICommand toolCommand = toolCommandSpec.ToCommand().CaptureStdOut(); var toolResult = toolCommand.Execute(); return(toolResult); }
public void GetExistsWithNonexistingFile() { // Setup var fileSystem = new TestFileSystem(); var directory = new TestDirectory(fileSystem, "\\directory\\does\\not\\exist"); // Execute var result = directory.Exists; // Assert Assert.IsFalse(result); }
public async Task RestoreCommand_ObservesLowercaseFlag(bool isLowercase) { // Arrange using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var sourceDir = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var projectDir = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); sourceDir.Create(); projectDir.Create(); var resolver = new VersionFolderPathResolver(packagesDir.FullName, isLowercase); var sources = new List <string>(); sources.Add(sourceDir.FullName); var projectJson = @" { ""frameworks"": { ""netstandard1.0"": { ""dependencies"": { ""PackageA"": ""1.0.0-Beta"" } } } }"; File.WriteAllText(Path.Combine(projectDir.FullName, "project.json"), projectJson); var specPath = Path.Combine(projectDir.FullName, "project.json"); var spec = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath); var logger = new TestLogger(); var request = new TestRestoreRequest( spec, sources.Select(x => Repository.Factory.GetCoreV3(x)), packagesDir.FullName, Enumerable.Empty <string>(), logger) { IsLowercasePackagesDirectory = isLowercase }; request.LockFilePath = Path.Combine(projectDir.FullName, "project.lock.json"); var packageId = "PackageA"; var packageVersion = "1.0.0-Beta"; var packageAContext = new SimpleTestPackageContext(packageId, packageVersion); packageAContext.AddFile("lib/netstandard1.0/a.dll"); SimpleTestPackageUtility.CreateFullPackage(sourceDir.FullName, packageAContext); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; // Assert Assert.True(result.Success); var library = lockFile .Libraries .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion); Assert.NotNull(library); Assert.Equal( PathUtility.GetPathWithForwardSlashes(resolver.GetPackageDirectory(packageId, library.Version)), library.Path); Assert.True(File.Exists(resolver.GetPackageFilePath(packageId, library.Version))); } }
public void GetFilePathByName() { // Setup var created = DateTime.UtcNow; var lastModified = DateTime.UtcNow; var fileSystem = new TestFileSystem(); fileSystem.StageFile(@"x:\mydirectory\file1.dat", new TestFileInstance { Size = 1024, CreatedTimeUtc = created, LastModifiedTimeUtc = lastModified }); fileSystem.StageFile(@"x:\mydirectory\file2.dat", new TestFileInstance { Size = 14067, CreatedTimeUtc = created, LastModifiedTimeUtc = lastModified }); fileSystem.StageFile(@"x:\mydirectory\file3.dat", new TestFileInstance { Size = 2017, CreatedTimeUtc = created, LastModifiedTimeUtc = lastModified }); fileSystem.StageFile(@"x:\mydirectory\otherdirectory\file4.dat", new TestFileInstance { Size = 8740, CreatedTimeUtc = created, LastModifiedTimeUtc = lastModified }); var directory = new TestDirectory(fileSystem, @"x:\mydirectory"); // Execute var result = directory.FilePath("File1.dat"); // Assert Assert.AreEqual(@"x:\mydirectory\File1.dat", result); }
[PlatformSpecific(PlatformID.Linux | PlatformID.FreeBSD)] // testing case-Sensitivity public void CaseSensitivity() { Assert.False(new DirectoryInfo(TestDirectory.ToUpperInvariant()).Exists); Assert.False(new DirectoryInfo(TestDirectory.ToLowerInvariant()).Exists); }
public void GetName() { // Setup var fileSystem = new TestFileSystem(); var directory = new TestDirectory(fileSystem, "\\this\\is\\a\\directory"); // Execute var result = directory.Name; // Assert Assert.AreEqual("directory", result); }
private void InitializeInstanceFields() { Dir = TestDirectory.testDirectory(Fs.get()); }
public void GetParent() { // Setup var fileSystem = new TestFileSystem(); var directory = new TestDirectory(fileSystem, "\\this\\is\\a\\directory"); // Execute var result = directory.Parent; // Assert Assert.IsNotNull(result); Assert.AreEqual("a", result.Name); }
public void GetProjectReferences_WhenDuplicateExistsOrMetadataSpecified_DuplicatesIgnoredAndMetadataReadCorrectly() { using (var testDirectory = TestDirectory.Create()) { var projectA = new MockMSBuildProject(Path.Combine(testDirectory, "ProjectA", "ProjectA.csproj")); var projectB = new MockMSBuildProject(Path.Combine(testDirectory, "ProjectB", "ProjectB.csproj")); var projectC = new MockMSBuildProject(Path.Combine(testDirectory, "ProjectC", "ProjectC.csproj")); var projectD = new MockMSBuildProject(Path.Combine(testDirectory, "ProjectD", "ProjectD.csproj")); var project = new MockMSBuildProject(testDirectory) { Items = new Dictionary <string, IList <IMSBuildItem> > { ["ProjectReference"] = new List <IMSBuildItem> { new MSBuildItem(@"ProjectA\ProjectA.csproj", new Dictionary <string, string> { ["FullPath"] = projectA.FullPath }), new MSBuildItem(@"ProjectA\ProjectA.csproj", new Dictionary <string, string> { ["FullPath"] = "ShouldBeDeduped" }), new MSBuildItem(@"ProjectB\ProjectB.csproj", new Dictionary <string, string> { ["FullPath"] = projectB.FullPath, ["ExcludeAssets"] = $"{LibraryIncludeFlags.Compile};{LibraryIncludeFlags.Runtime}" }), new MSBuildItem(@"ProjectC\ProjectC.csproj", new Dictionary <string, string> { ["FullPath"] = projectC.FullPath, ["IncludeAssets"] = $"{LibraryIncludeFlags.Build};{LibraryIncludeFlags.BuildTransitive}" }), new MSBuildItem(@"ProjectD\ProjectD.csproj", new Dictionary <string, string> { ["FullPath"] = projectD.FullPath, ["PrivateAssets"] = $"{LibraryIncludeFlags.Runtime};{LibraryIncludeFlags.ContentFiles}" }), new MSBuildItem(@"ProjectE\ProjectE.csproj", new Dictionary <string, string> { ["ReferenceOutputAssembly"] = bool.FalseString }), } } }; var actual = MSBuildStaticGraphRestore.GetProjectReferences(project); actual.ShouldBeEquivalentTo(new[] { new ProjectRestoreReference { ProjectPath = projectA.FullPath, ProjectUniqueName = projectA.FullPath }, new ProjectRestoreReference { ProjectPath = projectB.FullPath, ProjectUniqueName = projectB.FullPath, ExcludeAssets = LibraryIncludeFlags.Runtime | LibraryIncludeFlags.Compile }, new ProjectRestoreReference { ProjectPath = projectC.FullPath, ProjectUniqueName = projectC.FullPath, IncludeAssets = LibraryIncludeFlags.Build | LibraryIncludeFlags.BuildTransitive }, new ProjectRestoreReference { ProjectPath = projectD.FullPath, ProjectUniqueName = projectD.FullPath, PrivateAssets = LibraryIncludeFlags.Runtime | LibraryIncludeFlags.ContentFiles } }); } }
public FilesSystem_load_from_file() { _testDirectory = new TestDirectory(); _testDirectory.ChangeDirectory(); }
public async Task GetDownloadResultUtility_WithTwoOfTheSameDownloads_DoesNotCollide() { // Arrange var uri = new Uri("http://fake/content.nupkg"); var expectedContent = "TestContent"; var identity = new PackageIdentity("PackageA", NuGetVersion.Parse("1.0.0-Beta")); var testHttpSource = new TestHttpSource( new PackageSource("http://fake"), new Dictionary <string, string> { { uri.ToString(), expectedContent } }); var logger = new TestLogger(); var token = CancellationToken.None; using (var cacheContext = new SourceCacheContext()) using (var downloadDirectory = TestDirectory.Create()) using (var globalPackagesFolder = TestDirectory.Create()) { var downloadContext = new PackageDownloadContext( cacheContext, downloadDirectory, directDownload: true); // Act using (var resultA = await GetDownloadResultUtility.GetDownloadResultAsync( testHttpSource, identity, uri, downloadContext, globalPackagesFolder, logger, token)) using (var resultB = await GetDownloadResultUtility.GetDownloadResultAsync( testHttpSource, identity, uri, downloadContext, globalPackagesFolder, logger, token)) { // Assert var files = Directory.EnumerateFileSystemEntries(downloadDirectory).ToArray(); Assert.Equal(2, files.Length); Assert.EndsWith(".nugetdirectdownload", Path.GetFileName(files[0])); Assert.EndsWith(".nugetdirectdownload", Path.GetFileName(files[1])); using (var reader = new StreamReader(resultA.PackageStream)) { var actualContentA = reader.ReadToEnd(); Assert.Equal(expectedContent, actualContentA); } using (var reader = new StreamReader(resultB.PackageStream)) { var actualContentB = reader.ReadToEnd(); Assert.Equal(expectedContent, actualContentB); } } Assert.Equal(0, Directory.EnumerateFileSystemEntries(downloadDirectory).Count()); Assert.Equal(0, Directory.EnumerateFileSystemEntries(globalPackagesFolder).Count()); } }
private void CommonInitialize() { NuGetExePath = Util.GetNuGetExePath(); WorkingPath = TestDirectory.Create(); }
public ProgramFacts(ITestOutputHelper output) { _console = new TextOutputWriter(output); _directory = TestDirectory.Create(); }
public void SaveAssembly_Logs_Save() { var module = new Module(GetType().Assembly.Location); string fileName = Path.GetFileName(module.AssemblyLocation); string path; using (var testDirectory = new TestDirectory()) { testDirectory.SaveAssembly(module); path = testDirectory.FullName; } string expectedMessage = string.Format("DEBUG|Writing assembly \"{0}\" to \"{1}\".|", fileName, path); AssertLogContains(expectedMessage); }
public void GetPackageReferences_WhenDuplicatesOrMetadataSpecified_DuplicatesIgnoredAndMetadataReadCorrectly() { using (var testDirectory = TestDirectory.Create()) { var project = new MockMSBuildProject(testDirectory) { Items = new Dictionary <string, IList <IMSBuildItem> > { ["PackageReference"] = new List <IMSBuildItem> { new MSBuildItem("PackageA", new Dictionary <string, string> { ["Version"] = "1.1.1" }), new MSBuildItem("PackageA", new Dictionary <string, string> { ["Version"] = "2.0.0" }), new MSBuildItem("PackageB", new Dictionary <string, string> { ["Version"] = "1.2.3", ["IsImplicitlyDefined"] = bool.TrueString }), new MSBuildItem("PackageC", new Dictionary <string, string> { ["Version"] = "4.5.6", ["GeneratePathProperty"] = bool.TrueString }), new MSBuildItem("PackageD", new Dictionary <string, string> { ["Version"] = "1.2.3", ["IncludeAssets"] = $"{LibraryIncludeFlags.Build};{LibraryIncludeFlags.Analyzers}" }), new MSBuildItem("PackageE", new Dictionary <string, string> { ["Version"] = "1.2.3", ["PrivateAssets"] = $"{LibraryIncludeFlags.Runtime};{LibraryIncludeFlags.Compile}" }), new MSBuildItem("PackageF", new Dictionary <string, string> { ["Version"] = "1.2.3", ["ExcludeAssets"] = $"{LibraryIncludeFlags.Build};{LibraryIncludeFlags.Analyzers}" }), new MSBuildItem("PackageG", new Dictionary <string, string> { ["Version"] = "1.2.3", ["IncludeAssets"] = $"{LibraryIncludeFlags.Build};{LibraryIncludeFlags.Analyzers};{LibraryIncludeFlags.Compile}", ["ExcludeAssets"] = $"{LibraryIncludeFlags.Analyzers}" }), new MSBuildItem("PackageH", new Dictionary <string, string> { ["Version"] = "1.2.3", ["NoWarn"] = "NU1001;\tNU1006 ; NU3017 " }), new MSBuildItem("PackageI", new Dictionary <string, string> { ["Version"] = null }), new MSBuildItem("PackageJ", new Dictionary <string, string> { ["Version"] = "1.2.4", ["Aliases"] = "Core" }), } } }; var actual = MSBuildStaticGraphRestore.GetPackageReferences(project, false); actual.ShouldBeEquivalentTo(new List <LibraryDependency> { new LibraryDependency { LibraryRange = new LibraryRange("PackageA", VersionRange.Parse("1.1.1"), LibraryDependencyTarget.Package), }, new LibraryDependency { AutoReferenced = true, LibraryRange = new LibraryRange("PackageB", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package), }, new LibraryDependency { GeneratePathProperty = true, LibraryRange = new LibraryRange("PackageC", VersionRange.Parse("4.5.6"), LibraryDependencyTarget.Package), }, new LibraryDependency { IncludeType = LibraryIncludeFlags.Build | LibraryIncludeFlags.Analyzers, LibraryRange = new LibraryRange("PackageD", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package), }, new LibraryDependency { SuppressParent = LibraryIncludeFlags.Runtime | LibraryIncludeFlags.Compile, LibraryRange = new LibraryRange("PackageE", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package), }, new LibraryDependency { IncludeType = LibraryIncludeFlags.Runtime | LibraryIncludeFlags.Compile | LibraryIncludeFlags.Native | LibraryIncludeFlags.ContentFiles | LibraryIncludeFlags.BuildTransitive, LibraryRange = new LibraryRange("PackageF", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package), }, new LibraryDependency { IncludeType = LibraryIncludeFlags.Compile | LibraryIncludeFlags.Build, LibraryRange = new LibraryRange("PackageG", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package), }, new LibraryDependency { LibraryRange = new LibraryRange("PackageH", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package), NoWarn = new List <NuGetLogCode> { NuGetLogCode.NU1001, NuGetLogCode.NU1006, NuGetLogCode.NU3017 } }, new LibraryDependency { LibraryRange = new LibraryRange("PackageI", VersionRange.All, LibraryDependencyTarget.Package), }, new LibraryDependency { LibraryRange = new LibraryRange("PackageJ", VersionRange.Parse("1.2.4"), LibraryDependencyTarget.Package), Aliases = "Core" } }); } }