示例#1
0
        public void It_should_create_suggested_workload_items()
        {
            var testProject = new TestProject()
            {
                Name             = "WorkloadTest",
                TargetFrameworks = "net5.0-missingworkloadtestplatform"
            };

            var testAsset = _testAssetsManager
                            .CreateTestProject(testProject);

            var getValuesCommand = new GetValuesCommand(testAsset, "SuggestedWorkload", GetValuesCommand.ValueType.Item);

            getValuesCommand.DependsOnTargets = "GetSuggestedWorkloads";
            getValuesCommand.MetadataNames.Add("VisualStudioComponentId");
            getValuesCommand.MetadataNames.Add("VisualStudioComponentIds");
            getValuesCommand.ShouldRestore = false;

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

            getValuesCommand.GetValuesWithMetadata().Select(valueAndMetadata => (valueAndMetadata.value, valueAndMetadata.metadata["VisualStudioComponentId"]))
            .Should()
            .BeEquivalentTo(("microsoft-net-sdk-missingtestworkload", "microsoft.net.sdk.missingtestworkload"));

            getValuesCommand.GetValuesWithMetadata().Select(valueAndMetadata => (valueAndMetadata.value, valueAndMetadata.metadata["VisualStudioComponentIds"]))
            .Should()
            .BeEquivalentTo(("microsoft-net-sdk-missingtestworkload", "microsoft.net.sdk.missingtestworkload"));
        }
示例#2
0
        public void It_has_target_path_and_final_outputput_path_metadata(string targetFramework)
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset("HelloWorld", identifier: targetFramework)
                            .WithSource()
                            .WithTargetFramework(targetFramework);

            var command = new GetValuesCommand(
                Log,
                testAsset.TestRoot,
                targetFramework,
                "BuiltProjectOutputGroupOutput",
                GetValuesCommand.ValueType.Item)
            {
                MetadataNames    = { "FinalOutputPath", "TargetPath" },
                DependsOnTargets = "BuiltProjectOutputGroup",
            };

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

            var outputDirectory   = command.GetOutputDirectory(targetFramework);
            var runtimeConfigFile = outputDirectory.File("HelloWorld.runtimeconfig.json");

            var(_, metadata) = command.GetValuesWithMetadata().Single(i => i.value == runtimeConfigFile.FullName);

            metadata.Count.Should().Be(2);
            metadata.Should().Contain(KeyValuePair.Create("FinalOutputPath", runtimeConfigFile.FullName));
            metadata.Should().Contain(KeyValuePair.Create("TargetPath", runtimeConfigFile.Name));
        }
        public void DuplicatePackageReferencesCanBeUsed()
        {
            var testProject = new TestProject()
            {
                Name             = "DuplicatePackageReference",
                TargetFrameworks = "netcoreapp3.0",
                IsSdkProject     = true,
            };

            testProject.PackageReferences.Add(new TestPackageReference("Newtonsoft.Json", "12.0.1"));
            testProject.PackageReferences.Add(new TestPackageReference("Newtonsoft.Json", "12.0.1"));

            testProject.SourceFiles["Test.cs"] = @"
public class Class1
{
    public static void Test()
    {
        Newtonsoft.Json.Linq.JToken.Parse(""{ }"");
    }
}";

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

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

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

            //  https://github.com/dotnet/sdk/issues/3027 could cause a situation where the build fails in VS
            //  but not the command line, apparently due to differences in how the different restores handle
            //  duplicate package references.  So for this test, check the metadata.

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

            getValuesCommand.MetadataNames.Add("PrivateAssets");
            getValuesCommand.MetadataNames.Add("ExcludeAssets");
            getValuesCommand.MetadataNames.Add("IsImplicitlyDefined");

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

            var packageReferences = getValuesCommand.GetValuesWithMetadata();

            var newtonsoftReferences = packageReferences.Where(pr => pr.value == "Newtonsoft.Json");

            newtonsoftReferences.Count().Should().BeGreaterOrEqualTo(1);

            foreach (var r in newtonsoftReferences)
            {
                r.metadata["PrivateAssets"].Should().BeEmpty();
                r.metadata["ExcludeAssets"].Should().BeEmpty();
                r.metadata["IsImplicitlyDefined"].Should().BeEmpty();
            }
        }
