Example #1
0
        public void WhenTargetingNetCore3_0AspNetCoreAllPackageReferenceErrors(bool useWebSdk, string packageVersion)
        {
            var testProject = new TestProject()
            {
                Name             = "AspNetCoreAll_On3_0",
                TargetFrameworks = "netcoreapp3.0",
                ProjectSdk       = useWebSdk ? "Microsoft.NET.Sdk.Web" : null,
                IsExe            = true
            };

            //  Add PackageReference
            testProject.PackageReferences.Add(new TestPackageReference("Microsoft.AspNetCore.All", packageVersion));

            var testAsset = _testAssetsManager.CreateTestProject(testProject, identifier: $"{useWebSdk}_{packageVersion}");

            var restoreCommand = new RestoreCommand(testAsset);

            restoreCommand.Execute()
            .Should()
            .Fail()
            .And
            .HaveStdOutContaining("NETSDK1079");

            var buildCommand = new BuildCommand(testAsset);

            buildCommand.Execute()
            .Should()
            .Fail()
            .And
            .HaveStdOutContaining("NETSDK1079");
        }
Example #2
0
        public void MultipleWarningsAreGeneratedForMultipleExplicitReferences()
        {
            var testProject = new TestProject()
            {
                Name             = "MultipleExplicitReferences",
                TargetFrameworks = "netcoreapp2.1",
                IsExe            = true
            };

            testProject.PackageReferences.Add(new TestPackageReference("Microsoft.NETCore.App", "2.1.0"));
            testProject.PackageReferences.Add(new TestPackageReference("Microsoft.AspNetCore.App", "2.1.0"));

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var restoreCommand = new RestoreCommand(testAsset);

            restoreCommand
            .Execute()
            .Should()
            .Pass()
            .And
            .NotHaveStdOutContaining("NETSDK1071");


            var buildCommand = new BuildCommand(testAsset);

            buildCommand
            .Execute()
            .Should()
            .Pass()
            .And
            .HaveStdOutContaining("NETSDK1071")
            .And
            .HaveStdOutContaining("NETSDK1023");
        }
Example #3
0
        private async Task <bool> Restore(PublishRoot root, PublishProject publishProject, string restoreDirectory, IEnumerable <FrameworkName> targetFrameworks)
        {
            var appEnv = PlatformServices.Default.Application;

            var feedOptions = new FeedOptions();

            feedOptions.IgnoreFailedSources = true;
            feedOptions.Sources.Add(root.TargetPackagesPath);
            feedOptions.TargetPackagesFolder = root.TargetPackagesPath;

            var restoreCommand = new RestoreCommand(appEnv);

            restoreCommand.TargetFrameworks.AddRange(targetFrameworks);
            restoreCommand.RequestedRuntimes = root.RuntimeIdentifiers;
            restoreCommand.SkipRestoreEvents = true;
            restoreCommand.SkipInstall       = true;
            // This is a workaround for #1322. Since we use restore to generate the lock file
            // after publish, it's possible to fail restore after copying the closure
            // if framework assemblies and packages have the same name. This is more likely now
            // since dependencies may exist in the top level
            restoreCommand.IgnoreMissingDependencies = true;
            restoreCommand.CheckHashFile             = false;
            restoreCommand.RestoreDirectories.Add(restoreDirectory);
            restoreCommand.FeedOptions = feedOptions;

            // Mute "dnu restore" subcommand
            restoreCommand.Reports = Reports.Constants.NullReports;

            var success = await restoreCommand.Execute();

            return(success);
        }
        private void Restore(string projectDirectory, string projectName = null)
        {
            var command = new RestoreCommand()
                          .WithWorkingDirectory(projectDirectory);

            if (projectName != null)
            {
                command.Execute($"{projectName}.csproj /p:SkipInvalidConfigurations=true;_InvalidConfigurationWarning=false")
                .Should().Pass();
            }
            else
            {
                command.Execute("/p:SkipInvalidConfigurations=true;_InvalidConfigurationWarning=false")
                .Should().Pass();
            }
        }
        public void It_does_not_fail_publishing_a_self_twice()
        {
            var runtimeIdentifier = RuntimeInformation.RuntimeIdentifier;

            var testAsset = _testAssetsManager
                            .CopyTestAsset(TestProjectName)
                            .WithSource();

            var msbuildArgs = new string[] { "/p:SelfContained=true",
                                             $"/p:TargetFramework={TargetFramework}",
                                             $"/p:RuntimeIdentifier={runtimeIdentifier}" };

            var restoreCommand = new RestoreCommand(testAsset);

            restoreCommand.Execute(msbuildArgs);

            var publishCommand = new PublishCommand(Log, testAsset.TestRoot);

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

            publishCommand
            .Execute(msbuildArgs)
            .Should().Pass().And.NotHaveStdOutContaining("HelloWorld.exe' already exists");
        }
        private void PublishAppWithLibraryAndRid(bool selfContained, out DirectoryInfo publishDirectory, out string runtimeIdentifier)
        {
            runtimeIdentifier = RuntimeEnvironment.GetRuntimeIdentifier();
            var testAsset = _testAssetsManager
                            .CopyTestAsset("AppWithLibraryAndRid", $"PublishAppWithLibraryAndRid{selfContained}")
                            .WithSource();

            var projectPath = Path.Combine(testAsset.TestRoot, "App");

            var msbuildArgs = new[]
            {
                $"/p:RuntimeIdentifier={runtimeIdentifier}",
                $"/p:TestRuntimeIdentifier={runtimeIdentifier}",
                $"/p:SelfContained={selfContained}"
            };

            var restoreCommand = new RestoreCommand(Log, projectPath, "App.csproj");

            restoreCommand
            .Execute(msbuildArgs)
            .Should()
            .Pass();

            var publishCommand = new PublishCommand(Log, projectPath);

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

            publishDirectory = publishCommand.GetOutputDirectory("netcoreapp1.1", runtimeIdentifier: runtimeIdentifier);
        }
        public void TestRestore()
        {
            var command = new RestoreCommand(HostEnvironment);

            command.Configure(null);

            string contents = @"{
  ""version"": ""1.0"",
  ""defaultProvider"": ""cdnjs"",
  ""defaultDestination"": ""wwwroot"",
  ""libraries"": [
    {
      ""library"": ""[email protected]"",
      ""files"": [ ""jquery.min.js"", ""core.js"" ]
    }
  ]
}";

            File.WriteAllText(Path.Combine(WorkingDir, "libman.json"), contents);

            int result = command.Execute();

            Assert.AreEqual(0, result);

            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.min.js")));
            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "core.js")));
        }
