Esempio n. 1
0
        internal static List <string> GetValuesFromTestLibrary(
            ITestOutputHelper log,
            TestAssetsManager testAssetsManager,
            string itemTypeOrPropertyName,
            Action <GetValuesCommand> setup         = null,
            string[] msbuildArgs                    = null,
            GetValuesCommand.ValueType valueType    = GetValuesCommand.ValueType.Item,
            [CallerMemberName] string callingMethod = "",
            Action <XDocument> projectChanges       = null)
        {
            msbuildArgs = msbuildArgs ?? Array.Empty <string>();

            string targetFramework = "netstandard1.6";

            var testAsset = testAssetsManager
                            .CopyTestAsset("AppWithLibraryFS", callingMethod)
                            .WithSource();

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

            var libraryProjectDirectory = Path.Combine(testAsset.TestRoot, "TestLibrary");

            var getValuesCommand = new GetValuesCommand(log, libraryProjectDirectory,
                                                        targetFramework, itemTypeOrPropertyName, valueType);

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

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

            var itemValues = getValuesCommand.GetValues();

            return(itemValues);
        }
        public void TheMaximumVersionsAreSupported(string targetFrameworkIdentifier)
        {
            var project = new TestProject
            {
                Name             = "packagethatwillgomissing",
                TargetFrameworks = targetFrameworkIdentifier == ".NETCoreApp" ? "netcoreapp3.0" : "netstandard2.1",
                IsSdkProject     = true,
            };

            TestAsset asset = _testAssetsManager
                              .CreateTestProject(project, identifier: targetFrameworkIdentifier);

            string testDirectory = Path.Combine(asset.TestRoot, project.Name);

            var getMaximumVersion = new GetValuesCommand(
                Log,
                testDirectory,
                project.TargetFrameworks,
                targetFrameworkIdentifier.Substring(1) + "MaximumVersion",
                GetValuesCommand.ValueType.Property);

            var getSupportedFrameworks = new GetValuesCommand(
                Log,
                testDirectory,
                project.TargetFrameworks,
                "SupportedTargetFramework",
                GetValuesCommand.ValueType.Item);

            getMaximumVersion.DependsOnTargets = "";
            getMaximumVersion.Execute().Should().Pass();

            getSupportedFrameworks.DependsOnTargets = "";
            getSupportedFrameworks.Execute().Should().Pass();

            string        maximumVersion      = getMaximumVersion.GetValues().Single();
            List <string> supportedFrameworks = getSupportedFrameworks.GetValues();

            string expectedTFM = $"{targetFrameworkIdentifier},Version=v{maximumVersion}";

            supportedFrameworks.Should().Contain(expectedTFM,
                                                 because: $"Microsoft.NET.SupportedTargetFrameworks.props should include an entry for {expectedTFM}");
        }
        public void It_always_accepts_user_defined_WarningLevel(int?warningLevel, int expectedWarningLevel)
        {
            var testProject = new TestProject
            {
                Name             = "HelloWorld",
                TargetFrameworks = ToolsetInfo.CurrentTargetFramework,
                IsExe            = true,
                SourceFiles      =
                {
                    ["Program.cs"] = @"
                        using System;

                        namespace ConsoleCore
                        {
                            class Program
                            {
                                static void Main()
                                {
                                }
                            }
                        }
                    ",
                }
            };

            testProject.AdditionalProperties.Add("WarningLevel", warningLevel?.ToString());
            var testAsset = _testAssetsManager
                            .CreateTestProject(testProject, identifier: "customWarningLevelConsoleApp", targetExtension: ".csproj");

            var buildCommand = new GetValuesCommand(
                Log,
                Path.Combine(testAsset.TestRoot, testProject.Name),
                ToolsetInfo.CurrentTargetFramework, "WarningLevel")
            {
                DependsOnTargets = "Build"
            };
            var buildResult          = buildCommand.Execute();
            var computedWarningLevel = buildCommand.GetValues()[0];

            buildResult.StdErr.Should().Be(string.Empty);
            computedWarningLevel.Should().Be(expectedWarningLevel.ToString());
        }
