public void WhenMigratingDeprecatedContentOptionsWarningsArePrinted()
        {
            var projectDirectory = TestAssets
                                   .GetProjectJson(TestAssetKinds.NonRestoredTestProjects, "PJDeprecatedContent")
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root;

            var cmd = new DotnetCommand()
                      .WithWorkingDirectory(projectDirectory)
                      .ExecuteWithCapturedOutput("migrate");

            cmd.Should().Pass();

            cmd.StdOut.Should().Contain(
                "The 'content' option is deprecated. Use 'publishOptions' to publish or 'copyToOutput' in 'buildOptions' to copy to build output instead.");
            cmd.StdOut.Should().Contain(
                "The 'contentExclude' option is deprecated. Use 'publishOptions' to publish or 'copyToOutput' in 'buildOptions' to copy to build output instead.");
            cmd.StdOut.Should().Contain(
                "The 'contentFiles' option is deprecated. Use 'publishOptions' to publish or 'copyToOutput' in 'buildOptions' to copy to build output instead.");
            cmd.StdOut.Should().Contain(
                "The 'contentBuiltIn' option is deprecated. Use 'publishOptions' to publish or 'copyToOutput' in 'buildOptions' to copy to build output instead.");
        }
Exemplo n.º 2
0
        public void WhenSolutionItemsExistInFolderParentFoldersAreNotRemoved()
        {
            var projectDirectory = _testAssetsManager
                                   .CopyTestAsset("SlnFileWithSolutionItemsInNestedFolders")
                                   .WithSource()
                                   .Path;

            var     solutionPath = Path.Combine(projectDirectory, "App.sln");
            SlnFile slnFile      = SlnFile.Read(solutionPath);

            var projectToRemove = Path.Combine("ConsoleApp1", "ConsoleApp1.csproj");
            var cmd             = new DotnetCommand(Log)
                                  .WithWorkingDirectory(projectDirectory)
                                  .Execute($"sln", "remove", projectToRemove);

            cmd.Should().Pass();
            cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectRemovedFromTheSolution, projectToRemove));

            slnFile = SlnFile.Read(solutionPath);
            File.ReadAllText(solutionPath)
            .Should()
            .BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemoveProjectInSolutionWithNestedSolutionItems);
        }
Exemplo n.º 3
0
        public void WhenPassedMultipleProjectsAndOneOfthemDoesNotExistItCancelsWholeOperation()
        {
            var projectDirectory = TestAssets
                                   .Get("TestAppWithSlnAndCsprojFiles")
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root
                                   .FullName;

            var slnFullPath   = Path.Combine(projectDirectory, "App.sln");
            var contentBefore = File.ReadAllText(slnFullPath);

            var projectToAdd = Path.Combine("Lib", "Lib.csproj");
            var cmd          = new DotnetCommand()
                               .WithWorkingDirectory(projectDirectory)
                               .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd} idonotexist.csproj");

            cmd.Should().Fail();
            cmd.StdErr.Should().Be("Project `idonotexist.csproj` does not exist.");

            File.ReadAllText(slnFullPath)
            .Should().BeVisuallyEquivalentTo(contentBefore);
        }
Exemplo n.º 4
0
        //ISSUE: https://github.com/dotnet/sdk/issues/522
        //[Fact]
        public void WhenPassedAnUnknownProjectTypeItFails()
        {
            var projectDirectory = TestAssets
                                   .Get("SlnFileWithNoProjectReferencesAndUnknownProject")
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root
                                   .FullName;

            var slnFullPath   = Path.Combine(projectDirectory, "App.sln");
            var contentBefore = File.ReadAllText(slnFullPath);

            var projectToAdd = Path.Combine("UnknownProject", "UnknownProject.unknownproj");
            var cmd          = new DotnetCommand()
                               .WithWorkingDirectory(projectDirectory)
                               .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}");

            cmd.Should().Fail();
            cmd.StdErr.Should().BeVisuallyEquivalentTo("Unsupported project type. Please check with your sdk provider.");

            File.ReadAllText(slnFullPath)
            .Should().BeVisuallyEquivalentTo(contentBefore);
        }
Exemplo n.º 5
0
        public void WhenProjectDirectoryIsAddedSolutionFoldersAreNotCreated()
        {
            var projectDirectory = TestAssets
                                   .Get("TestAppWithSlnAndCsprojFiles")
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root
                                   .FullName;

            var projectToAdd = Path.Combine("Lib", "Lib.csproj");
            var cmd          = new DotnetCommand()
                               .WithWorkingDirectory(projectDirectory)
                               .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}");

            cmd.Should().Pass();

            var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln"));
            var solutionFolderProjects = slnFile.Projects.Where(
                p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid);

            solutionFolderProjects.Count().Should().Be(0);
            slnFile.Sections.GetSection("NestedProjects").Should().BeNull();
        }
