private TestPackageReference GeneratePackageToGoMissing()
        {
            var project = new TestProject
            {
                Name             = "packagethatwillgomissing",
                TargetFrameworks = "netstandard1.3",
                IsSdkProject     = true,
            };

            var asset = _testAssetsManager
                        .CreateTestProject(project, project.Name)
                        .Restore(Log, project.Name);

            var pack = new PackCommand(
                Log,
                Path.Combine(asset.TestRoot, project.Name));

            pack.Execute().Should().Pass();

            return(new TestPackageReference(
                       project.Name,
                       "1.0.0",
                       pack.GetNuGetPackage(project.Name)));
        }
コード例 #2
0
        public void CompatibleFrameworksInPackage()
        {
            string      name        = Path.GetFileNameWithoutExtension(Path.GetTempFileName());
            TestProject testProject = new()
            {
                Name             = name,
                TargetFrameworks = "netstandard2.0;net5.0",
            };

            string sourceCode = @"
namespace PackageValidationTests
{
    public class First
    {
        public void test() { }
#if NETSTANDARD2_0
        public void test(string test) { }
#endif
    }
}";

            testProject.SourceFiles.Add("Hello.cs", sourceCode);
            TestAsset   asset       = _testAssetsManager.CreateTestProject(testProject, testProject.Name);
            PackCommand packCommand = new PackCommand(Log, Path.Combine(asset.TestRoot, testProject.Name));
            var         result      = packCommand.Execute();

            Assert.Equal(string.Empty, result.StdErr);
            Package package = NupkgParser.CreatePackage(packCommand.GetNuGetPackage(), null);

            new CompatibleFrameworkInPackageValidator(string.Empty, null, false, _log, null).Validate(package);
            Assert.NotEmpty(_log.errors);
            // TODO: add asserts for assembly and header metadata.
            string assemblyName = $"{asset.TestProject.Name}.dll";

            Assert.Contains($"CP0002 Member 'PackageValidationTests.First.test(string)' exists on lib/netstandard2.0/{assemblyName} but not on lib/net5.0/{assemblyName}", _log.errors);
        }
コード例 #3
0
ファイル: PackTests.cs プロジェクト: impanda-cookie/cli
        public void OutputsPackagesToConfigurationSubdirWhenOutputParameterIsNotPassed()
        {
            var testInstance = TestAssets.Get("TestLibraryWithConfiguration")
                               .CreateInstance()
                               .WithSourceFiles()
                               .WithRestoreFiles();

            var packCommand = new PackCommand(configuration: "Test")
                              .WithWorkingDirectory(testInstance.Root);

            var result = packCommand.Execute();

            result.Should().Pass();

            var outputDir = testInstance.Root
                            .GetDirectory("bin", "Test");

            outputDir.Should().Exist()
            .And.HaveFiles(new []
            {
                "TestLibraryWithConfiguration.1.0.0.nupkg",
                "TestLibraryWithConfiguration.1.0.0.symbols.nupkg"
            });
        }
コード例 #4
0
        List <XElement> PackAndGetDependencyGroups(TestProject testProject, out XNamespace ns)
        {
            var testProjectInstance = _testAssetsManager.CreateTestProject(testProject, testProject.Name)
                                      .Restore(Log, testProject.Name);

            var packCommand = new PackCommand(Log, testProjectInstance.TestRoot, testProject.Name);

            packCommand.Execute()
            .Should()
            .Pass();

            string nuspecPath = packCommand.GetIntermediateNuspecPath();
            var    nuspec     = XDocument.Load(nuspecPath);

            ns = nuspec.Root.Name.Namespace;

            var dependencyGroups = nuspec.Root
                                   .Element(ns + "metadata")
                                   .Element(ns + "dependencies")
                                   .Elements()
                                   .ToList();

            return(dependencyGroups);
        }
