You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

DiagnosticVerifier.cs 14 kB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Text;
  4. using Microsoft.CodeAnalysis;
  5. using Microsoft.CodeAnalysis.Diagnostics;
  6. using Xunit;
  7. //using Microsoft.VisualStudio.TestTools.UnitTesting;
  8. namespace TestHelper
  9. {
  10. /// <summary>
  11. /// Superclass of all Unit Tests for DiagnosticAnalyzers
  12. /// </summary>
  13. public abstract partial class DiagnosticVerifier
  14. {
  15. #region Formatting Diagnostics
  16. /// <summary>
  17. /// Helper method to format a Diagnostic into an easily readable string
  18. /// </summary>
  19. /// <param name="analyzer">The analyzer that this verifier tests</param>
  20. /// <param name="diagnostics">The Diagnostics to be formatted</param>
  21. /// <returns>The Diagnostics formatted as a string</returns>
  22. private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diagnostic[] diagnostics)
  23. {
  24. var builder = new StringBuilder();
  25. for (var i = 0; i < diagnostics.Length; ++i)
  26. {
  27. builder.AppendLine("// " + diagnostics[i]);
  28. var analyzerType = analyzer.GetType();
  29. var rules = analyzer.SupportedDiagnostics;
  30. foreach (var rule in rules)
  31. if (rule != null && rule.Id == diagnostics[i].Id)
  32. {
  33. var location = diagnostics[i].Location;
  34. if (location == Location.None)
  35. builder.AppendFormat("GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id);
  36. else
  37. {
  38. Assert.True(location.IsInSource,
  39. $"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n");
  40. var resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs")
  41. ? "GetCSharpResultAt"
  42. : "GetBasicResultAt";
  43. var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition;
  44. builder.AppendFormat("{0}({1}, {2}, {3}.{4})",
  45. resultMethodName,
  46. linePosition.Line + 1,
  47. linePosition.Character + 1,
  48. analyzerType.Name,
  49. rule.Id);
  50. }
  51. if (i != diagnostics.Length - 1) builder.Append(',');
  52. builder.AppendLine();
  53. break;
  54. }
  55. }
  56. return builder.ToString();
  57. }
  58. #endregion
  59. #region To be implemented by Test classes
  60. /// <summary>
  61. /// Get the CSharp analyzer being tested - to be implemented in non-abstract class
  62. /// </summary>
  63. protected virtual DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() => null;
  64. /// <summary>
  65. /// Get the Visual Basic analyzer being tested (C#) - to be implemented in non-abstract class
  66. /// </summary>
  67. protected virtual DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() => null;
  68. #endregion
  69. #region Verifier wrappers
  70. /// <summary>
  71. /// Called to test a C# DiagnosticAnalyzer when applied on the single inputted string as a source
  72. /// Note: input a DiagnosticResult for each Diagnostic expected
  73. /// </summary>
  74. /// <param name="source">A class in the form of a string to run the analyzer on</param>
  75. /// <param name="expected"> DiagnosticResults that should appear after the analyzer is run on the source</param>
  76. protected void VerifyCSharpDiagnostic(string source, params DiagnosticResult[] expected) =>
  77. VerifyDiagnostics(new[] {source}, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected);
  78. /// <summary>
  79. /// Called to test a VB DiagnosticAnalyzer when applied on the single inputted string as a source
  80. /// Note: input a DiagnosticResult for each Diagnostic expected
  81. /// </summary>
  82. /// <param name="source">A class in the form of a string to run the analyzer on</param>
  83. /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the source</param>
  84. protected void VerifyBasicDiagnostic(string source, params DiagnosticResult[] expected) =>
  85. VerifyDiagnostics(new[] {source}, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected);
  86. /// <summary>
  87. /// Called to test a C# DiagnosticAnalyzer when applied on the inputted strings as a source
  88. /// Note: input a DiagnosticResult for each Diagnostic expected
  89. /// </summary>
  90. /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param>
  91. /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param>
  92. protected void VerifyCSharpDiagnostic(string[] sources, params DiagnosticResult[] expected) =>
  93. VerifyDiagnostics(sources, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected);
  94. /// <summary>
  95. /// Called to test a VB DiagnosticAnalyzer when applied on the inputted strings as a source
  96. /// Note: input a DiagnosticResult for each Diagnostic expected
  97. /// </summary>
  98. /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param>
  99. /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param>
  100. protected void VerifyBasicDiagnostic(string[] sources, params DiagnosticResult[] expected) =>
  101. VerifyDiagnostics(sources, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected);
  102. /// <summary>
  103. /// General method that gets a collection of actual diagnostics found in the source after the analyzer is run,
  104. /// then verifies each of them.
  105. /// </summary>
  106. /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param>
  107. /// <param name="language">The language of the classes represented by the source strings</param>
  108. /// <param name="analyzer">The analyzer to be run on the source code</param>
  109. /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param>
  110. private void VerifyDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer,
  111. params DiagnosticResult[] expected)
  112. {
  113. var diagnostics = GetSortedDiagnostics(sources, language, analyzer);
  114. VerifyDiagnosticResults(diagnostics, analyzer, expected);
  115. }
  116. #endregion
  117. #region Actual comparisons and verifications
  118. /// <summary>
  119. /// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult in the array
  120. /// of expected results.
  121. /// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the
  122. /// DiagnosticResult match the actual diagnostic.
  123. /// </summary>
  124. /// <param name="actualResults">The Diagnostics found by the compiler after running the analyzer on the source code</param>
  125. /// <param name="analyzer">The analyzer that was being run on the sources</param>
  126. /// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param>
  127. private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults, DiagnosticAnalyzer analyzer,
  128. params DiagnosticResult[] expectedResults)
  129. {
  130. var expectedCount = expectedResults.Length;
  131. var actualCount = actualResults.Count();
  132. if (expectedCount != actualCount)
  133. {
  134. var diagnosticsOutput = actualResults.Any()
  135. ? FormatDiagnostics(analyzer, actualResults.ToArray())
  136. : " NONE.";
  137. Assert.True(false,
  138. string.Format(
  139. "Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n",
  140. expectedCount, actualCount, diagnosticsOutput));
  141. }
  142. for (var i = 0; i < expectedResults.Length; i++)
  143. {
  144. var actual = actualResults.ElementAt(i);
  145. var expected = expectedResults[i];
  146. if (expected.Line == -1 && expected.Column == -1)
  147. {
  148. if (actual.Location != Location.None)
  149. Assert.True(false,
  150. string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}",
  151. FormatDiagnostics(analyzer, actual)));
  152. }
  153. else
  154. {
  155. VerifyDiagnosticLocation(analyzer, actual, actual.Location, expected.Locations.First());
  156. var additionalLocations = actual.AdditionalLocations.ToArray();
  157. if (additionalLocations.Length != expected.Locations.Length - 1)
  158. Assert.True(false,
  159. string.Format(
  160. "Expected {0} additional locations but got {1} for Diagnostic:\r\n {2}\r\n",
  161. expected.Locations.Length - 1, additionalLocations.Length,
  162. FormatDiagnostics(analyzer, actual)));
  163. for (var j = 0; j < additionalLocations.Length; ++j)
  164. VerifyDiagnosticLocation(analyzer, actual, additionalLocations[j], expected.Locations[j + 1]);
  165. }
  166. if (actual.Id != expected.Id)
  167. Assert.True(false,
  168. string.Format(
  169. "Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
  170. expected.Id, actual.Id, FormatDiagnostics(analyzer, actual)));
  171. if (actual.Severity != expected.Severity)
  172. Assert.True(false,
  173. string.Format(
  174. "Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
  175. expected.Severity, actual.Severity, FormatDiagnostics(analyzer, actual)));
  176. if (actual.GetMessage() != expected.Message)
  177. Assert.True(false,
  178. string.Format(
  179. "Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
  180. expected.Message, actual.GetMessage(), FormatDiagnostics(analyzer, actual)));
  181. }
  182. }
  183. /// <summary>
  184. /// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with the location
  185. /// in the expected DiagnosticResult.
  186. /// </summary>
  187. /// <param name="analyzer">The analyzer that was being run on the sources</param>
  188. /// <param name="diagnostic">The diagnostic that was found in the code</param>
  189. /// <param name="actual">The Location of the Diagnostic found in the code</param>
  190. /// <param name="expected">The DiagnosticResultLocation that should have been found</param>
  191. private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic,
  192. Location actual, DiagnosticResultLocation expected)
  193. {
  194. var actualSpan = actual.GetLineSpan();
  195. Assert.True(
  196. actualSpan.Path == expected.Path || actualSpan.Path != null && actualSpan.Path.Contains("Test0.") &&
  197. expected.Path.Contains("Test."),
  198. string.Format(
  199. "Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
  200. expected.Path, actualSpan.Path, FormatDiagnostics(analyzer, diagnostic)));
  201. var actualLinePosition = actualSpan.StartLinePosition;
  202. // Only check line position if there is an actual line in the real diagnostic
  203. if (actualLinePosition.Line > 0)
  204. if (actualLinePosition.Line + 1 != expected.Line)
  205. Assert.True(false,
  206. string.Format(
  207. "Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
  208. expected.Line, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic)));
  209. // Only check column position if there is an actual column position in the real diagnostic
  210. if (actualLinePosition.Character <= 0) return;
  211. if (actualLinePosition.Character + 1 != expected.Column)
  212. Assert.True(false,
  213. string.Format(
  214. "Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
  215. expected.Column, actualLinePosition.Character + 1,
  216. FormatDiagnostics(analyzer, diagnostic)));
  217. }
  218. #endregion
  219. }
  220. }