示例#4
0
        public void It_disables_copying_conflicting_transitive_content(bool copyConflictingTransitiveContent, bool explicitlySet)
        {
            var tfm          = "netcoreapp3.1";
            var contentName  = "script.sh";
            var childProject = new TestProject()
            {
                TargetFrameworks = tfm,
                Name             = "ChildProject",
                IsSdkProject     = true
            };
            var childAsset = _testAssetsManager.CreateTestProject(childProject)
                             .WithProjectChanges(project => AddProjectChanges(project));

            File.WriteAllText(Path.Combine(childAsset.Path, childProject.Name, contentName), childProject.Name);

            var parentProject = new TestProject()
            {
                TargetFrameworks = tfm,
                Name             = "ParentProject",
                IsSdkProject     = true
            };

            if (explicitlySet)
            {
                parentProject.AdditionalProperties["CopyConflictingTransitiveContent"] = copyConflictingTransitiveContent.ToString().ToLower();
            }
            var parentAsset = _testAssetsManager.CreateTestProject(parentProject)
                              .WithProjectChanges(project => AddProjectChanges(project, Path.Combine(childAsset.Path, childProject.Name, childProject.Name + ".csproj")));

            File.WriteAllText(Path.Combine(parentAsset.Path, parentProject.Name, contentName), parentProject.Name);

            var buildCommand = new BuildCommand(parentAsset);

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

            var getValuesCommand = new GetValuesCommand(Log, Path.Combine(parentAsset.Path, parentProject.Name), tfm, "ResultOutput");

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

            var valuesResult = getValuesCommand.GetValuesWithMetadata().Select(pair => Path.GetFullPath(pair.value));

            if (copyConflictingTransitiveContent)
            {
                valuesResult.Count().Should().Be(2);
                valuesResult.Should().BeEquivalentTo(Path.GetFullPath(Path.Combine(parentAsset.Path, parentProject.Name, contentName)),
                                                     Path.GetFullPath(Path.Combine(childAsset.Path, childProject.Name, contentName)));
            }
            else
            {
                valuesResult.Count().Should().Be(1);
                valuesResult.First().Should().Contain(Path.GetFullPath(Path.Combine(parentAsset.Path, parentProject.Name, contentName)));
            }
        }
示例#5
0
        private Dictionary <string, List <(string asset, string isTrimmable)> > GetRuntimeAssetTrimInfo(TestProject testProject,
                                                                                                        Action <XDocument> projectChanges       = null,
                                                                                                        [CallerMemberName] string callingMethod = null,
                                                                                                        string identifier = null)
        {
            string targetFramework = "netcoreapp3.0";

            testProject.Name              = "TrimInfoTest";
            testProject.TargetFrameworks  = targetFramework;;
            testProject.IsSdkProject      = true;
            testProject.IsExe             = true;
            testProject.RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(testProject.TargetFrameworks);

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

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

            testAsset.Restore(Log, testProject.Name);

            var command = new GetValuesCommand(Log, Path.Combine(testAsset.Path, testProject.Name), targetFramework,
                                               "ResolvedFileToPublish", GetValuesCommand.ValueType.Item)
            {
                DependsOnTargets = "ComputeFilesToPublish",
                MetadataNames    = { "PackageName", "IsTrimmable" },
            };

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

            var trimInfo = new Dictionary <string, List <(string asset, string isTrimmable)> > ();

            foreach (var item in items)
            {
                List <(string asset, string isTrimmable)> assets;
                if (!trimInfo.TryGetValue(item.PackageName, out assets))
                {
                    assets = trimInfo[item.PackageName] = new List <(string asset, string isTrimmable)> (3);
                }
                assets.Add((item.Identity, item.IsTrimmable));
            }

            return(trimInfo);
        }