Example #8
0
        private static void SetupStaticTestProject()
        {
            AssetsRoot = Path.Combine(AppContext.BaseDirectory, "bin");
            RestoredTestProjectDirectory = Path.Combine(AssetsRoot, s_testdirName);

            // Ignore Delete Failure
            try
            {
                Directory.Delete(RestoredTestProjectDirectory, true);
            }
            catch (Exception) { }

            Directory.CreateDirectory(RestoredTestProjectDirectory);

            // Todo: this is a hack until corefx is on nuget.org remove this After RC 2 Release
            NuGetConfig.Write(RestoredTestProjectDirectory);

            var newCommand = new NewCommand();

            newCommand.WorkingDirectory = RestoredTestProjectDirectory;
            newCommand.Execute().Should().Pass();

            var restoreCommand = new RestoreCommand();

            restoreCommand.WorkingDirectory = RestoredTestProjectDirectory;
            restoreCommand.Execute("/p:SkipInvalidConfigurations=true")
            .Should().Pass();
        }
Example #9
0
        private async Task <bool> Restore(PublishRoot root, PublishProject publishProject, string restoreDirectory)
        {
            var appEnv = (IApplicationEnvironment)root.HostServices.GetService(typeof(IApplicationEnvironment));

            var feedOptions = new FeedOptions();

            feedOptions.IgnoreFailedSources = true;
            feedOptions.Sources.Add(root.TargetPackagesPath);
            feedOptions.TargetPackagesFolder = root.TargetPackagesPath;

            var restoreCommand = new RestoreCommand(appEnv);

            foreach (var runtime in root.Runtimes)
            {
                restoreCommand.TargetFrameworks.Add(publishProject.SelectFrameworkForRuntime(runtime));
            }

            restoreCommand.SkipRestoreEvents = true;
            restoreCommand.SkipInstall       = true;
            // This is a workaround for #1322. Since we use restore to generate the lock file
            // after publish, it's possible to fail restore after copying the closure
            // if framework assemblies and packages have the same name. This is more likely now
            // since dependencies may exist in the top level
            restoreCommand.IgnoreMissingDependencies = true;
            restoreCommand.CheckHashFile             = false;
            restoreCommand.RestoreDirectories.Add(restoreDirectory);
            restoreCommand.FeedOptions = feedOptions;

            // Mute "dnu restore" subcommand
            restoreCommand.Reports = Reports.Constants.NullReports;

            var success = await restoreCommand.Execute();

            return(success);
        }
        public void TestRestoreErrors()
        {
            var command = new RestoreCommand(HostEnvironment);

            command.Configure(null);

            string contents = @"{
  ""version"": ""1.0"",
  ""defaultProvider"": ""cdnjs"",
  ""defaultDestination"": ""wwwroot"",
  ""libraries"": [
    {
      ""library"": ""[email protected]"",
      ""files"": [ ""jquery.min.js"", ""core123.js"" ]
    }
  ]
}";

            File.WriteAllText(Path.Combine(WorkingDir, "libman.json"), contents);

            int result = command.Execute();

            Assert.AreEqual(0, result);

            Assert.IsFalse(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.min.js")));
            Assert.IsFalse(File.Exists(Path.Combine(WorkingDir, "wwwroot", "core.js")));

            var logger = HostEnvironment.Logger as TestLogger;

            Assert.IsTrue(logger.Messages.Any(m => m.Key == LibraryManager.Contracts.LogLevel.Error));
        }
        public void GroupNotPopulatedWithoutRid()
        {
            var testProject = this.SetupProject();
            var testAsset   = _testAssetsManager.CreateTestProject(testProject);

            var restoreCommand = new RestoreCommand(Log, testAsset.Path, testProject.Name);

            restoreCommand
            .Execute()
            .Should()
            .Pass();

            var buildCommand = new BuildCommand(Log, testAsset.Path, testProject.Name);

            buildCommand
            .Execute("/t:PublishItemsOutputGroup")
            .Should()
            .Pass();

            var testOutputDir = new DirectoryInfo(Path.Combine(testAsset.Path, testProject.Name, "TestOutput"));

            Log.WriteLine("Contents of PublishItemsOutputGroup dumped to '{0}'.", testOutputDir.FullName);

            // Since no RID was specified the output group should only contain framework dependent output
            testOutputDir.Should().HaveFile($"{testProject.Name}{Constants.ExeSuffix}");
            testOutputDir.Should().HaveFile($"{testProject.Name}.deps.json");
            testOutputDir.Should().NotHaveFiles(FrameworkAssemblies);
        }
        public void GroupPopulatedWithRid()
        {
            var testProject = this.SetupProject();
            var testAsset   = _testAssetsManager.CreateTestProject(testProject);

            var restoreCommand = new RestoreCommand(Log, testAsset.Path, testProject.Name);

            restoreCommand
            .Execute()
            .Should()
            .Pass();

            var buildCommand = new BuildCommand(Log, testAsset.Path, testProject.Name);

            buildCommand
            .Execute("/p:RuntimeIdentifier=win-x86", "/t:PublishItemsOutputGroup")
            .Should()
            .Pass();

            var testOutputDir = new DirectoryInfo(Path.Combine(testAsset.Path, testProject.Name, "TestOutput"));

            Log.WriteLine("Contents of PublishItemsOutputGroup dumped to '{0}'.", testOutputDir.FullName);

            // Check for the existence of a few specific files that should be in the directory where the
            // contents of PublishItemsOutputGroup were dumped to make sure it's getting populated.
            testOutputDir.Should().HaveFile($"{testProject.Name}.exe");
            testOutputDir.Should().HaveFile($"{testProject.Name}.deps.json");
            testOutputDir.Should().HaveFiles(FrameworkAssemblies);
        }
        public void WhenTargetingNetCore3_0AspNetCoreAppPackageReferenceWarns(bool useWebSdk, string packageVersion)
        {
            var testProject = new TestProject()
            {
                Name             = "AspNetCoreApp_On3_0",
                TargetFrameworks = "netcoreapp3.0",
                IsSdkProject     = true,
                ProjectSdk       = useWebSdk ? "Microsoft.NET.Sdk.Web" : null,
                IsExe            = true
            };

            //  Add PackageReference
            testProject.PackageReferences.Add(new TestPackageReference("Microsoft.AspNetCore.App", packageVersion));

            var testAsset = _testAssetsManager.CreateTestProject(testProject, identifier: $"{useWebSdk}_{packageVersion}");

            var restoreCommand = new RestoreCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            restoreCommand.Execute()
            .Should()
            .Pass()
            .And
            .HaveStdOutContaining("NETSDK1080");

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            buildCommand.Execute()
            .Should()
            .Pass()
            .And
            .HaveStdOutContaining("NETSDK1080");
        }
