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

SensorContextTester.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2019 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.api.batch.sensor.internal;
  21. import java.io.File;
  22. import java.io.Serializable;
  23. import java.nio.charset.Charset;
  24. import java.nio.file.Path;
  25. import java.util.ArrayList;
  26. import java.util.Collection;
  27. import java.util.Collections;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Objects;
  31. import java.util.Set;
  32. import java.util.stream.Stream;
  33. import javax.annotation.CheckForNull;
  34. import javax.annotation.Nullable;
  35. import org.sonar.api.SonarQubeSide;
  36. import org.sonar.api.SonarRuntime;
  37. import org.sonar.api.batch.bootstrap.ProjectDefinition;
  38. import org.sonar.api.batch.fs.InputFile;
  39. import org.sonar.api.batch.fs.InputModule;
  40. import org.sonar.api.batch.fs.TextRange;
  41. import org.sonar.api.batch.fs.internal.DefaultFileSystem;
  42. import org.sonar.api.batch.fs.internal.DefaultInputFile;
  43. import org.sonar.api.batch.fs.internal.DefaultInputModule;
  44. import org.sonar.api.batch.fs.internal.DefaultTextPointer;
  45. import org.sonar.api.batch.rule.ActiveRules;
  46. import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
  47. import org.sonar.api.batch.sensor.Sensor;
  48. import org.sonar.api.batch.sensor.SensorContext;
  49. import org.sonar.api.batch.sensor.code.NewSignificantCode;
  50. import org.sonar.api.batch.sensor.code.internal.DefaultSignificantCode;
  51. import org.sonar.api.batch.sensor.coverage.NewCoverage;
  52. import org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage;
  53. import org.sonar.api.batch.sensor.cpd.NewCpdTokens;
  54. import org.sonar.api.batch.sensor.cpd.internal.DefaultCpdTokens;
  55. import org.sonar.api.batch.sensor.cpd.internal.TokensLine;
  56. import org.sonar.api.batch.sensor.error.AnalysisError;
  57. import org.sonar.api.batch.sensor.error.NewAnalysisError;
  58. import org.sonar.api.batch.sensor.error.internal.DefaultAnalysisError;
  59. import org.sonar.api.batch.sensor.highlighting.NewHighlighting;
  60. import org.sonar.api.batch.sensor.highlighting.TypeOfText;
  61. import org.sonar.api.batch.sensor.highlighting.internal.DefaultHighlighting;
  62. import org.sonar.api.batch.sensor.highlighting.internal.SyntaxHighlightingRule;
  63. import org.sonar.api.batch.sensor.issue.ExternalIssue;
  64. import org.sonar.api.batch.sensor.issue.Issue;
  65. import org.sonar.api.batch.sensor.issue.NewExternalIssue;
  66. import org.sonar.api.batch.sensor.issue.NewIssue;
  67. import org.sonar.api.batch.sensor.issue.internal.DefaultExternalIssue;
  68. import org.sonar.api.batch.sensor.issue.internal.DefaultIssue;
  69. import org.sonar.api.batch.sensor.measure.Measure;
  70. import org.sonar.api.batch.sensor.measure.NewMeasure;
  71. import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
  72. import org.sonar.api.batch.sensor.rule.AdHocRule;
  73. import org.sonar.api.batch.sensor.rule.NewAdHocRule;
  74. import org.sonar.api.batch.sensor.rule.internal.DefaultAdHocRule;
  75. import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
  76. import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable;
  77. import org.sonar.api.config.Configuration;
  78. import org.sonar.api.config.Settings;
  79. import org.sonar.api.config.internal.ConfigurationBridge;
  80. import org.sonar.api.config.internal.MapSettings;
  81. import org.sonar.api.internal.ApiVersion;
  82. import org.sonar.api.internal.SonarRuntimeImpl;
  83. import org.sonar.api.measures.Metric;
  84. import org.sonar.api.utils.System2;
  85. import org.sonar.api.utils.Version;
  86. import static java.util.Collections.unmodifiableMap;
  87. /**
  88. * Utility class to help testing {@link Sensor}. This is not an API and method signature may evolve.
  89. *
  90. * Usage: call {@link #create(File)} to create an "in memory" implementation of {@link SensorContext} with a filesystem initialized with provided baseDir.
  91. * <p>
  92. * You have to manually register inputFiles using:
  93. * <pre>
  94. * sensorContextTester.fileSystem().add(new DefaultInputFile("myProjectKey", "src/Foo.java")
  95. .setLanguage("java")
  96. .initMetadata("public class Foo {\n}"));
  97. * </pre>
  98. * <p>
  99. * Then pass it to your {@link Sensor}. You can then query elements provided by your sensor using methods {@link #allIssues()}, ...
  100. *
  101. */
  102. public class SensorContextTester implements SensorContext {
  103. private Settings settings;
  104. private DefaultFileSystem fs;
  105. private ActiveRules activeRules;
  106. private InMemorySensorStorage sensorStorage;
  107. private DefaultInputModule module;
  108. private SonarRuntime runtime;
  109. private boolean cancelled;
  110. private SensorContextTester(Path moduleBaseDir) {
  111. this.settings = new MapSettings();
  112. this.fs = new DefaultFileSystem(moduleBaseDir).setEncoding(Charset.defaultCharset());
  113. this.activeRules = new ActiveRulesBuilder().build();
  114. this.sensorStorage = new InMemorySensorStorage();
  115. this.module = new DefaultInputModule(ProjectDefinition.create().setKey("projectKey").setBaseDir(moduleBaseDir.toFile()).setWorkDir(moduleBaseDir.resolve(".sonar").toFile()));
  116. this.runtime = SonarRuntimeImpl.forSonarQube(ApiVersion.load(System2.INSTANCE), SonarQubeSide.SCANNER);
  117. }
  118. public static SensorContextTester create(File moduleBaseDir) {
  119. return new SensorContextTester(moduleBaseDir.toPath());
  120. }
  121. public static SensorContextTester create(Path moduleBaseDir) {
  122. return new SensorContextTester(moduleBaseDir);
  123. }
  124. @Override
  125. public Settings settings() {
  126. return settings;
  127. }
  128. @Override
  129. public Configuration config() {
  130. return new ConfigurationBridge(settings);
  131. }
  132. public SensorContextTester setSettings(Settings settings) {
  133. this.settings = settings;
  134. return this;
  135. }
  136. @Override
  137. public DefaultFileSystem fileSystem() {
  138. return fs;
  139. }
  140. public SensorContextTester setFileSystem(DefaultFileSystem fs) {
  141. this.fs = fs;
  142. return this;
  143. }
  144. @Override
  145. public ActiveRules activeRules() {
  146. return activeRules;
  147. }
  148. public SensorContextTester setActiveRules(ActiveRules activeRules) {
  149. this.activeRules = activeRules;
  150. return this;
  151. }
  152. /**
  153. * Default value is the version of this API at compilation time. You can override it
  154. * using {@link #setRuntime(SonarRuntime)} to test your Sensor behaviour.
  155. */
  156. @Override
  157. public Version getSonarQubeVersion() {
  158. return runtime().getApiVersion();
  159. }
  160. /**
  161. * @see #setRuntime(SonarRuntime) to override defaults (SonarQube scanner with version
  162. * of this API as used at compilation time).
  163. */
  164. @Override
  165. public SonarRuntime runtime() {
  166. return runtime;
  167. }
  168. public SensorContextTester setRuntime(SonarRuntime runtime) {
  169. this.runtime = runtime;
  170. return this;
  171. }
  172. @Override
  173. public boolean isCancelled() {
  174. return cancelled;
  175. }
  176. public void setCancelled(boolean cancelled) {
  177. this.cancelled = cancelled;
  178. }
  179. @Override
  180. public InputModule module() {
  181. return module;
  182. }
  183. @Override
  184. public <G extends Serializable> NewMeasure<G> newMeasure() {
  185. return new DefaultMeasure<>(sensorStorage);
  186. }
  187. public Collection<Measure> measures(String componentKey) {
  188. return sensorStorage.measuresByComponentAndMetric.row(componentKey).values();
  189. }
  190. public <G extends Serializable> Measure<G> measure(String componentKey, Metric<G> metric) {
  191. return measure(componentKey, metric.key());
  192. }
  193. public <G extends Serializable> Measure<G> measure(String componentKey, String metricKey) {
  194. return sensorStorage.measuresByComponentAndMetric.row(componentKey).get(metricKey);
  195. }
  196. @Override
  197. public NewIssue newIssue() {
  198. return new DefaultIssue(module, sensorStorage);
  199. }
  200. public Collection<Issue> allIssues() {
  201. return sensorStorage.allIssues;
  202. }
  203. @Override
  204. public NewExternalIssue newExternalIssue() {
  205. return new DefaultExternalIssue(module, sensorStorage);
  206. }
  207. @Override
  208. public NewAdHocRule newAdHocRule() {
  209. return new DefaultAdHocRule(sensorStorage);
  210. }
  211. public Collection<ExternalIssue> allExternalIssues() {
  212. return sensorStorage.allExternalIssues;
  213. }
  214. public Collection<AdHocRule> allAdHocRules() {
  215. return sensorStorage.allAdHocRules;
  216. }
  217. public Collection<AnalysisError> allAnalysisErrors() {
  218. return sensorStorage.allAnalysisErrors;
  219. }
  220. @CheckForNull
  221. public Integer lineHits(String fileKey, int line) {
  222. return sensorStorage.coverageByComponent.get(fileKey).stream()
  223. .map(c -> c.hitsByLine().get(line))
  224. .flatMap(Stream::of)
  225. .filter(Objects::nonNull)
  226. .reduce(null, SensorContextTester::sumOrNull);
  227. }
  228. @CheckForNull
  229. public static Integer sumOrNull(@Nullable Integer o1, @Nullable Integer o2) {
  230. return o1 == null ? o2 : (o1 + o2);
  231. }
  232. @CheckForNull
  233. public Integer conditions(String fileKey, int line) {
  234. return sensorStorage.coverageByComponent.get(fileKey).stream()
  235. .map(c -> c.conditionsByLine().get(line))
  236. .flatMap(Stream::of)
  237. .filter(Objects::nonNull)
  238. .reduce(null, SensorContextTester::maxOrNull);
  239. }
  240. @CheckForNull
  241. public Integer coveredConditions(String fileKey, int line) {
  242. return sensorStorage.coverageByComponent.get(fileKey).stream()
  243. .map(c -> c.coveredConditionsByLine().get(line))
  244. .flatMap(Stream::of)
  245. .filter(Objects::nonNull)
  246. .reduce(null, SensorContextTester::maxOrNull);
  247. }
  248. @CheckForNull
  249. public TextRange significantCodeTextRange(String fileKey, int line) {
  250. if (sensorStorage.significantCodePerComponent.containsKey(fileKey)) {
  251. return sensorStorage.significantCodePerComponent.get(fileKey)
  252. .significantCodePerLine()
  253. .get(line);
  254. }
  255. return null;
  256. }
  257. @CheckForNull
  258. public static Integer maxOrNull(@Nullable Integer o1, @Nullable Integer o2) {
  259. return o1 == null ? o2 : Math.max(o1, o2);
  260. }
  261. @CheckForNull
  262. public List<TokensLine> cpdTokens(String componentKey) {
  263. DefaultCpdTokens defaultCpdTokens = sensorStorage.cpdTokensByComponent.get(componentKey);
  264. return defaultCpdTokens != null ? defaultCpdTokens.getTokenLines() : null;
  265. }
  266. @Override
  267. public NewHighlighting newHighlighting() {
  268. return new DefaultHighlighting(sensorStorage);
  269. }
  270. @Override
  271. public NewCoverage newCoverage() {
  272. return new DefaultCoverage(sensorStorage);
  273. }
  274. @Override
  275. public NewCpdTokens newCpdTokens() {
  276. return new DefaultCpdTokens(config(), sensorStorage);
  277. }
  278. @Override
  279. public NewSymbolTable newSymbolTable() {
  280. return new DefaultSymbolTable(sensorStorage);
  281. }
  282. @Override
  283. public NewAnalysisError newAnalysisError() {
  284. return new DefaultAnalysisError(sensorStorage);
  285. }
  286. /**
  287. * Return list of syntax highlighting applied for a given position in a file. The result is a list because in theory you
  288. * can apply several styles to the same range.
  289. * @param componentKey Key of the file like 'myProjectKey:src/foo.php'
  290. * @param line Line you want to query
  291. * @param lineOffset Offset you want to query.
  292. * @return List of styles applied to this position or empty list if there is no highlighting at this position.
  293. */
  294. public List<TypeOfText> highlightingTypeAt(String componentKey, int line, int lineOffset) {
  295. DefaultHighlighting syntaxHighlightingData = sensorStorage.highlightingByComponent.get(componentKey);
  296. if (syntaxHighlightingData == null) {
  297. return Collections.emptyList();
  298. }
  299. List<TypeOfText> result = new ArrayList<>();
  300. DefaultTextPointer location = new DefaultTextPointer(line, lineOffset);
  301. for (SyntaxHighlightingRule sortedRule : syntaxHighlightingData.getSyntaxHighlightingRuleSet()) {
  302. if (sortedRule.range().start().compareTo(location) <= 0 && sortedRule.range().end().compareTo(location) > 0) {
  303. result.add(sortedRule.getTextType());
  304. }
  305. }
  306. return result;
  307. }
  308. /**
  309. * Return list of symbol references ranges for the symbol at a given position in a file.
  310. * @param componentKey Key of the file like 'myProjectKey:src/foo.php'
  311. * @param line Line you want to query
  312. * @param lineOffset Offset you want to query.
  313. * @return List of references for the symbol (potentially empty) or null if there is no symbol at this position.
  314. */
  315. @CheckForNull
  316. public Collection<TextRange> referencesForSymbolAt(String componentKey, int line, int lineOffset) {
  317. DefaultSymbolTable symbolTable = sensorStorage.symbolsPerComponent.get(componentKey);
  318. if (symbolTable == null) {
  319. return null;
  320. }
  321. DefaultTextPointer location = new DefaultTextPointer(line, lineOffset);
  322. for (Map.Entry<TextRange, Set<TextRange>> symbol : symbolTable.getReferencesBySymbol().entrySet()) {
  323. if (symbol.getKey().start().compareTo(location) <= 0 && symbol.getKey().end().compareTo(location) > 0) {
  324. return symbol.getValue();
  325. }
  326. }
  327. return null;
  328. }
  329. @Override
  330. public void addContextProperty(String key, String value) {
  331. sensorStorage.storeProperty(key, value);
  332. }
  333. /**
  334. * @return an immutable map of the context properties defined with {@link SensorContext#addContextProperty(String, String)}.
  335. * @since 6.1
  336. */
  337. public Map<String, String> getContextProperties() {
  338. return unmodifiableMap(sensorStorage.contextProperties);
  339. }
  340. @Override
  341. public void markForPublishing(InputFile inputFile) {
  342. DefaultInputFile file = (DefaultInputFile) inputFile;
  343. file.setPublished(true);
  344. }
  345. @Override
  346. public NewSignificantCode newSignificantCode() {
  347. return new DefaultSignificantCode(sensorStorage);
  348. }
  349. }