示例#6
0
        public void PackageErrorsAreSet(string targetFramework)
        {
            var designTimeArgs = GetDesignTimeMSBuildArgs();

            if (designTimeArgs == null)
            {
                //  Design-time targets couldn't be found
                return;
            }

            var testProject = new TestProject()
            {
                Name             = "DesignTimePackageDependencies",
                TargetFrameworks = targetFramework,
                IsSdkProject     = true
            };

            //  Downgrade will cause an error
            testProject.AdditionalProperties["ContinueOnError"] = "ErrorAndContinue";

            testProject.PackageReferences.Add(new TestPackageReference("NuGet.Commands", "4.0.0"));
            testProject.PackageReferences.Add(new TestPackageReference("NuGet.Packaging", "3.5.0"));

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

            new RestoreCommand(testAsset)
            .Execute()
            .Should()
            .Fail();

            var getValuesCommand = new GetValuesCommand(testAsset, "_PackageDependenciesDesignTime", GetValuesCommand.ValueType.Item);

            getValuesCommand.ShouldRestore    = false;
            getValuesCommand.DependsOnTargets = "ResolvePackageDependenciesDesignTime";
            getValuesCommand.MetadataNames    = new List <string>()
            {
                "DiagnosticLevel"
            };

            getValuesCommand
            .WithWorkingDirectory(testAsset.TestRoot)
            .Execute(designTimeArgs)
            .Should()
            .Fail();

            var valuesWithMetadata     = getValuesCommand.GetValuesWithMetadata();
            var nugetPackagingMetadata = valuesWithMetadata.Single(kvp => kvp.value.Equals("NuGet.Packaging/3.5.0")).metadata;

            nugetPackagingMetadata["DiagnosticLevel"].Should().Be("Error");
        }
        public void Given_duplicated_ResolvedFileToPublish_It_Can_Publish()
        {
            const string ProjectName = "WindowsDesktopSdkTest_without_ProjectSdk_set";

            const string tfm = "net5.0";

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

            var testAsset = _testAssetsManager.CreateTestProject(testProject).WithProjectChanges((project) =>
            {
                var ns = project.Root.Name.Namespace;
                var duplicatedResolvedFileToPublish = XElement.Parse(@"
<ItemGroup>
    <ResolvedFileToPublish Include=""obj\Debug\net5.0\WindowsDesktopSdkTest_without_ProjectSdk_set.dll"">
      <RelativePath>WindowsDesktopSdkTest_without_ProjectSdk_set.dll</RelativePath>
    </ResolvedFileToPublish>
    <ResolvedFileToPublish Include=""obj\Debug\net5.0\WindowsDesktopSdkTest_without_ProjectSdk_set.dll"">
      <RelativePath>WindowsDesktopSdkTest_without_ProjectSdk_set.dll</RelativePath>
    </ResolvedFileToPublish>
  </ItemGroup>
");
                project.Root.Add(duplicatedResolvedFileToPublish);
            });

            var publishItemsOutputGroupOutputsCommand = new GetValuesCommand(
                Log,
                Path.Combine(testAsset.Path, testProject.Name),
                testProject.TargetFrameworks,
                "PublishItemsOutputGroupOutputs",
                GetValuesCommand.ValueType.Item)
            {
                DependsOnTargets = "Publish",
                MetadataNames    = { "OutputPath" },
            };

            publishItemsOutputGroupOutputsCommand.Execute().Should().Pass();
            var publishItemsOutputGroupOutputsItems =
                from item in publishItemsOutputGroupOutputsCommand.GetValuesWithMetadata()
                select new
            {
                OutputPath = item.metadata["OutputPath"]
            };
        }
示例#8
0
        public void It_marks_package_references_as_externally_resolved(bool?markAsExternallyResolved)
        {
            var project = new TestProject
            {
                Name             = "Library",
                TargetFrameworks = "netstandard2.0",
                IsSdkProject     = true,
                // references from packages go through a different code path to be marked externally resolved.
                PackageReferences = { new TestPackageReference("NewtonSoft.Json", "10.0.1") }
            };

            var asset = _testAssetsManager.CreateTestProject(
                project,
                "ExternallyResolvedPackages",
                markAsExternallyResolved.ToString())
                        .WithProjectChanges((path, p) =>
            {
                if (markAsExternallyResolved != null)
                {
                    var ns = p.Root.Name.Namespace;
                    p.Root.Add(
                        new XElement(ns + "PropertyGroup",
                                     new XElement(ns + "MarkPackageReferencesAsExternallyResolved",
                                                  markAsExternallyResolved)));
                }
            })
                        .Restore(Log, project.Name);

            var command = new GetValuesCommand(
                Log,
                Path.Combine(asset.Path, project.Name),
                project.TargetFrameworks,
                "Reference",
                GetValuesCommand.ValueType.Item);

            command.MetadataNames.Add("ExternallyResolved");
            command.Execute().Should().Pass();

            var references = command.GetValuesWithMetadata();

            references.Should().NotBeEmpty();

            foreach (var(value, metadata) in references)
            {
                metadata["ExternallyResolved"].Should().BeEquivalentTo((markAsExternallyResolved ?? true) ? "true" : "");
            }
        }
示例#9
0
        public void ItUsesCorrectWindowsSdkPackVersion(string targetFramework, bool?useWindowsSDKPreview, string windowsSdkPackageVersion, string expectedWindowsSdkPackageVersion)
        {
            var testProject = new TestProject()
            {
                TargetFrameworks = targetFramework
            };

            if (useWindowsSDKPreview != null)
            {
                testProject.AdditionalProperties["UsewindowsSdkPreview"] = useWindowsSDKPreview.Value.ToString();
            }
            if (!string.IsNullOrEmpty(windowsSdkPackageVersion))
            {
                testProject.AdditionalProperties["WindowsSdkPackageVersion"] = windowsSdkPackageVersion;
            }

            var testAsset = _testAssetsManager.CreateTestProject(testProject, identifier: targetFramework + useWindowsSDKPreview + windowsSdkPackageVersion);

            var getValueCommand = new GetValuesCommand(testAsset, "PackageDownload", GetValuesCommand.ValueType.Item);

            getValueCommand.ShouldRestore    = false;
            getValueCommand.DependsOnTargets = "_CheckForInvalidConfigurationAndPlatform;CollectPackageDownloads";
            getValueCommand.MetadataNames.Add("Version");
            getValueCommand.Execute()
            .Should()
            .Pass();

            var packageDownloadValues = getValueCommand.GetValuesWithMetadata().Where(kvp => kvp.value == "Microsoft.Windows.SDK.NET.Ref").ToList();

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

            var packageDownloadVersion = packageDownloadValues.Single().metadata["Version"];

            packageDownloadVersion[0].Should().Be('[');
            packageDownloadVersion.Last().Should().Be(']');

            //  The patch version of the Windows SDK Ref pack will change over time, so we use a '*' in the expected version to indicate that and replace it with
            //  the 4th part of the version number of the resolved package.
            var trimmedPackageDownloadVersion = packageDownloadVersion.Substring(1, packageDownloadVersion.Length - 2);

            if (expectedWindowsSdkPackageVersion.Contains('*'))
            {
                expectedWindowsSdkPackageVersion = expectedWindowsSdkPackageVersion.Replace("*", new Version(trimmedPackageDownloadVersion).Revision.ToString());
            }

            trimmedPackageDownloadVersion.Should().Be(expectedWindowsSdkPackageVersion);
        }
示例#10
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;
            }
        }
