Ejemplo n.º 1
0
        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()));

            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);
        }
Ejemplo n.º 2
0
        public void TrivialSourceFileOnlyCsc()
        {
            var hello       = Temp.CreateFile().WriteAllText(helloWorldCS).Path;
            var touchedDir  = Temp.CreateDirectory();
            var touchedBase = Path.Combine(touchedDir.Path, "touched");

            var cmd = new MockCSharpCompiler(null, _baseDirectory, new[] { "/nologo", hello,
                                                                           string.Format(@"/touchedfiles:""{0}""", touchedBase) });
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);

            List <string> expectedReads;
            List <string> expectedWrites;

            BuildTouchedFiles(cmd,
                              Path.ChangeExtension(hello, "exe"),
                              out expectedReads,
                              out expectedWrites);
            var exitCode = cmd.Run(outWriter);

            Assert.Equal("", outWriter.ToString().Trim());
            Assert.Equal(0, exitCode);
            AssertTouchedFilesEqual(expectedReads,
                                    expectedWrites,
                                    touchedBase);

            CleanupAllGeneratedFiles(hello);
        }
Ejemplo n.º 3
0
        public void StrongNameKeyCsc()
        {
            var hello       = Temp.CreateFile().WriteAllText(helloWorldCS).Path;
            var snkPath     = Temp.CreateFile("TestKeyPair_", ".snk").WriteAllBytes(TestResources.General.snKey).Path;
            var touchedDir  = Temp.CreateDirectory();
            var touchedBase = Path.Combine(touchedDir.Path, "touched");

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            var cmd       = new MockCSharpCompiler(null, _baseDirectory,
                                                   new[] { "/nologo",
                                                           "/touchedfiles:" + touchedBase,
                                                           "/keyfile:" + snkPath,
                                                           hello });

            List <string> expectedReads;
            List <string> expectedWrites;

            BuildTouchedFiles(cmd,
                              Path.ChangeExtension(hello, "exe"),
                              out expectedReads,
                              out expectedWrites);
            expectedReads.Add(snkPath);

            var exitCode = cmd.Run(outWriter);

            Assert.Equal(string.Empty, outWriter.ToString().Trim());
            Assert.Equal(0, exitCode);

            AssertTouchedFilesEqual(expectedReads,
                                    expectedWrites,
                                    touchedBase);

            CleanupAllGeneratedFiles(hello);
        }
Ejemplo n.º 4
0
        internal override string GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(
            MockCSharpCompiler cmd
            )
        {
            string expectedOutput =
                @"{{
  ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"",
  ""version"": ""2.1.0"",
  ""runs"": [
    {{
{5},
      ""tool"": {{
        ""driver"": {{
          ""name"": ""{0}"",
          ""version"": ""{1}"",
          ""dottedQuadFileVersion"": ""{2}"",
          ""semanticVersion"": ""{3}"",
          ""language"": ""{4}"",
{6}
        }}
      }},
      ""columnKind"": ""utf16CodeUnits""
    }}
  ]
}}";

            return(FormatOutputText(
                       expectedOutput,
                       cmd,
                       AnalyzerForErrorLogTest.GetExpectedV2ErrorLogResultsText(cmd.Compilation),
                       AnalyzerForErrorLogTest.GetExpectedV2ErrorLogRulesText()
                       ));
        }