Exemplo n.º 6
0
        public void WhenNoProjectIsPassedItPrintsErrorAndUsage()
        {
            var projectDirectory = TestAssets
                                   .Get("TestAppWithSlnAndCsprojFiles")
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root
                                   .FullName;

            var cmd = new DotnetCommand()
                      .WithWorkingDirectory(projectDirectory)
                      .ExecuteWithCapturedOutput(@"sln App.sln add");

            cmd.Should().Fail();
            cmd.StdErr.Should().Be("You must specify at least one project to add.");

            _output.WriteLine("[STD OUT]");
            _output.WriteLine(cmd.StdOut);
            _output.WriteLine("[HelpText]");
            _output.WriteLine(HelpText);

            cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
        }
        public void WhenRefWithNoCondAlreadyExistsItDoesntDuplicate()
        {
            var setup = Setup();
            var lib   = NewLibWithFrameworks(dir: setup.TestRoot);

            new DotnetCommand(Log, "add", lib.CsProjPath, "reference")
            .WithWorkingDirectory(setup.TestRoot)
            .Execute(setup.ValidRefCsprojPath)
            .Should().Pass();

            int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
            var cmd          = new DotnetCommand(Log, "add", lib.CsProjName, "reference")
                               .WithWorkingDirectory(lib.Path)
                               .Execute(setup.ValidRefCsprojPath);

            cmd.Should().Pass();
            cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectAlreadyHasAreference, @"ValidRef\ValidRef.csproj"));

            var csproj = lib.CsProj();

            csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
            csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
        }
        public void ItFailsToAddInvalidRefWithProperlyFormattedError()
        {
            var invalidProjDirectory = Path.Combine(_testAssetsManager.CreateTestDirectory().Path, "InvalidProj");
            var invalidProjPath      = Path.Combine(invalidProjDirectory, "InvalidProj.csproj");

            Directory.CreateDirectory(invalidProjDirectory);
            File.WriteAllText(invalidProjPath, @"<Project Sdk=""Microsoft.NET.Sdk"">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>
  <Import Project=""fake.props"" />
</Project>");

            var cmd = new DotnetCommand(Log, "add", "reference", invalidProjPath)
                      .WithWorkingDirectory(invalidProjDirectory)
                      .Execute();

            cmd.Should().Fail();
            cmd.StdErr.Should().Contain(string.Format(
                                            CommonLocalizableStrings.ProjectCouldNotBeEvaluated.Substring(0, CommonLocalizableStrings.ProjectCouldNotBeEvaluated.Length - 4), // Remove the '{0}.' from the end
                                            invalidProjPath));
            cmd.StdErr.Should().NotContain("Microsoft.DotNet.Cli.Utils.GracefulException");
        }
Exemplo n.º 9
0
        public void WhenPropertiesAreSetItCanGenerateSupportedOSPlatformAttribute()
        {
            TestProject testProject = SetUpProject();

            var targetPlatformIdentifier = "iOS";

            testProject.AdditionalProperties["TargetPlatformIdentifier"]       = targetPlatformIdentifier;
            testProject.AdditionalProperties["TargetPlatformSupported"]        = "true";
            testProject.AdditionalProperties["TargetPlatformVersionSupported"] = "true";
            testProject.AdditionalProperties["SupportedOSPlatformVersion"]     = "13.2";
            testProject.AdditionalProperties["TargetPlatformVersion"]          = "14.0";

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var runCommand = new DotnetCommand(Log, "run");

            runCommand.WorkingDirectory = Path.Combine(testAsset.TestRoot, testProject.Name);
            runCommand.Execute()
            .Should()
            .Pass()
            .And.HaveStdOutContaining(TargetPlatformAttribute("iOS14.0"))
            .And.HaveStdOutContaining(SupportedOSPlatformAttribute("iOS13.2"));
        }
Exemplo n.º 10
0
        public void MigratingDeprecatedResource()
        {
            var projectDirectory = TestAssets
                                   .GetProjectJson(TestAssetKinds.NonRestoredTestProjects, "PJDeprecatedResource")
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root
                                   .GetDirectory("project");

            new DotnetCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute("migrate")
            .Should().Pass();

            new DotnetCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute("restore")
            .Should().Pass();

            new DotnetCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute("build -c Debug")
            .Should().Pass();

            if (!EnvironmentInfo.HasSharedFramework("netcoreapp1.0"))
            {
                // running the app requires netcoreapp1.0
                return;
            }

            var cmd = new DotnetCommand()
                      .WithWorkingDirectory(projectDirectory)
                      .ExecuteWithCapturedOutput("run -c Debug");

            cmd.Should().Pass();
            cmd.StdOut.Should().Contain("3 Resources Found:");
        }
Exemplo n.º 11
0
        public void UseWPFCanBeSetInDirectoryBuildTargets()
        {
            var testDir = _testAssetsManager.CreateTestDirectory();

            var newCommand = new DotnetCommand(Log);

            newCommand.WorkingDirectory = testDir.Path;

            newCommand.Execute("new", "wpf", "--debug:ephemeral-hive").Should().Pass();

            var projectPath = Path.Combine(testDir.Path, Path.GetFileName(testDir.Path) + ".csproj");

            var project = XDocument.Load(projectPath);
            var ns      = project.Root.Name.Namespace;

            project.Root.Element(ns + "PropertyGroup")
            .Element(ns + "UseWPF")
            .Remove();

            project.Save(projectPath);

            string DirectoryBuildTargetsContent = @"
<Project>
  <PropertyGroup>
    <UseWPF>true</UseWPF>
  </PropertyGroup>
</Project>
";

            File.WriteAllText(Path.Combine(testDir.Path, "Directory.Build.targets"), DirectoryBuildTargetsContent);

            var buildCommand = new BuildCommand(Log, testDir.Path);

            buildCommand.Execute()
            .Should()
            .Pass();
        }
Exemplo n.º 12
0
        public void WhenReferenceIsRemovedBuildConfigsAreAlsoRemoved()
        {
            var projectDirectory = TestAssets
                                   .Get("TestAppWithSlnAndCsprojToRemove")
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root
                                   .FullName;

            var     solutionPath = Path.Combine(projectDirectory, "App.sln");
            SlnFile slnFile      = SlnFile.Read(solutionPath);

            slnFile.Projects.Count.Should().Be(2);

            var projectToRemove = Path.Combine("Lib", "Lib.csproj");
            var cmd             = new DotnetCommand()
                                  .WithWorkingDirectory(projectDirectory)
                                  .ExecuteWithCapturedOutput($"sln remove {projectToRemove}");

            cmd.Should().Pass();

            File.ReadAllText(solutionPath)
            .Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemove);
        }