コード例 #5
0
        public void Nuget_reference_compat(string referencerTarget, string testDescription, string rawDependencyTargets,
                                           bool restoreSucceeds, bool buildSucceeds)
        {
            string referencerDirectoryNamePostfix = "_" + referencerTarget + "_" + testDescription;

            TestProject referencerProject = GetTestProject(ConstantStringValues.ReferencerDirectoryName, referencerTarget, true);

            //  Skip running test if not running on Windows
            //        https://github.com/dotnet/sdk/issues/335
            if (!(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || referencerProject.BuildsOnNonWindows))
            {
                return;
            }

            foreach (string dependencyTarget in rawDependencyTargets.Split(',', ';', ' ').ToList())
            {
                TestProject          dependencyProject          = GetTestProject(ConstantStringValues.DependencyDirectoryNamePrefix + dependencyTarget.Replace('.', '_'), dependencyTarget, true);
                TestPackageReference dependencyPackageReference = new TestPackageReference(
                    dependencyProject.Name,
                    "1.0.0",
                    ConstantStringValues.ConstructNuGetPackageReferencePath(dependencyProject));

                //  Skip creating the NuGet package if not running on Windows; or if the NuGet package already exists
                //        https://github.com/dotnet/sdk/issues/335
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || dependencyProject.BuildsOnNonWindows)
                {
                    if (!dependencyPackageReference.NuGetPackageExists())
                    {
                        //  Create the NuGet packages
                        var dependencyTestAsset        = _testAssetsManager.CreateTestProject(dependencyProject, ConstantStringValues.TestDirectoriesNamePrefix, ConstantStringValues.NuGetSharedDirectoryNamePostfix);
                        var dependencyRestoreCommand   = dependencyTestAsset.GetRestoreCommand(Log, relativePath: dependencyProject.Name).Execute().Should().Pass();
                        var dependencyProjectDirectory = Path.Combine(dependencyTestAsset.TestRoot, dependencyProject.Name);

                        var dependencyPackCommand = new PackCommand(Log, dependencyProjectDirectory);
                        var dependencyPackResult  = dependencyPackCommand.Execute().Should().Pass();
                    }

                    referencerProject.PackageReferences.Add(dependencyPackageReference);
                }
            }

            //  Skip running tests if no NuGet packages are referenced
            //        https://github.com/dotnet/sdk/issues/335
            if (referencerProject.PackageReferences == null)
            {
                return;
            }

            //  Set the referencer project as an Exe unless it targets .NET Standard
            if (!referencerProject.ShortTargetFrameworkIdentifiers.Contains(ConstantStringValues.NetstandardToken))
            {
                referencerProject.IsExe = true;
            }

            //  Create the referencing app and run the compat test
            var referencerTestAsset      = _testAssetsManager.CreateTestProject(referencerProject, ConstantStringValues.TestDirectoriesNamePrefix, referencerDirectoryNamePostfix);
            var referencerRestoreCommand = referencerTestAsset.GetRestoreCommand(Log, relativePath: referencerProject.Name);

            //  Modify the restore command to refer to the created NuGet packages
            foreach (TestPackageReference packageReference in referencerProject.PackageReferences)
            {
                var source = Path.Combine(packageReference.NupkgPath, packageReference.ID, "bin", "Debug");
                referencerRestoreCommand.AddSource(source);
            }

            if (restoreSucceeds)
            {
                referencerRestoreCommand.Execute().Should().Pass();
            }
            else
            {
                referencerRestoreCommand.Execute().Should().Fail();
            }

            var referencerBuildCommand = new BuildCommand(Log, Path.Combine(referencerTestAsset.TestRoot, referencerProject.Name));
            var referencerBuildResult  = referencerBuildCommand.Execute();

            if (buildSucceeds)
            {
                referencerBuildResult.Should().Pass();
            }
            else
            {
                referencerBuildResult.Should().Fail().And.HaveStdOutContaining("It cannot be referenced by a project that targets");
            }
        }
コード例 #6
0
        //  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)
                                      .Restore(Log, toolProject.Name, "/p:RestoreSources=https://dotnetfeed.blob.core.windows.net/dotnet-core/packages/index.json;https://dotnet.myget.org/F/dotnet-buildtools/api/v3/index.json;https://dotnet.myget.org/F/dotnet-core/api/v3/index.json;https://dotnet.myget.org/F/msbuild/api/v3/index.json;https://dotnet.myget.org/F/nuget-build/api/v3/index.json");

            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")));
            });

            var restoreCommand = toolReferencerInstance.GetRestoreCommand(Log, toolReferencer.Name);

            restoreCommand.AddSource(nupkgPath);
            restoreCommand.AddSource("https://dotnet.myget.org/F/dotnet-core/api/v3/index.json");
            restoreCommand.Execute().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 generateDepsProjectPath = Path.Combine(TestContext.Current.ToolsetUnderTest.SdksPath, "Microsoft.NET.Sdk", "build", "GenerateDeps", "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}");
                    }
                }
            }

            var generateDepsCommand = new MSBuildCommand(Log, "BuildDepsJson", generateDepsProjectPath);

            generateDepsCommand.Execute(args.ToArray())
            .Should()
            .Pass();

            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);
        }