示例#11
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();
        }
示例#12
0
        public void RunPublishItemsOutputGroupOutputsTest(bool specifyRid, bool singleFile)
        {
            var testProject = new TestProject()
            {
                Name             = "TestPublishItemsOutputGroupOutputs",
                TargetFrameworks = "netcoreapp3.0",
                IsExe            = true
            };

            testProject.AdditionalProperties["RuntimeIdentifiers"]  = "win-x86";
            testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\..\pkg";
            if (specifyRid)
            {
                testProject.AdditionalProperties["RuntimeIdentifier"] = "win-x86";
            }

            if (singleFile)
            {
                testProject.AdditionalProperties["PublishSingleFile"] = "true";
            }

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var restoreCommand = new RestoreCommand(testAsset);

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

            var command = new GetValuesCommand(
                Log,
                Path.Combine(testAsset.Path, testProject.Name),
                testProject.TargetFrameworks,
                "PublishItemsOutputGroupOutputs",
                GetValuesCommand.ValueType.Item)
            {
                DependsOnTargets = "Publish",
                MetadataNames    = { "OutputPath" },
            };

            command.Execute().Should().Pass();
            var items = from item in command.GetValuesWithMetadata()
                        select new
            {
                Identity   = item.value,
                OutputPath = Path.GetFileName(Path.GetFullPath(Path.Combine(testAsset.Path, testProject.Name, item.metadata["OutputPath"])))
            };

            Log.WriteLine("PublishItemsOutputGroupOutputs contains '{0}' items:", items.Count());
            foreach (var item in items)
            {
                Log.WriteLine("    '{0}': OutputPath = '{1}'", item.Identity, item.OutputPath);
            }

            // Check for the main exe
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                string exeSuffix = specifyRid ? ".exe" : Constants.ExeSuffix;
                items.Should().ContainSingle(i => i.OutputPath.Equals($"{testProject.Name}{exeSuffix}", StringComparison.OrdinalIgnoreCase));
            }

            // Framework assemblies should be there if we specified and rid and this isn't in the single file case
            if (specifyRid && !singleFile)
            {
                FrameworkAssemblies.ForEach(fa => items.Should().ContainSingle(i => i.OutputPath.Equals(fa, StringComparison.OrdinalIgnoreCase)));
                items.Should().Contain(i => i.OutputPath.Equals($"{testProject.Name}.deps.json", StringComparison.OrdinalIgnoreCase));
            }
            else
            {
                FrameworkAssemblies.ForEach(fa => items.Should().NotContain(i => i.OutputPath.Equals(fa, StringComparison.OrdinalIgnoreCase)));
            }
        }
        public void RunFilesCopiedToPublishDirTest(bool specifyRid, bool singleFile)
        {
            var testProject = new TestProject()
            {
                Name             = "TestFilesCopiedToPublishDir",
                TargetFrameworks = "netcoreapp3.0",
                IsSdkProject     = true,
                IsExe            = true
            };

            testProject.AdditionalProperties["RuntimeIdentifiers"]  = "win-x86";
            testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\..\pkg";
            if (specifyRid)
            {
                testProject.AdditionalProperties["RuntimeIdentifier"] = "win-x86";
            }

            if (singleFile)
            {
                testProject.AdditionalProperties["PublishSingleFile"] = "true";
            }

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

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

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

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

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

            Log.WriteLine("FilesCopiedToPublishDir contains '{0}' items:", items.Count());
            foreach (var item in items)
            {
                Log.WriteLine("    '{0}': RelativePath = '{1}'", item.Identity, item.RelativePath);
            }

            // Check for the main exe
            if (RuntimeEnvironment.OperatingSystemPlatform != Platform.Darwin)
            {
                string exeSuffix = specifyRid ? ".exe" : Constants.ExeSuffix;
                items.Should().ContainSingle(i => i.RelativePath.Equals($"{testProject.Name}{exeSuffix}", StringComparison.OrdinalIgnoreCase));
            }

            // Framework assemblies should be there if we specified and rid and this isn't in the single file case
            if (specifyRid && !singleFile)
            {
                FrameworkAssemblies.ForEach(fa => items.Should().ContainSingle(i => i.RelativePath.Equals(fa, StringComparison.OrdinalIgnoreCase)));
            }
            else
            {
                FrameworkAssemblies.ForEach(fa => items.Should().NotContain(i => i.RelativePath.Equals(fa, StringComparison.OrdinalIgnoreCase)));
            }

            // FilesCopiedToPublishDir should never contain the deps.json file
            items.Should().NotContain(i => i.RelativePath.Equals($"{testProject.Name}.deps.json", StringComparison.OrdinalIgnoreCase));
        }
        public void RunPublishItemsOutputGroupTest(bool specifyRid, bool singleFile)
        {
            var testProject = this.SetupProject(specifyRid, singleFile);
            var testAsset   = _testAssetsManager.CreateTestProject(testProject, identifier: specifyRid.ToString() + singleFile.ToString());

            var restoreCommand = new RestoreCommand(testAsset);

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

            var command = new GetValuesCommand(
                Log,
                Path.Combine(testAsset.Path, testProject.Name),
                testProject.TargetFrameworks,
                "PublishItemsOutputGroupOutputs",
                GetValuesCommand.ValueType.Item)
            {
                DependsOnTargets = "PublishItemsOutputGroup",
                MetadataNames    = { "TargetPath", "IsKeyOutput" },
            };

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

            Log.WriteLine("PublishItemsOutputGroup contains '{0}' items:", items.Count());
            foreach (var item in items)
            {
                Log.WriteLine("    '{0}': TargetPath = '{1}', IsKeyOutput = '{2}'", item.Identity, item.TargetPath, item.IsKeyOutput);
            }

            if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                // Check that there's only one key item, and it's the exe
                string exeSuffix = specifyRid ? ".exe" : Constants.ExeSuffix;
                items.
                Where(i => i.IsKeyOutput.Equals("true", StringComparison.OrdinalIgnoreCase)).
                Should().
                ContainSingle(i => i.TargetPath.Equals($"{testProject.Name}{exeSuffix}", StringComparison.OrdinalIgnoreCase));
            }

            // Framework assemblies should be there if we specified and rid and this isn't in the single file case
            if (specifyRid && !singleFile)
            {
                FrameworkAssemblies.ForEach(fa => items.Should().ContainSingle(i => i.TargetPath.Equals(fa, StringComparison.OrdinalIgnoreCase)));
            }
            else
            {
                FrameworkAssemblies.ForEach(fa => items.Should().NotContain(i => i.TargetPath.Equals(fa, StringComparison.OrdinalIgnoreCase)));
            }

            // The deps.json file should be included unless this is the single file case
            if (!singleFile)
            {
                items.Should().ContainSingle(i => i.TargetPath.Equals($"{testProject.Name}.deps.json", StringComparison.OrdinalIgnoreCase));
            }
        }
        public void It_marks_extension_references_as_externally_resolved(bool?markAsExternallyResolved)
        {
            var project = new TestProject
            {
                Name             = "NETFrameworkLibrary",
                TargetFrameworks = "net462",
                IsSdkProject     = true
            };

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

            project.ReferencedProjects.Add(netStandard2Project);

            var asset = _testAssetsManager.CreateTestProject(
                project,
                "ExternallyResolvedExtensions",
                markAsExternallyResolved.ToString())
                        .WithProjectChanges((path, p) =>
            {
                if (markAsExternallyResolved != null)
                {
                    var ns = p.Root.Name.Namespace;
                    p.Root.Add(
                        new XElement(ns + "PropertyGroup",
                                     new XElement(ns + "MarkNETFrameworkExtensionAssembliesAsExternallyResolved",
                                                  markAsExternallyResolved)));
                }
            })
                        .Restore(Log, project.Name);

            var command = new GetValuesCommand(
                Log,
                Path.Combine(asset.Path, project.Name),
                project.TargetFrameworks,
                "Reference",
                GetValuesCommand.ValueType.Item);

            command.MetadataNames.AddRange(new[] { "ExternallyResolved", "HintPath" });
            command.Execute().Should().Pass();

            int frameworkReferenceCount = 0;
            int extensionReferenceCount = 0;
            var references = command.GetValuesWithMetadata();

            foreach (var(value, metadata) in references)
            {
                if (metadata["HintPath"] == "")
                {
                    // implicit framework reference (not externally resolved)
                    metadata["ExternallyResolved"].Should().BeEmpty();
                    frameworkReferenceCount++;
                }
                else
                {
                    // reference added by Microsoft.NET.Build.Extensions
                    metadata["ExternallyResolved"].Should().BeEquivalentTo((markAsExternallyResolved ?? true).ToString());
                    extensionReferenceCount++;
                }
            }

            // make sure both cases were encountered
            frameworkReferenceCount.Should().BeGreaterThan(0);
            extensionReferenceCount.Should().BeGreaterThan(0);
        }