Ejemplo n.º 5
0
        public void XmlDocumentFileCsc()
        {
            var sourcePath  = Temp.CreateFile().WriteAllText(@"
/// <summary>
/// A subtype of <see cref=""object""/>.
/// </summary>
public class C { }").Path;
            var xml         = Temp.CreateFile();
            var touchedDir  = Temp.CreateDirectory();
            var touchedBase = Path.Combine(touchedDir.Path, "touched");

            var cmd = new MockCSharpCompiler(null, _baseDirectory, new[]
            {
                "/nologo",
                "/target:library",
                "/doc:" + xml.Path,
                "/touchedfiles:" + touchedDir.Path + "\\touched",
                sourcePath
            });

            // Build touched files
            List <string> expectedReads;
            List <string> expectedWrites;

            BuildTouchedFiles(cmd,
                              Path.ChangeExtension(sourcePath, "dll"),
                              out expectedReads,
                              out expectedWrites);
            expectedWrites.Add(xml.Path);

            var writer   = new StringWriter(CultureInfo.InvariantCulture);
            var exitCode = cmd.Run(writer);

            Assert.Equal(string.Empty, writer.ToString().Trim());
            Assert.Equal(0, exitCode);
            Assert.Equal(string.Format(@"
<?xml version=""1.0""?>
<doc>
    <assembly>
        <name>{0}</name>
    </assembly>
    <members>
        <member name=""T:C"">
            <summary>
            A subtype of <see cref=""T:System.Object""/>.
            </summary>
        </member>
    </members>
</doc>", Path.GetFileNameWithoutExtension(sourcePath)).Trim(),
                         xml.ReadAllText().Trim());

            AssertTouchedFilesEqual(expectedReads,
                                    expectedWrites,
                                    touchedBase);

            CleanupAllGeneratedFiles(sourcePath);
        }
Ejemplo n.º 6
0
        internal override string GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(
            MockCSharpCompiler cmd
            )
        {
            var expectedHeader = GetExpectedErrorLogHeader(cmd);
            var expectedIssues = AnalyzerForErrorLogTest.GetExpectedV1ErrorLogResultsAndRulesText(
                cmd.Compilation
                );

            return(expectedHeader + expectedIssues);
        }
Ejemplo n.º 7
0
        public void AppConfigCsc()
        {
            var hello         = Temp.CreateFile().WriteAllText(helloWorldCS).Path;
            var touchedDir    = Temp.CreateDirectory();
            var touchedBase   = Path.Combine(touchedDir.Path, "touched");
            var appConfigPath = Temp.CreateFile().WriteAllText(
                @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1"">
       <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/>
    </assemblyBinding>
  </runtime>
</configuration>").Path;

            var silverlight = Temp.CreateFile().WriteAllBytes(TestResources.NetFX.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).Path;
            var net4_0dll   = Temp.CreateFile().WriteAllBytes(TestResources.NetFX.v4_0_30319.System).Path;

            var outWriter = new StringWriter(CultureInfo.InvariantCulture);
            var cmd       = new MockCSharpCompiler(null, _baseDirectory,
                                                   new[] { "/nologo",
                                                           "/r:" + silverlight,
                                                           "/r:" + net4_0dll,
                                                           "/appconfig:" + appConfigPath,
                                                           "/touchedfiles:" + touchedBase,
                                                           hello });

            List <string> expectedReads;
            List <string> expectedWrites;

            BuildTouchedFiles(cmd,
                              Path.ChangeExtension(hello, "exe"),
                              out expectedReads,
                              out expectedWrites);
            expectedReads.Add(appConfigPath);

            var exitCode = cmd.Run(outWriter);

            Assert.Equal("", outWriter.ToString().Trim());
            Assert.Equal(0, exitCode);
            AssertTouchedFilesEqual(expectedReads,
                                    expectedWrites,
                                    touchedBase);

            CleanupAllGeneratedFiles(hello);
        }
Ejemplo n.º 8
0
        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 = @"
      ""results"": [
      ]
    }
  ]
}";
            var expectedText   = expectedHeader + expectedIssues;

            Assert.Equal(expectedText, actualOutput);

            CleanupAllGeneratedFiles(hello);
            CleanupAllGeneratedFiles(errorLogFile);
        }