Example #14
0
        public void DuplicateFrameworkReferencesCauseError()
        {
            var testProject = new TestProject()
            {
                Name             = "DuplicateFrameworkReference",
                TargetFrameworks = "netcoreapp3.0",
            };

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

                project.Root.Element(ns + "PropertyGroup").Add(
                    new XElement(ns + "DisableImplicitFrameworkReferences", "true"));

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

                itemGroup.Add(new XElement(ns + "FrameworkReference",
                                           new XAttribute("Include", "Microsoft.NETCore.App")));

                itemGroup.Add(new XElement(ns + "FrameworkReference",
                                           new XAttribute("Include", "Microsoft.NETCore.App")));
            });

            var restoreCommand = new RestoreCommand(testAsset);

            restoreCommand
            .Execute()
            .Should()
            .Fail()
            .And.HaveStdOutContaining("NETSDK1087");
        }
Example #15
0
        public void BuildFailsIfInvalidRuntimeIdentifierIsSpecified()
        {
            var testProject = new TestProject()
            {
                Name              = "RuntimePackNotAvailable",
                TargetFrameworks  = "netcoreapp3.0",
                IsSdkProject      = true,
                IsExe             = true,
                RuntimeIdentifier = "invalid-rid"
            };

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var restoreCommand = new RestoreCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            restoreCommand
            //  Pass "/clp:summary" so that we can check output for string "1 Error(s)"
            .Execute("/clp:summary")
            .Should()
            .Fail()
            .And
            .HaveStdOutContaining("NETSDK1083")
            .And
            .HaveStdOutContaining("1 Error(s)");
        }
        public void GroupBuildsWithoutPublish()
        {
            var testProject = this.SetupProject();
            var testAsset   = _testAssetsManager.CreateTestProject(testProject);

            var restoreCommand = new RestoreCommand(testAsset);

            restoreCommand
            .Execute()
            .Should()
            .Pass();

            var buildCommand = new BuildCommand(testAsset);

            buildCommand
            .Execute("/p:RuntimeIdentifier=win-x86;DesignTimeBuild=true", "/t:PublishItemsOutputGroup")
            .Should()
            .Pass();

            // Confirm we were able to build the output group without the publish actually happening
            var publishDir = new DirectoryInfo(Path.Combine(buildCommand.GetOutputDirectory(testProject.TargetFrameworks).FullName, "win-x86", "publish"));

            publishDir
            .Should()
            .NotExist();
        }
