public void The_default_configuration_can_be_set_to_release()
        {
            TestProject project = new TestProject()
            {
                Name             = "DirectoryBuildPropsTest",
                TargetFrameworks = "netstandard1.4",
                IsSdkProject     = true
            };

            var testAsset = _testAssetsManager.CreateTestProject(project);

            string directoryBuildPropsPath = Path.Combine(testAsset.Path, "Directory.Build.props");

            var directoryBuildPropsContent = @"
<Project>
  <PropertyGroup>
    <Configuration Condition="" '$(Configuration)' == '' "">Release</Configuration>
  </PropertyGroup>
</Project>
";

            File.WriteAllText(directoryBuildPropsPath, directoryBuildPropsContent);

            var restoreCommand = testAsset.GetRestoreCommand(Log, project.Name);

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

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

            var buildCommand = new BuildCommand(Log, projectFolder);

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

            string GetPropertyValue(string propertyName)
            {
                var getValuesCommand = new GetValuesCommand(Log, projectFolder,
                                                            project.TargetFrameworks, propertyName, GetValuesCommand.ValueType.Property)
                {
                    Configuration = "Release"
                };

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

                var values = getValuesCommand.GetValues();

                values.Count.Should().Be(1);
                return(values[0]);
            }

            GetPropertyValue("Configuration").Should().Be("Release");
            GetPropertyValue("Optimize").Should().Be("true");
        }