Exemplo n.º 13
0
        public void WhenIncompatibleFrameworkDetectedItPrintsError(bool useFrameworkArg)
        {
            var setup    = Setup(useFrameworkArg.ToString());
            var lib      = new ProjDir(setup.LibDir);
            var net45lib = new ProjDir(Path.Combine(setup.TestRoot, "Net45Lib"));

            List <string> args = new List <string>();

            if (useFrameworkArg)
            {
                args.Add("-f");
                args.Add("net45");
            }
            args.Add(lib.CsProjPath);

            var csProjContent = net45lib.CsProjContent();
            var cmd           = new DotnetCommand(Log, "add", net45lib.CsProjPath, "reference")
                                .Execute(args);

            cmd.Should().Fail();
            cmd.StdErr.Should().MatchRegex(ProjectNotCompatibleErrorMessageRegEx);
            cmd.StdErr.Should().MatchRegex(" - net45");
            net45lib.CsProjContent().Should().BeEquivalentTo(csProjContent);
        }
Exemplo n.º 14
0
        public TestCommand Setup(ITestOutputHelper log, TestAssetsManager testAssets, [CallerMemberName] string testName = null)
        {
            TestDirectory = testAssets.CreateTestDirectory(testName).Path;
            var testNuGetHome         = Path.Combine(TestDirectory, "nuget_home");
            var cliTestFallbackFolder = Path.Combine(testNuGetHome, ".dotnet", "NuGetFallbackFolder");
            var profiled = Path.Combine(TestDirectory, "profile.d");
            var pathsd   = Path.Combine(TestDirectory, "paths.d");

            var command = new DotnetCommand(log)
                          .WithWorkingDirectory(TestDirectory)
                          .WithEnvironmentVariable("HOME", testNuGetHome)
                          .WithEnvironmentVariable("USERPROFILE", testNuGetHome)
                          .WithEnvironmentVariable("APPDATA", testNuGetHome)
                          .WithEnvironmentVariable("DOTNET_CLI_TEST_FALLBACKFOLDER", cliTestFallbackFolder)
                          .WithEnvironmentVariable("DOTNET_CLI_TEST_LINUX_PROFILED_PATH", profiled)
                          .WithEnvironmentVariable("DOTNET_CLI_TEST_OSX_PATHSD_PATH", pathsd)
                          .WithEnvironmentVariable("SkipInvalidConfigurations", "true")
                          .WithEnvironmentVariable(CliFolderPathCalculator.DotnetHomeVariableName, "");

            NugetFallbackFolder = new DirectoryInfo(cliTestFallbackFolder);
            DotDotnetFolder     = new DirectoryInfo(Path.Combine(testNuGetHome, ".dotnet"));

            return(command);
        }
Exemplo n.º 15
0
        public void It_builds_successfully_when_targeting_net_framework()
        {
            var testDirectory = _testAssetsManager.CreateTestDirectory().Path;
            var newCommand    = new DotnetCommand(Log, "new", "wpf", "--no-restore");

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

            // Set TargetFramework to net472
            var projFile = Path.Combine(testDirectory, Path.GetFileName(testDirectory) + ".csproj");
            var project  = XDocument.Load(projFile);
            var ns       = project.Root.Name.Namespace;

            project.Root.Elements(ns + "PropertyGroup").Elements(ns + "TargetFramework").Single().Value = "net472";
            project.Save(projFile);

            var buildCommand = new BuildCommand(Log, testDirectory);

            buildCommand.Execute()
            .Should()
            .Pass();
        }