Example #17
0
        public void It_builds_a_framework_dependent_RID_specific_runnable_output()
        {
            var runtimeIdentifier = RuntimeInformation.RuntimeIdentifier;
            var testAsset         = _testAssetsManager
                                    .CopyTestAsset("AppWithLibraryAndRid", "BuildFrameworkDependentRIDSpecific")
                                    .WithSource();

            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX))
            {
                //  .NET Core 2.1.0 packages don't support latest versions of OS X, so roll forward to the
                //  latest patch which does
                testAsset = testAsset.WithProjectChanges(project =>
                {
                    var ns = project.Root.Name.Namespace;

                    var propertyGroup = project.Root.Elements(ns + "PropertyGroup").First();
                    propertyGroup.Add(new XElement("TargetLatestRuntimePatch", true));
                });
            }

            var restoreCommand = new RestoreCommand(testAsset, "App");

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

            var buildCommand = new BuildCommand(testAsset, "App");

            buildCommand
            .Execute($"/p:RuntimeIdentifier={runtimeIdentifier}", $"/p:TestRuntimeIdentifier={runtimeIdentifier}", "/p:SelfContained=false")
            .Should().Pass();

            var outputDirectory = buildCommand.GetOutputDirectory(ToolsetInfo.CurrentTargetFramework, runtimeIdentifier: runtimeIdentifier);

            outputDirectory.Should().NotHaveSubDirectories();

            string[] expectedFiles = new[] {
                $"App{Constants.ExeSuffix}",
                "App.dll",
                "App.pdb",
                "App.deps.json",
                "App.runtimeconfig.json",
                "LibraryWithoutRid.dll",
                "LibraryWithoutRid.pdb",
                "LibraryWithRid.dll",
                "LibraryWithRid.pdb",
                "LibraryWithRids.dll",
                "LibraryWithRids.pdb",
                $"{FileConstants.DynamicLibPrefix}sqlite3{FileConstants.DynamicLibSuffix}"
            };

            outputDirectory.Should().OnlyHaveFiles(expectedFiles.Where(x => !String.IsNullOrEmpty(x)).ToList());

            new DotnetCommand(Log, Path.Combine(outputDirectory.FullName, "App.dll"))
            .Execute()
            .Should().Pass()
            .And.HaveStdOutContaining($"3.13.0 '{runtimeIdentifier}' 3.13.0 '{runtimeIdentifier}' Hello World");
        }
        public void It_builds_a_framework_dependent_RID_specific_runnable_output()
        {
            var runtimeIdentifier = RuntimeEnvironment.GetRuntimeIdentifier();
            var testAsset         = _testAssetsManager
                                    .CopyTestAsset("AppWithLibraryAndRid", "BuildFrameworkDependentRIDSpecific")
                                    .WithSource();

            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX))
            {
                //  .NET Core 2.1.0 packages don't support latest versions of OS X, so roll forward to the
                //  latest patch which does
                testAsset = testAsset.WithProjectChanges(project =>
                {
                    var ns = project.Root.Name.Namespace;

                    var propertyGroup = project.Root.Elements(ns + "PropertyGroup").First();
                    propertyGroup.Add(new XElement("TargetLatestRuntimePatch", true));
                });
            }

            var projectPath = Path.Combine(testAsset.TestRoot, "App");

            var restoreCommand = new RestoreCommand(Log, projectPath, "App.csproj");

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

            var buildCommand = new BuildCommand(Log, projectPath);

            buildCommand
            .Execute($"/p:RuntimeIdentifier={runtimeIdentifier}", $"/p:TestRuntimeIdentifier={runtimeIdentifier}", "/p:SelfContained=false")
            .Should().Pass();

            var outputDirectory = buildCommand.GetOutputDirectory("netcoreapp2.1", runtimeIdentifier: runtimeIdentifier);

            outputDirectory.Should().NotHaveSubDirectories();
            outputDirectory.Should().OnlyHaveFiles(new[] {
                $"App{Constants.ExeSuffix}",
                "App.dll",
                "App.pdb",
                "App.deps.json",
                "App.runtimeconfig.json",
                "App.runtimeconfig.dev.json",
                "LibraryWithoutRid.dll",
                "LibraryWithoutRid.pdb",
                "LibraryWithRid.dll",
                "LibraryWithRid.pdb",
                "LibraryWithRids.dll",
                "LibraryWithRids.pdb",
            });

            Command.Create(TestContext.Current.ToolsetUnderTest.DotNetHostPath, new[] { Path.Combine(outputDirectory.FullName, "App.dll") })
            .CaptureStdOut()
            .Execute()
            .Should().Pass()
            .And.HaveStdOutContaining($"3.13.0 '{runtimeIdentifier}' 3.13.0 '{runtimeIdentifier}' Hello World");
        }
        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);

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

            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");
        }
