public void ItCanNewRestoreBuildRunCleanMSBuildProject() { using (DisposableDirectory directory = Temp.CreateDirectory()) { string projectDirectory = directory.Path; new NewCommand() .WithWorkingDirectory(projectDirectory) .Execute("") .Should().Pass(); new RestoreCommand() .WithWorkingDirectory(projectDirectory) .Execute("/p:SkipInvalidConfigurations=true") .Should().Pass(); new BuildCommand() .WithWorkingDirectory(projectDirectory) .Execute() .Should().Pass(); new RunCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput() .Should().Pass() .And.HaveStdOutContaining("Hello World!"); var binDirectory = new DirectoryInfo(projectDirectory).Sub("bin"); binDirectory.Should().HaveFilesMatching("*.dll", SearchOption.AllDirectories); new CleanCommand() .WithWorkingDirectory(projectDirectory) .Execute() .Should().Pass(); binDirectory.Should().NotHaveFilesMatching("*.dll", SearchOption.AllDirectories); } }
private void MigratingPublishOptionsForConsoleAppIncludeExcludePopulatesContentItemWithInclude() { var testDirectory = Temp.CreateDirectory().Path; WriteFilesInProjectDirectory(testDirectory); var mockProj = RunPublishOptionsRuleOnPj(@" { ""publishOptions"": { ""include"": [""root"", ""src"", ""rootfile.cs""], ""exclude"": [""src"", ""rootfile.cs""], ""includeFiles"": [""src/file1.cs"", ""src/file2.cs""], ""excludeFiles"": [""src/file2.cs""] } }", testDirectory: testDirectory); mockProj.Items.Count(i => i.ItemType.Equals("Content", StringComparison.Ordinal)).Should().Be(2); foreach (var item in mockProj.Items.Where(i => i.ItemType.Equals("Content", StringComparison.Ordinal))) { item.Metadata.Count(m => m.Name == "CopyToPublishDirectory").Should().Be(1); if (item.Include.Contains(@"src\file1.cs")) { item.Include.Should().Be(@"src\file1.cs;src\file2.cs"); item.Exclude.Should().Be(@"src\file2.cs"); } else { item.Include.Should() .Be(@"root\**\*;src\**\*;rootfile.cs"); item.Exclude.Should() .Be(@"src\**\*;rootfile.cs;src\file2.cs"); } } }
public void MigratingProjectWithCompileResourcesPopulatesAppropriateProjectItemElements() { var testDirectory = Temp.CreateDirectory().Path; WriteCompileResourceFiles(testDirectory); var pj = @" { ""version"": ""1.0.0-*"", ""dependencies"": { ""NETStandard.Library"": ""1.6.0"" }, ""frameworks"": { ""netstandard1.5"": {} } }"; var mockProj = RunBuildOptionsRuleOnPj(pj, testDirectory); var compileItems = mockProj.Items.Where(i => i.ItemType.Equals("Compile", StringComparison.Ordinal)); compileItems.Count().Should().Be(1); var compileItem = compileItems.Single(); compileItem.Include.Should().BeEmpty(); compileItem.Exclude.Should().BeEmpty(); compileItem.Remove.Should().Be(@"compiler\resources\*"); var embeddedResourceItems = mockProj.Items.Where( i => i.ItemType.Equals("EmbeddedResource", StringComparison.Ordinal)); embeddedResourceItems.Count().Should().Be(1); var embeddedResourceItem = embeddedResourceItems.Single(); embeddedResourceItem.Include.Should().Be(@"compiler\resources\*"); embeddedResourceItem.Exclude.Should().BeEmpty(); embeddedResourceItem.Remove.Should().BeEmpty(); }
public void GetEffectiveIncludes_OneLevel() { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet> "; string includeSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(ruleSetSource); var include = dir.CreateFile("file1.ruleset"); include.WriteAllText(includeSource); var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path); Assert.Equal(expected: 2, actual: includePaths.Length); Assert.Equal(expected: file.Path, actual: includePaths[0]); Assert.Equal(expected: include.Path, actual: includePaths[1]); }
public void TestRuleSetIncludeError() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Default"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); var newFile = dir.CreateFile("file1.ruleset"); newFile.WriteAllText(source1); using (new EnsureEnglishUICulture()) { try { RuleSet.LoadEffectiveRuleSetFromFile(file.Path); Assert.True(false, "Didn't throw an exception"); } catch (InvalidRuleSetException e) { Assert.Contains(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, newFile.Path, string.Format(CodeAnalysisResources.RuleSetBadAttributeValue, "Action", "Default")), e.Message, StringComparison.Ordinal); } } }
public void NoDiagnostics() { var helloWorldCS = @"using System; class C { public static void Main(string[] args) { Console.WriteLine(""Hello, world""); } }"; var hello = Temp.CreateFile().WriteAllText(helloWorldCS).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); var cmd = new MockCSharpCompiler(null, _baseDirectory, new[] { "/nologo", hello, $"/errorlog:{errorLogFile}" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString().Trim()); Assert.Equal(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedHeader = GetExpectedErrorLogHeader(actualOutput, cmd); var expectedIssues = @" ""issues"": [ ] }"; var expectedText = expectedHeader + expectedIssues; Assert.Equal(expectedText, actualOutput); CleanupAllGeneratedFiles(hello); CleanupAllGeneratedFiles(errorLogFile); }
protected void SimpleCompilerDiagnosticsImpl() { var source = @" public class C { private int x; }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); Assert.Contains("CS0169", actualConsoleOutput); Assert.Contains("CS5001", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedOutput = GetExpectedOutputForSimpleCompilerDiagnostics(cmd, sourceFile); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); }
public void AnalyzerDiagnosticsWithAndWithoutLocation() { var source = @" public class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var outputDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(outputDir.Path, "ErrorLog.txt"); var outputFilePath = Path.Combine(outputDir.Path, "test.dll"); var cmd = new MockCSharpCompiler(null, _baseDirectory, new[] { "/nologo", "/t:library", $"/out:{outputFilePath}", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}" }, analyzers: ImmutableArray.Create <DiagnosticAnalyzer>(new AnalyzerForErrorLogTest()), loader: new DesktopAnalyzerAssemblyLoader()); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); Assert.Contains(AnalyzerForErrorLogTest.Descriptor1.Id, actualConsoleOutput); Assert.Contains(AnalyzerForErrorLogTest.Descriptor2.Id, actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedHeader = GetExpectedErrorLogHeader(actualOutput, cmd); var expectedIssues = AnalyzerForErrorLogTest.GetExpectedErrorLogResultsText(cmd.Compilation); var expectedText = expectedHeader + expectedIssues; Assert.Equal(expectedText, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(outputFilePath); CleanupAllGeneratedFiles(errorLogFile); }
public void LineNumber_Information_On_Exception() { var source = @"Console.WriteLine(""OK""); throw new Exception(""Error!""); "; var cwd = Temp.CreateDirectory(); cwd.CreateFile("a.csx").WriteAllText(source); var result = ProcessUtilities.Run(CsiPath, "a.csx", workingDirectory: cwd.Path); Assert.True(result.ContainsErrors); AssertEx.AssertEqualToleratingWhitespaceDifferences("OK", result.Output); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@" System.Exception: Error! + <Initialize>.MoveNext(){string.Format(ScriptingResources.AtFileLine, $"{cwd}{Path.DirectorySeparatorChar}a.csx", "2")} ", result.Errors ); }
public void MigratingProjectJsonWithServerGCAndOtherRuntimeOptionsProducesRuntimeConfigTemplateJsonFile() { var testDirectory = Temp.CreateDirectory().Path; var pj = @" { ""runtimeOptions"": { ""configProperties"": { ""System.GC.Server"": false }, ""Other"": false } }"; RunMigrateRuntimeOptionsRulePj(pj, testDirectory); var migratedRuntimeOptionsPath = Path.Combine(testDirectory, s_runtimeConfigFileName); File.Exists(migratedRuntimeOptionsPath).Should().BeTrue(); var root = JObject.Parse(File.ReadAllText(migratedRuntimeOptionsPath)); root.Value <JObject>("configProperties").Should().BeNull(); }
public void MigratingCopyToOutputIncludeOnlyPopulatesAppropriateProjectItemElement( string group, string itemName, string expectedRootFiles) { var testDirectory = Temp.CreateDirectory().Path; WriteExtraFiles(testDirectory); var pj = @" { ""buildOptions"": { ""<group>"": [""root"", ""src"", ""rootfile.cs""] } }".Replace("<group>", group); var mockProj = RunBuildOptionsRuleOnPj(pj, testDirectory: testDirectory); mockProj.Items.Count(i => i.ItemType.Equals(itemName, StringComparison.Ordinal)).Should().Be(1); mockProj.Items.Single().Update.Should().Be($@"root\**\*;src\**\*{expectedRootFiles}"); }
public void Migrating_MultiTFM_project_Populates_TargetFrameworks_with_short_tfms() { var testDirectory = Temp.CreateDirectory().Path; var testPJ = new ProjectJsonBuilder(TestAssetsManager) .FromTestAssetBase("TestLibraryWithMultipleFrameworks") .SaveToDisk(testDirectory); var projectContexts = ProjectContext.CreateContextForEachFramework(testDirectory); var mockProj = ProjectRootElement.Create(); var migrationSettings = new MigrationSettings(testDirectory, testDirectory, mockProj); var migrationInputs = new MigrationRuleInputs( projectContexts, mockProj, mockProj.AddItemGroup(), mockProj.AddPropertyGroup()); new MigrateTFMRule().Apply(migrationSettings, migrationInputs); mockProj.Properties.Count(p => p.Name == "TargetFrameworks").Should().Be(1); mockProj.Properties.First(p => p.Name == "TargetFrameworks") .Value.Should().Be("net20;net35;net40;net461;netstandard1.5"); }
public void MigratingProjectWithFullFrameworkTFMsDoesNotAddRuntimeIdentifiersOrRuntimeIdentiferWhenNoRuntimesExistAlready() { var testDirectory = Temp.CreateDirectory().Path; var testPJ = new ProjectJsonBuilder(TestAssets) .FromTestAssetBase("AppWith4netTfm0Rid") .SaveToDisk(testDirectory); var projectContexts = ProjectContext.CreateContextForEachFramework(testDirectory); var mockProj = ProjectRootElement.Create(); var migrationSettings = MigrationSettings.CreateMigrationSettingsTestHook(testDirectory, testDirectory, mockProj); var migrationInputs = new MigrationRuleInputs( projectContexts, mockProj, mockProj.AddItemGroup(), mockProj.AddPropertyGroup()); new MigrateTFMRule().Apply(migrationSettings, migrationInputs); mockProj.Properties.Count(p => p.Name == "RuntimeIdentifiers").Should().Be(0); mockProj.Properties.Where(p => p.Name == "RuntimeIdentifier").Should().HaveCount(0); }
public void PublishScriptsRun() { // create unique directories in the 'temp' folder var root = Temp.CreateDirectory(); var testAppDir = root.CreateDirectory("TestApp"); var testLibDir = root.CreateDirectory("TestLibrary"); //copy projects to the temp dir CopyProjectToTempDir(Path.Combine(_testProjectsRoot, "TestApp"), testAppDir); CopyProjectToTempDir(Path.Combine(_testProjectsRoot, "TestLibrary"), testLibDir); RunRestore(testAppDir.Path); RunRestore(testLibDir.Path); // run publish var testProject = GetProjectPath(testAppDir); var publishCommand = new PublishCommand(testProject); var result = publishCommand.ExecuteWithCapturedOutput(); result.Should().StdOutMatchPattern("\nprepublish_output( \\?[^%]+\\?){5}.+\npostpublish_output( \\?[^%]+\\?){5}", RegexOptions.Singleline); result.Should().Pass(); }
public void TestLibraryPublishTest() { // create unique directories in the 'temp' folder var root = Temp.CreateDirectory(); var testLibDir = root.CreateDirectory("TestLibraryWithRunner"); //copy projects to the temp dir CopyProjectToTempDir(Path.Combine(_testProjectsRoot, "TestLibraryWithRunner"), testLibDir); RunRestore(testLibDir.Path); var testProject = GetProjectPath(testLibDir); var publishCommand = new PublishCommand(testProject); publishCommand.Execute().Should().Pass(); publishCommand.GetOutputDirectory().Should().HaveFile("TestLibraryWithRunner.dll"); publishCommand.GetOutputDirectory().Should().HaveFile("TestLibraryWithRunner.pdb"); publishCommand.GetOutputDirectory().Should().HaveFile("TestLibraryWithRunner.deps"); publishCommand.GetOutputDirectory().Should().HaveFile("TestLibraryWithRunner.dll.config"); // dependencies should also be copied publishCommand.GetOutputDirectory().Should().HaveFile("Newtonsoft.Json.dll"); }
public void DifferingMvids() { var directory = Temp.CreateDirectory(); // Load Beta.dll from the future Alpha.dll path to prime the assembly loader var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Beta); var assemblyLoader = new InMemoryAssemblyLoader(); var betaAssembly = assemblyLoader.LoadFromPath(alphaDll.Path); alphaDll.WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var gammaDll = directory.CreateFile("Gamma.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Gamma); var deltaDll = directory.CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var analyzerReferences = ImmutableArray.Create( new CommandLineAnalyzerReference("Alpha.dll"), new CommandLineAnalyzerReference("Gamma.dll"), new CommandLineAnalyzerReference("Delta.dll")); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, assemblyLoader); Assert.False(result); }
public void TestLoadErrors3() { var directory = Temp.CreateDirectory(); var alphaDll = directory .CreateFile("Alpha.dll") .WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); AnalyzerFileReference reference = CreateAnalyzerFileReference(alphaDll.Path); List <AnalyzerLoadFailureEventArgs> errors = new List <AnalyzerLoadFailureEventArgs>(); EventHandler <AnalyzerLoadFailureEventArgs> errorHandler = (o, e) => errors.Add(e); reference.AnalyzerLoadFailed += errorHandler; var builder = ImmutableArray.CreateBuilder <DiagnosticAnalyzer>(); reference.AddAnalyzers(builder, LanguageNames.CSharp); var analyzers = builder.ToImmutable(); reference.AnalyzerLoadFailed -= errorHandler; File.Delete(alphaDll.Path); Assert.Equal(0, errors.Count); }
public void Migrating_desktop_TFMs_adds_RuntimeIdentifiers() { var testDirectory = Temp.CreateDirectory().Path; var testPJ = new ProjectJsonBuilder(TestAssetsManager) .FromTestAssetBase("TestLibraryWithMultipleFrameworks") .SaveToDisk(testDirectory); var projectContexts = ProjectContext.CreateContextForEachFramework(testDirectory); var mockProj = ProjectRootElement.Create(); var migrationSettings = new MigrationSettings(testDirectory, testDirectory, mockProj); var migrationInputs = new MigrationRuleInputs( projectContexts, mockProj, mockProj.AddItemGroup(), mockProj.AddPropertyGroup()); new MigrateTFMRule().Apply(migrationSettings, migrationInputs); mockProj.Properties.Count(p => p.Name == "RuntimeIdentifiers").Should().Be(1); mockProj.Properties.First(p => p.Name == "RuntimeIdentifiers") .Value.Should().Be("win7-x64;win7-x86;osx.10.10-x64;osx.10.11-x64;ubuntu.14.04-x64;ubuntu.16.04-x64;centos.7-x64;rhel.7.2-x64;debian.8-x64;fedora.23-x64;opensuse.13.2-x64"); }
public void AssemblyAndPdb(bool exactPdbPath) { var dir = Temp.CreateDirectory(); var dllFile = dir.CreateFile("lib.dll"); var pdbFile = dir.CreateFile("lib.pdb"); var source = @"class C { public static void Main() { int x = 1; } }"; var compilation = CSharpTestBase.CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var debugDirPdbPath = exactPdbPath ? pdbFile.Path : "a/y/z/lib.pdb"; var peImage = compilation.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb, pdbFilePath: debugDirPdbPath), pdbStream: pdbStream); pdbStream.Position = 0; dllFile.WriteAllBytes(peImage); pdbFile.WriteAllBytes(pdbStream.ToArray()); var outputs = new CompilationOutputFilesWithImplicitPdbPath(dllFile.Path); using (var pdb = outputs.OpenPdb()) { var encReader = pdb.CreateEditAndContinueMethodDebugInfoReader(); Assert.True(encReader.IsPortable); var localSig = encReader.GetLocalSignature(MetadataTokens.MethodDefinitionHandle(1)); Assert.Equal(MetadataTokens.StandaloneSignatureHandle(1), localSig); } using (var metadata = outputs.OpenAssemblyMetadata(prefetch: false)) { var mdReader = metadata.GetMetadataReader(); Assert.Equal("lib", mdReader.GetString(mdReader.GetAssemblyDefinition().Name)); } // make sure all files are closed and can be deleted Directory.Delete(dir.Path, recursive: true); }
public void ReferenceSearchPaths_Change1() { var dir = Temp.CreateDirectory(); var main = dir.CreateFile("C.dll").WriteAllBytes(TestResources.General.C1); var runner = CreateRunner(input: $@"ReferencePaths #r ""C.dll"" ReferencePaths.Add(@""{dir.Path}"") #r ""C.dll"" new C() "); runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Microsoft (R) Visual C# Interactive Compiler version {s_compilerVersion} Copyright (C) Microsoft Corporation. All rights reserved. Type ""#help"" for more information. > ReferencePaths SearchPaths {{ }} > #r ""C.dll"" «Red» (1,1): error CS0006: Metadata file 'C.dll' could not be found «Gray» > ReferencePaths.Add(@""{dir.Path}"") > #r ""C.dll"" > new C() C {{ }} > ", runner.Console.Out.ToString()); AssertEx.AssertEqualToleratingWhitespaceDifferences( @"(1,1): error CS0006: Metadata file 'C.dll' could not be found", runner.Console.Error.ToString()); }
public void SourceSearchPaths_Change1() { var dir = Temp.CreateDirectory(); var main = dir.CreateFile("a.csx").WriteAllText("int X = 1;"); var runner = CreateRunner(input: $@"SourcePaths #load ""a.csx"" SourcePaths.Add(@""{dir.Path}"") #load ""a.csx"" X "); runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Microsoft (R) Visual C# Interactive Compiler version {s_compilerVersion} Copyright (C) Microsoft Corporation. All rights reserved. Type ""#help"" for more information. > SourcePaths SearchPaths {{ }} > #load ""a.csx"" «Red» (1,7): error CS1504: Source file 'a.csx' could not be opened -- Could not find file. «Gray» > SourcePaths.Add(@""{dir.Path}"") > #load ""a.csx"" > X 1 > ", runner.Console.Out.ToString()); AssertEx.AssertEqualToleratingWhitespaceDifferences( @"(1,7): error CS1504: Source file 'a.csx' could not be opened -- Could not find file.", runner.Console.Error.ToString()); }
public void AssemblyLoading() { StringBuilder sb = new StringBuilder(); var directory = Temp.CreateDirectory(); var alphaDll = Temp.CreateDirectory().CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var betaDll = Temp.CreateDirectory().CreateFile("Beta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Beta); var gammaDll = Temp.CreateDirectory().CreateFile("Gamma.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Gamma); var deltaDll = Temp.CreateDirectory().CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var loader = new DesktopAnalyzerAssemblyLoader(); loader.AddDependencyLocation(alphaDll.Path); loader.AddDependencyLocation(betaDll.Path); loader.AddDependencyLocation(gammaDll.Path); loader.AddDependencyLocation(deltaDll.Path); Assembly alpha = loader.LoadFromPath(alphaDll.Path); var a = alpha.CreateInstance("Alpha.A"); a.GetType().GetMethod("Write").Invoke(a, new object[] { sb, "Test A" }); Assembly beta = loader.LoadFromPath(betaDll.Path); var b = beta.CreateInstance("Beta.B"); b.GetType().GetMethod("Write").Invoke(b, new object[] { sb, "Test B" }); var expected = @"Delta: Gamma: Alpha: Test A Delta: Gamma: Beta: Test B "; var actual = sb.ToString(); Assert.Equal(expected, actual); }
public void ReferencesVersioning() { using (MetadataCache.LockAndClean()) { var dir1 = Temp.CreateDirectory(); var dir2 = Temp.CreateDirectory(); var dir3 = Temp.CreateDirectory(); var file1 = dir1.CreateFile("C.dll").WriteAllBytes(TestResources.SymbolsTests.General.C1); var file2 = dir2.CreateFile("C.dll").WriteAllBytes(TestResources.SymbolsTests.General.C2); var file3 = dir3.CreateFile("main.dll"); var b = CreateCompilationWithMscorlib( @"public class B { public static int Main() { return C.Main(); } }", assemblyName: "b", references: new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.General.C2) }, options: TestOptions.ReleaseDll); using (MemoryStream output = new MemoryStream()) { var emitResult = b.Emit(output); Assert.True(emitResult.Success); file3.WriteAllBytes(output.ToArray()); } var a = CreateCompilationWithMscorlib( @"class A { public static void Main() { B.Main(); } }", assemblyName: "a", references: new[] { new MetadataFileReference(file1.Path), new MetadataFileReference(file2.Path), new MetadataFileReference(file3.Path) }, options: TestOptions.ReleaseDll); using (var stream = new MemoryStream()) { a.Emit(stream); } } }
public void AddReference_Dependencies_Versions() { var dir1 = Temp.CreateDirectory(); var dir2 = Temp.CreateDirectory(); var dir3 = Temp.CreateDirectory(); // [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.General.C1); // [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.General.C2); Assert.True(LoadReference(file1.Path)); Assert.True(LoadReference(file2.Path)); var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(TestResources.General.C2.AsImmutableOrNull())); Assert.True(LoadReference(main.Path)); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("2", ReadOutputToEnd().Trim()); }
public void ReferencePaths() { var directory = Temp.CreateDirectory(); var assemblyName = GetUniqueName(); CompileLibrary(directory, assemblyName + ".dll", assemblyName, @"public class C { }"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText("/lib:" + directory.Path); Host.ResetAsync(new InteractiveHostOptions(initializationFile: rspFile.Path, culture: CultureInfo.InvariantCulture)).Wait(); Execute( $@"#r ""{assemblyName}.dll"" typeof(C).Assembly.GetName()"); Assert.Equal("", ReadErrorOutputToEnd()); var output = SplitLines(ReadOutputToEnd()); Assert.Equal(2, output.Length); Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[0]); Assert.Equal($"[{assemblyName}, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", output[1]); }
public void When_dotnet_test_is_invoked_Then_tests_run_without_errors() { var rootPath = Temp.CreateDirectory().Path; new TestCommand("dotnet") { WorkingDirectory = rootPath } .Execute("new --type nunittest"); new TestCommand("dotnet") { WorkingDirectory = rootPath } .Execute("restore"); var buildResult = new TestCommand("dotnet") .WithWorkingDirectory(rootPath) .ExecuteWithCapturedOutput("test") .Should() .Pass() .And .NotHaveStdErr(); }
public async Task AddReference_MultipleReferencesWeakVersioning() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C1 { }"; var c1 = CreateCompilation(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = @"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C2 { }"; var c2 = CreateCompilation(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); await Execute( $@" #r ""{file1.Path}"" #r ""{file2.Path}"" " ); await Execute("new C1()"); await Execute("new C2()"); // TODO: We should report an error that assembly named 'c' was already loaded with different content. // In future we can let it load and improve error reporting around type conversions. var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("TODO: error", error.Trim()); Assert.Equal("", output.Trim()); }
public async Task AddReference_AlreadyLoadedDependencies() { var dir = Temp.CreateDirectory(); var lib1 = CompileLibrary(dir, "lib1.dll", "lib1", @"public interface I { int M(); }"); var lib2 = CompileLibrary( dir, "lib2.dll", "lib2", @"public class C : I { public int M() { return 1; } }", MetadataReference.CreateFromFile(lib1.Path) ); await Execute("#r \"" + lib1.Path + "\""); await Execute("#r \"" + lib2.Path + "\""); await Execute("new C().M()"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences("1", output); }
public void DefaultUsings() { var source = @" dynamic d = new ExpandoObject(); Process p = new Process(); Expression<Func<int>> e = () => 1; var squares = from x in new[] { 1, 2, 3 } select x * x; var sb = new StringBuilder(); var list = new List<int>(); var stream = new MemoryStream(); await Task.Delay(10); Console.Write(""OK""); "; var cwd = Temp.CreateDirectory(); cwd.CreateFile("a.csx").WriteAllText(source); var result = ProcessUtilities.Run(CsiPath, "a.csx", workingDirectory: cwd.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences("OK", result.Output); Assert.False(result.ContainsErrors); }
private async Task <(byte[] assemblyBytes, string finalFlags)> CompileAndGetBytes(string source) { // Setup var tempDir = Temp.CreateDirectory(); var srcFile = tempDir.CreateFile("test.cs").WriteAllText(source).Path; var outFile = srcFile.Replace("test.cs", "test.dll"); try { string finalFlags = null; using (var serverData = await ServerUtil.CreateServer()) { finalFlags = $"{ _flags } /shared:{ serverData.PipeName } /pathmap:{tempDir.Path}=/ /out:{ outFile } { srcFile }"; var result = CompilerServerUnitTests.RunCommandLineCompiler( CompilerServerUnitTests.CSharpCompilerClientExecutable, finalFlags, currentDirectory: tempDir); if (result.ExitCode != 0) { AssertEx.Fail($"Deterministic compile failed \n stdout: { result.Output }"); } var listener = await serverData.Complete().ConfigureAwait(false); Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single()); } var bytes = File.ReadAllBytes(outFile); AssertEx.NotNull(bytes); return(bytes, finalFlags); } finally { File.Delete(srcFile); File.Delete(outFile); } }