Exemplo n.º 16
0
        public void ItBuildsARunnableOutput()
        {
            var testAppName  = "MSBuildTestApp";
            var testInstance = TestAssets.Get(testAppName)
                               .CreateInstance(testAppName)
                               .WithSourceFiles()
                               .WithRestoreFiles();

            new BuildCommand()
            .WithWorkingDirectory(testInstance.Root)
            .Execute()
            .Should().Pass();

            var configuration = Environment.GetEnvironmentVariable("CONFIGURATION") ?? "Debug";

            var outputDll = testInstance.Root.GetDirectory("bin", configuration, "netcoreapp3.0")
                            .GetFile($"{testAppName}.dll");

            var outputRunCommand = new DotnetCommand();

            outputRunCommand.ExecuteWithCapturedOutput(outputDll.FullName)
            .Should().Pass()
            .And.HaveStdOutContaining("Hello World");
        }
Exemplo n.º 17
0
        public void WhenFinalReferenceIsRemovedEmptySectionsAreRemoved()
        {
            var projectDirectory = _testAssetsManager
                                   .CopyTestAsset("TestAppWithSlnAndCsprojToRemove")
                                   .WithSource()
                                   .Path;

            var     solutionPath = Path.Combine(projectDirectory, "App.sln");
            SlnFile slnFile      = SlnFile.Read(solutionPath);

            slnFile.Projects.Count.Should().Be(2);

            var appPath = Path.Combine("App", "App.csproj");
            var libPath = Path.Combine("Lib", "Lib.csproj");
            var cmd     = new DotnetCommand(Log)
                          .WithWorkingDirectory(projectDirectory)
                          .Execute($"sln", "remove", libPath, appPath);

            cmd.Should().Pass();

            var solutionContents = File.ReadAllText(solutionPath);

            solutionContents.Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemoveAllProjects);
        }
        public void It_cleans_for_mvc_projects()
        {
            // Create new mvc app from template
            var testDir    = _testAssetsManager.CreateTestDirectory();
            var assetName  = "MVCPublishProject";
            var runtimeId  = "win-x86";
            var newCommand = new DotnetCommand(Log);

            newCommand.WorkingDirectory = testDir.Path;
            newCommand.Execute("new", "mvc", "-n", assetName).Should().Pass();

            var expectedRegularFiles = new string[] { ".dll", ".deps.json", ".runtimeconfig.json", ".Views.dll" }
            .Select(ending => assetName + ending);
            var expectedSingleFiles = new string[] { ".Views.pdb", ".pdb", ".exe" }.Select(ending => assetName + ending)
            .Concat(new string[] { "appsettings.json", "appsettings.Development.json", "web.config" });

            // Publish normally
            new PublishCommand(Log, Path.Combine(testDir.Path, assetName))
            .Execute(@"/p:RuntimeIdentifier=" + runtimeId)
            .Should()
            .Pass();
            var publishDir = Path.Combine(Directory.GetDirectories(Path.Combine(testDir.Path, assetName, "bin", "Debug")).FirstOrDefault(), runtimeId, "publish");

            CheckPublishOutput(publishDir, expectedSingleFiles.Concat(expectedRegularFiles), null);
            Directory.Exists(Path.Combine(publishDir, "wwwroot"));

            File.WriteAllText(Path.Combine(publishDir, "UserData.txt"), string.Empty);

            // Publish as a single file
            new PublishCommand(Log, Path.Combine(testDir.Path, assetName))
            .Execute(@"/p:RuntimeIdentifier=win-x86;PublishSingleFile=true")
            .Should()
            .Pass();
            CheckPublishOutput(publishDir, expectedSingleFiles.Append("UserData.txt"), expectedRegularFiles);
            Directory.Exists(Path.Combine(publishDir, "wwwroot"));
        }
Exemplo n.º 19
0
        public void WhenPassedAReferenceItRemovesTheReferenceButNotOtherReferences()
        {
            var projectDirectory = _testAssetsManager
                                   .CopyTestAsset("TestAppWithSlnAndExistingCsprojReferences")
                                   .WithSource()
                                   .Path;

            var     solutionPath = Path.Combine(projectDirectory, "App.sln");
            SlnFile slnFile      = SlnFile.Read(solutionPath);

            slnFile.Projects.Count.Should().Be(2);

            var projectToRemove = Path.Combine("Lib", "Lib.csproj");
            var cmd             = new DotnetCommand(Log)
                                  .WithWorkingDirectory(projectDirectory)
                                  .Execute($"sln", "remove", projectToRemove);

            cmd.Should().Pass();
            cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectRemovedFromTheSolution, projectToRemove));

            slnFile = SlnFile.Read(solutionPath);
            slnFile.Projects.Count.Should().Be(1);
            slnFile.Projects[0].FilePath.Should().Be(Path.Combine("App", "App.csproj"));
        }
Exemplo n.º 20
0
        public void WhenProjectIsRemovedSolutionHasUTF8BOM()
        {
            var projectDirectory = _testAssetsManager
                                   .CopyTestAsset("TestAppWithSlnAndCsprojToRemove")
                                   .WithSource()
                                   .Path;

            var projectToRemove = Path.Combine("Lib", "Lib.csproj");
            var cmd             = new DotnetCommand(Log)
                                  .WithWorkingDirectory(projectDirectory)
                                  .Execute($"sln", "App.sln", "remove", projectToRemove);

            cmd.Should().Pass();

            var preamble = Encoding.UTF8.GetPreamble();

            preamble.Length.Should().Be(3);
            using (var stream = new FileStream(Path.Combine(projectDirectory, "App.sln"), FileMode.Open))
            {
                var bytes = new byte[preamble.Length];
                stream.Read(bytes, 0, bytes.Length);
                bytes.Should().BeEquivalentTo(preamble);
            }
        }