Example #2
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 filesCopiedToPublishDirCommand = new GetValuesCommand(
                Log,
                Path.Combine(asset.Path, testProject.Name),
                testProject.TargetFrameworks,
                "FilesCopiedToPublishDir",
                GetValuesCommand.ValueType.Item)
            {
                DependsOnTargets = "ComputeFilesCopiedToPublishDir",
                MetadataNames    = { "RelativePath" },
            };

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

            filesCopiedToPublishDircommandItems
            .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");
            filesCopiedToPublishDircommandItems
            .Should()
            .Contain(i => i.RelativePath == "WinRT.Runtime.dll" && Path.GetFileName(i.Identity) == "WinRT.Runtime.dll",
                     because: "wapproj should copy cswinrt dlls");

            var publishItemsOutputGroupOutputsCommand = new GetValuesCommand(
                Log,
                Path.Combine(asset.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
            {
                FullAssetPath = Path.GetFullPath(Path.Combine(asset.Path, testProject.Name, item.metadata["OutputPath"]))
            };

            publishItemsOutputGroupOutputsItems
            .Should().Contain(i => Path.GetFileName(Path.GetFullPath(i.FullAssetPath)) == "WinRT.Runtime.dll" && File.Exists(i.FullAssetPath),
                              because: (string)"as the replacement for FilesCopiedToPublishDir, wapproj should copy cswinrt dlls");
            publishItemsOutputGroupOutputsItems
            .Should()
            .Contain(i => Path.GetFileName(Path.GetFullPath(i.FullAssetPath)) == "WinRT.Runtime.dll" && File.Exists(i.FullAssetPath),
                     because: "as the replacement for FilesCopiedToPublishDir, 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();
        }
        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")));
                }
            })
                            .Restore(Log, project.Name);

            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(Log);
                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);
        }
        public void It_provides_runtime_configuration_and_shadow_copy_files_via_outputgroup(string targetFramework)
        {
            if (targetFramework == "net5.0-windows" && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // net5.0-windows is windows only scenario
                return;
            }

            var projectRef = new TestProject
            {
                Name             = "ReferencedProject",
                TargetFrameworks = targetFramework,
            };

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

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

            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":
            case "net5.0-windows":
                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();
                // runtimeconfiguration should not have platform.
                // it should be net5.0 instead of net5.0-windows
                options["tfm"].Value <string>().Should().Be(targetFramework.Split('-')[0]);
                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;
            }
        }
        public void It_publishes_the_project_with_a_refs_folder_and_correct_deps_file(string appTargetFramework, string libraryTargetFramework, bool withoutCopyingRefs)
        {
            if (appTargetFramework == "net46" && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return;
            }

            var testLibraryProject = new TestProject()
            {
                Name             = "TestLibrary",
                IsSdkProject     = true,
                TargetFrameworks = libraryTargetFramework
            };

            var testProject = new TestProject()
            {
                Name              = "TestApp",
                IsSdkProject      = true,
                IsExe             = true,
                TargetFrameworks  = appTargetFramework,
                RuntimeIdentifier = "win7-x86"
            };

            testProject.AdditionalProperties["PreserveCompilationContext"] = "true";

            if (withoutCopyingRefs)
            {
                testProject.AdditionalProperties["PreserveCompilationReferences"] = "false";
            }

            testProject.ReferencedProjects.Add(testLibraryProject);
            testProject.PackageReferences.Add(new TestPackageReference("Newtonsoft.Json", "9.0.1"));
            testProject.PackageReferences.Add(new TestPackageReference("System.Data.SqlClient", "4.4.3"));

            var testAsset = _testAssetsManager.CreateTestProject(testProject, identifier: appTargetFramework + withoutCopyingRefs);

            var appProjectDirectory = Path.Combine(testAsset.TestRoot, "TestApp");

            var getValuesCommand = new GetValuesCommand(Log, appProjectDirectory, testProject.TargetFrameworks, "LangVersion");

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

            var langVersion = getValuesCommand.GetValues().FirstOrDefault() ?? string.Empty;

            var publishCommand = new PublishCommand(Log, appProjectDirectory);

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

            var publishDirectory = publishCommand.GetOutputDirectory(appTargetFramework, runtimeIdentifier: "win7-x86");

            publishDirectory.Should().HaveFiles(new[] {
                appTargetFramework == "net46" ? "TestApp.exe" : "TestApp.dll",
                "TestLibrary.dll",
                "Newtonsoft.Json.dll"
            });

            var refsDirectory = new DirectoryInfo(Path.Combine(publishDirectory.FullName, "refs"));

            if (withoutCopyingRefs)
            {
                refsDirectory.Should().NotExist();
            }
            else
            {
                // Should have compilation time assemblies
                refsDirectory.Should().HaveFile("System.IO.dll");
                // Libraries in which lib==ref should be deduped
                refsDirectory.Should().NotHaveFile("TestLibrary.dll");
                refsDirectory.Should().NotHaveFile("Newtonsoft.Json.dll");
            }

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

                string[] expectedDefines;
                if (appTargetFramework == "net46")
                {
                    expectedDefines = new[] { "DEBUG", "TRACE", "NETFRAMEWORK", "NET46" };
                }
                else
                {
                    expectedDefines = new[] { "DEBUG", "TRACE", "NETCOREAPP", appTargetFramework.ToUpperInvariant().Replace('.', '_') };
                }

                dependencyContext.CompilationOptions.Defines.Should().BeEquivalentTo(expectedDefines);
                dependencyContext.CompilationOptions.LanguageVersion.Should().Be(langVersion);
                dependencyContext.CompilationOptions.Platform.Should().Be("x86");
                dependencyContext.CompilationOptions.Optimize.Should().Be(false);
                dependencyContext.CompilationOptions.KeyFile.Should().Be("");
                dependencyContext.CompilationOptions.EmitEntryPoint.Should().Be(true);
                dependencyContext.CompilationOptions.DebugType.Should().Be("portable");

                var compileLibraryAssemblyNames = dependencyContext.CompileLibraries.SelectMany(cl => cl.Assemblies)
                                                  .Select(a => a.Split('/').Last())
                                                  .Distinct().ToList();
                var expectedCompileLibraryNames = CompileLibraryNames[appTargetFramework].Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

                var extraCompileLibraryNames   = compileLibraryAssemblyNames.Except(expectedCompileLibraryNames).ToList();
                var missingCompileLibraryNames = expectedCompileLibraryNames.Except(compileLibraryAssemblyNames).ToList();

                if (extraCompileLibraryNames.Any())
                {
                    Log.WriteLine("Unexpected compile libraries: " + string.Join(' ', extraCompileLibraryNames));
                }
                if (missingCompileLibraryNames.Any())
                {
                    Log.WriteLine("Missing compile libraries: " + string.Join(' ', missingCompileLibraryNames));
                }

                compileLibraryAssemblyNames.Should().BeEquivalentTo(expectedCompileLibraryNames);

                // Ensure P2P references are specified correctly
                var testLibrary = dependencyContext
                                  .CompileLibraries
                                  .FirstOrDefault(l => string.Equals(l.Name, "testlibrary", StringComparison.OrdinalIgnoreCase));

                testLibrary.Assemblies.Count.Should().Be(1);
                testLibrary.Assemblies[0].Should().Be("TestLibrary.dll");

                // Ensure framework references are specified correctly
                if (appTargetFramework == "net46")
                {
                    var mscorlibLibrary = dependencyContext
                                          .CompileLibraries
                                          .FirstOrDefault(l => string.Equals(l.Name, "mscorlib", StringComparison.OrdinalIgnoreCase));
                    mscorlibLibrary.Assemblies.Count.Should().Be(1);
                    mscorlibLibrary.Assemblies[0].Should().Be(".NETFramework/v4.6/mscorlib.dll");

                    var systemCoreLibrary = dependencyContext
                                            .CompileLibraries
                                            .FirstOrDefault(l => string.Equals(l.Name, "system.core", StringComparison.OrdinalIgnoreCase));
                    systemCoreLibrary.Assemblies.Count.Should().Be(1);
                    systemCoreLibrary.Assemblies[0].Should().Be(".NETFramework/v4.6/System.Core.dll");

                    var systemCollectionsLibrary = dependencyContext
                                                   .CompileLibraries
                                                   .FirstOrDefault(l => string.Equals(l.Name, "system.collections.reference", StringComparison.OrdinalIgnoreCase));
                    systemCollectionsLibrary.Assemblies.Count.Should().Be(1);
                    systemCollectionsLibrary.Assemblies[0].Should().Be(".NETFramework/v4.6/Facades/System.Collections.dll");
                }
            }
        }
        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(Log, relativePath: "TestLibrary");

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

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

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

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

            var definedConstants = getValuesCommand.GetValues();

            definedConstants.Should().BeEquivalentTo(new[] { "DEBUG", "TRACE" }.Concat(expectedDefines).ToArray());
        }