Ejemplo n.º 9
0
        public void SimpleCompilerDiagnostics()
        {
            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");

            var cmd = new MockCSharpCompiler(null, _baseDirectory, new[] {
                "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}"
            });
            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 expectedHeader = GetExpectedErrorLogHeader(actualOutput, cmd);
            var expectedIssues = string.Format(@"
      ""results"": [
        {{
          ""ruleId"": ""CS0169"",
          ""level"": ""warning"",
          ""message"": ""The field 'C.x' is never used"",
          ""locations"": [
            {{
              ""resultFile"": {{
                ""uri"": ""{0}"",
                ""region"": {{
                  ""startLine"": 4,
                  ""startColumn"": 17,
                  ""endLine"": 4,
                  ""endColumn"": 18
                }}
              }}
            }}
          ],
          ""properties"": {{
            ""warningLevel"": 3
          }}
        }},
        {{
          ""ruleId"": ""CS5001"",
          ""level"": ""error"",
          ""message"": ""Program does not contain a static 'Main' method suitable for an entry point""
        }}
      ],
      ""rules"": {{
        ""CS0169"": {{
          ""id"": ""CS0169"",
          ""shortDescription"": ""Field is never used"",
          ""defaultLevel"": ""warning"",
          ""properties"": {{
            ""category"": ""Compiler"",
            ""isEnabledByDefault"": true,
            ""tags"": [
              ""Compiler"",
              ""Telemetry""
            ]
          }}
        }},
        ""CS5001"": {{
          ""id"": ""CS5001"",
          ""defaultLevel"": ""error"",
          ""properties"": {{
            ""category"": ""Compiler"",
            ""isEnabledByDefault"": true,
            ""tags"": [
              ""Compiler"",
              ""Telemetry"",
              ""NotConfigurable""
            ]
          }}
        }}
      }}
    }}
  ]
}}", AnalyzerForErrorLogTest.GetUriForPath(sourceFile));

            var expectedText = expectedHeader + expectedIssues;

            Assert.Equal(expectedText, actualOutput);

            CleanupAllGeneratedFiles(sourceFile);
            CleanupAllGeneratedFiles(errorLogFile);
        }
Ejemplo n.º 10
0
 internal abstract string GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(MockCSharpCompiler cmd);
Ejemplo n.º 11
0
        public void SimpleCompilerDiagnostics_Suppressed()
        {
            var source       = @"
public class C
{
#pragma warning disable CS0169
    private int x;
#pragma warning restore CS0169
}";
            var sourceFile   = Temp.CreateFile().WriteAllText(source).Path;
            var errorLogDir  = Temp.CreateDirectory();
            var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt");

            var cmd = new MockCSharpCompiler(null, _baseDirectory, new[] {
                "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}"
            });
            var outWriter = new StringWriter(CultureInfo.InvariantCulture);

            var exitCode            = cmd.Run(outWriter);
            var actualConsoleOutput = outWriter.ToString().Trim();

            // Suppressed diagnostics are only report in the error log, not the console output.
            Assert.DoesNotContain("CS0169", actualConsoleOutput);
            Assert.Contains("CS5001", actualConsoleOutput);
            Assert.NotEqual(0, exitCode);

            var actualOutput = File.ReadAllText(errorLogFile).Trim();

            var expectedHeader = GetExpectedErrorLogHeader(actualOutput, cmd);
            var expectedIssues = string.Format(@"
      ""issues"": [
        {{
          ""ruleId"": ""CS0169"",
          ""locations"": [
            {{
              ""analysisTarget"": [
                {{
                  ""uri"": ""{0}"",
                  ""region"": {{
                    ""startLine"": 5,
                    ""startColumn"": 17,
                    ""endLine"": 5,
                    ""endColumn"": 18
                  }}
                }}
              ]
            }}
          ],
          ""fullMessage"": ""The field 'C.x' is never used"",
          ""properties"": {{
            ""severity"": ""Warning"",
            ""warningLevel"": ""3"",
            ""defaultSeverity"": ""Warning"",
            ""title"": ""Field is never used"",
            ""category"": ""Compiler"",
            ""isEnabledByDefault"": ""True"",
            ""isSuppressedInSource"": ""True"",
            ""customTags"": ""Compiler;Telemetry""
          }}
        }},
        {{
          ""ruleId"": ""CS5001"",
          ""locations"": [
          ],
          ""fullMessage"": ""Program does not contain a static 'Main' method suitable for an entry point"",
          ""properties"": {{
            ""severity"": ""Error"",
            ""defaultSeverity"": ""Error"",
            ""category"": ""Compiler"",
            ""isEnabledByDefault"": ""True"",
            ""isSuppressedInSource"": ""False"",
            ""customTags"": ""Compiler;Telemetry;NotConfigurable""
          }}
        }}
      ]
    }}
  ]
}}", AnalyzerForErrorLogTest.GetEscapedUriForPath(sourceFile));

            var expectedText = expectedHeader + expectedIssues;

            Assert.Equal(expectedText, actualOutput);

            CleanupAllGeneratedFiles(sourceFile);
            CleanupAllGeneratedFiles(errorLogFile);
        }
Ejemplo n.º 12
0
 internal abstract string GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(MockCSharpCompiler cmd, string justification);