Esempio n. 4
0
        public void It_resolves_multitargeted_analyzers()
        {
            var testProject = new TestProject()
            {
                TargetFrameworks = "net6.0;net472"
            };

            //  Disable analyzers built in to the SDK so we can more easily test the ones coming from NuGet packages
            testProject.AdditionalProperties["EnableNETAnalyzers"] = "false";

            testProject.ProjectChanges.Add(project =>
            {
                var ns = project.Root.Name.Namespace;

                var itemGroup = XElement.Parse(@"
  <ItemGroup>
    <PackageReference Include=""System.Text.Json"" Version=""4.7.0"" Condition="" '$(TargetFramework)' == 'net472' "" />
    <PackageReference Include=""System.Text.Json"" Version=""6.0.0-preview.4.21253.7"" Condition="" '$(TargetFramework)' == 'net6.0' "" />
  </ItemGroup>");

                project.Root.Add(itemGroup);
            });

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            List <(string package, string version, string path)> GetAnalyzersForTargetFramework(string targetFramework)
            {
                var getValuesCommand = new GetValuesCommand(testAsset,
                                                            valueName: "Analyzer",
                                                            GetValuesCommand.ValueType.Item,
                                                            targetFramework);

                getValuesCommand.DependsOnTargets = "ResolveLockFileAnalyzers";

                getValuesCommand.Execute("-p:TargetFramework=" + targetFramework).Should().Pass();

                return(getValuesCommand.GetValues().Select(x => GetPackageAndPath(x)).ToList());
            }

            GetAnalyzersForTargetFramework("net6.0").Should().BeEquivalentTo(("system.text.json", "6.0.0-preview.4.21253.7", "analyzers/dotnet/cs/System.Text.Json.SourceGeneration.dll"));
            GetAnalyzersForTargetFramework("net472").Should().BeEmpty();
        }
        public void It_defaults_WarningLevel_To_The_Current_TFM_When_Net(string tfm, string warningLevel)
        {
            int parsedWarningLevel = (int)double.Parse(warningLevel);
            var testProject        = new TestProject
            {
                Name             = "HelloWorld",
                TargetFrameworks = tfm,
                IsExe            = true,
                SourceFiles      =
                {
                    ["Program.cs"] = @"
                        using System;

                        namespace ConsoleCore
                        {
                            class Program
                            {
                                static void Main()
                                {
                                }
                            }
                        }
                    ",
                }
            };

            var testAsset = _testAssetsManager
                            .CreateTestProject(testProject, identifier: "warningLevelConsoleApp" + tfm, targetExtension: ".csproj");

            var buildCommand = new GetValuesCommand(
                Log,
                Path.Combine(testAsset.TestRoot, testProject.Name),
                tfm, "WarningLevel")
            {
                DependsOnTargets = "Build"
            };
            var buildResult          = buildCommand.Execute();
            var computedWarningLevel = buildCommand.GetValues()[0];

            buildResult.StdErr.Should().Be(string.Empty);
            computedWarningLevel.Should().Be(parsedWarningLevel.ToString());
        }
        private void AssertDefinedConstantsOutput(TestAsset testAsset, string targetFramework, string[] expectedDefines)
        {
            var libraryProjectDirectory = Path.Combine(testAsset.TestRoot, "TestLibrary");

            var getValuesCommand = new GetValuesCommand(Log, libraryProjectDirectory,
                                                        targetFramework, "DefineConstants")
            {
                ShouldCompile = false,
                TargetName    = "CoreCompile" // Overwrite core compile with our target to get DefineConstants
            };

            getValuesCommand
            .Execute()
            .Should()
            .Pass();

            var definedConstants = getValuesCommand.GetValues();

            definedConstants.Should().BeEquivalentTo(new[] { "DEBUG", "TRACE" }.Concat(expectedDefines).ToArray());
        }
Esempio n. 7
0
        public void It_respects_explicit_platform_target()
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset("DesktopMinusRid")
                            .WithSource()
                            .Restore(Log, "", $"/p:RuntimeIdentifier=win7-x86");

            var getValuesCommand = new GetValuesCommand(Log, testAsset.TestRoot,
                                                        "net46", "PlatformTarget", GetValuesCommand.ValueType.Property);

            getValuesCommand
            .Execute($"/p:RuntimeIdentifier=win7-x86", "/p:PlatformTarget=x64")
            .Should()
            .Pass();

            getValuesCommand
            .GetValues()
            .Should()
            .BeEquivalentTo("x64");
        }
Esempio n. 8
0
        public void It_builds_with_inferred_platform_target(string runtimeIdentifier, string expectedPlatformTarget)
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset("DesktopMinusRid", identifier: Path.DirectorySeparatorChar + runtimeIdentifier)
                            .WithSource()
                            .Restore(Log, "", $"/p:RuntimeIdentifier={runtimeIdentifier}");

            var getValuesCommand = new GetValuesCommand(Log, testAsset.TestRoot,
                                                        "net46", "PlatformTarget", GetValuesCommand.ValueType.Property);

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

            getValuesCommand
            .GetValues()
            .Should()
            .BeEquivalentTo(expectedPlatformTarget);
        }
