Esempio n. 1
0
        public void BuildRoslynCompilers(ProjectPerfOperation operation)
        {
            string sourceProject = @"C:\git\roslyn";
            var    testDir       = _testAssetsManager.CreateTestDirectory("Perf_Roslyn", identifier: operation.ToString());

            Console.WriteLine($"Mirroring {sourceProject} to {testDir.Path}...");
            FolderSnapshot.MirrorFiles(sourceProject, testDir.Path);
            TestContext.Current.WriteGlobalJson(testDir.Path);
            Console.WriteLine("Done");

            //  Override global.json from repo
            File.Delete(Path.Combine(testDir.Path, "global.json"));

            //  Run Roslyn's restore script
            var restoreCmd = new SdkCommandSpec()
            {
                FileName         = Path.Combine(testDir.Path, "Restore.cmd"),
                WorkingDirectory = testDir.Path
            };

            TestContext.Current.AddTestEnvironmentVariables(restoreCmd);
            restoreCmd.ToCommand().Execute().Should().Pass();

            TestProject(Path.Combine(testDir.Path, "Compilers.sln"), "Roslyn", operation);
        }
Esempio n. 2
0
        public void It_publishes_and_runs_self_contained_wpf_app()
        {
            var testDir = _testAssetsManager.CreateTestDirectory();

            var newCommand = new DotnetCommand(Log);

            newCommand.WorkingDirectory = testDir.Path;

            newCommand.Execute("new", "wpf").Should().Pass();

            var    project         = XDocument.Load(Path.Combine(testDir.Path, Path.GetFileName(testDir.Path) + ".csproj"));
            var    ns              = project.Root.Name.Namespace;
            string targetFramework = project.Root.Elements(ns + "PropertyGroup")
                                     .Elements(ns + "TargetFramework")
                                     .Single().Value;

            var rid = EnvironmentInfo.GetCompatibleRid(targetFramework);

            string mainWindowXamlCsPath = Path.Combine(testDir.Path, "MainWindow.xaml.cs");
            string csContents           = File.ReadAllText(mainWindowXamlCsPath);

            csContents = csContents.Replace("InitializeComponent();", @"InitializeComponent();

    this.Loaded += delegate { Application.Current.Shutdown(42); };");

            File.WriteAllText(mainWindowXamlCsPath, csContents);

            var restoreCommand = new RestoreCommand(Log, testDir.Path);

            restoreCommand.Execute($"/p:RuntimeIdentifier={rid}")
            .Should()
            .Pass();

            var publishCommand = new PublishCommand(Log, testDir.Path);

            publishCommand.Execute($"/p:RuntimeIdentifier={rid}")
            .Should()
            .Pass();

            var publishDirectory = publishCommand.GetOutputDirectory(
                targetFramework: targetFramework,
                runtimeIdentifier: rid);

            var runAppCommand = new SdkCommandSpec()
            {
                FileName = Path.Combine(publishDirectory.FullName, Path.GetFileName(testDir.Path) + ".exe")
            };

            runAppCommand.Environment["DOTNET_ROOT"] = Path.GetDirectoryName(TestContext.Current.ToolsetUnderTest.DotNetHostPath);

            var result = runAppCommand.ToCommand()
                         .CaptureStdErr()
                         .CaptureStdOut()
                         .Execute();

            result.ExitCode.Should().Be(42);
        }
Esempio n. 3
0
        public void It_publishes_and_runs_self_contained_web_app()
        {
            var testProject = new TestProject()
            {
                Name             = "SelfContainedWebApp",
                TargetFrameworks = "netcoreapp3.0",
                IsSdkProject     = true,
                IsExe            = true
            };

            testProject.RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(testProject.TargetFrameworks);

            var testAsset = _testAssetsManager.CreateTestProject(testProject)
                            .WithProjectChanges(project =>
            {
                var ns = project.Root.Name.Namespace;

                var itemGroup = new XElement(ns + "ItemGroup");
                project.Root.Add(itemGroup);

                itemGroup.Add(new XElement(ns + "FrameworkReference",
                                           new XAttribute("Include", "Microsoft.AspNetCore.App")));
            })
                            .Restore(Log, testProject.Name);

            var publishCommand = new PublishCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            publishCommand.Execute()
            .Should()
            .Pass();

            var publishDirectory = publishCommand.GetOutputDirectory(
                targetFramework: testProject.TargetFrameworks,
                runtimeIdentifier: testProject.RuntimeIdentifier);

            var runAppCommand = new SdkCommandSpec()
            {
                FileName = Path.Combine(publishDirectory.FullName, testProject.Name + EnvironmentInfo.ExecutableExtension)
            };

            runAppCommand.Environment["DOTNET_ROOT"] = Path.GetDirectoryName(TestContext.Current.ToolsetUnderTest.DotNetHostPath);

            var result = runAppCommand.ToCommand()
                         .CaptureStdErr()
                         .CaptureStdOut()
                         .Execute();

            result
            .Should()
            .Pass()
            .And
            .HaveStdOutContaining("Hello World");
        }
        //  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);
        }
        //  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);
        }
        public void It_discovers_assembly_parts(string aspnetVersion)
        {
            var testProject = new TestProject()
            {
                Name             = "AssemblyPartDiscovery",
                IsSdkProject     = true,
                TargetFrameworks = "net461",
                IsExe            = true
            };

            testProject.SourceFiles["Program.cs"] = @"
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.Extensions.DependencyModel;
using System.IO;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        var parts = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(""" + testProject.Name + @""");
        foreach (var item in parts)
        {
            System.Console.WriteLine(item.Name);
        }
    }
}";

            TestProject referencedProjectWithPart = new TestProject()
            {
                Name             = "ReferencedProjectWithPart",
                IsSdkProject     = true,
                TargetFrameworks = "net461",
                IsExe            = false
            };


            referencedProjectWithPart.References.Add("System.ServiceModel");

            referencedProjectWithPart.SourceFiles["Class1.cs"] = @"
class Class1
{
    public string X => typeof(System.ServiceModel.AddressFilterMode).ToString();
}";

            TestProject referencedProjectWithMvc = new TestProject()
            {
                Name             = "ReferencedProjectWithMVC",
                IsSdkProject     = true,
                ProjectSdk       = "Microsoft.NET.Sdk.Web",
                TargetFrameworks = "net461",
                IsExe            = false
            };

            referencedProjectWithMvc.PackageReferences.Add(new TestPackageReference("Microsoft.AspNetCore.Mvc", aspnetVersion));

            testProject.ReferencedProjects.Add(referencedProjectWithPart);
            testProject.ReferencedProjects.Add(referencedProjectWithMvc);

            var testProjectInstance = _testAssetsManager
                                      .CreateTestProject(testProject, identifier: aspnetVersion)
                                      .Restore(Log, testProject.Name);

            var buildCommand = new BuildCommand(Log, testProjectInstance.TestRoot, testProject.Name);

            buildCommand.Execute()
            .Should()
            .Pass();

            string outputPath = buildCommand.GetOutputDirectory(testProject.TargetFrameworks).FullName;

            string exePath = Path.Combine(outputPath, testProject.Name + ".exe");

            var toolCommandSpec = new SdkCommandSpec()
            {
                FileName = exePath
            };

            TestContext.Current.AddTestEnvironmentVariables(toolCommandSpec);

            ICommand toolCommand = toolCommandSpec.ToCommand().CaptureStdOut();

            var toolResult = toolCommand.Execute();

            toolResult.Should().Pass();
        }