Example #7
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)
                            .Restore(Log, testProject.Name);

            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");
                }
            }
        }
        public void TestPreviewFeatures(bool enablePreviewFeatures, bool generateRequiresPreviewFeaturesAttribute, string targetFramework)
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset("HelloWorld", identifier: $"{enablePreviewFeatures}${generateRequiresPreviewFeaturesAttribute}${targetFramework}")
                            .WithSource()
                            .WithTargetFramework(targetFramework)
                            .WithProjectChanges((path, project) =>
            {
                var ns = project.Root.Name.Namespace;

                project.Root.Add(
                    new XElement(ns + "PropertyGroup",
                                 new XElement(ns + "EnablePreviewFeatures", $"{enablePreviewFeatures}")));

                if (enablePreviewFeatures && !generateRequiresPreviewFeaturesAttribute)
                {
                    project.Root.Add(
                        new XElement(ns + "PropertyGroup",
                                     new XElement(ns + "GenerateRequiresPreviewFeaturesAttribute", $"False")));
                }
            });

            var buildCommand = new BuildCommand(testAsset);

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

            var assemblyPath = Path.Combine(buildCommand.GetOutputDirectory(targetFramework).FullName, "HelloWorld.dll");

            var  parameterlessAttributes = AssemblyInfo.GetParameterlessAttributes(assemblyPath);
            bool contains = false;

            foreach (var attribute in parameterlessAttributes)
            {
                if (attribute.Equals("RequiresPreviewFeaturesAttribute", System.StringComparison.Ordinal))
                {
                    contains = true;
                    break;
                }
            }

            var getValuesCommand = new GetValuesCommand(testAsset, "LangVersion", targetFramework: targetFramework);

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

            var values      = getValuesCommand.GetValues();
            var langVersion = values.FirstOrDefault() ?? string.Empty;

            if (enablePreviewFeatures && generateRequiresPreviewFeaturesAttribute)
            {
                if (targetFramework == ToolsetInfo.CurrentTargetFramework)
                {
                    Assert.Equal("Preview", langVersion);
                    Assert.True(contains);
                }
                else
                {
                    // The assembly level attribute is generated only for the latest TFM for the given sdk
                    Assert.False(contains);
                    Assert.NotEqual("Preview", langVersion);
                }
            }

            if (!generateRequiresPreviewFeaturesAttribute)
            {
                Assert.False(contains);
            }
        }
