public void It_stores_when_targeting_netcoreapp3(bool isExe) { const string TFM = "netcoreapp3.0"; var testProject = new TestProject() { Name = "Test", IsSdkProject = true, TargetFrameworks = TFM, IsExe = isExe, }; testProject.PackageReferences.Add(new TestPackageReference("Newtonsoft.Json", "12.0.1")); var testProjectInstance = _testAssetsManager.CreateTestProject(testProject, identifier: isExe.ToString()); var outputFolder = Path.Combine(testProjectInstance.TestRoot, "o"); var workingDir = Path.Combine(testProjectInstance.TestRoot, "w"); new ComposeStoreCommand(Log, testProjectInstance.TestRoot, testProject.Name) .Execute( $"/p:RuntimeIdentifier={EnvironmentInfo.GetCompatibleRid(TFM)}", $"/p:ComposeDir={outputFolder}", $"/p:ComposeWorkingDir={workingDir}", "/p:DoNotDecorateComposeDir=true", "/p:CreateProfilingSymbols=false") .Should() .Pass() .And .NotHaveStdOutContaining("NU1604"); new DirectoryInfo(outputFolder).Should().OnlyHaveFiles(new List <string> { "artifact.xml", "newtonsoft.json/12.0.1/lib/netstandard2.0/Newtonsoft.Json.dll", }); }
private void Versions_are_included(bool build, [CallerMemberName] string callingMethod = "") { var testProject = GetTestProject(); if (!EnvironmentInfo.SupportsTargetFramework(testProject.TargetFrameworks)) { return; } testProject.RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(testProject.TargetFrameworks); var testAsset = _testAssetsManager.CreateTestProject(testProject, callingMethod); MSBuildCommand command; if (build) { command = new BuildCommand(testAsset); } else { command = new PublishCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name)); } command.Execute() .Should() .Pass(); var outputDirectory = command.GetOutputDirectory(testProject.TargetFrameworks, runtimeIdentifier: testProject.RuntimeIdentifier); outputDirectory.Should().HaveFile(testProject.Name + ".deps.json"); var depsFilePath = Path.Combine(outputDirectory.FullName, $"{testProject.Name}.deps.json"); CheckVersionsInDepsFile(depsFilePath); }
public void Publish_self_contained_app_with_dot_in_the_name() { var targetFramework = "netcoreapp2.1"; var rid = EnvironmentInfo.GetCompatibleRid(targetFramework); TestProject testProject = new TestProject() { Name = "Hello.World", TargetFrameworks = targetFramework, RuntimeIdentifier = rid, IsExe = true, }; testProject.AdditionalProperties["CopyLocalLockFileAssemblies"] = "true"; testProject.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { Console.WriteLine(""Hello from a netcoreapp2.1!""); } } "; var testProjectInstance = _testAssetsManager.CreateTestProject(testProject); var publishCommand = new PublishCommand(testProjectInstance); publishCommand.Execute().Should().Pass(); var publishDirectory = publishCommand.GetOutputDirectory( targetFramework: targetFramework, runtimeIdentifier: rid); publishDirectory.Should().HaveFile($"Hello.World{Constants.ExeSuffix}"); }
private TestProject CreateTestProject(string targetFramework, string projectName, bool trimmer = false, bool r2r = false, bool singleFile = false) { var testProject = new TestProject() { Name = projectName, TargetFrameworks = targetFramework, IsExe = true, IsSdkProject = true, RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(targetFramework) }; if (r2r) { testProject.AdditionalProperties["PublishReadyToRun"] = "True"; } if (trimmer) { testProject.AdditionalProperties["PublishTrimmed"] = "True"; } if (singleFile) { testProject.AdditionalProperties["PublishSingleFile"] = "True"; } testProject.SourceFiles[$"{projectName}.cs"] = @" using System; public class Program { public static void Main() { Console.WriteLine(""Hello world""); } }"; return(testProject); }
public void It_succeeds_when_RuntimeIdentifier_and_PlatformTarget_mismatch_but_PT_is_AnyCPU() { var targetFramework = "netcoreapp1.1"; var runtimeIdentifier = EnvironmentInfo.GetCompatibleRid(targetFramework); var testAsset = _testAssetsManager .CopyTestAsset("HelloWorld") .WithSource() .WithProjectChanges(project => { var ns = project.Root.Name.Namespace; var propertyGroup = project.Root.Elements(ns + "PropertyGroup").First(); propertyGroup.Add(new XElement(ns + "RuntimeIdentifier", runtimeIdentifier)); propertyGroup.Add(new XElement(ns + "PlatformTarget", "AnyCPU")); }) .Restore(Log); var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot)); buildCommand .Execute() .Should() .Pass(); var outputDirectory = buildCommand.GetOutputDirectory(targetFramework, runtimeIdentifier: runtimeIdentifier); var selfContainedExecutable = $"HelloWorld{Constants.ExeSuffix}"; string selfContainedExecutableFullPath = Path.Combine(outputDirectory.FullName, selfContainedExecutable); Command.Create(selfContainedExecutableFullPath, new string[] { }) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World!"); }
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.")); }
public void DuplicateRuntimeIdentifiers() { var testProject = new TestProject() { Name = "DuplicateRuntimeIdentifiers", TargetFrameworks = "netcoreapp3.0", IsSdkProject = true, IsExe = true }; var compatibleRid = EnvironmentInfo.GetCompatibleRid(testProject.TargetFrameworks); testProject.AdditionalProperties["RuntimeIdentifiers"] = compatibleRid + ";" + compatibleRid; testProject.RuntimeIdentifier = compatibleRid; var testAsset = _testAssetsManager.CreateTestProject(testProject); var buildCommand = new BuildCommand(testAsset); buildCommand .Execute() .Should() .Pass(); }
public void ItTestsWithTheSpecifiedRuntimeOption() { var testInstance = TestAssets.Get("XunitCore") .CreateInstance() .WithSourceFiles() .WithVersionVariables(); var rootPath = testInstance.Root.FullName; var rid = EnvironmentInfo.GetCompatibleRid(); new BuildCommand() .WithWorkingDirectory(rootPath) .ExecuteWithCapturedOutput($"--runtime {rid}") .Should() .Pass() .And.NotHaveStdErr(); var result = new DotnetTestCommand() .WithWorkingDirectory(rootPath) .ExecuteWithCapturedOutput($"{TestBase.ConsoleLoggerOutputNormal} --no-build --runtime {rid}"); result .Should() .NotHaveStdErrContaining("MSB1001") .And .HaveStdOutContaining(rid); if (!DotnetUnderTest.IsLocalized()) { result.StdOut.Should().Contain("Total tests: 2"); result.StdOut.Should().Contain("Passed: 1"); result.StdOut.Should().Contain("Failed: 1"); } result.ExitCode.Should().Be(1); }
public void ItPublishesFrameworkDependentWithRid(string args) { var testAppName = "MSBuildTestApp"; var rid = EnvironmentInfo.GetCompatibleRid(); var outputDirectory = PublishApp(testAppName, rid, args); outputDirectory.Should().OnlyHaveFiles(new[] { $"{testAppName}{Constants.ExeSuffix}", $"{testAppName}.dll", $"{testAppName}.pdb", $"{testAppName}.deps.json", $"{testAppName}.runtimeconfig.json", }); var outputProgram = Path.Combine(outputDirectory.FullName, $"{testAppName}{Constants.ExeSuffix}"); var command = new RunExeCommand(Log, outputProgram); command.Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World"); }
public void NativeAot_compiler_runs_when_PublishAot_is_enabled(string targetFramework) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { var projectName = "WarningAppWithPublishAot"; var rid = EnvironmentInfo.GetCompatibleRid(targetFramework); // PublishAot should enable the EnableAotAnalyzer, EnableTrimAnalyzer and EnableSingleFileAnalyzer var testProject = CreateTestProjectWithAnalysisWarnings(targetFramework, projectName, true); testProject.AdditionalProperties["PublishAot"] = "true"; testProject.AdditionalProperties["SuppressTrimAnalysisWarnings"] = "false"; testProject.AdditionalProperties["RuntimeIdentifier"] = rid; var testAsset = _testAssetsManager.CreateTestProject(testProject); var publishCommand = new PublishCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name)); publishCommand .Execute() .Should().Pass() .And.HaveStdOutContaining("warning IL3050") .And.HaveStdOutContaining("warning IL3056") .And.HaveStdOutContaining("warning IL2026") .And.HaveStdOutContaining("warning IL3002"); var publishDirectory = publishCommand.GetOutputDirectory(targetFramework: targetFramework, runtimeIdentifier: rid); var publishedExe = Path.Combine(publishDirectory.FullName, $"{testProject.Name}{Constants.ExeSuffix}"); // The exe exist and should be native File.Exists(publishedExe).Should().BeTrue(); IsNativeImage(publishedExe).Should().BeTrue(); var command = new RunExeCommand(Log, publishedExe) .Execute().Should().Pass() .And.HaveStdOutContaining("Hello world"); } }
public void It_can_make_a_Windows_GUI_exe() { var runtimeIdentifier = EnvironmentInfo.GetCompatibleRid("netcoreapp2.0"); var testAsset = _testAssetsManager .CopyTestAsset(TestProjectName) .WithSource() .WithProjectChanges(doc => { doc.Root.Element("PropertyGroup").Element("TargetFramework").SetValue(TargetFramework); }) .Restore(Log, relativePath: "", args: $"/p:RuntimeIdentifier={runtimeIdentifier}"); var publishCommand = new PublishCommand(Log, testAsset.TestRoot); publishCommand .Execute( "/p:SelfContained=true", "/p:OutputType=WinExe", $"/p:TargetFramework={TargetFramework}", $"/p:RuntimeIdentifier={runtimeIdentifier}") .Should() .Pass(); string outputDirectory = publishCommand.GetOutputDirectory( targetFramework: TargetFramework, runtimeIdentifier: runtimeIdentifier).FullName; byte[] fileContent = File.ReadAllBytes(Path.Combine(outputDirectory, TestProjectName + ".exe")); UInt32 peHeaderOffset = BitConverter.ToUInt32(fileContent, PEHeaderPointerOffset); BitConverter .ToUInt16(fileContent, (int)(peHeaderOffset + SubsystemOffset)) .Should() .Be(2); }
public void PublishWebAppWithPublishProfile(bool?selfContained, bool?useAppHost) { var tfm = "netcoreapp2.2"; var rid = EnvironmentInfo.GetCompatibleRid(tfm); var testProject = new TestProject() { Name = "WebWithPublishProfile", TargetFrameworks = tfm, ProjectSdk = "Microsoft.NET.Sdk.Web", IsExe = true, }; testProject.AdditionalProperties.Add("AspNetCoreHostingModel", "InProcess"); testProject.PackageReferences.Add(new TestPackageReference("Microsoft.AspNetCore.App")); testProject.PackageReferences.Add(new TestPackageReference("Microsoft.AspNetCore.Razor.Design", version: "2.2.0", privateAssets: "all")); var identifier = (selfContained == null ? "null" : selfContained.ToString()) + (useAppHost == null ? "null" : useAppHost.ToString()); var testProjectInstance = _testAssetsManager.CreateTestProject(testProject, identifier: identifier); var projectDirectory = Path.Combine(testProjectInstance.Path, testProject.Name); var publishProfilesDirectory = Path.Combine(projectDirectory, "Properties", "PublishProfiles"); Directory.CreateDirectory(publishProfilesDirectory); File.WriteAllText(Path.Combine(publishProfilesDirectory, "test.pubxml"), $@" <Project> <PropertyGroup> <RuntimeIdentifier>{rid}</RuntimeIdentifier> {(selfContained.HasValue ? $"<SelfContained>{selfContained}</SelfContained>" : "")} {((!(selfContained ?? true) && useAppHost.HasValue) ? $"<UseAppHost>{useAppHost}</UseAppHost>" : "")} </PropertyGroup> </Project> "); var command = new PublishCommand(testProjectInstance); command .Execute("/p:PublishProfile=test") .Should() .Pass(); var output = command.GetOutputDirectory(targetFramework: tfm, runtimeIdentifier: rid); output.Should().HaveFiles(new[] { $"{testProject.Name}.dll", $"{testProject.Name}.pdb", $"{testProject.Name}.deps.json", $"{testProject.Name}.runtimeconfig.json", "web.config", }); if (selfContained ?? true) { output.Should().HaveFiles(new[] { $"{FileConstants.DynamicLibPrefix}hostfxr{FileConstants.DynamicLibSuffix}", $"{FileConstants.DynamicLibPrefix}hostpolicy{FileConstants.DynamicLibSuffix}", }); } else { output.Should().NotHaveFiles(new[] { $"{FileConstants.DynamicLibPrefix}hostfxr{FileConstants.DynamicLibSuffix}", $"{FileConstants.DynamicLibPrefix}hostpolicy{FileConstants.DynamicLibSuffix}", }); } if ((selfContained ?? true) || (useAppHost ?? true)) { output.Should().HaveFile($"{testProject.Name}{Constants.ExeSuffix}"); } else { output.Should().NotHaveFile($"{testProject.Name}{Constants.ExeSuffix}"); } }
public void It_publishes_with_a_publish_profile(bool?publishSingleFile) { var tfm = "netcoreapp3.1"; var rid = EnvironmentInfo.GetCompatibleRid(tfm); var testProject = new TestProject() { Name = "ConsoleWithPublishProfile", TargetFrameworks = tfm, ProjectSdk = "Microsoft.NET.Sdk;Microsoft.NET.Sdk.Publish", IsExe = true, }; testProject.PackageReferences.Add(new TestPackageReference("NewtonSoft.Json", "9.0.1")); var testProjectInstance = _testAssetsManager.CreateTestProject(testProject); var projectDirectory = Path.Combine(testProjectInstance.Path, testProject.Name); var publishProfilesDirectory = Path.Combine(projectDirectory, "Properties", "PublishProfiles"); Directory.CreateDirectory(publishProfilesDirectory); File.WriteAllText(Path.Combine(publishProfilesDirectory, "test.pubxml"), $@" <Project> <PropertyGroup> <PublishUrl>publish\</PublishUrl> <Install>true</Install> <InstallFrom>Disk</InstallFrom> <ApplicationRevision>4</ApplicationRevision> <ApplicationVersion>1.2.3.*</ApplicationVersion> <PublishProtocol>ClickOnce</PublishProtocol> <BootstrapperEnabled>True</BootstrapperEnabled> <UpdateEnabled>False</UpdateEnabled> <IsWebBootstrapper>false</IsWebBootstrapper> <CreateWebPageOnPublish>true</CreateWebPageOnPublish> <GenerateManifests>true</GenerateManifests> <PublishWizardCompleted>true</PublishWizardCompleted> <SelfContained>false</SelfContained> {(publishSingleFile.HasValue ? $"<PublishSingleFile>{publishSingleFile}</PublishSingleFile>" : "")} {(publishSingleFile ?? false ? $"<RuntimeIdentifier>{rid}</RuntimeIdentifier>" : "")} </PropertyGroup> </Project> "); var command = new PublishCommand(testProjectInstance); command .Execute("/p:PublishProfile=test") .Should() .Pass(); DirectoryInfo output = null; if (publishSingleFile ?? false) { output = command.GetOutputDirectory(targetFramework: tfm, runtimeIdentifier: rid); } else { output = command.GetOutputDirectory(targetFramework: tfm); } output = output.Parent; output.Should().HaveFiles(new[] { $"app.Publish\\setup.exe", $"app.Publish\\{testProject.Name}.application", $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\launcher{Constants.ExeSuffix}", }); if (publishSingleFile ?? false) { output.Should().HaveFiles(new[] { $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\{testProject.Name}{Constants.ExeSuffix}", $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\{testProject.Name}.dll.manifest", }); output.Should().NotHaveFiles(new[] { $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\{testProject.Name}.dll", $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\Newtonsoft.Json.dll", $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\{testProject.Name}.deps.json", }); } else { output.Should().HaveFiles(new[] { $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\{testProject.Name}.dll", $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\{testProject.Name}.dll.manifest", $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\Newtonsoft.Json.dll", $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\{testProject.Name}.deps.json", $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\{testProject.Name}.runtimeconfig.json", $"app.Publish\\application files\\{testProject.Name}_1_2_3_4\\{testProject.Name}{Constants.ExeSuffix}", }); } }
public void It_builds_a_runnable_output(string targetFramework, bool dependenciesIncluded) { if (!EnvironmentInfo.SupportsTargetFramework(targetFramework)) { return; } var runtimeIdentifier = EnvironmentInfo.GetCompatibleRid(targetFramework); var testAsset = _testAssetsManager .CopyTestAsset("HelloWorld", identifier: targetFramework) .WithSource() .WithTargetFramework(targetFramework) .WithProjectChanges(project => { var ns = project.Root.Name.Namespace; var propertyGroup = project.Root.Elements(ns + "PropertyGroup").First(); propertyGroup.Add(new XElement(ns + "RuntimeIdentifier", runtimeIdentifier)); }) .Restore(Log); var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot)); buildCommand .Execute() .Should() .Pass(); var outputDirectory = buildCommand.GetOutputDirectory(targetFramework, runtimeIdentifier: runtimeIdentifier); var selfContainedExecutable = $"HelloWorld{Constants.ExeSuffix}"; string selfContainedExecutableFullPath = Path.Combine(outputDirectory.FullName, selfContainedExecutable); string[] expectedFiles = new[] { selfContainedExecutable, "HelloWorld.dll", "HelloWorld.pdb", "HelloWorld.deps.json", "HelloWorld.runtimeconfig.dev.json", "HelloWorld.runtimeconfig.json", $"{FileConstants.DynamicLibPrefix}hostfxr{FileConstants.DynamicLibSuffix}", $"{FileConstants.DynamicLibPrefix}hostpolicy{FileConstants.DynamicLibSuffix}", }; if (dependenciesIncluded) { outputDirectory.Should().HaveFiles(expectedFiles); } else { outputDirectory.Should().OnlyHaveFiles(expectedFiles); } outputDirectory.Should().NotHaveFiles(new[] { $"apphost{Constants.ExeSuffix}", }); new RunExeCommand(Log, selfContainedExecutableFullPath) .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World!"); }
public void ReferencedExeFailsToBuildWhenReferencesExeWithSelfContainedMismatchForSameTargetFramework() { MainSelfContained = true; ReferencedSelfContained = false; CreateProjects(); // Reference project which is self-contained for net5.0-windows, not self-contained for net5.0. ReferencedProject.TargetFrameworks = "net5.0;net5.0-windows"; ReferencedProject.ProjectChanges.Add(project => { var ns = project.Root.Name.Namespace; project.Root.Element(ns + "PropertyGroup") .Add(XElement.Parse(@"<RuntimeIdentifier Condition=""'$(TargetFramework)' == 'net5.0-windows'"">" + EnvironmentInfo.GetCompatibleRid() + "</RuntimeIdentifier>")); }); RunTest("NETSDK1150"); }
private void RunAppFromOutputFolder(string testName, bool useRid, bool includeConflicts, string targetFramework = "netcoreapp2.0") { var runtimeIdentifier = useRid ? EnvironmentInfo.GetCompatibleRid(targetFramework) : null; TestProject project = new TestProject() { Name = testName, IsSdkProject = true, TargetFrameworks = targetFramework, RuntimeIdentifier = runtimeIdentifier, IsExe = true, }; string outputMessage = $"Hello from {project.Name}!"; project.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { TestConflictResolution(); Console.WriteLine(""" + outputMessage + @"""); } " + ConflictResolutionAssets.ConflictResolutionTestMethod + @" } "; var testAsset = _testAssetsManager.CreateTestProject(project, project.Name) .WithProjectChanges(p => { if (includeConflicts) { var ns = p.Root.Name.Namespace; var itemGroup = new XElement(ns + "ItemGroup"); p.Root.Add(itemGroup); foreach (var dependency in ConflictResolutionAssets.ConflictResolutionDependencies) { itemGroup.Add(new XElement(ns + "PackageReference", new XAttribute("Include", dependency.Item1), new XAttribute("Version", dependency.Item2))); } } }) .Restore(Log, project.Name); string projectFolder = Path.Combine(testAsset.Path, project.Name); var buildCommand = new BuildCommand(Log, projectFolder); buildCommand .Execute() .Should() .Pass(); string outputFolder = buildCommand.GetOutputDirectory(project.TargetFrameworks, runtimeIdentifier: runtimeIdentifier ?? "").FullName; Command.Create(TestContext.Current.ToolsetUnderTest.DotNetHostPath, new[] { Path.Combine(outputFolder, project.Name + ".dll") }) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining(outputMessage); }
private void It_targets_the_right_framework( string testIdentifier, string targetFramework, string runtimeFrameworkVersion, bool selfContained, bool isExe, string expectedPackageVersion, string expectedRuntimeVersion, string extraMSBuildArguments = null) { string runtimeIdentifier = null; if (selfContained) { runtimeIdentifier = EnvironmentInfo.GetCompatibleRid(targetFramework); } var testProject = new TestProject() { Name = "FrameworkTargetTest", TargetFrameworks = targetFramework, RuntimeFrameworkVersion = runtimeFrameworkVersion, IsSdkProject = true, IsExe = isExe, RuntimeIdentifier = runtimeIdentifier }; var extraArgs = extraMSBuildArguments?.Split(' ') ?? Array.Empty <string>(); var testAsset = _testAssetsManager.CreateTestProject(testProject, testIdentifier) .Restore(Log, testProject.Name, extraArgs); NuGetConfigWriter.Write(testAsset.TestRoot, NuGetConfigWriter.DotnetCoreBlobFeed); var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name)); buildCommand .Execute(extraArgs) .Should() .Pass(); var outputDirectory = buildCommand.GetOutputDirectory(targetFramework, runtimeIdentifier: runtimeIdentifier); if (isExe) { // Self-contained apps don't write a framework version to the runtimeconfig, so only check this for framework-dependent apps if (!selfContained) { string runtimeConfigFile = Path.Combine(outputDirectory.FullName, testProject.Name + ".runtimeconfig.json"); string runtimeConfigContents = File.ReadAllText(runtimeConfigFile); JObject runtimeConfig = JObject.Parse(runtimeConfigContents); string actualRuntimeFrameworkVersion = ((JValue)runtimeConfig["runtimeOptions"]["framework"]["version"]).Value <string>(); actualRuntimeFrameworkVersion.Should().Be(expectedRuntimeVersion); } var runtimeconfigDevFileName = testProject.Name + ".runtimeconfig.dev.json"; outputDirectory.Should() .HaveFile(runtimeconfigDevFileName); string devruntimeConfigContents = File.ReadAllText(Path.Combine(outputDirectory.FullName, runtimeconfigDevFileName)); JObject devruntimeConfig = JObject.Parse(devruntimeConfigContents); var additionalProbingPaths = ((JArray)devruntimeConfig["runtimeOptions"]["additionalProbingPaths"]).Values <string>(); // can't use Path.Combine on segments with an illegal `|` character var expectedPath = $"{Path.Combine(FileConstants.UserProfileFolder, ".dotnet", "store")}{Path.DirectorySeparatorChar}|arch|{Path.DirectorySeparatorChar}|tfm|"; additionalProbingPaths.Should().Contain(expectedPath); } LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(buildCommand.ProjectRootPath, "obj", "project.assets.json"), NullLogger.Instance); var target = lockFile.GetTarget(NuGetFramework.Parse(targetFramework), null); var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App"); netCoreAppLibrary.Version.ToString().Should().Be(expectedPackageVersion); }
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"); } } }
public void Publish_standalone_post_netcoreapp2_app_and_it_should_run() { var targetFramework = "netcoreapp2.0"; var rid = EnvironmentInfo.GetCompatibleRid(targetFramework); TestProject testProject = new TestProject() { Name = "Hello", IsSdkProject = true, TargetFrameworks = targetFramework, RuntimeIdentifier = rid, IsExe = true, }; testProject.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { Console.WriteLine(""Hello from a netcoreapp2.0.!""); } } "; var testProjectInstance = _testAssetsManager.CreateTestProject(testProject); testProjectInstance.Restore(Log, testProject.Name); var publishCommand = new PublishCommand(Log, Path.Combine(testProjectInstance.TestRoot, testProject.Name)); var publishResult = publishCommand.Execute(); publishResult.Should().Pass(); var publishDirectory = publishCommand.GetOutputDirectory( targetFramework: targetFramework, runtimeIdentifier: rid); var selfContainedExecutable = $"Hello{Constants.ExeSuffix}"; string selfContainedExecutableFullPath = Path.Combine(publishDirectory.FullName, selfContainedExecutable); publishDirectory.Should().HaveFiles(new[] { selfContainedExecutable, "Hello.dll", "Hello.pdb", "Hello.deps.json", "Hello.runtimeconfig.json", $"{FileConstants.DynamicLibPrefix}coreclr{FileConstants.DynamicLibSuffix}", $"{FileConstants.DynamicLibPrefix}hostfxr{FileConstants.DynamicLibSuffix}", $"{FileConstants.DynamicLibPrefix}hostpolicy{FileConstants.DynamicLibSuffix}", $"mscorlib.dll", $"System.Private.CoreLib.dll", }); Command.Create(selfContainedExecutableFullPath, new string[] { }) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello from a netcoreapp2.0.!"); }
public void ItRunsAppsDirectlyReferencingAssemblies( string referencerTarget, string dependencyTarget) { string identifier = referencerTarget.ToString() + "_" + dependencyTarget.ToString(); TestProject dependencyProject = new TestProject() { Name = "Dependency", IsSdkProject = true, TargetFrameworks = dependencyTarget, }; // Skip running test if not running on Windows if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !dependencyProject.BuildsOnNonWindows) { return; } dependencyProject.SourceFiles["Class1.cs"] = @" public class Class1 { public static string GetMessage() { return ""Hello from a direct reference.""; } } "; var dependencyAsset = _testAssetsManager.CreateTestProject(dependencyProject, identifier: identifier); string dependencyAssemblyPath = RestoreAndBuild(dependencyAsset, dependencyProject); TestProject referencerProject = new TestProject() { Name = "Referencer", IsSdkProject = true, TargetFrameworks = referencerTarget, RuntimeFrameworkVersion = RepoInfo.NetCoreApp20Version, // Need to use a self-contained app for now because we don't use a CLI that has a "2.0" shared framework RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(referencerTarget), IsExe = true, }; referencerProject.References.Add(dependencyAssemblyPath); referencerProject.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { Console.WriteLine(Class1.GetMessage()); } } "; var referencerAsset = _testAssetsManager.CreateTestProject(referencerProject, identifier: identifier); string applicationPath = RestoreAndBuild(referencerAsset, referencerProject); Command.Create(RepoInfo.DotNetHostPath, new[] { applicationPath }) .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from a direct reference."); }
public void It_publishes_with_a_publish_profile(bool?selfContained, bool?useAppHost) { var tfm = "netcoreapp2.2"; var rid = EnvironmentInfo.GetCompatibleRid(tfm); var testProject = new TestProject() { Name = "ConsoleWithPublishProfile", TargetFrameworks = tfm, IsSdkProject = true, ProjectSdk = "Microsoft.NET.Sdk;Microsoft.NET.Sdk.Publish", IsExe = true, }; var testProjectInstance = _testAssetsManager.CreateTestProject(testProject); var projectDirectory = Path.Combine(testProjectInstance.Path, testProject.Name); var publishProfilesDirectory = Path.Combine(projectDirectory, "Properties", "PublishProfiles"); Directory.CreateDirectory(publishProfilesDirectory); File.WriteAllText(Path.Combine(publishProfilesDirectory, "test.pubxml"), $@" <Project> <PropertyGroup> <RuntimeIdentifier>{rid}</RuntimeIdentifier> {(selfContained.HasValue ? $"<SelfContained>{selfContained}</SelfContained>" : "")} {((!(selfContained ?? true) && useAppHost.HasValue) ? $"<UseAppHost>{useAppHost}</UseAppHost>" : "")} </PropertyGroup> </Project> "); var command = new PublishCommand(Log, projectDirectory); command .Execute("/restore", "/p:PublishProfile=test") .Should() .Pass(); var output = command.GetOutputDirectory(targetFramework: tfm, runtimeIdentifier: rid); output.Should().HaveFiles(new[] { $"{testProject.Name}.dll", $"{testProject.Name}.pdb", $"{testProject.Name}.deps.json", $"{testProject.Name}.runtimeconfig.json", }); if (selfContained ?? true) { output.Should().HaveFiles(new[] { $"{FileConstants.DynamicLibPrefix}hostfxr{FileConstants.DynamicLibSuffix}", $"{FileConstants.DynamicLibPrefix}hostpolicy{FileConstants.DynamicLibSuffix}", }); } else { output.Should().NotHaveFiles(new[] { $"{FileConstants.DynamicLibPrefix}hostfxr{FileConstants.DynamicLibSuffix}", $"{FileConstants.DynamicLibPrefix}hostpolicy{FileConstants.DynamicLibSuffix}", }); } if ((selfContained ?? true) || (useAppHost ?? true)) { output.Should().HaveFile($"{testProject.Name}{Constants.ExeSuffix}"); } else { output.Should().NotHaveFile($"{testProject.Name}{Constants.ExeSuffix}"); } }
// "No build" scenario doesn't currently work: https://github.com/dotnet/sdk/issues/2956 //[InlineData(true)] public void PublishWithRuntimeIdentifier(bool publishNoBuild) { var testProject = new TestProject() { Name = "PublishWithRid", TargetFrameworks = "netcoreapp3.0", IsExe = true }; var compatibleRid = EnvironmentInfo.GetCompatibleRid(testProject.TargetFrameworks); var runtimeIdentifiers = new[] { "win-x64", "linux-x64", compatibleRid }; testProject.AdditionalProperties["RuntimeIdentifiers"] = string.Join(';', runtimeIdentifiers); // Use a test-specific packages folder testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\..\pkg"; var testAsset = _testAssetsManager.CreateTestProject(testProject, identifier: publishNoBuild ? "nobuild" : string.Empty); var buildCommand = new BuildCommand(testAsset); buildCommand .Execute() .Should() .Pass(); foreach (var runtimeIdentifier in runtimeIdentifiers) { var publishArgs = new List <string>() { $"/p:RuntimeIdentifier={runtimeIdentifier}" }; if (publishNoBuild) { publishArgs.Add("/p:NoBuild=true"); } var publishCommand = new PublishCommand(Log, Path.Combine(testAsset.Path, testProject.Name)); publishCommand.Execute(publishArgs.ToArray()) .Should() .Pass(); if (runtimeIdentifier == compatibleRid) { var outputDirectory = publishCommand.GetOutputDirectory(testProject.TargetFrameworks, runtimeIdentifier: runtimeIdentifier); var selfContainedExecutable = $"{testProject.Name}{Constants.ExeSuffix}"; string selfContainedExecutableFullPath = Path.Combine(outputDirectory.FullName, selfContainedExecutable); new RunExeCommand(Log, selfContainedExecutableFullPath) .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World!"); } } }
public void ItRunsAppsDirectlyReferencingAssembliesWithSatellites( string referencerTarget, string dependencyTarget) { string identifier = referencerTarget.ToString() + "_" + dependencyTarget.ToString(); TestProject dependencyProject = new TestProject() { Name = "Dependency", IsSdkProject = true, TargetFrameworks = dependencyTarget, }; // Skip running test if not running on Windows if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !dependencyProject.BuildsOnNonWindows) { return; } dependencyProject.SourceFiles["Class1.cs"] = @" using System; using System.Globalization; using System.Reflection; using System.Resources; using System.Threading; public class Class1 { public static string GetMessage() { CultureInfo.CurrentUICulture = new CultureInfo(""en-US""); var resources = new ResourceManager(""Dependency.Strings"", typeof(Class1).GetTypeInfo().Assembly); return resources.GetString(""HelloWorld""); } } "; dependencyProject.EmbeddedResources["Strings.en.resx"] = @"<?xml version=""1.0"" encoding=""utf-8""?> <root> <xsd:schema id=""root"" xmlns="""" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xsd:element name=""root"" msdata:IsDataSet=""true""> <xsd:complexType> <xsd:choice maxOccurs=""unbounded""> <xsd:element name=""data""> <xsd:complexType> <xsd:sequence> <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" /> <xsd:element name=""comment"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""2"" /> </xsd:sequence> <xsd:attribute name=""name"" type=""xsd:string"" msdata:Ordinal=""1"" /> <xsd:attribute name=""type"" type=""xsd:string"" msdata:Ordinal=""3"" /> <xsd:attribute name=""mimetype"" type=""xsd:string"" msdata:Ordinal=""4"" /> </xsd:complexType> </xsd:element> <xsd:element name=""resheader""> <xsd:complexType> <xsd:sequence> <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" /> </xsd:sequence> <xsd:attribute name=""name"" type=""xsd:string"" use=""required"" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name=""resmimetype""> <value>text/microsoft-resx</value> </resheader> <resheader name=""version""> <value>1.3</value> </resheader> <resheader name=""reader""> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name=""writer""> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name=""HelloWorld"" xml:space=""preserve""> <value>Hello World from en satellite assembly for a direct reference.</value> </data> </root> "; var dependencyAsset = _testAssetsManager.CreateTestProject(dependencyProject, identifier: identifier); string dependencyAssemblyPath = RestoreAndBuild(dependencyAsset, dependencyProject); TestProject referencerProject = new TestProject() { Name = "Referencer", IsSdkProject = true, TargetFrameworks = referencerTarget, // Need to use a self-contained app for now because we don't use a CLI that has a "2.0" shared framework RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(referencerTarget), IsExe = true, }; referencerProject.References.Add(dependencyAssemblyPath); referencerProject.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { Console.WriteLine(Class1.GetMessage()); } } "; var referencerAsset = _testAssetsManager.CreateTestProject(referencerProject, identifier: identifier); string applicationPath = RestoreAndBuild(referencerAsset, referencerProject); Command.Create(TestContext.Current.ToolsetUnderTest.DotNetHostPath, new[] { applicationPath }) .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World from en satellite assembly for a direct reference."); }
private ResolvedVersionInfo GetResolvedVersions(TestProject testProject, Action <XDocument> projectChanges = null, [CallerMemberName] string callingMethod = null, string identifier = null) { testProject.Name = "ResolvedVersionsTest"; testProject.TargetFrameworks = "netcoreapp3.0"; testProject.IsSdkProject = true; testProject.IsExe = true; testProject.AdditionalProperties["DisableImplicitFrameworkReferences"] = "true"; testProject.RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(testProject.TargetFrameworks); var testAsset = _testAssetsManager.CreateTestProject(testProject, callingMethod, identifier) .WithProjectChanges(project => { var ns = project.Root.Name.Namespace; var itemGroup = new XElement(ns + "ItemGroup"); project.Root.Add(itemGroup); var frameworkReference = new XElement(ns + "FrameworkReference", new XAttribute("Include", "Microsoft.NETCore.APP")); itemGroup.Add(frameworkReference); var knownFrameworkReferenceUpdate = new XElement(ns + "KnownFrameworkReference", new XAttribute("Update", "Microsoft.NETCore.App"), new XAttribute("DefaultRuntimeFrameworkVersion", "3.0.0-defaultversion"), new XAttribute("LatestRuntimeFrameworkVersion", "3.0.0-latestversion"), new XAttribute("TargetingPackVersion", "3.0.0-targetingpackversion")); itemGroup.Add(knownFrameworkReferenceUpdate); var knownAppHostPackUpdate = new XElement(ns + "KnownAppHostPack", new XAttribute("Update", "Microsoft.NETCore.App"), new XAttribute("AppHostPackVersion", "3.0.0-apphostversion")); itemGroup.Add(knownAppHostPackUpdate); string writeResolvedVersionsTarget = @" <Target Name=`WriteResolvedVersions` DependsOnTargets=`PrepareForBuild;ResolveFrameworkReferences`> <ItemGroup> <LinesToWrite Include=`RuntimeFramework%09%(RuntimeFramework.Identity)%09%(RuntimeFramework.Version)`/> <LinesToWrite Include=`PackageDownload%09%(PackageDownload.Identity)%09%(PackageDownload.Version)`/> <LinesToWrite Include=`TargetingPack%09%(TargetingPack.Identity)%09%(TargetingPack.PackageVersion)`/> <LinesToWrite Include=`RuntimePack%09%(RuntimePack.Identity)%09%(RuntimePack.PackageVersion)`/> <LinesToWrite Include=`AppHostPack%09%(AppHostPack.Identity)%09%(AppHostPack.PackageVersion)`/> </ItemGroup> <WriteLinesToFile File=`$(OutputPath)resolvedversions.txt` Lines=`@(LinesToWrite)` Overwrite=`true` Encoding=`Unicode`/> </Target>"; writeResolvedVersionsTarget = writeResolvedVersionsTarget.Replace('`', '"'); project.Root.Add(XElement.Parse(writeResolvedVersionsTarget)); }); if (projectChanges != null) { testAsset = testAsset.WithProjectChanges(projectChanges); } var command = new MSBuildCommand(Log, "WriteResolvedVersions", Path.Combine(testAsset.TestRoot, testProject.Name)); command.Execute() .Should() .Pass(); var outputDirectory = command.GetOutputDirectory(testProject.TargetFrameworks, runtimeIdentifier: testProject.RuntimeIdentifier); var resolvedVersions = ResolvedVersionInfo.ParseFrom(Path.Combine(outputDirectory.FullName, "resolvedversions.txt")); return(resolvedVersions); }
void TestPackagesNotDownloaded(bool referenceAspNet, bool selfContained, [CallerMemberName] string testName = null) { string nugetPackagesFolder = _testAssetsManager.CreateTestDirectory(testName, identifier: "packages_" + referenceAspNet).Path; var testProject = new TestProject(testName) { TargetFrameworks = ToolsetInfo.CurrentTargetFramework, IsExe = true, }; if (selfContained) { testProject.RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(); testProject.AdditionalProperties["SelfContained"] = "true"; } else { // Don't use AppHost in order to avoid additional download to packages folder testProject.AdditionalProperties["UseAppHost"] = "False"; } if (referenceAspNet) { testProject.FrameworkReferences.Add("Microsoft.AspNetCore.App"); } testProject.AdditionalProperties["DisableTransitiveFrameworkReferenceDownloads"] = "True"; testProject.AdditionalProperties["RestorePackagesPath"] = nugetPackagesFolder; // Set packs folder to nonexistant folder so the project won't use installed targeting or runtime packs testProject.AdditionalProperties["NetCoreTargetingPackRoot"] = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var testAsset = _testAssetsManager.CreateTestProject(testProject, testName, identifier: referenceAspNet.ToString()); var buildCommand = new BuildCommand(testAsset); buildCommand.Execute() .Should() .Pass(); var expectedPackages = new List <string>() { "microsoft.netcore.app.ref" }; if (selfContained) { expectedPackages.Add("microsoft.netcore.app.runtime.**RID**"); expectedPackages.Add("microsoft.netcore.app.host.**RID**"); } if (referenceAspNet) { expectedPackages.Add("microsoft.aspnetcore.app.ref"); } Directory.EnumerateDirectories(nugetPackagesFolder) .Select(Path.GetFileName) .Select(package => { if (package.Contains(".runtime.") || (package.Contains(".host."))) { // Replace RuntimeIdentifier, which should be the last dotted segment in the package name, with "**RID**" package = package.Substring(0, package.LastIndexOf('.') + 1) + "**RID**"; } return(package); }) .Should().BeEquivalentTo(expectedPackages); }
void Conflicts_are_resolved_when_publishing(bool selfContained, bool ridSpecific, [CallerMemberName] string callingMethod = "") { if (selfContained && !ridSpecific) { throw new ArgumentException("Self-contained apps must be rid specific"); } var targetFramework = "netcoreapp2.0"; var rid = ridSpecific ? EnvironmentInfo.GetCompatibleRid(targetFramework) : null; TestProject testProject = new TestProject() { Name = selfContained ? "SelfContainedWithConflicts" : (ridSpecific ? "RidSpecificSharedConflicts" : "PortableWithConflicts"), IsSdkProject = true, TargetFrameworks = targetFramework, RuntimeIdentifier = rid, IsExe = true, }; string outputMessage = $"Hello from {testProject.Name}!"; testProject.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { TestConflictResolution(); Console.WriteLine(""" + outputMessage + @"""); } " + ConflictResolutionAssets.ConflictResolutionTestMethod + @" } "; var testProjectInstance = _testAssetsManager.CreateTestProject(testProject, testProject.Name) .WithProjectChanges(p => { var ns = p.Root.Name.Namespace; var itemGroup = new XElement(ns + "ItemGroup"); p.Root.Add(itemGroup); foreach (var dependency in ConflictResolutionAssets.ConflictResolutionDependencies) { itemGroup.Add(new XElement(ns + "PackageReference", new XAttribute("Include", dependency.Item1), new XAttribute("Version", dependency.Item2))); } if (!selfContained && ridSpecific) { var propertyGroup = new XElement(ns + "PropertyGroup"); p.Root.Add(propertyGroup); propertyGroup.Add(new XElement(ns + "SelfContained", "false")); } }) .Restore(Log, testProject.Name); var publishCommand = new PublishCommand(Log, Path.Combine(testProjectInstance.TestRoot, testProject.Name)); var publishResult = publishCommand.Execute(); publishResult.Should().Pass(); var publishDirectory = publishCommand.GetOutputDirectory( targetFramework: targetFramework, runtimeIdentifier: rid ?? string.Empty); DependencyContext dependencyContext; using (var depsJsonFileStream = File.OpenRead(Path.Combine(publishDirectory.FullName, $"{testProject.Name}.deps.json"))) { dependencyContext = new DependencyContextJsonReader().Read(depsJsonFileStream); } dependencyContext.Should() .HaveNoDuplicateRuntimeAssemblies(rid ?? "") .And .HaveNoDuplicateNativeAssets(rid ?? "") .And .OnlyHavePackagesWithPathProperties(); ICommand runCommand; if (selfContained) { var selfContainedExecutable = testProject.Name + Constants.ExeSuffix; string selfContainedExecutableFullPath = Path.Combine(publishDirectory.FullName, selfContainedExecutable); var libPrefix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "" : "lib"; publishDirectory.Should().HaveFiles(new[] { selfContainedExecutable, $"{testProject.Name}.dll", $"{testProject.Name}.pdb", $"{testProject.Name}.deps.json", $"{testProject.Name}.runtimeconfig.json", $"{libPrefix}coreclr{FileConstants.DynamicLibSuffix}", $"{libPrefix}hostfxr{FileConstants.DynamicLibSuffix}", $"{libPrefix}hostpolicy{FileConstants.DynamicLibSuffix}", $"mscorlib.dll", $"System.Private.CoreLib.dll", }); dependencyContext.Should() .OnlyHaveRuntimeAssembliesWhichAreInFolder(rid, publishDirectory.FullName) .And .OnlyHaveNativeAssembliesWhichAreInFolder(rid, publishDirectory.FullName, testProject.Name); runCommand = Command.Create(selfContainedExecutableFullPath, new string[] { }); } else { publishDirectory.Should().OnlyHaveFiles(new[] { $"{testProject.Name}.dll", $"{testProject.Name}.pdb", $"{testProject.Name}.deps.json", $"{testProject.Name}.runtimeconfig.json" }); dependencyContext.Should() .OnlyHaveRuntimeAssemblies(rid ?? "", testProject.Name); runCommand = Command.Create(TestContext.Current.ToolsetUnderTest.DotNetHostPath, new[] { Path.Combine(publishDirectory.FullName, $"{testProject.Name}.dll") }); } runCommand .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining(outputMessage); }
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"); } }