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.

ScannerMediumTester.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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.scanner.mediumtest;
  21. import com.google.common.collect.Maps;
  22. import java.io.File;
  23. import java.io.FileInputStream;
  24. import java.io.IOException;
  25. import java.io.InputStreamReader;
  26. import java.io.Reader;
  27. import java.nio.charset.StandardCharsets;
  28. import java.nio.file.Path;
  29. import java.util.ArrayList;
  30. import java.util.Collections;
  31. import java.util.Date;
  32. import java.util.HashMap;
  33. import java.util.LinkedList;
  34. import java.util.List;
  35. import java.util.Map;
  36. import java.util.Properties;
  37. import javax.annotation.CheckForNull;
  38. import javax.annotation.Nullable;
  39. import org.apache.commons.io.FileUtils;
  40. import org.junit.rules.ExternalResource;
  41. import org.sonar.api.Plugin;
  42. import org.sonar.api.SonarEdition;
  43. import org.sonar.api.SonarProduct;
  44. import org.sonar.api.SonarQubeSide;
  45. import org.sonar.api.SonarRuntime;
  46. import org.sonar.api.batch.rule.LoadedActiveRule;
  47. import org.sonar.api.impl.server.RulesDefinitionContext;
  48. import org.sonar.api.measures.CoreMetrics;
  49. import org.sonar.api.measures.Metric;
  50. import org.sonar.api.rule.RuleKey;
  51. import org.sonar.api.server.rule.RulesDefinition;
  52. import org.sonar.api.server.rule.RulesDefinition.Repository;
  53. import org.sonar.api.utils.DateUtils;
  54. import org.sonar.api.utils.Version;
  55. import org.sonar.batch.bootstrapper.Batch;
  56. import org.sonar.batch.bootstrapper.EnvironmentInformation;
  57. import org.sonar.batch.bootstrapper.LogOutput;
  58. import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
  59. import org.sonar.scanner.repository.FileData;
  60. import org.sonar.scanner.repository.MetricsRepository;
  61. import org.sonar.scanner.repository.MetricsRepositoryLoader;
  62. import org.sonar.scanner.repository.ProjectRepositories;
  63. import org.sonar.scanner.repository.ProjectRepositoriesLoader;
  64. import org.sonar.scanner.repository.QualityProfileLoader;
  65. import org.sonar.scanner.repository.SingleProjectRepository;
  66. import org.sonar.scanner.repository.settings.GlobalSettingsLoader;
  67. import org.sonar.scanner.repository.settings.ProjectSettingsLoader;
  68. import org.sonar.scanner.rule.ActiveRulesLoader;
  69. import org.sonar.scanner.rule.RulesLoader;
  70. import org.sonar.scanner.scan.ScanProperties;
  71. import org.sonar.scanner.scan.branch.BranchConfiguration;
  72. import org.sonar.scanner.scan.branch.BranchConfigurationLoader;
  73. import org.sonar.scanner.scan.branch.BranchType;
  74. import org.sonar.scanner.scan.branch.ProjectBranches;
  75. import org.sonar.scanner.scan.branch.ProjectPullRequests;
  76. import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
  77. import org.sonarqube.ws.Rules.ListResponse.Rule;
  78. /**
  79. * Main utility class for writing scanner medium tests.
  80. */
  81. public class ScannerMediumTester extends ExternalResource {
  82. private static Path userHome = null;
  83. private Map<String, String> globalProperties = new HashMap<>();
  84. private final FakeMetricsRepositoryLoader globalRefProvider = new FakeMetricsRepositoryLoader();
  85. private final FakeBranchConfigurationLoader branchConfigurationLoader = new FakeBranchConfigurationLoader();
  86. private final FakeBranchConfiguration branchConfiguration = new FakeBranchConfiguration();
  87. private final FakeProjectRepositoriesLoader projectRefProvider = new FakeProjectRepositoriesLoader();
  88. private final FakePluginInstaller pluginInstaller = new FakePluginInstaller();
  89. private final FakeGlobalSettingsLoader globalSettingsLoader = new FakeGlobalSettingsLoader();
  90. private final FakeProjectSettingsLoader projectSettingsLoader = new FakeProjectSettingsLoader();
  91. private final FakeRulesLoader rulesLoader = new FakeRulesLoader();
  92. private final FakeQualityProfileLoader qualityProfiles = new FakeQualityProfileLoader();
  93. private final FakeActiveRulesLoader activeRules = new FakeActiveRulesLoader();
  94. private final FakeSonarRuntime sonarRuntime = new FakeSonarRuntime();
  95. private LogOutput logOutput = null;
  96. private static void createWorkingDirs() throws IOException {
  97. destroyWorkingDirs();
  98. userHome = java.nio.file.Files.createTempDirectory("mediumtest-userHome");
  99. }
  100. private static void destroyWorkingDirs() throws IOException {
  101. if (userHome != null) {
  102. FileUtils.deleteDirectory(userHome.toFile());
  103. userHome = null;
  104. }
  105. }
  106. public ScannerMediumTester setLogOutput(LogOutput logOutput) {
  107. this.logOutput = logOutput;
  108. return this;
  109. }
  110. public ScannerMediumTester registerPlugin(String pluginKey, File location) {
  111. return registerPlugin(pluginKey, location, 1L);
  112. }
  113. public ScannerMediumTester registerPlugin(String pluginKey, File location, long lastUpdatedAt) {
  114. pluginInstaller.add(pluginKey, location, lastUpdatedAt);
  115. return this;
  116. }
  117. public ScannerMediumTester registerPlugin(String pluginKey, Plugin instance) {
  118. return registerPlugin(pluginKey, instance, 1L);
  119. }
  120. public ScannerMediumTester registerPlugin(String pluginKey, Plugin instance, long lastUpdatedAt) {
  121. pluginInstaller.add(pluginKey, instance, lastUpdatedAt);
  122. return this;
  123. }
  124. public ScannerMediumTester registerCoreMetrics() {
  125. for (Metric<?> m : CoreMetrics.getMetrics()) {
  126. registerMetric(m);
  127. }
  128. return this;
  129. }
  130. public ScannerMediumTester registerMetric(Metric<?> metric) {
  131. globalRefProvider.add(metric);
  132. return this;
  133. }
  134. public ScannerMediumTester addQProfile(String language, String name) {
  135. qualityProfiles.add(language, name);
  136. return this;
  137. }
  138. public ScannerMediumTester addRule(Rule rule) {
  139. rulesLoader.addRule(rule);
  140. return this;
  141. }
  142. public ScannerMediumTester addRule(String key, String repoKey, String internalKey, String name) {
  143. Rule.Builder builder = Rule.newBuilder();
  144. builder.setKey(key);
  145. builder.setRepository(repoKey);
  146. if (internalKey != null) {
  147. builder.setInternalKey(internalKey);
  148. }
  149. builder.setName(name);
  150. rulesLoader.addRule(builder.build());
  151. return this;
  152. }
  153. public ScannerMediumTester addRules(RulesDefinition rulesDefinition) {
  154. RulesDefinition.Context context = new RulesDefinitionContext();
  155. rulesDefinition.define(context);
  156. List<Repository> repositories = context.repositories();
  157. for (Repository repo : repositories) {
  158. for (RulesDefinition.Rule rule : repo.rules()) {
  159. this.addRule(rule.key(), rule.repository().key(), rule.internalKey(), rule.name());
  160. }
  161. }
  162. return this;
  163. }
  164. public ScannerMediumTester addDefaultQProfile(String language, String name) {
  165. addQProfile(language, name);
  166. return this;
  167. }
  168. public ScannerMediumTester bootstrapProperties(Map<String, String> props) {
  169. globalProperties.putAll(props);
  170. return this;
  171. }
  172. public ScannerMediumTester activateRule(LoadedActiveRule activeRule) {
  173. activeRules.addActiveRule(activeRule);
  174. return this;
  175. }
  176. public ScannerMediumTester addActiveRule(String repositoryKey, String ruleKey, @Nullable String templateRuleKey, String name, @Nullable String severity,
  177. @Nullable String internalKey, @Nullable String language) {
  178. LoadedActiveRule r = new LoadedActiveRule();
  179. r.setInternalKey(internalKey);
  180. r.setRuleKey(RuleKey.of(repositoryKey, ruleKey));
  181. r.setName(name);
  182. r.setTemplateRuleKey(templateRuleKey);
  183. r.setLanguage(language);
  184. r.setSeverity(severity);
  185. activeRules.addActiveRule(r);
  186. return this;
  187. }
  188. public ScannerMediumTester addFileData(String path, FileData fileData) {
  189. projectRefProvider.addFileData(path, fileData);
  190. return this;
  191. }
  192. public ScannerMediumTester addGlobalServerSettings(String key, String value) {
  193. globalSettingsLoader.getGlobalSettings().put(key, value);
  194. return this;
  195. }
  196. public ScannerMediumTester addProjectServerSettings(String key, String value) {
  197. projectSettingsLoader.getProjectSettings().put(key, value);
  198. return this;
  199. }
  200. @Override
  201. protected void before() {
  202. try {
  203. createWorkingDirs();
  204. } catch (IOException e) {
  205. throw new IllegalStateException(e);
  206. }
  207. registerCoreMetrics();
  208. globalProperties.put(GlobalAnalysisMode.MEDIUM_TEST_ENABLED, "true");
  209. globalProperties.put(ScanProperties.KEEP_REPORT_PROP_KEY, "true");
  210. globalProperties.put("sonar.userHome", userHome.toString());
  211. }
  212. @Override
  213. protected void after() {
  214. try {
  215. destroyWorkingDirs();
  216. } catch (IOException e) {
  217. throw new IllegalStateException(e);
  218. }
  219. }
  220. public AnalysisBuilder newAnalysis() {
  221. return new AnalysisBuilder(this);
  222. }
  223. public AnalysisBuilder newAnalysis(File sonarProps) {
  224. Properties prop = new Properties();
  225. try (Reader reader = new InputStreamReader(new FileInputStream(sonarProps), StandardCharsets.UTF_8)) {
  226. prop.load(reader);
  227. } catch (Exception e) {
  228. throw new IllegalStateException("Unable to read configuration file", e);
  229. }
  230. AnalysisBuilder builder = new AnalysisBuilder(this);
  231. builder.property("sonar.projectBaseDir", sonarProps.getParentFile().getAbsolutePath());
  232. for (Map.Entry<Object, Object> entry : prop.entrySet()) {
  233. builder.property(entry.getKey().toString(), entry.getValue().toString());
  234. }
  235. return builder;
  236. }
  237. public static class AnalysisBuilder {
  238. private final Map<String, String> taskProperties = new HashMap<>();
  239. private ScannerMediumTester tester;
  240. public AnalysisBuilder(ScannerMediumTester tester) {
  241. this.tester = tester;
  242. }
  243. public AnalysisResult execute() {
  244. AnalysisResult result = new AnalysisResult();
  245. Map<String, String> props = new HashMap<>();
  246. props.putAll(tester.globalProperties);
  247. props.putAll(taskProperties);
  248. Batch.builder()
  249. .setGlobalProperties(props)
  250. .setEnableLoggingConfiguration(true)
  251. .addComponents(new EnvironmentInformation("mediumTest", "1.0"),
  252. tester.pluginInstaller,
  253. tester.globalRefProvider,
  254. tester.qualityProfiles,
  255. tester.rulesLoader,
  256. tester.branchConfigurationLoader,
  257. tester.projectRefProvider,
  258. tester.activeRules,
  259. tester.globalSettingsLoader,
  260. tester.projectSettingsLoader,
  261. tester.sonarRuntime,
  262. result)
  263. .setLogOutput(tester.logOutput)
  264. .build().execute();
  265. return result;
  266. }
  267. public AnalysisBuilder properties(Map<String, String> props) {
  268. taskProperties.putAll(props);
  269. return this;
  270. }
  271. public AnalysisBuilder property(String key, String value) {
  272. taskProperties.put(key, value);
  273. return this;
  274. }
  275. }
  276. private static class FakeRulesLoader implements RulesLoader {
  277. private List<org.sonarqube.ws.Rules.ListResponse.Rule> rules = new LinkedList<>();
  278. public FakeRulesLoader addRule(Rule rule) {
  279. rules.add(rule);
  280. return this;
  281. }
  282. @Override
  283. public List<Rule> load() {
  284. return rules;
  285. }
  286. }
  287. private static class FakeActiveRulesLoader implements ActiveRulesLoader {
  288. private List<LoadedActiveRule> activeRules = new LinkedList<>();
  289. public void addActiveRule(LoadedActiveRule activeRule) {
  290. this.activeRules.add(activeRule);
  291. }
  292. @Override
  293. public List<LoadedActiveRule> load(String qualityProfileKey) {
  294. return activeRules;
  295. }
  296. }
  297. private static class FakeMetricsRepositoryLoader implements MetricsRepositoryLoader {
  298. private int metricId = 1;
  299. private List<Metric> metrics = new ArrayList<>();
  300. @Override
  301. public MetricsRepository load() {
  302. return new MetricsRepository(metrics);
  303. }
  304. public FakeMetricsRepositoryLoader add(Metric<?> metric) {
  305. metric.setId(metricId++);
  306. metrics.add(metric);
  307. metricId++;
  308. return this;
  309. }
  310. }
  311. private static class FakeProjectRepositoriesLoader implements ProjectRepositoriesLoader {
  312. private Map<String, FileData> fileDataMap = Maps.newHashMap();
  313. @Override
  314. public ProjectRepositories load(String projectKey, @Nullable String branchBase) {
  315. return new SingleProjectRepository(fileDataMap);
  316. }
  317. public FakeProjectRepositoriesLoader addFileData(String path, FileData fileData) {
  318. fileDataMap.put(path, fileData);
  319. return this;
  320. }
  321. }
  322. private static class FakeBranchConfiguration implements BranchConfiguration {
  323. private BranchType branchType = BranchType.LONG;
  324. private String branchName = null;
  325. private String branchTarget = null;
  326. private String longLivingSonarReferenceBranch = null;
  327. @Override
  328. public BranchType branchType() {
  329. return branchType;
  330. }
  331. @CheckForNull
  332. @Override
  333. public String branchName() {
  334. return branchName;
  335. }
  336. @CheckForNull
  337. @Override
  338. public String targetBranchName() {
  339. return branchTarget;
  340. }
  341. @CheckForNull
  342. @Override
  343. public String longLivingSonarReferenceBranch() {
  344. return longLivingSonarReferenceBranch;
  345. }
  346. @Override
  347. public String pullRequestKey() {
  348. throw new UnsupportedOperationException();
  349. }
  350. }
  351. private static class FakeSonarRuntime implements SonarRuntime {
  352. private SonarEdition edition;
  353. FakeSonarRuntime() {
  354. this.edition = SonarEdition.COMMUNITY;
  355. }
  356. @Override
  357. public Version getApiVersion() {
  358. return Version.create(7, 8);
  359. }
  360. @Override
  361. public SonarProduct getProduct() {
  362. return SonarProduct.SONARQUBE;
  363. }
  364. @Override
  365. public SonarQubeSide getSonarQubeSide() {
  366. return SonarQubeSide.SCANNER;
  367. }
  368. @Override
  369. public SonarEdition getEdition() {
  370. return edition;
  371. }
  372. public void setEdition(SonarEdition edition) {
  373. this.edition = edition;
  374. }
  375. }
  376. public ScannerMediumTester setBranchType(BranchType branchType) {
  377. branchConfiguration.branchType = branchType;
  378. return this;
  379. }
  380. public ScannerMediumTester setBranchName(String branchName) {
  381. this.branchConfiguration.branchName = branchName;
  382. return this;
  383. }
  384. public ScannerMediumTester setBranchTarget(String branchTarget) {
  385. this.branchConfiguration.branchTarget = branchTarget;
  386. return this;
  387. }
  388. public ScannerMediumTester setLongLivingSonarReferenceBranch(String longLivingSonarReferenceBranch) {
  389. this.branchConfiguration.longLivingSonarReferenceBranch = longLivingSonarReferenceBranch;
  390. return this;
  391. }
  392. public ScannerMediumTester setEdition(SonarEdition edition) {
  393. this.sonarRuntime.setEdition(edition);
  394. return this;
  395. }
  396. private class FakeBranchConfigurationLoader implements BranchConfigurationLoader {
  397. @Override
  398. public BranchConfiguration load(Map<String, String> projectSettings, ProjectBranches branches, ProjectPullRequests pullRequests) {
  399. return branchConfiguration;
  400. }
  401. }
  402. private static class FakeQualityProfileLoader implements QualityProfileLoader {
  403. private List<QualityProfile> qualityProfiles = new LinkedList<>();
  404. public void add(String language, String name) {
  405. qualityProfiles.add(QualityProfile.newBuilder()
  406. .setLanguage(language)
  407. .setKey(name)
  408. .setName(name)
  409. .setRulesUpdatedAt(DateUtils.formatDateTime(new Date(1234567891212L)))
  410. .build());
  411. }
  412. @Override
  413. public List<QualityProfile> load(String projectKey) {
  414. return qualityProfiles;
  415. }
  416. }
  417. private static class FakeGlobalSettingsLoader implements GlobalSettingsLoader {
  418. private Map<String, String> globalSettings = new HashMap<>();
  419. public Map<String, String> getGlobalSettings() {
  420. return globalSettings;
  421. }
  422. @Override
  423. public Map<String, String> loadGlobalSettings() {
  424. return Collections.unmodifiableMap(globalSettings);
  425. }
  426. }
  427. private static class FakeProjectSettingsLoader implements ProjectSettingsLoader {
  428. private Map<String, String> projectSettings = new HashMap<>();
  429. public Map<String, String> getProjectSettings() {
  430. return projectSettings;
  431. }
  432. @Override
  433. public Map<String, String> loadProjectSettings() {
  434. return Collections.unmodifiableMap(projectSettings);
  435. }
  436. }
  437. }