Esempio n. 9
0
        private void GetReferences(TestProject testProject, bool expectConflicts, out List <string> references, out List <string> referenceCopyLocalPaths)
        {
            string    targetFramework = testProject.TargetFrameworks;
            TestAsset tempTestAsset   = _testAssetsManager.CreateTestProject(testProject)
                                        .Restore(Log, testProject.Name);

            string projectFolder = Path.Combine(tempTestAsset.TestRoot, testProject.Name);

            var getReferenceCommand = new GetValuesCommand(
                Log,
                projectFolder,
                targetFramework,
                "Reference",
                GetValuesCommand.ValueType.Item);

            getReferenceCommand.DependsOnTargets = "Build";
            var result = getReferenceCommand.Execute("/v:normal").Should().Pass();

            if (expectConflicts)
            {
                result.And.HaveStdOutMatching("Encountered conflict", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
            }
            else
            {
                result.And.NotHaveStdOutMatching("Encountered conflict", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
            }

            references = getReferenceCommand.GetValues();

            var getReferenceCopyLocalPathsCommand = new GetValuesCommand(
                Log,
                projectFolder,
                targetFramework,
                "ReferenceCopyLocalPaths",
                GetValuesCommand.ValueType.Item);

            getReferenceCopyLocalPathsCommand.DependsOnTargets = "Build";
            getReferenceCopyLocalPathsCommand.Execute().Should().Pass();

            referenceCopyLocalPaths = getReferenceCopyLocalPathsCommand.GetValues();
        }
Esempio n. 10
0
        string GetRollForwardNetCoreAppVersion()
        {
            var testProject = new TestProject()
            {
                Name             = nameof(GetRollForwardNetCoreAppVersion),
                TargetFrameworks = "netcoreapp2.1",
                IsSdkProject     = true,
                IsExe            = true
            };
            var testAsset = _testAssetsManager.CreateTestProject(testProject)
                            .Restore(Log, testProject.Name);
            var getValuesCommand = new GetValuesCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name),
                                                        testProject.TargetFrameworks, "RuntimeFrameworkVersion")
            {
                ShouldCompile = false
            };

            getValuesCommand.Execute().Should().Pass();

            return(getValuesCommand.GetValues().Single());
        }
        public void It_defines_target_platform_from_target_framework_with_explicit_version()
        {
            var targetPlatformVersion = "10.0.19041.0";
            var targetFramework       = "net5.0-windows";
            var testProj = new TestProject()
            {
                Name             = "TargetPlatformTests",
                TargetFrameworks = targetFramework
            };

            testProj.AdditionalProperties["TargetPlatformVersion"] = targetPlatformVersion;
            var testAsset = _testAssetsManager.CreateTestProject(testProj);

            var getValuesCommand = new GetValuesCommand(Log, Path.Combine(testAsset.Path, testProj.Name), targetFramework, "TargetPlatformIdentifier");

            getValuesCommand
            .Execute()
            .Should()
            .Pass();
            getValuesCommand.GetValues().ShouldBeEquivalentTo(new[] { "Windows" });
        }
        public void It_defines_windows_version_default_correctly(string targetFramework)
        {
            TestProject testProject = new TestProject()
            {
                Name             = "WindowsVersionDefault",
                ProjectSdk       = "Microsoft.NET.Sdk.WindowsDesktop",
                TargetFrameworks = targetFramework
            };

            testProject.AdditionalProperties["TargetPlatformIdentifier"] = "windows";
            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var getValuesCommand = new GetValuesCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name), targetFramework, "TargetPlatformVersion");

            getValuesCommand
            .Execute()
            .Should()
            .Pass();

            getValuesCommand.GetValues().ShouldBeEquivalentTo(new[] { "7.0" });
        }
        public void It_combines_inner_rids_for_restore(
            string identifier,
            string outerRid,
            string outerRids,
            string firstFrameworkRid,
            string firstFrameworkRids,
            string secondFrameworkRid,
            string secondFrameworkRids,
            string expectedCombination)
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset(Path.Combine("CrossTargeting", "NetStandardAndNetCoreApp"), identifier: identifier)
                            .WithSource()
                            .WithProjectChanges(project =>
            {
                var ns            = project.Root.Name.Namespace;
                var propertyGroup = project.Root.Elements(ns + "PropertyGroup").First();

                propertyGroup.Add(
                    new XElement(ns + "RuntimeIdentifier", outerRid),
                    new XElement(ns + "RuntimeIdentifiers", outerRids));

                propertyGroup.AddAfterSelf(
                    new XElement(ns + "PropertyGroup",
                                 new XAttribute(ns + "Condition", "'$(TargetFramework)' == 'netstandard1.5'"),
                                 new XElement(ns + "RuntimeIdentifier", firstFrameworkRid),
                                 new XElement(ns + "RuntimeIdentifiers", firstFrameworkRids)),
                    new XElement(ns + "PropertyGroup",
                                 new XAttribute(ns + "Condition", "'$(TargetFramework)' == 'netcoreapp1.1'"),
                                 new XElement(ns + "RuntimeIdentifier", secondFrameworkRid),
                                 new XElement(ns + "RuntimeIdentifiers", secondFrameworkRids)));
            });

            var command = new GetValuesCommand(Stage0MSBuild, testAsset.TestRoot, "", valueName: "RuntimeIdentifiers");

            command.DependsOnTargets = "GetAllRuntimeIdentifiers";
            command.Execute().Should().Pass();
            command.GetValues().Should().BeEquivalentTo(expectedCombination.Split(';'));
        }
        public void It_includes_source_revision_id_if_available__version_with_plus()
        {
            TestProject testProject = new TestProject()
            {
                Name             = "ProjectWithSourceRevisionId",
                IsSdkProject     = true,
                TargetFrameworks = "netcoreapp2.0",
            };

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

                project.Root.Add(
                    new XElement(ns + "Target",
                                 new XAttribute("Name", "_SetSourceRevisionId"),
                                 new XAttribute("BeforeTargets", "InitializeSourceControlInformation"),
                                 new XElement(ns + "PropertyGroup",
                                              new XElement("SourceRevisionId", "xyz"))));

                project.Root.Add(
                    new XElement(ns + "Target",
                                 new XAttribute("Name", "InitializeSourceControlInformation")));

                project.Root.Add(
                    new XElement(ns + "PropertyGroup",
                                 new XElement("SourceControlInformationFeatureSupported", "true"),
                                 new XElement("InformationalVersion", "1.2.3+abc")));
            });

            testAsset.Restore(Log, testProject.Name);

            var command = new GetValuesCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name), testProject.TargetFrameworks, valueName: "InformationalVersion");

            command.Execute().Should().Pass();

            command.GetValues().ShouldBeEquivalentTo(new[] { "1.2.3+abc.xyz" });
        }
Esempio n. 15
0
        public void It_restores_only_ridless_tfm()
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset("HelloWorld")
                            .WithSource()
                            .Restore(Log);

            var getValuesCommand = new GetValuesCommand(Log, testAsset.TestRoot,
                                                        "netcoreapp1.1", "TargetDefinitions", GetValuesCommand.ValueType.Item);

            getValuesCommand
            .Execute()
            .Should()
            .Pass();

            // When RuntimeIdentifier is not specified, the assets file
            // should only contain one target with no RIDs
            var targetDefs = getValuesCommand.GetValues();

            targetDefs.Count.Should().Be(1);
            targetDefs.Should().Contain(".NETCoreApp,Version=v1.1");
        }