Exemplo n.º 21
0
        public void It_cleans_the_project_successfully_with_static_graph_and_isolation()
        {
            var(testAsset, outputDirectories) = BuildAppWithTransitiveDependenciesAndTransitiveCompileReference(new [] { "/graph", "/isolate" });

            var cleanCommand = new DotnetCommand(
                Log,
                "msbuild",
                Path.Combine(testAsset.TestRoot, "1", "1.csproj"),
                "/t:clean",
                "/graph",
                "/isolate");

            cleanCommand
            .Execute()
            .Should()
            .Pass();

            foreach (var outputDirectory in outputDirectories)
            {
                outputDirectory.Value.GetFileSystemInfos()
                .Should()
                .BeEmpty();
            }
        }
Exemplo n.º 22
0
        public void WhenProjectsPresentInTheReadonlySolutionItListsThem()
        {
            var expectedOutput = $@"{CommandLocalizableStrings.ProjectsHeader}
{new string('-', CommandLocalizableStrings.ProjectsHeader.Length)}
{Path.Combine("App", "App.csproj")}
{Path.Combine("Lib", "Lib.csproj")}";

            var projectDirectory = _testAssetsManager
                                   .CopyTestAsset("TestAppWithSlnAndExistingCsprojReferences")
                                   .WithSource()
                                   .Path;

            var slnFileName = Path.Combine(projectDirectory, "App.sln");
            var attributes  = File.GetAttributes(slnFileName);

            File.SetAttributes(slnFileName, attributes | FileAttributes.ReadOnly);

            var cmd = new DotnetCommand(Log)
                      .WithWorkingDirectory(projectDirectory)
                      .Execute("sln", "list");

            cmd.Should().Pass();
            cmd.StdOut.Should().BeVisuallyEquivalentTo(expectedOutput);
        }
        internal static void TestSatelliteResources(
            ITestOutputHelper log,
            TestAssetsManager testAssetsManager,
            Action <XDocument> projectChanges       = null,
            Action <BuildCommand> setup             = null,
            [CallerMemberName] string callingMethod = null)
        {
            var testAsset = testAssetsManager
                            .CopyTestAsset("AllResourcesInSatellite", callingMethod)
                            .WithSource();

            if (projectChanges != null)
            {
                testAsset = testAsset.WithProjectChanges(projectChanges);
            }

            testAsset = testAsset.Restore(log);

            var buildCommand = new BuildCommand(log, testAsset.TestRoot);

            if (setup != null)
            {
                setup(buildCommand);
            }

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

            foreach (var targetFramework in new[] { "net46", "netcoreapp1.1" })
            {
                if (targetFramework == "net46" && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    continue;
                }

                var outputDirectory = buildCommand.GetOutputDirectory(targetFramework);

                var outputFiles = new List <string>
                {
                    "AllResourcesInSatellite.pdb",
                    "en/AllResourcesInSatellite.resources.dll"
                };

                TestCommand command;
                if (targetFramework == "net46")
                {
                    outputFiles.Add("AllResourcesInSatellite.exe");
                    outputFiles.Add("AllResourcesInSatellite.exe.config");
                    command = new RunExeCommand(log, Path.Combine(outputDirectory.FullName, "AllResourcesInSatellite.exe"));
                }
                else
                {
                    outputFiles.Add("AllResourcesInSatellite.dll");
                    outputFiles.Add("AllResourcesInSatellite.deps.json");
                    outputFiles.Add("AllResourcesInSatellite.runtimeconfig.json");
                    outputFiles.Add("AllResourcesInSatellite.runtimeconfig.dev.json");
                    command = new DotnetCommand(log, Path.Combine(outputDirectory.FullName, "AllResourcesInSatellite.dll"));
                }

                outputDirectory.Should().OnlyHaveFiles(outputFiles);

                command
                .Execute()
                .Should()
                .Pass()
                .And
                .HaveStdOutContaining("Hello World from en satellite assembly");
            }
        }