Example #20
0
        public void BuildWithRuntimeIdentifier()
        {
            var testProject = new TestProject()
            {
                Name = "BuildWithRid",
                TargetFrameworks = "netcoreapp3.0",
                IsSdkProject = true,
                IsExe = true
            };

            var compatibleRid = EnvironmentInfo.GetCompatibleRid(testProject.TargetFrameworks);

            var runtimeIdentifiers = new[]
            {
                "win-x64",
                "linux-x64",
                compatibleRid
            };

            testProject.AdditionalProperties["RuntimeIdentifiers"] = string.Join(';', runtimeIdentifiers);

            //  Use a test-specific packages folder
            testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\..\pkg";

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var restoreCommand = new RestoreCommand(Log, testAsset.Path, testProject.Name);

            restoreCommand
                .Execute()
                .Should()
                .Pass();

            foreach (var runtimeIdentifier in runtimeIdentifiers)
            {
                var buildCommand = new BuildCommand(Log, testAsset.Path, testProject.Name);

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

                if (runtimeIdentifier == compatibleRid)
                {
                    var outputDirectory = buildCommand.GetOutputDirectory(testProject.TargetFrameworks, runtimeIdentifier: runtimeIdentifier);
                    var selfContainedExecutable = $"{testProject.Name}{Constants.ExeSuffix}";
                    string selfContainedExecutableFullPath = Path.Combine(outputDirectory.FullName, selfContainedExecutable);

                    Command.Create(selfContainedExecutableFullPath, new string[] { })
                        .CaptureStdOut()
                        .Execute()
                        .Should()
                        .Pass()
                        .And
                        .HaveStdOutContaining("Hello World!");
                }
            }
        }
Example #21
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);
        }
Example #22
0
        public void TestUpdateCommand()
        {
            var command = new UpdateCommand(HostEnvironment);

            command.Configure(null);

            string contents = @"{
  ""version"": ""1.0"",
  ""defaultProvider"": ""cdnjs"",
  ""defaultDestination"": ""wwwroot"",
  ""libraries"": [
    {
      ""library"": ""[email protected]"",
      ""files"": [ ""jquery.min.js"", ""jquery.js"" ]
    }
  ]
}";

            string libmanjsonPath = Path.Combine(WorkingDir, "libman.json");

            File.WriteAllText(libmanjsonPath, contents);

            var restoreCommand = new RestoreCommand(HostEnvironment);

            restoreCommand.Configure(null);

            restoreCommand.Execute();

            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.min.js")));
            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.js")));

            int result = command.Execute("jquery");

            Assert.AreEqual(0, result);
            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.min.js")));
            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.js")));

            string actualText = File.ReadAllText(libmanjsonPath);

            string expectedText = @"{
  ""version"": ""1.0"",
  ""defaultProvider"": ""cdnjs"",
  ""defaultDestination"": ""wwwroot"",
  ""libraries"": [
    {
      ""library"": ""[email protected]"",
      ""files"": [
        ""jquery.min.js"",
        ""jquery.js""
      ]
    }
  ]
}";

            Assert.AreEqual(StringHelper.NormalizeNewLines(expectedText), StringHelper.NormalizeNewLines(actualText));
        }
Example #23
0
        private void Restore(DirectoryInfo projectDirectory, string projectName = null, string runtime = null)
        {
            var command = new RestoreCommand()
                          .WithWorkingDirectory(projectDirectory)
                          .WithRuntime(runtime);

            if (projectName != null)
            {
                if (!Path.HasExtension(projectName))
                {
                    projectName += ".csproj";
                }
                command.Execute($"{projectName} /p:SkipInvalidConfigurations=true;_InvalidConfigurationWarning=false")
                .Should().Pass();
            }
            else
            {
                command.Execute("/p:SkipInvalidConfigurations=true;_InvalidConfigurationWarning=false")
                .Should().Pass();
            }
        }
        public void It_builds_a_framework_dependent_RID_specific_runnable_output()
        {
            if (UsingFullFrameworkMSBuild)
            {
                //  Disable this test on full framework, as the current build won't have access to
                //  https://github.com/Microsoft/msbuild/pull/1674
                //  See https://github.com/dotnet/sdk/issues/877
                return;
            }

            var runtimeIdentifier = RuntimeEnvironment.GetRuntimeIdentifier();
            var testAsset         = _testAssetsManager
                                    .CopyTestAsset("AppWithLibraryAndRid", "BuildFrameworkDependentRIDSpecific")
                                    .WithSource();

            var projectPath = Path.Combine(testAsset.TestRoot, "App");

            var restoreCommand = new RestoreCommand(Stage0MSBuild, projectPath, "App.csproj");

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

            var buildCommand = new BuildCommand(Stage0MSBuild, projectPath);

            buildCommand
            .Execute($"/p:RuntimeIdentifier={runtimeIdentifier}", $"/p:TestRuntimeIdentifier={runtimeIdentifier}", "/p:SelfContained=false")
            .Should().Pass();

            var outputDirectory = buildCommand.GetOutputDirectory("netcoreapp1.1", runtimeIdentifier: runtimeIdentifier);

            outputDirectory.Should().NotHaveSubDirectories();
            outputDirectory.Should().OnlyHaveFiles(new[] {
                "App.dll",
                "App.pdb",
                "App.deps.json",
                "App.runtimeconfig.json",
                "App.runtimeconfig.dev.json",
                "LibraryWithoutRid.dll",
                "LibraryWithoutRid.pdb",
                "LibraryWithRid.dll",
                "LibraryWithRid.pdb",
                "LibraryWithRids.dll",
                "LibraryWithRids.pdb",
            });

            Command.Create(RepoInfo.DotNetHostPath, new[] { Path.Combine(outputDirectory.FullName, "App.dll") })
            .CaptureStdOut()
            .Execute()
            .Should().Pass()
            .And.HaveStdOutContaining($"3.13.0 '{runtimeIdentifier}' 3.13.0 '{runtimeIdentifier}' Hello World");
        }
        public void TestUninstall_NoLibraryToUninstall()
        {
            var command = new UninstallCommand(HostEnvironment);

            command.Configure(null);

            string contents = @"{
  ""version"": ""1.0"",
  ""defaultProvider"": ""cdnjs"",
  ""defaultDestination"": ""wwwroot"",
  ""libraries"": [
    {
      ""provider"": ""cdnjs"",
      ""library"": ""[email protected]"",
      ""destination"": ""wwwroot"",
      ""files"": [
        ""jquery.min.js"",
        ""core.js""
      ]
    }
  ]
}";

            string libmanjsonPath = Path.Combine(WorkingDir, "libman.json");

            File.WriteAllText(libmanjsonPath, contents);

            var restoreCommand = new RestoreCommand(HostEnvironment);

            restoreCommand.Configure(null);

            restoreCommand.Execute();

            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.min.js")));
            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "core.js")));

            int result = command.Execute("[email protected]");

            Assert.AreEqual(0, result);
            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.min.js")));
            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "core.js")));

            var logger = HostEnvironment.Logger as TestLogger;

            Assert.AreEqual("Library \"[email protected]\" is not installed. Nothing to uninstall", logger.Messages[logger.Messages.Count - 1].Value);

            string actualText = File.ReadAllText(libmanjsonPath);

            Assert.AreEqual(StringHelper.NormalizeNewLines(contents), StringHelper.NormalizeNewLines(actualText));
        }