Esempio n. 16
0
        public void It_implicitly_defines_compilation_constants_for_the_configuration(string configuration, string expectedDefine)
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset("AppWithLibraryFS", "ImplicitConfigurationConstantsFS", configuration)
                            .WithSource();

            var libraryProjectDirectory = Path.Combine(testAsset.TestRoot, "TestLibrary");

            var getValuesCommand = new GetValuesCommand(Log, libraryProjectDirectory,
                                                        "netstandard1.6", "DefineConstants");

            getValuesCommand.ShouldCompile = true;
            getValuesCommand.Configuration = configuration;

            getValuesCommand
            .Execute("/p:Configuration=" + configuration)
            .Should()
            .Pass();

            var definedConstants = getValuesCommand.GetValues();

            definedConstants.Should().BeEquivalentTo(new[] { expectedDefine, "TRACE", "NETSTANDARD", "NETSTANDARD1_6" });
        }
        public void It_implicitly_defines_compilation_constants_for_the_configuration(string configuration, string[] expectedDefines)
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset("AppWithLibraryVB", "ImplicitConfigurationConstantsVB", configuration)
                            .WithSource();

            var libraryProjectDirectory = Path.Combine(testAsset.TestRoot, "TestLibrary");

            var getValuesCommand = new GetValuesCommand(Log, libraryProjectDirectory,
                                                        "netstandard1.5", "FinalDefineConstants");

            getValuesCommand.ShouldCompile = true;
            getValuesCommand.Configuration = configuration;

            getValuesCommand
            .Execute("/p:Configuration=" + configuration)
            .Should()
            .Pass();

            var definedConstants = ExpandSequence(getValuesCommand.GetValues()).ToList();

            definedConstants.Should().BeEquivalentTo(expectedDefines.Concat(new[] { "PLATFORM=\"AnyCPU\"", "NETSTANDARD=-1", "NETSTANDARD1_5=-1" }));
        }
Esempio n. 18
0
        public void It_does_not_contain_apphost_exe(bool multiTarget)
        {
            var extension = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : "";

            _targetFrameworkOrFrameworks = "netcoreapp3.0";

            var nugetPackage = SetupNuGetPackage(multiTarget);

            using (var nupkgReader = new PackageArchiveReader(nugetPackage))
            {
                IEnumerable <NuGet.Frameworks.NuGetFramework> supportedFrameworks = nupkgReader.GetSupportedFrameworks();
                supportedFrameworks.Should().NotBeEmpty();

                foreach (NuGet.Frameworks.NuGetFramework framework in supportedFrameworks)
                {
                    var allItems = nupkgReader.GetToolItems().SelectMany(i => i.Items).ToList();
                    allItems.Should().NotContain($"tools/{framework.GetShortFolderName()}/any/consoledemo{extension}");
                }
            }

            var getValuesCommand = new GetValuesCommand(
                Log,
                _testRoot,
                _targetFrameworkOrFrameworks,
                "RunCommand",
                GetValuesCommand.ValueType.Property);

            if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                getValuesCommand.Execute();
                string runCommandPath = getValuesCommand.GetValues().Single();
                Path.GetExtension(runCommandPath)
                .Should().Be(extension);
                File.Exists(runCommandPath).Should()
                .BeTrue("run command should be apphost executable (for WinExe) to debug. But it will not be packed");
            }
        }
Esempio n. 19
0
        public void It_should_import_AutoImports_for_installed_workloads()
        {
            var testProject = new TestProject()
            {
                Name             = "WorkloadTest",
                TargetFrameworks = "net5.0"
            };

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var expectedProperty = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "WinTestWorkloadAutoImportPropsImported" : "UnixTestWorkloadAutoImportPropsImported";

            var getValuesCommand = new GetValuesCommand(testAsset, expectedProperty);

            getValuesCommand
            .Execute()
            .Should()
            .Pass();

            getValuesCommand
            .GetValues()
            .Should()
            .BeEquivalentTo("true");
        }
Esempio n. 20
0
        public void It_defines_target_platform_from_target_framework(string targetFramework, string expectedTargetFrameworkIdentifier, string expectedTargetFrameworkVersion, string expectedTargetPlatformIdentifier, string expectedTargetPlatformVersion)
        {
            var testProj = new TestProject()
            {
                Name             = "TargetPlatformTests",
                IsSdkProject     = true,
                TargetFrameworks = targetFramework
            };
            var testAsset = _testAssetsManager.CreateTestProject(testProj);

            Action <string, string> assertValue = (string valueName, string expected) =>
            {
                var getValuesCommand = new GetValuesCommand(Log, Path.Combine(testAsset.Path, testProj.Name), targetFramework, valueName);
                getValuesCommand
                .Execute()
                .Should()
                .Pass();
                if (expected.Trim().Equals(string.Empty))
                {
                    getValuesCommand.GetValues().Count.Should().Be(0, $"expect '{valueName}' to be '{expected}'. But get {string.Join(";", getValuesCommand.GetValues())}");
                }
                else
                {
                    getValuesCommand.GetValues().ShouldBeEquivalentTo(new[] { expected }, $"Asserting \"{valueName}\"'s value");
                }
            };

            assertValue("TargetFrameworkIdentifier", expectedTargetFrameworkIdentifier);
            assertValue("TargetFrameworkVersion", expectedTargetFrameworkVersion);
            assertValue("TargetPlatformIdentifier", expectedTargetPlatformIdentifier);
            assertValue("TargetPlatformIdentifier", expectedTargetPlatformIdentifier);
            assertValue("TargetPlatformVersion", expectedTargetPlatformVersion);
            assertValue("TargetPlatformMoniker", expectedTargetPlatformIdentifier.Equals(string.Empty) && expectedTargetPlatformVersion.Equals(string.Empty) ?
                        string.Empty : $"{expectedTargetPlatformIdentifier},Version={expectedTargetPlatformVersion}");
            assertValue("TargetPlatformDisplayName", $"{expectedTargetPlatformIdentifier} {expectedTargetPlatformVersion}");
        }