示例#16
0
        public void It_resolves_runtimepack_from_packs_folder()
        {
            var testProject = new TestProject()
            {
                IsExe             = true,
                TargetFrameworks  = ToolsetInfo.CurrentTargetFramework,
                RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid()
            };

            //  Use separate packages download folder for this project so that we can verify whether it had to download runtime packs
            testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\packages";

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var getValuesCommand = new GetValuesCommand(testAsset, "RuntimePack", GetValuesCommand.ValueType.Item);

            getValuesCommand.MetadataNames = new List <string>()
            {
                "NuGetPackageId", "NuGetPackageVersion"
            };
            getValuesCommand.DependsOnTargets = "ProcessFrameworkReferences";
            getValuesCommand.ShouldRestore    = false;

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

            var runtimePacks = getValuesCommand.GetValuesWithMetadata();

            var packageDownloadProject = new TestProject()
            {
                Name             = "PackageDownloadProject",
                TargetFrameworks = testProject.TargetFrameworks
            };

            //  Add PackageDownload items for runtime packs which will be needed
            foreach (var runtimePack in runtimePacks)
            {
                packageDownloadProject.AddItem("PackageDownload",
                                               new Dictionary <string, string>()
                {
                    { "Include", runtimePack.metadata["NuGetPackageId"] },
                    { "Version", "[" + runtimePack.metadata["NuGetPackageVersion"] + "]" }
                });
            }

            //  Download runtime packs into separate folder under test assets
            packageDownloadProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\packs";

            var packageDownloadAsset = _testAssetsManager.CreateTestProject(packageDownloadProject);

            new RestoreCommand(packageDownloadAsset)
            .Execute()
            .Should()
            .Pass();

            //  Package download folders use lowercased package names, but pack folders use mixed case
            //  So change casing of the downloaded runtime pack folders to match what is expected
            //  for packs folders
            foreach (var runtimePack in runtimePacks)
            {
                string oldCasing = Path.Combine(packageDownloadAsset.TestRoot, packageDownloadProject.Name, "packs", runtimePack.metadata["NuGetPackageId"].ToLowerInvariant());
                string newCasing = Path.Combine(packageDownloadAsset.TestRoot, packageDownloadProject.Name, "packs", runtimePack.metadata["NuGetPackageId"]);
                Directory.Move(oldCasing, newCasing);
            }

            //  Now build the original test project with the packs folder with the runtime packs we just downloaded
            var buildCommand = new BuildCommand(testAsset)
                               .WithEnvironmentVariable(EnvironmentVariableNames.WORKLOAD_PACK_ROOTS, Path.Combine(packageDownloadAsset.TestRoot, packageDownloadProject.Name));

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

            //  Verify that runtime packs weren't downloaded to test project's packages folder
            var packagesFolder = Path.Combine(testAsset.TestRoot, testProject.Name, "packages");

            foreach (var runtimePack in runtimePacks)
            {
                var path = Path.Combine(packagesFolder, runtimePack.metadata["NuGetPackageId"].ToLowerInvariant());
                new DirectoryInfo(path).Should().NotExist("Runtime Pack should have been resolved from packs folder");
            }
        }