Example #26
0
        public void TestUpdateCommand_InvalidLibraryName()
        {
            var command = new UpdateCommand(HostEnvironment);

            command.Configure(null);

            string contents = @"{
  ""version"": ""1.0"",
  ""defaultProvider"": ""cdnjs"",
  ""defaultDestination"": ""wwwroot"",
  ""libraries"": [
    {
      ""library"": ""[email protected]"",
      ""files"": [
        ""jquery.min.js"",
        ""jquery.js""
      ]
    }
  ]
}";

            string libmanjsonPath = Path.Combine(WorkingDir, "libman.json");

            File.WriteAllText(libmanjsonPath, contents);

            var restoreCommand = new RestoreCommand(HostEnvironment);

            restoreCommand.Configure(null);

            restoreCommand.Execute();

            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.min.js")));
            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.js")));

            int result = command.Execute("[email protected]");

            Assert.AreEqual(0, result);
            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.min.js")));
            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.js")));

            var    logger  = HostEnvironment.Logger as TestLogger;
            string message = "No library found with name \"[email protected]\" to update.\r\nPlease specify a library name without the version information to update.";

            Assert.AreEqual(StringHelper.NormalizeNewLines(message), StringHelper.NormalizeNewLines(logger.Messages.Last().Value));

            string actualText = File.ReadAllText(libmanjsonPath);

            Assert.AreEqual(StringHelper.NormalizeNewLines(contents), StringHelper.NormalizeNewLines(actualText));
        }
        public void GroupPopulatedCorrectlyWithSingleFile()
        {
            var testProject = this.SetupProject();
            var testAsset   = _testAssetsManager.CreateTestProject(testProject);

            var restoreCommand = new RestoreCommand(Log, testAsset.Path, testProject.Name);

            restoreCommand
            .Execute()
            .Should()
            .Pass();

            var buildCommand = new BuildCommand(Log, testAsset.Path, testProject.Name);

            buildCommand
            .Execute("/p:RuntimeIdentifier=win-x86;DesignTimeBuild=true;PublishSingleFile=true", "/t:PublishItemsOutputGroup")
            .Should()
            .Pass();

            var testOutputDir = new DirectoryInfo(Path.Combine(testAsset.Path, testProject.Name, "TestOutput"));

            Log.WriteLine("Contents of PublishItemsOutputGroup dumped to '{0}'.", testOutputDir.FullName);

            if (RuntimeEnvironment.OperatingSystemPlatform != Platform.Darwin)
            {
                testOutputDir.Should().HaveFile($"{testProject.Name}{Constants.ExeSuffix}");
            }

            // In the single file case there shouldn't be a deps.json file
            testOutputDir.Should().NotHaveFile($"{testProject.Name}.deps.json");

            // The framework assemblies should also get bundled with the main exe
            testOutputDir.Should().NotHaveFiles(FrameworkAssemblies);

            var testKeyOutputDir = new DirectoryInfo(Path.Combine(testAsset.Path, testProject.Name, "TestOutput_Key"));

            Log.WriteLine("PublishItemsOutputGroup key items dumped to '{0}'.", testKeyOutputDir.FullName);

            if (RuntimeEnvironment.OperatingSystemPlatform != Platform.Darwin)
            {
                // Verify the only key item is the exe
                testKeyOutputDir.Should()
                .OnlyHaveFiles(new List <string>()
                {
                    $"{testProject.Name}{Constants.ExeSuffix}"
                });
            }
        }