Exemplo n.º 24
0
        BuildAppWithTransitiveDependenciesAndTransitiveCompileReference(string[] msbuildArguments, [CallerMemberName] string callingMethod = "")
        {
            var testAsset = _testAssetsManager.CreateTestProject(DiamondShapeGraphWithRuntimeDependencies(), callingMethod);

            testAsset.Restore(Log, "1");

            string[] targetFrameworks = { "netcoreapp2.1", "net472" };

            var(buildResult, outputDirectories) = Build(testAsset, targetFrameworks, msbuildArguments);

            buildResult.Should()
            .Pass();

            var coreExeFiles = new[]
            {
                "1.dll",
                "1.pdb",
                "1.deps.json",
                "1.runtimeconfig.json",
                "1.runtimeconfig.dev.json"
            };

            var netFrameworkExeFiles = new[]
            {
                "1.exe",
                "1.pdb",
                "1.exe.config",
                "System.Diagnostics.DiagnosticSource.dll"
            };

            foreach (var targetFramework in targetFrameworks)
            {
                var runtimeFiles = targetFramework.StartsWith("netcoreapp")
                    ? coreExeFiles
                    : netFrameworkExeFiles;

                outputDirectories[targetFramework].Should()
                .OnlyHaveFiles(
                    runtimeFiles.Concat(
                        new[]
                {
                    "2.dll",
                    "2.pdb",
                    "3.dll",
                    "3.pdb",
                    "4.dll",
                    "4.pdb",
                    "5.dll",
                    "5.pdb"
                }));

                if (targetFramework.StartsWith("net4") && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // only windows can build full framework tfms
                    break;
                }

                DotnetCommand runCommand = new DotnetCommand(
                    Log,
                    "run",
                    "--framework",
                    targetFramework,
                    "--project",
                    Path.Combine(testAsset.TestRoot, "1", "1.csproj"));

                runCommand
                .Execute()
                .Should()
                .Pass()
                .And
                .HaveStdOutContaining("Hello World from 1")
                .And
                .HaveStdOutContaining("Hello World from 2")
                .And
                .HaveStdOutContaining("Hello World from 4")
                .And
                .HaveStdOutContaining("Hello World from 5")
                .And
                .HaveStdOutContaining("Hello World from 3")
                .And
                .HaveStdOutContaining("Hello World from 4")
                .And
                .HaveStdOutContaining("Hello World from 5");
            }

            return(testAsset, outputDirectories);
        }
        void Conflicts_are_resolved_when_publishing(bool selfContained, bool ridSpecific, [CallerMemberName] string callingMethod = "")
        {
            if (selfContained && !ridSpecific)
            {
                throw new ArgumentException("Self-contained apps must be rid specific");
            }

            var targetFramework = "netcoreapp2.0";

            if (!EnvironmentInfo.SupportsTargetFramework(targetFramework))
            {
                return;
            }
            var rid = ridSpecific ? EnvironmentInfo.GetCompatibleRid(targetFramework) : null;

            TestProject testProject = new TestProject()
            {
                Name = selfContained ? "SelfContainedWithConflicts" :
                       (ridSpecific ? "RidSpecificSharedConflicts" : "PortableWithConflicts"),
                IsSdkProject      = true,
                TargetFrameworks  = targetFramework,
                RuntimeIdentifier = rid,
                IsExe             = true,
            };

            string outputMessage = $"Hello from {testProject.Name}!";

            testProject.AdditionalProperties["CopyLocalLockFileAssemblies"] = "true";
            testProject.SourceFiles["Program.cs"] = @"
using System;
public static class Program
{
    public static void Main()
    {
        TestConflictResolution();
        Console.WriteLine(""" + outputMessage + @""");
    }
" + ConflictResolutionAssets.ConflictResolutionTestMethod + @"
}
";
            var testProjectInstance = _testAssetsManager.CreateTestProject(testProject, testProject.Name)
                                      .WithProjectChanges(p =>
            {
                var ns = p.Root.Name.Namespace;

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

                foreach (var dependency in ConflictResolutionAssets.ConflictResolutionDependencies)
                {
                    itemGroup.Add(new XElement(ns + "PackageReference",
                                               new XAttribute("Include", dependency.Item1),
                                               new XAttribute("Version", dependency.Item2)));
                }

                if (!selfContained && ridSpecific)
                {
                    var propertyGroup = new XElement(ns + "PropertyGroup");
                    p.Root.Add(propertyGroup);

                    propertyGroup.Add(new XElement(ns + "SelfContained",
                                                   "false"));
                }
            })
                                      .Restore(Log, testProject.Name);

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

            publishResult.Should().Pass();

            var publishDirectory = publishCommand.GetOutputDirectory(
                targetFramework: targetFramework,
                runtimeIdentifier: rid ?? string.Empty);
            var outputDirectory = publishDirectory.Parent;

            DependencyContext dependencyContext;

            using (var depsJsonFileStream = File.OpenRead(Path.Combine(publishDirectory.FullName, $"{testProject.Name}.deps.json")))
            {
                dependencyContext = new DependencyContextJsonReader().Read(depsJsonFileStream);
            }

            dependencyContext.Should()
            .HaveNoDuplicateRuntimeAssemblies(rid ?? "")
            .And
            .HaveNoDuplicateNativeAssets(rid ?? "")
            .And
            .OnlyHavePackagesWithPathProperties();

            TestCommand runCommand;

            if (selfContained)
            {
                var selfContainedExecutable = testProject.Name + Constants.ExeSuffix;

                string selfContainedExecutableFullPath = Path.Combine(publishDirectory.FullName, selfContainedExecutable);

                var libPrefix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "" : "lib";

                var filesPublished = new[] {
                    selfContainedExecutable,
                    $"{testProject.Name}.dll",
                    $"{testProject.Name}.pdb",
                    $"{testProject.Name}.deps.json",
                    $"{testProject.Name}.runtimeconfig.json",
                    $"{libPrefix}coreclr{FileConstants.DynamicLibSuffix}",
                    $"{libPrefix}hostfxr{FileConstants.DynamicLibSuffix}",
                    $"{libPrefix}hostpolicy{FileConstants.DynamicLibSuffix}",
                    $"mscorlib.dll",
                    $"System.Private.CoreLib.dll",
                };

                outputDirectory.Should().HaveFiles(filesPublished);
                publishDirectory.Should().HaveFiles(filesPublished);

                dependencyContext.Should()
                .OnlyHaveRuntimeAssembliesWhichAreInFolder(rid, publishDirectory.FullName)
                .And
                .OnlyHaveNativeAssembliesWhichAreInFolder(rid, publishDirectory.FullName, testProject.Name);

                runCommand = new RunExeCommand(Log, selfContainedExecutableFullPath);
            }
            else
            {
                var filesPublished = new[] {
                    $"{testProject.Name}.dll",
                    $"{testProject.Name}.pdb",
                    $"{testProject.Name}.deps.json",
                    $"{testProject.Name}.runtimeconfig.json"
                };

                outputDirectory.Should().HaveFiles(filesPublished);
                publishDirectory.Should().HaveFiles(filesPublished);

                dependencyContext.Should()
                .OnlyHaveRuntimeAssemblies(rid ?? "", testProject.Name);

                runCommand = new DotnetCommand(Log, Path.Combine(publishDirectory.FullName, $"{testProject.Name}.dll"));
            }

            runCommand
            .Execute()
            .Should()
            .Pass()
            .And
            .HaveStdOutContaining(outputMessage);
        }