コード例 #7
0
        //  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.DotnetCoreBlobFeed);

            // Workaorund https://github.com/dotnet/cli/issues/9701
            var useBundledNETCoreAppPackage = "/p:UseBundledNETCoreAppPackageVersionAsDefaultNetCorePatchVersion=true";

            toolProjectInstance.Restore(Log, toolProject.Name, "/v:n", useBundledNETCoreAppPackage);

            var packCommand = new PackCommand(Log, Path.Combine(toolProjectInstance.TestRoot, toolProject.Name));

            packCommand.Execute(useBundledNETCoreAppPackage)
            .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.DotnetCoreBlobFeed
            };

            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
                string dotnetSdkDir = TestContext.Current.ToolsetUnderTest.GetDotnetSdkDir(Log);
                currentToolsetSdksPath = Path.Combine(dotnetSdkDir, "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);
        }
コード例 #8
0
        public void It_can_restore_with_netcoreapp2_2()
        {
            TestProject toolProject = new TestProject()
            {
                Name             = "TestTool" + nameof(It_can_restore_with_netcoreapp2_2),
                IsSdkProject     = true,
                TargetFrameworks = "netcoreapp1.0",
                IsExe            = true
            };

            toolProject.AdditionalProperties.Add("PackageType", "DotnetCliTool");

            var toolProjectInstance = _testAssetsManager.CreateTestProject(toolProject, identifier: toolProject.Name);

            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 toolReferenceProject = new TestProject()
            {
                Name             = "DotNetCliToolReferenceProject",
                IsSdkProject     = true,
                IsExe            = true,
                TargetFrameworks = "netcoreapp1.0",
            };

            toolReferenceProject.DotNetCliToolReferences.Add(
                new TestPackageReference(id: toolProject.Name,
                                         version: ProjectToolVersion,
                                         nupkgPath: null));

            TestAsset toolReferenceProjectInstance = _testAssetsManager.CreateTestProject(toolReferenceProject, identifier: toolReferenceProject.Name);

            DeleteFolder(Path.Combine(TestContext.Current.NuGetCachePath, toolProject.Name.ToLowerInvariant()));
            DeleteFolder(Path.Combine(TestContext.Current.NuGetCachePath, ".tools", toolProject.Name.ToLowerInvariant()));
            NuGetConfigWriter.Write(toolReferenceProjectInstance.TestRoot, NuGetConfigWriter.DotnetCoreBlobFeed, nupkgPath);

            RestoreCommand restoreCommand =
                toolReferenceProjectInstance.GetRestoreCommand(log: Log, relativePath: toolReferenceProject.Name);

            var restoreResult = restoreCommand
                                .Execute("/v:n");

            if (restoreResult.ExitCode != 0)
            {
                // retry once since it downloads from the web
                toolReferenceProjectInstance.Restore(Log, toolReferenceProject.Name, "/v:n");
            }

            var assetsJsonPath = Path.Combine(TestContext.Current.NuGetCachePath,
                                              ".tools",
                                              toolProject.Name.ToLowerInvariant(),
                                              ProjectToolVersion,
                                              ExpectedProjectToolRestoreTargetFrameworkMoniker,
                                              "project.assets.json");
            LockFile lockFile = LockFileUtilities.GetLockFile(assetsJsonPath, NullLogger.Instance);

            lockFile.Targets.Single().TargetFramework
            .Should().Be(NuGetFramework.Parse(ExpectedProjectToolRestoreTargetFrameworkMoniker),
                         "Restore target framework should be capped at netcoreapp2.2 due to moving away from project tools." +
                         "Even when SDK's TFM is higher and the project's TFM is netcoreapp1.0");
        }