Example #28
0
        public void TestUpdateCommand_InvalidUpdatedLibrary()
        {
            var command = new UpdateCommand(HostEnvironment);

            command.Configure(null);

            string contents = @"{
  ""version"": ""1.0"",
  ""defaultProvider"": ""cdnjs"",
  ""defaultDestination"": ""wwwroot"",
  ""libraries"": [
    {
      ""library"": ""[email protected]"",
      ""files"": [ ""jquery.min.js"", ""jquery.js"" ]
    }
  ]
}";

            string libmanjsonPath = Path.Combine(WorkingDir, "libman.json");

            File.WriteAllText(libmanjsonPath, contents);

            var restoreCommand = new RestoreCommand(HostEnvironment);

            restoreCommand.Configure(null);

            restoreCommand.Execute();

            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.min.js")));
            Assert.IsTrue(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.js")));

            int result = command.Execute("jquery", "--to", "[email protected]");

            Assert.IsFalse(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.min.js")));
            Assert.IsFalse(File.Exists(Path.Combine(WorkingDir, "wwwroot", "jquery.js")));

            string actualText = File.ReadAllText(libmanjsonPath);

            Assert.AreEqual(StringHelper.NormalizeNewLines(contents), StringHelper.NormalizeNewLines(actualText));

            var logger = HostEnvironment.Logger as TestLogger;

            Assert.AreEqual(LogLevel.Error, logger.Messages.Last().Key);

            string expectedMessage = "Failed to update \"jquery\" to \"[email protected]\"";

            Assert.IsTrue(logger.Messages.Any(m => m.Value == expectedMessage));
        }
Example #29
0
        public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IApplicationEnvironment applicationEnvironment, IRuntimeEnvironment runtimeEnvironment)
        {
            cmdApp.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot = c.Argument("[root]",
                    "List of projects and project folders to restore. Each value can be: a path to a project.json or global.json file, or a folder to recursively search for project.json files.",
                    multipleValues: true);
                var feedCommandLineOptions = FeedCommandLineOptions.Add(c);
                var optLock = c.Option("--lock",
                    "Creates dependencies file with locked property set to true. Overwrites file if it exists.",
                    CommandOptionType.NoValue);
                var optUnlock = c.Option("--unlock",
                    "Creates dependencies file with locked property set to false. Overwrites file if it exists.",
                    CommandOptionType.NoValue);
                var optRuntimes = c.Option("--runtime <RID>",
                    "List of runtime identifiers to restore for",
                    CommandOptionType.MultipleValue);

                c.HelpOption("-?|-h|--help");

                c.OnExecute(async () =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var feedOptions = feedCommandLineOptions.GetOptions();
                    var command = new RestoreCommand(applicationEnvironment);
                    command.Reports = reportsFactory.CreateReports(feedOptions.Quiet);
                    command.RestoreDirectories.AddRange(argRoot.Values);
                    command.FeedOptions = feedOptions;
                    command.Lock = optLock.HasValue();
                    command.Unlock = optUnlock.HasValue();
                    command.RequestedRuntimes = optRuntimes.Values;
                    command.FallbackRuntimes = runtimeEnvironment.GetDefaultRestoreRuntimes();

                    if (!string.IsNullOrEmpty(feedOptions.Proxy))
                    {
                        Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                    }

                    var success = await command.Execute();

                    return success ? 0 : 1;
                });
            });
        }
        public void GroupNotPopulatedWithoutRid()
        {
            var testProject = this.SetupProject();
            var testAsset   = _testAssetsManager.CreateTestProject(testProject);

            var restoreCommand = new RestoreCommand(Log, testAsset.Path, testProject.Name);

            restoreCommand
            .Execute()
            .Should()
            .Pass();

            var buildCommand = new BuildCommand(Log, testAsset.Path, testProject.Name);

            buildCommand
            .Execute("/p:DesignTimeBuild=true", "/t:PublishItemsOutputGroup")
            .Should()
            .Pass();

            var testOutputDir = new DirectoryInfo(Path.Combine(testAsset.Path, testProject.Name, "TestOutput"));

            Log.WriteLine("Contents of PublishItemsOutputGroup dumped to '{0}'.", testOutputDir.FullName);

            if (RuntimeEnvironment.OperatingSystemPlatform != Platform.Darwin)
            {
                testOutputDir.Should().HaveFile($"{testProject.Name}{Constants.ExeSuffix}");
            }

            testOutputDir.Should().HaveFile($"{testProject.Name}.deps.json");

            // Since no RID was specified the output group should not contain framework assemblies
            testOutputDir.Should().NotHaveFiles(FrameworkAssemblies);

            var testKeyOutputDir = new DirectoryInfo(Path.Combine(testAsset.Path, testProject.Name, "TestOutput_Key"));

            Log.WriteLine("PublishItemsOutputGroup key items dumped to '{0}'.", testKeyOutputDir.FullName);

            if (RuntimeEnvironment.OperatingSystemPlatform != Platform.Darwin)
            {
                // Verify the only key item is the exe
                testKeyOutputDir.Should()
                .OnlyHaveFiles(new List <string>()
                {
                    $"{testProject.Name}{Constants.ExeSuffix}"
                });
            }
        }