Exemplo n.º 26
0
        private void TestInvalidTargetFramework(string testName, string targetFramework, bool useSolution, string expectedOutput)
        {
            var testProject = new TestProject()
            {
                Name             = testName,
                TargetFrameworks = targetFramework,
                IsSdkProject     = true
            };

            string identifier = useSolution ? "_Solution" : "";
            var    testAsset  = _testAssetsManager.CreateTestProject(testProject, testProject.Name, identifier);

            if (targetFramework.Contains(";"))
            {
                //  The TestProject class doesn't differentiate between TargetFramework and TargetFrameworks, and helpfully selects
                //  which property to use based on whether there's a semicolon.
                //  For this test, we need to override this behavior
                testAsset = testAsset.WithProjectChanges(project =>
                {
                    var ns = project.Root.Name.Namespace;

                    project.Root.Element(ns + "PropertyGroup")
                    .Element(ns + "TargetFrameworks")
                    .Name = ns + "TargetFramework";
                });
            }

            TestCommand restoreCommand;
            TestCommand buildCommand;

            if (useSolution)
            {
                var dotnetCommand = new DotnetCommand(Log)
                {
                    WorkingDirectory = testAsset.TestRoot
                };

                dotnetCommand.Execute("new", "sln")
                .Should()
                .Pass();

                var relativePathToProject = Path.Combine(testProject.Name, testProject.Name + ".csproj");
                dotnetCommand.Execute($"sln", "add", relativePathToProject)
                .Should()
                .Pass();

                var relativePathToSln = Path.GetFileName(testAsset.Path) + ".sln";

                restoreCommand = testAsset.GetRestoreCommand(Log, relativePathToSln);
                buildCommand   = new BuildCommand(Log, testAsset.TestRoot, relativePathToSln);
            }
            else
            {
                restoreCommand = testAsset.GetRestoreCommand(Log, testProject.Name);
                buildCommand   = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));
            }

            //  Set RestoreContinueOnError=ErrorAndContinue to force failure on error
            //  See https://github.com/NuGet/Home/issues/5309
            var restore = restoreCommand.Execute("/p:RestoreContinueOnError=ErrorAndContinue");

            if (targetFramework.Contains(';'))
            {
                // Restore does not error on TargetFramework with semicolons, it treats it equivalently to TargetFrameworks.
                // The error is therefore deferred to the build check below.
                restore.Should().Pass();
            }
            else
            {
                // Intentionally not checking the error message on restore here as we can't put ourselves in front of
                // restore and customize the message for invalid target frameworks as that would break restoring packages
                // like MSBuild.Sdk.Extras that add support for extra TFMs.
                restore.Should().Fail();
            }

            buildCommand
            .Execute()
            .Should()
            .Fail()
            .And
            .HaveStdOutContaining(expectedOutput)
            .And.NotHaveStdOutContaining(">=");     // old error about comparing empty string to version when TargetFramework was blank;
        }
        private (string coreDir, string publishDir, string immutableDir) TestConflictResult(
            Action <TestProject> testProjectChanges = null,
            Action <string> publishFolderChanges    = null,
            [CallerMemberName] string callingMethod = "")
        {
            var testProject = GetTestProject();

            testProject.SourceFiles["Program.cs"] = @"
using System;

static class Program
{
    public static void Main()
    {
        Console.WriteLine(typeof(object).Assembly.Location);
        Console.WriteLine(typeof(System.Collections.Immutable.ImmutableList).Assembly.Location);
    }
}
";
            if (testProjectChanges != null)
            {
                testProjectChanges(testProject);
            }


            var testAsset = _testAssetsManager.CreateTestProject(testProject, callingMethod: callingMethod);

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

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

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

            if (publishFolderChanges != null)
            {
                publishFolderChanges(publishDirectory.FullName);
            }

            //  Assembly from package should be deployed, as it is newer than the in-box version for netcoreapp2.0,
            //  which is what the app targets
            publishDirectory.Should().HaveFile("System.Collections.Immutable.dll");

            var exePath = Path.Combine(publishDirectory.FullName, testProject.Name + ".dll");

            //  We want to test a .NET Core 2.0 app rolling forward to .NET Core 2.2.
            //  This wouldn't happen in our test environment as we also have the .NET Core 2.0 shared
            //  framework installed.  So we get the RuntimeFrameworkVersion of an app
            //  that targets .NET Core 2.1, and then use the --fx-version parameter to the host
            //  to force the .NET Core 2.0 app to run on that version
            string rollForwardVersion = GetRollForwardNetCoreAppVersion();

            var runAppCommand = new DotnetCommand(Log, "exec", "--fx-version", rollForwardVersion, exePath);

            var runAppResult = runAppCommand
                               .Execute();

            runAppResult
            .Should()
            .Pass();

            var stdOutLines = runAppResult.StdOut.Split(Environment.NewLine);

            string coreDir      = Path.GetDirectoryName(stdOutLines[0]);
            string immutableDir = Path.GetDirectoryName(stdOutLines[1]);

            return(coreDir, publishDirectory.FullName, immutableDir);
        }
 public void Main(DotnetCommand cmd)
 {
     cmd.Invoke();
 }