Example #9
0
        public void It_resolves_runtimepack_from_packs_folder()
        {
            var testProject = new TestProject()
            {
                IsExe             = true,
                TargetFrameworks  = "net6.0",
                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");
            }
        }
Example #10
0
        public void It_resolves_analyzers_correctly(string language, string testAssetName)
        {
            var asset = _testAssetsManager
                        .CopyTestAsset(testAssetName, identifier: language)
                        .WithSource()
                        .WithProjectChanges(project =>
            {
                var ns = project.Root.Name.Namespace;
                project.Root.Add(
                    new XElement(ns + "ItemGroup",
                                 new XElement(ns + "PackageReference",
                                              new XAttribute("Include", "Microsoft.DependencyValidation.Analyzers"),
                                              new XAttribute("Version", "0.9.0")),
                                 new XElement(ns + "PackageReference",
                                              new XAttribute("Include", "Microsoft.CodeQuality.Analyzers"),
                                              new XAttribute("Version", "2.6.0"))));
            });

            var command = new GetValuesCommand(
                Log,
                Path.Combine(asset.Path, "TestApp"),
                "netcoreapp1.1",
                "Analyzer",
                GetValuesCommand.ValueType.Item);

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

            var analyzers = command.GetValues();

            List <string> nugetRoots = new List <string>()
            {
                TestContext.Current.NuGetCachePath,
                Path.Combine(FileConstants.UserProfileFolder, ".dotnet", "NuGetFallbackFolder")
            };

            string RelativeNuGetPath(string absoluteNuGetPath)
            {
                foreach (var nugetRoot in nugetRoots)
                {
                    if (absoluteNuGetPath.StartsWith(nugetRoot + Path.DirectorySeparatorChar))
                    {
                        return(absoluteNuGetPath.Substring(nugetRoot.Length + 1)
                               .Replace(Path.DirectorySeparatorChar, '/'));
                    }
                }
                throw new InvalidDataException("Expected path to be under a NuGet root: " + absoluteNuGetPath);
            }

            switch (language)
            {
            case "C#":
                analyzers.Select(RelativeNuGetPath).Should().BeEquivalentTo(
                    "microsoft.codeanalysis.analyzers/1.1.0/analyzers/dotnet/cs/Microsoft.CodeAnalysis.Analyzers.dll",
                    "microsoft.codeanalysis.analyzers/1.1.0/analyzers/dotnet/cs/Microsoft.CodeAnalysis.CSharp.Analyzers.dll",
                    "microsoft.codequality.analyzers/2.6.0/analyzers/dotnet/cs/Microsoft.CodeQuality.Analyzers.dll",
                    "microsoft.codequality.analyzers/2.6.0/analyzers/dotnet/cs/Microsoft.CodeQuality.CSharp.Analyzers.dll",
                    "microsoft.dependencyvalidation.analyzers/0.9.0/analyzers/dotnet/Microsoft.DependencyValidation.Analyzers.dll"
                    );
                break;

            case "VB":
                analyzers.Select(RelativeNuGetPath).Should().BeEquivalentTo(
                    "microsoft.codeanalysis.analyzers/1.1.0/analyzers/dotnet/vb/Microsoft.CodeAnalysis.Analyzers.dll",
                    "microsoft.codeanalysis.analyzers/1.1.0/analyzers/dotnet/vb/Microsoft.CodeAnalysis.VisualBasic.Analyzers.dll",
                    "microsoft.codequality.analyzers/2.6.0/analyzers/dotnet/vb/Microsoft.CodeQuality.Analyzers.dll",
                    "microsoft.codequality.analyzers/2.6.0/analyzers/dotnet/vb/Microsoft.CodeQuality.VisualBasic.Analyzers.dll",
                    "microsoft.dependencyvalidation.analyzers/0.9.0/analyzers/dotnet/Microsoft.DependencyValidation.Analyzers.dll"
                    );
                break;

            case "F#":
                analyzers.Should().BeEmpty();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(language));
            }
        }