Example #31
0
        public void PublishDepsFilePathIsEmptyForSingleFileApps()
        {
            var testProject    = SetupProject(singleFile: true);
            var testAsset      = _testAssetsManager.CreateTestProject(testProject);
            var restoreCommand = new RestoreCommand(testAsset);

            restoreCommand
            .Execute()
            .Should()
            .Pass();

            var projectPath         = Path.Combine(testAsset.Path, testProject.Name);
            var targetFramework     = testProject.TargetFrameworks;
            var publishDepsFilePath = GetPropertyValue(projectPath, targetFramework, "PublishDepsFilePath");

            String.IsNullOrEmpty(publishDepsFilePath).Should().BeTrue();
        }
Example #32
0
        private async Task<bool> Restore(PublishRoot root, PublishProject publishProject, string restoreDirectory, IEnumerable<FrameworkName> targetFrameworks)
        {
            var appEnv = PlatformServices.Default.Application;

            var feedOptions = new FeedOptions();
            feedOptions.IgnoreFailedSources = true;
            feedOptions.Sources.Add(root.TargetPackagesPath);
            feedOptions.TargetPackagesFolder = root.TargetPackagesPath;

            var restoreCommand = new RestoreCommand(appEnv);

            restoreCommand.TargetFrameworks.AddRange(targetFrameworks);
            restoreCommand.RequestedRuntimes = root.RuntimeIdentifiers;
            restoreCommand.SkipRestoreEvents = true;
            restoreCommand.SkipInstall = true;
            // This is a workaround for #1322. Since we use restore to generate the lock file
            // after publish, it's possible to fail restore after copying the closure
            // if framework assemblies and packages have the same name. This is more likely now
            // since dependencies may exist in the top level
            restoreCommand.IgnoreMissingDependencies = true;
            restoreCommand.CheckHashFile = false;
            restoreCommand.RestoreDirectories.Add(restoreDirectory);
            restoreCommand.FeedOptions = feedOptions;

            // Mute "dnu restore" subcommand
            restoreCommand.Reports = Reports.Constants.NullReports;

            var success = await restoreCommand.Execute();
            return success;
        }
Example #33
0
        private bool UpdateLockFile(PublishRoot root)
        {
            var appEnv = (IApplicationEnvironment)root.HostServices.GetService(typeof(IApplicationEnvironment));

            var feedOptions = new FeedOptions();
            feedOptions.IgnoreFailedSources = true;
            feedOptions.Sources.Add(root.TargetPackagesPath);
            feedOptions.TargetPackagesFolder = root.TargetPackagesPath;

            var tasks = new Task<bool>[root.Projects.Count];
            for (int i = 0; i < root.Projects.Count; i++)
            {
                var project = root.Projects[i];
                var restoreCommand = new RestoreCommand(appEnv);

                foreach (var runtime in root.Runtimes)
                {
                    restoreCommand.TargetFrameworks.Add(project.SelectFrameworkForRuntime(runtime));
                }

                var restoreDirectory = project.IsPackage ? Path.Combine(project.TargetPath, "root") : project.TargetPath;
                restoreCommand.SkipRestoreEvents = true;
                restoreCommand.SkipInstall = true;
                // This is a workaround for #1322. Since we use restore to generate the lock file
                // after publish, it's possible to fail restore after copying the closure
                // if framework assemblies and packages have the same name. This is more likely now
                // since dependencies may exist in the top level
                restoreCommand.IgnoreMissingDependencies = true;
                restoreCommand.CheckHashFile = false;
                restoreCommand.RestoreDirectories.Add(restoreDirectory);
                restoreCommand.FeedOptions = feedOptions;
                restoreCommand.Reports = root.Reports.ShallowCopy();

                // Mute "dnu restore" completely if it is invoked by "dnu publish --quiet"
                restoreCommand.Reports.Information = root.Reports.Quiet;

                tasks[i] = restoreCommand.Execute();
            }

            Task.WaitAll(tasks);

            return tasks.All(t => t.Result);
        }
Example #34
0
        private async Task<bool> Restore(PublishRoot root, PublishProject publishProject, string restoreDirectory)
        {
            var appEnv = (IApplicationEnvironment)root.HostServices.GetService(typeof(IApplicationEnvironment));

            var feedOptions = new FeedOptions();
            feedOptions.IgnoreFailedSources = true;
            feedOptions.Sources.Add(root.TargetPackagesPath);
            feedOptions.TargetPackagesFolder = root.TargetPackagesPath;

            var restoreCommand = new RestoreCommand(appEnv);

            foreach (var framework in root.Frameworks)
            {
                restoreCommand.TargetFrameworks.Add(framework.Key);
            }

            restoreCommand.SkipRestoreEvents = true;
            restoreCommand.SkipInstall = true;
            // This is a workaround for #1322. Since we use restore to generate the lock file
            // after publish, it's possible to fail restore after copying the closure
            // if framework assemblies and packages have the same name. This is more likely now
            // since dependencies may exist in the top level
            restoreCommand.IgnoreMissingDependencies = true;
            restoreCommand.CheckHashFile = false;
            restoreCommand.RestoreDirectories.Add(restoreDirectory);
            restoreCommand.FeedOptions = feedOptions;

            // Mute "dnu restore" subcommand
            restoreCommand.Reports = Reports.Constants.NullReports;

            var success = await restoreCommand.Execute();
            return success;
        }