Exemplo n.º 29
0
        private void TestProject(string projectFolderOrFile, string testName, ProjectPerfOperation perfOperation, string restoreSources = null)
        {
            string testProjectPath;
            string testProjectDirectory;
            bool   projectFileSpecified;

            if (File.Exists(projectFolderOrFile))
            {
                projectFileSpecified = true;
                testProjectPath      = projectFolderOrFile;
                testProjectDirectory = Path.GetDirectoryName(projectFolderOrFile);
            }
            else
            {
                projectFileSpecified = false;
                testProjectPath      = Directory.GetFiles(projectFolderOrFile, "*.sln", SearchOption.AllDirectories).SingleOrDefault();
                if (testProjectPath == null)
                {
                    testProjectPath = Directory.GetFiles(projectFolderOrFile, "*.csproj", SearchOption.AllDirectories).SingleOrDefault();
                    if (testProjectPath == null)
                    {
                        throw new ArgumentException("Could not find project file to test in folder: " + projectFolderOrFile);
                    }
                }
                testProjectDirectory = Path.GetDirectoryName(testProjectPath);
            }

            TestCommand commandToTest;
            var         perfTest = new PerfTest();

            perfTest.ScenarioName = testName;

            if (perfOperation == ProjectPerfOperation.NoOpRestore)
            {
                TestCommand restoreCommand;

                if (TestContext.Current.ToolsetUnderTest.ShouldUseFullFrameworkMSBuild)
                {
                    restoreCommand = new RestoreCommand(Log, testProjectPath);
                }
                else
                {
                    restoreCommand = new RestoreCommand(Log, testProjectPath);
                    restoreCommand = new DotnetCommand(Log, "restore");
                    if (projectFileSpecified)
                    {
                        restoreCommand.Arguments.Add(testProjectPath);
                    }
                }
                if (!string.IsNullOrEmpty(restoreSources))
                {
                    restoreCommand.Arguments.Add($"/p:RestoreSources={restoreSources}");
                }
                restoreCommand.WorkingDirectory = testProjectDirectory;

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

                commandToTest     = restoreCommand;
                perfTest.TestName = "Restore (No-op)";
            }
            else
            {
                if (TestContext.Current.ToolsetUnderTest.ShouldUseFullFrameworkMSBuild)
                {
                    commandToTest = new BuildCommand(Log, projectFileSpecified ? testProjectPath : testProjectDirectory);
                    commandToTest.Arguments.Add("/restore");
                }
                else
                {
                    commandToTest = new DotnetCommand(Log, "build");
                    if (projectFileSpecified)
                    {
                        commandToTest.Arguments.Add(testProjectPath);
                    }
                }
                if (!string.IsNullOrEmpty(restoreSources))
                {
                    commandToTest.Arguments.Add($"/p:RestoreSources={restoreSources}");
                }
                commandToTest.WorkingDirectory = testProjectDirectory;

                if (perfOperation == ProjectPerfOperation.CleanBuild)
                {
                    perfTest.TestName = "Build";
                }
                else if (perfOperation == ProjectPerfOperation.BuildWithNoChanges)
                {
                    //  Build once before taking folder snaspshot
                    commandToTest.Execute().Should().Pass();

                    perfTest.TestName = "Build (no changes)";
                }
                else
                {
                    throw new ArgumentException("Unexpected perf operation: " + perfOperation);
                }
            }

            perfTest.ProcessToMeasure = commandToTest.GetProcessStartInfo();
            perfTest.TestFolder       = testProjectDirectory;

            perfTest.Run();
        }
 public ToolCommand(DotnetCommand parentCommand)
 {
     _dotnetCommand = parentCommand;
 }