示例#17
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);
        }
示例#18
0
        public void ResolvedFrameworkReferences_are_generated()
        {
            var testProject = new TestProject()
            {
                Name              = "ResolvedFrameworkReferenceTest",
                IsSdkProject      = true,
                IsExe             = true,
                TargetFrameworks  = "netcoreapp3.0",
                RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid()
            };

            testProject.FrameworkReferences.Add("Microsoft.AspNetCore.App");
            testProject.FrameworkReferences.Add("Microsoft.WindowsDesktop.App");

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var projectFolder = Path.Combine(testAsset.TestRoot, testProject.Name);

            var buildCommand = new BuildCommand(Log, projectFolder);

            var expectedMetadata = new[]
            {
                "OriginalItemSpec",
                "IsImplicitlyDefined",
                "TargetingPackName",
                "TargetingPackVersion",
                "TargetingPackPath",
                "RuntimePackName",
                "RuntimePackVersion",
                "RuntimePackPath"
            };

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

            getValuesCommand.DependsOnTargets = "ResolveFrameworkReferences";
            getValuesCommand.MetadataNames.AddRange(expectedMetadata);

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

            var resolvedFrameworkReferences = getValuesCommand.GetValuesWithMetadata();

            resolvedFrameworkReferences.Select(rfr => rfr.value)
            .Should()
            .BeEquivalentTo(
                "Microsoft.NETCore.App",
                "Microsoft.AspNetCore.App",
                "Microsoft.WindowsDesktop.App");

            foreach (var resolvedFrameworkReference in resolvedFrameworkReferences)
            {
                foreach (var expectedMetadataName in expectedMetadata)
                {
                    if (expectedMetadataName == "IsImplicitlyDefined" &&
                        resolvedFrameworkReference.value != "Microsoft.NETCore.App")
                    {
                        continue;
                    }

                    resolvedFrameworkReference.metadata[expectedMetadataName]
                    .Should()
                    .NotBeNullOrEmpty(because:
                                      $"ResolvedFrameworkReference for {resolvedFrameworkReference.value} should have " +
                                      $"{expectedMetadataName} metadata");
                }
            }
        }