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

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