Esempio n. 21
0
        public void It_solves_conflicts_between_package_and_implicit_references()
        {
            // Test case from https://github.com/dotnet/sdk/issues/3904.
            // This dll is included in both the explicit package reference and Microsoft.NET.Build.Extensions. We prevent a double write in
            // _ComputeResolvedCopyLocalPublishAssets by removing dlls duplicated between package references and implicitly expanded .NET references.
            var reference       = "System.Runtime.InteropServices.RuntimeInformation";
            var targetFramework = "net461";
            var testProject     = new TestProject()
            {
                Name             = "ConflictingFilePublish",
                IsSdkProject     = true,
                TargetFrameworks = targetFramework
            };

            testProject.PackageReferences.Add(new TestPackageReference(reference, "4.3.0"));
            testProject.PackageReferences.Add(new TestPackageReference("Microsoft.AspNetCore", "2.1.4"));
            var testAsset = _testAssetsManager.CreateTestProject(testProject, testProject.Name);

            var getValuesCommand = new GetValuesCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name), targetFramework, "ResolvedFileToPublish", GetValuesCommand.ValueType.Item)
            {
                DependsOnTargets = "Publish"
            };

            getValuesCommand
            .Execute()
            .Should()
            .Pass();

            var files = getValuesCommand.GetValues()
                        .Where(file => file.Contains(reference));

            files.Count().Should().Be(1);

            // We should choose the system.runtime.interopservices.runtimeinformation file from Microsoft.NET.Build.Extensions as it has a higher AssemblyVersion (4.0.2.0 compared to 4.0.1.0)
            files.FirstOrDefault().Contains(@"Microsoft.NET.Build.Extensions\net461\lib\System.Runtime.InteropServices.RuntimeInformation.dll").Should().BeTrue();
        }
Esempio n. 22
0
        public void Net50TargetFrameworkParsesAsNetCoreAppTargetFrameworkIdentifier()
        {
            var testProject = new TestProject()
            {
                Name             = "Net5Test",
                TargetFrameworks = "net5.0",
            };

            var testAsset = _testAssetsManager.CreateTestProject(testProject, testProject.Name);

            var buildCommand = new BuildCommand(testAsset);

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

            var getValuesCommand = new GetValuesCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name), testProject.TargetFrameworks, "TargetFrameworkIdentifier");

            getValuesCommand.Execute()
            .Should()
            .Pass();

            getValuesCommand.GetValues().Should().BeEquivalentTo(".NETCoreApp");
        }
Esempio n. 23
0
        public void RuntimePackWithLabelIsSelected()
        {
            var testProject = new TestProject()
            {
                TargetFrameworks  = "net5.0",
                IsSdkProject      = true,
                IsExe             = true,
                RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid()
            };

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var knownRuntimePack = CreateTestKnownRuntimePack();

            AddItem(testAsset, knownRuntimePack);

            var frameworkReferenceUpdate = new XElement("FrameworkReference",
                                                        new XAttribute("Update", "Microsoft.NETCore.App"),
                                                        new XAttribute("RuntimePackLabels", "Mono"));

            AddItem(testAsset, frameworkReferenceUpdate);

            var getValuesCommand = new GetValuesCommand(testAsset, "RuntimePack", GetValuesCommand.ValueType.Item)
            {
                DependsOnTargets = "ProcessFrameworkReferences",
                ShouldRestore    = false
            };

            getValuesCommand
            .Execute()
            .Should()
            .Pass();

            //  StartsWith instead of exact match because current RID is likely to be more specific than the runtime pack RID
            getValuesCommand.GetValues().Should().Contain(rp => rp.StartsWith("Microsoft.NETCore.App.Runtime.Mono."));
        }
Esempio n. 24
0
        public void It_Has_Unescaped_PackageConflictPreferredPackages_Values()
        {
            string targetFramework = ToolsetInfo.CurrentTargetFramework;

            var testAsset = _testAssetsManager
                            .CopyTestAsset("AppWithLibrary", identifier: targetFramework)
                            .WithSource()
                            .WithTargetFramework(targetFramework, "TestLibrary");

            var getValuesCommand = new GetValuesCommand(Log, Path.Combine(testAsset.TestRoot, "TestLibrary"), targetFramework, "PackageConflictPreferredPackages");

            getValuesCommand
            .Execute()
            .Should()
            .Pass();

            List <string> preferredPackages = getValuesCommand.GetValues();

            preferredPackages.Should().NotBeEmpty();
            preferredPackages.Count.Should().BeGreaterThan(1);

            preferredPackages.Should().NotContain(packageName => packageName.Contains(';'),
                                                  because: "No package name should have a semicolon in it--PackageConflictPreferredPackages should be a semicolon delimited list of package names");
        }
Esempio n. 25
0
        public void It_uses_hintpath_when_replacing_simple_name_references(bool useFacades)
        {
            TestProject project = new TestProject()
            {
                Name             = "NETFrameworkLibrary",
                TargetFrameworks = "net462",
                IsSdkProject     = true
            };

            if (useFacades)
            {
                var netStandard2Project = new TestProject()
                {
                    Name             = "NETStandard20Project",
                    TargetFrameworks = "netstandard2.0",
                    IsSdkProject     = true
                };

                project.ReferencedProjects.Add(netStandard2Project);
            }


            var testAsset = _testAssetsManager.CreateTestProject(project, "SimpleNamesWithHintPaths", identifier: useFacades ? "_useFacades" : "")
                            .WithProjectChanges((path, p) =>
            {
                if (Path.GetFileNameWithoutExtension(path) == project.Name)
                {
                    var ns = p.Root.Name.Namespace;

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

                    if (!useFacades)
                    {
                        itemGroup.Add(new XElement(ns + "PackageReference",
                                                   new XAttribute("Include", "System.Net.Http"),
                                                   new XAttribute("Version", "4.3.2")));
                    }

                    itemGroup.Add(new XElement(ns + "Reference",
                                               new XAttribute("Include", "System.Net.Http")));
                }
            });

            string projectFolder = Path.Combine(testAsset.Path, project.Name);

            var getValuesCommand = new GetValuesCommand(Log, projectFolder, project.TargetFrameworks, "Reference", GetValuesCommand.ValueType.Item);

            getValuesCommand.MetadataNames.Add("HintPath");

            getValuesCommand
            .Execute()
            .Should()
            .Pass();

            string correctHttpReference;

            if (useFacades)
            {
                string microsoftNETBuildExtensionsPath = TestContext.Current.ToolsetUnderTest.GetMicrosoftNETBuildExtensionsPath();
                correctHttpReference = Path.Combine(microsoftNETBuildExtensionsPath, @"net461\lib\System.Net.Http.dll");
            }
            else
            {
                correctHttpReference = Path.Combine(TestContext.Current.NuGetCachePath, "system.net.http", "4.3.2", "ref", "net46", "System.Net.Http.dll");
            }

            var valuesWithMetadata = getValuesCommand.GetValuesWithMetadata();

            //  There shouldn't be a Reference item where the ItemSpec is the path to the System.Net.Http.dll from a NuGet package
            valuesWithMetadata.Should().NotContain(v => v.value == correctHttpReference);

            //  There should be a Reference item where the ItemSpec is the simple name System.Net.Http
            valuesWithMetadata.Should().ContainSingle(v => v.value == "System.Net.Http");

            //  The Reference item with the simple name should have a HintPath to the DLL in the NuGet package
            valuesWithMetadata.Single(v => v.value == "System.Net.Http")
            .metadata["HintPath"]
            .Should().Be(correctHttpReference);
        }
Esempio n. 26
0
        public void When_TargetPlatformVersion_is_set_higher_than_10_It_can_reference_cswinrt_api()
        {
            const string ProjectName = "WindowsDesktopSdkTest_without_ProjectSdk_set";

            const string tfm = "net5.0";

            var testProject = new TestProject()
            {
                Name             = ProjectName,
                TargetFrameworks = tfm,
                IsWinExe         = true,
            };

            testProject.SourceFiles.Add("Program.cs", _useCsWinrtApi);
            testProject.AdditionalProperties.Add("TargetPlatformIdentifier", "Windows");
            testProject.AdditionalProperties.Add("TargetPlatformVersion", "10.0.17763");

            var asset = _testAssetsManager.CreateTestProject(testProject);

            var buildCommand = new BuildCommand(Log, Path.Combine(asset.Path, ProjectName));

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

            void Assert(DirectoryInfo outputDir)
            {
                outputDir.File("Microsoft.Windows.SDK.NET.dll").Exists.Should().BeTrue("The output has cswinrt dll");
                outputDir.File("WinRT.Runtime.dll").Exists.Should().BeTrue("The output has cswinrt dll");
                var runtimeconfigjson = File.ReadAllText(outputDir.File(ProjectName + ".runtimeconfig.json").FullName);

                runtimeconfigjson.Contains(@"""name"": ""Microsoft.NETCore.App""").Should().BeTrue("runtimeconfig.json only reference Microsoft.NETCore.App");
                runtimeconfigjson.Contains("Microsoft.Windows.SDK.NET").Should().BeFalse("runtimeconfig.json does not reference windows SDK");
            }

            Assert(buildCommand.GetOutputDirectory(tfm));

            var publishCommand    = new PublishCommand(asset);
            var runtimeIdentifier = "win-x64";

            publishCommand.Execute("-p:SelfContained=true", $"-p:RuntimeIdentifier={runtimeIdentifier}")
            .Should()
            .Pass();

            Assert(publishCommand.GetOutputDirectory(tfm, runtimeIdentifier: runtimeIdentifier));

            var command = new GetValuesCommand(
                Log,
                Path.Combine(asset.Path, testProject.Name),
                testProject.TargetFrameworks,
                "FilesCopiedToPublishDir",
                GetValuesCommand.ValueType.Item)
            {
                DependsOnTargets = "ComputeFilesCopiedToPublishDir",
                MetadataNames    = { "RelativePath" },
            };

            command.Execute().Should().Pass();
            var items = from item in command.GetValuesWithMetadata()
                        select new
            {
                Identity     = item.value,
                RelativePath = item.metadata["RelativePath"]
            };

            items
            .Should().Contain(i => i.RelativePath == "Microsoft.Windows.SDK.NET.dll" && Path.GetFileName(i.Identity) == "Microsoft.Windows.SDK.NET.dll",
                              because: "wapproj should copy cswinrt dlls");
            items
            .Should()
            .Contain(i => i.RelativePath == "WinRT.Runtime.dll" && Path.GetFileName(i.Identity) == "WinRT.Runtime.dll",
                     because: "wapproj should copy cswinrt dlls");

            // ready to run is supported
            publishCommand.Execute("-p:SelfContained=true", $"-p:RuntimeIdentifier={runtimeIdentifier}", $"-p:PublishReadyToRun=true")
            .Should()
            .Pass();

            // PublishSingleFile is supported
            publishCommand.Execute("-p:SelfContained=true", $"-p:RuntimeIdentifier={runtimeIdentifier}", $"-p:PublishSingleFile=true")
            .Should()
            .Pass();
        }
Esempio n. 27
0
        public void It_builds_a_simple_vb_project(string targetFramework, bool isExe)
        {
            var(expectedVBRuntime, expectedOutputFiles) = GetExpectedOutputs(targetFramework, isExe);

            var testProject = new TestProject
            {
                Name             = "HelloWorld",
                IsSdkProject     = true,
                TargetFrameworks = targetFramework,
                IsExe            = isExe,
                SourceFiles      =
                {
                    ["Program.vb"] = @"
                        Imports System

                        Module Program
                            #If NETFRAMEWORK Or NETCOREAPP3_0
                                ' https://github.com/dotnet/sdk/issues/2793
                                Private Const TabChar As Char = Chr(9)
                            #End If

                            Function MyComputerName() As String
                                #If NETFRAMEWORK
                                    Return My.Computer.Name
                                #End If

                                #If NETFRAMEWORK Or NETCOREAPP_3_0
                                    ' https://github.com/dotnet/sdk/issues/3379
                                    End
                                #End If
                            End Function

                            Sub Main(args As String())
                                Console.WriteLine(""Hello World from "" & MyComputerName())
                            End Sub
                        End Module
                        ",
                }
            };

            var testAsset = _testAssetsManager
                            .CreateTestProject(testProject, identifier: targetFramework + isExe, targetExtension: ".vbproj");

            var buildCommand = new GetValuesCommand(
                Log,
                Path.Combine(testAsset.TestRoot, testProject.Name),
                targetFramework,
                "VBRuntime")
            {
                DependsOnTargets = "Build"
            };

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

            var outputDirectory = buildCommand.GetOutputDirectory(targetFramework);
            var actualVBRuntime = GetVBRuntime(buildCommand.GetValues().FirstOrDefault());

            File.Delete(outputDirectory.File("VBRuntimeValues.txt").FullName);

            outputDirectory.Should().OnlyHaveFiles(expectedOutputFiles);
            actualVBRuntime.Should().Be(expectedVBRuntime);
        }
Esempio n. 28
0
        public void It_builds_a_simple_project(string targetFramework)
        {
            if (targetFramework == "net45" && !TestProject.ReferenceAssembliesAreInstalled("v4.5"))
            {
                // skip net45 when we do not have .NET Framework 4.5 reference assemblies
                // due to https://github.com/dotnet/core-sdk/issues/3228
                return;
            }

            var(expectedVBRuntime, expectedOutputFiles) = GetExpectedOutputs(targetFramework);

            var testProject = new TestProject
            {
                Name                 = "HelloWorld",
                IsSdkProject         = true,
                TargetFrameworks     = targetFramework,
                IsExe                = targetFramework != "netstandard2.0",
                AdditionalProperties =
                {
                    ["MyType"] = "Console",
                },
                SourceFiles =
                {
                    ["Program.vb"] = @"
                        Imports System

                        Module Program
                            Function MyComputerName() As String
                                #If NETFRAMEWORK Or NETCOREAPP3_0 Then
                                    Return My.Computer.Name
                                #End If
                            End Function

                            Sub Main(args As String())
                                Console.WriteLine(""Hello World from "" & MyComputerName())
                            End Sub
                        End Module
                        ",
                }
            };

            var testAsset = _testAssetsManager
                            .CreateTestProject(testProject, identifier: targetFramework, targetExtension: ".vbproj")
                            .Restore(Log, testProject.Name);

            var buildCommand = new GetValuesCommand(
                Log,
                Path.Combine(testAsset.TestRoot, testProject.Name),
                targetFramework,
                "VBRuntime")
            {
                DependsOnTargets = "Build"
            };

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

            var outputDirectory = buildCommand.GetOutputDirectory(targetFramework);
            var actualVBRuntime = GetVBRuntime(buildCommand.GetValues().FirstOrDefault());

            File.Delete(outputDirectory.File("VBRuntimeValues.txt").FullName);

            outputDirectory.Should().OnlyHaveFiles(expectedOutputFiles);
            actualVBRuntime.Should().Be(expectedVBRuntime);
        }
Esempio n. 29
0
        public void It_provides_runtime_configuration_and_shadow_copy_files_via_outputgroup(string targetFramework)
        {
            var projectRef = new TestProject
            {
                Name             = "ReferencedProject",
                TargetFrameworks = targetFramework,
                IsSdkProject     = true,
            };

            var project = new TestProject
            {
                Name               = "DesignerTest",
                IsExe              = true,
                TargetFrameworks   = targetFramework,
                IsSdkProject       = true,
                PackageReferences  = { new TestPackageReference("NewtonSoft.Json", "12.0.1") },
                ReferencedProjects = { projectRef }
            };

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

            var command = new GetValuesCommand(
                Log,
                Path.Combine(asset.Path, project.Name),
                targetFramework,
                "DesignerRuntimeImplementationProjectOutputGroupOutput",
                GetValuesCommand.ValueType.Item)
            {
                DependsOnTargets = "DesignerRuntimeImplementationProjectOutputGroup",
                MetadataNames    = { "TargetPath" },
            };

            command.Execute().Should().Pass();

            var items =
                from item in command.GetValuesWithMetadata()
                select new
            {
                Identity   = item.value,
                TargetPath = item.metadata["TargetPath"]
            };

            string depsFile      = null;
            string runtimeConfig = null;
            var    otherFiles    = new List <string>();

            foreach (var item in items)
            {
                Path.IsPathFullyQualified(item.Identity).Should().BeTrue();
                Path.GetFileName(item.Identity).Should().Be(item.TargetPath);

                switch (item.TargetPath)
                {
                case "DesignerTest.designer.deps.json":
                    depsFile = item.Identity;
                    break;

                case "DesignerTest.designer.runtimeconfig.json":
                    runtimeConfig = item.Identity;
                    break;

                default:
                    otherFiles.Add(item.TargetPath);
                    break;
                }
            }

            switch (targetFramework)
            {
            case "netcoreapp3.0":
                var depsFileLibraries = GetRuntimeLibraryFileNames(depsFile);
                depsFileLibraries.Should().BeEquivalentTo(new[] { "Newtonsoft.Json.dll" });

                var options = GetRuntimeOptions(runtimeConfig);
                options["configProperties"]["Microsoft.NETCore.DotNetHostPolicy.SetAppPaths"].Value <bool>().Should().BeTrue();
                options["tfm"].Value <string>().Should().Be(targetFramework);
                options["additionalProbingPaths"].Value <JArray>().Should().NotBeEmpty();

                otherFiles.Should().BeEquivalentTo(new[] { "ReferencedProject.dll", "ReferencedProject.pdb" });
                break;

            case "net46":
                depsFile.Should().BeNull();
                runtimeConfig.Should().BeNull();
                otherFiles.Should().BeEquivalentTo(new[] { "Newtonsoft.Json.dll", "ReferencedProject.dll", "ReferencedProject.pdb" });
                break;
            }
        }
        //[Theory]
        //[InlineData(".NETStandard,Version=v1.0", new[] { "NETSTANDARD1_0" }, false)]
        //[InlineData("netstandard1.3", new[] { "NETSTANDARD1_3" }, false)]
        //[InlineData("netstandard1.6", new[] { "NETSTANDARD1_6" }, false)]
        //[InlineData("net45", new[] { "NET45" }, true)]
        //[InlineData("net461", new[] { "NET461" }, true)]
        //[InlineData("netcoreapp1.0", new[] { "NETCOREAPP1_0" }, false)]
        //[InlineData(".NETPortable,Version=v4.5,Profile=Profile78", new string[] { }, false)]
        //[InlineData(".NETFramework,Version=v4.0,Profile=Client", new string[] { "NET40" }, false)]
        //[InlineData("Xamarin.iOS,Version=v1.0", new string[] { "XAMARINIOS1_0" }, false)]
        //[InlineData("UnknownFramework,Version=v3.14", new string[] { "UNKNOWNFRAMEWORK3_14" }, false)]
        public void It_implicitly_defines_compilation_constants_for_the_target_framework(string targetFramework, string[] expectedDefines, bool buildOnlyOnWindows)
        {
            bool shouldCompile = true;

            var testAsset = _testAssetsManager
                            .CopyTestAsset("AppWithLibrary", "ImplicitFrameworkConstants", targetFramework)
                            .WithSource()
                            .WithProjectChanges(project =>
            {
                //  Update target framework in project
                var ns = project.Root.Name.Namespace;
                var targetFrameworkProperties = project.Root
                                                .Elements(ns + "PropertyGroup")
                                                .Elements(ns + "TargetFramework")
                                                .ToList();

                targetFrameworkProperties.Count.Should().Be(1);

                if (targetFramework.Contains(",Version="))
                {
                    //  We use the full TFM for frameworks we don't have built-in support for targeting, so we don't want to run the Compile target
                    shouldCompile = false;

                    var frameworkName = new FrameworkName(targetFramework);

                    var targetFrameworkProperty = targetFrameworkProperties.Single();
                    targetFrameworkProperty.AddBeforeSelf(new XElement(ns + "TargetFrameworkIdentifier", frameworkName.Identifier));
                    targetFrameworkProperty.AddBeforeSelf(new XElement(ns + "TargetFrameworkVersion", "v" + frameworkName.Version.ToString()));
                    if (!string.IsNullOrEmpty(frameworkName.Profile))
                    {
                        targetFrameworkProperty.AddBeforeSelf(new XElement(ns + "TargetFrameworkProfile", frameworkName.Profile));
                    }

                    //  For the NuGet restore task to work with package references, it needs the TargetFramework property to be set.
                    //  Otherwise we would just remove the property.
                    targetFrameworkProperty.SetValue(targetFramework);
                }
                else
                {
                    shouldCompile = true;
                    targetFrameworkProperties.Single().SetValue(targetFramework);
                }
            })
                            .Restore(relativePath: "TestLibrary");

            if (buildOnlyOnWindows && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                shouldCompile = false;
            }

            var libraryProjectDirectory = Path.Combine(testAsset.TestRoot, "TestLibrary");

            var getValuesCommand = new GetValuesCommand(Stage0MSBuild, libraryProjectDirectory,
                                                        targetFramework, "DefineConstants")
            {
                ShouldCompile = shouldCompile
            };

            getValuesCommand
            .Execute()
            .Should()
            .Pass();

            var definedConstants = getValuesCommand.GetValues();

            definedConstants.Should().BeEquivalentTo(new[] { "DEBUG", "TRACE" }.Concat(expectedDefines).ToArray());
        }