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.

MeasureActionTest.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 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.server.badge.ws;
  21. import com.tngtech.java.junit.dataprovider.DataProvider;
  22. import com.tngtech.java.junit.dataprovider.DataProviderRunner;
  23. import com.tngtech.java.junit.dataprovider.UseDataProvider;
  24. import java.text.ParseException;
  25. import java.text.SimpleDateFormat;
  26. import java.util.Date;
  27. import java.util.Locale;
  28. import org.junit.Rule;
  29. import org.junit.Test;
  30. import org.junit.rules.ExpectedException;
  31. import org.junit.runner.RunWith;
  32. import org.sonar.api.config.internal.MapSettings;
  33. import org.sonar.api.measures.CoreMetrics;
  34. import org.sonar.api.measures.Metric.Level;
  35. import org.sonar.api.server.ws.WebService;
  36. import org.sonar.api.server.ws.WebService.Param;
  37. import org.sonar.db.DbTester;
  38. import org.sonar.db.component.BranchType;
  39. import org.sonar.db.component.ComponentDto;
  40. import org.sonar.db.component.ComponentTesting;
  41. import org.sonar.db.metric.MetricDto;
  42. import org.sonar.db.user.UserDto;
  43. import org.sonar.server.badge.ws.SvgGenerator.Color;
  44. import org.sonar.server.component.ComponentFinder;
  45. import org.sonar.server.measure.Rating;
  46. import org.sonar.server.tester.UserSessionRule;
  47. import org.sonar.server.ws.TestResponse;
  48. import org.sonar.server.ws.WsActionTester;
  49. import static org.assertj.core.api.Assertions.assertThat;
  50. import static org.assertj.core.api.Assertions.tuple;
  51. import static org.sonar.api.measures.CoreMetrics.BUGS_KEY;
  52. import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY;
  53. import static org.sonar.api.measures.CoreMetrics.SQALE_RATING_KEY;
  54. import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY;
  55. import static org.sonar.api.measures.Metric.Level.ERROR;
  56. import static org.sonar.api.measures.Metric.Level.OK;
  57. import static org.sonar.api.measures.Metric.Level.WARN;
  58. import static org.sonar.api.measures.Metric.ValueType.INT;
  59. import static org.sonar.api.measures.Metric.ValueType.LEVEL;
  60. import static org.sonar.api.measures.Metric.ValueType.PERCENT;
  61. import static org.sonar.api.measures.Metric.ValueType.RATING;
  62. import static org.sonar.api.measures.Metric.ValueType.WORK_DUR;
  63. import static org.sonar.api.web.UserRole.USER;
  64. import static org.sonar.db.component.BranchType.BRANCH;
  65. import static org.sonar.server.badge.ws.SvgGenerator.Color.DEFAULT;
  66. import static org.sonar.server.badge.ws.SvgGenerator.Color.QUALITY_GATE_ERROR;
  67. import static org.sonar.server.badge.ws.SvgGenerator.Color.QUALITY_GATE_OK;
  68. import static org.sonar.server.badge.ws.SvgGenerator.Color.QUALITY_GATE_WARN;
  69. @RunWith(DataProviderRunner.class)
  70. public class MeasureActionTest {
  71. @Rule
  72. public ExpectedException expectedException = ExpectedException.none();
  73. @Rule
  74. public UserSessionRule userSession = UserSessionRule.standalone();
  75. @Rule
  76. public DbTester db = DbTester.create();
  77. private MapSettings mapSettings = new MapSettings().setProperty("sonar.sonarcloud.enabled", false);
  78. private WsActionTester ws = new WsActionTester(
  79. new MeasureAction(
  80. db.getDbClient(),
  81. new ProjectBadgesSupport(userSession, new ComponentFinder(db.getDbClient(), null)),
  82. new SvgGenerator(mapSettings.asConfig())));
  83. @Test
  84. public void int_measure() {
  85. ComponentDto project = db.components().insertPublicProject();
  86. userSession.registerComponents(project);
  87. MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY).setValueType(INT.name()));
  88. db.measures().insertLiveMeasure(project, metric, m -> m.setValue(10_000d));
  89. TestResponse response = ws.newRequest()
  90. .setParam("project", project.getKey())
  91. .setParam("metric", metric.getKey())
  92. .execute();
  93. checkSvg(response, "bugs", "10k", DEFAULT);
  94. // Second call with If-None-Match must return 304
  95. checkWithIfNoneMatchHeader(project, metric, response);
  96. }
  97. @Test
  98. public void percent_measure() {
  99. ComponentDto project = db.components().insertPublicProject();
  100. userSession.registerComponents(project);
  101. MetricDto metric = db.measures().insertMetric(m -> m.setKey(COVERAGE_KEY).setValueType(PERCENT.name()));
  102. db.measures().insertLiveMeasure(project, metric, m -> m.setValue(12.345d));
  103. TestResponse response = ws.newRequest()
  104. .setParam("project", project.getKey())
  105. .setParam("metric", metric.getKey())
  106. .execute();
  107. checkSvg(response, "coverage", "12.3%", DEFAULT);
  108. // Second call with If-None-Match must return 304
  109. checkWithIfNoneMatchHeader(project, metric, response);
  110. }
  111. @Test
  112. public void duration_measure() {
  113. ComponentDto project = db.components().insertPublicProject();
  114. userSession.registerComponents(project);
  115. MetricDto metric = db.measures().insertMetric(m -> m.setKey(TECHNICAL_DEBT_KEY).setValueType(WORK_DUR.name()));
  116. db.measures().insertLiveMeasure(project, metric, m -> m.setValue(10_000d));
  117. TestResponse response = ws.newRequest()
  118. .setParam("project", project.getKey())
  119. .setParam("metric", metric.getKey())
  120. .execute();
  121. checkSvg(response, "technical debt", "21d", DEFAULT);
  122. // Second call with If-None-Match must return 304
  123. checkWithIfNoneMatchHeader(project, metric, response);
  124. }
  125. @DataProvider
  126. public static Object[][] ratings() {
  127. return new Object[][] {
  128. {Rating.A, Color.RATING_A},
  129. {Rating.B, Color.RATING_B},
  130. {Rating.C, Color.RATING_C},
  131. {Rating.D, Color.RATING_D},
  132. {Rating.E, Color.RATING_E}
  133. };
  134. }
  135. @Test
  136. @UseDataProvider("ratings")
  137. public void rating_measure(Rating rating, Color color) {
  138. ComponentDto project = db.components().insertPublicProject();
  139. userSession.registerComponents(project);
  140. MetricDto metric = db.measures().insertMetric(m -> m.setKey(SQALE_RATING_KEY).setValueType(RATING.name()));
  141. db.measures().insertLiveMeasure(project, metric, m -> m.setValue((double) rating.getIndex()).setData(rating.name()));
  142. TestResponse response = ws.newRequest()
  143. .setParam("project", project.getKey())
  144. .setParam("metric", metric.getKey())
  145. .execute();
  146. checkSvg(response, "maintainability", rating.name(), color);
  147. // Second call with If-None-Match must return 304
  148. checkWithIfNoneMatchHeader(project, metric, response);
  149. }
  150. @DataProvider
  151. public static Object[][] qualityGates() {
  152. return new Object[][] {
  153. {OK, "passed", QUALITY_GATE_OK},
  154. {ERROR, "failed", QUALITY_GATE_ERROR}
  155. };
  156. }
  157. @Test
  158. @UseDataProvider("qualityGates")
  159. public void quality_gate(Level status, String expectedValue, Color expectedColor) {
  160. ComponentDto project = db.components().insertPublicProject();
  161. userSession.registerComponents(project);
  162. MetricDto metric = createQualityGateMetric();
  163. db.measures().insertLiveMeasure(project, metric, m -> m.setData(status.name()));
  164. TestResponse response = ws.newRequest()
  165. .setParam("project", project.getKey())
  166. .setParam("metric", metric.getKey())
  167. .execute();
  168. checkSvg(response, "quality gate", expectedValue, expectedColor);
  169. // Second call with If-None-Match must return 304
  170. checkWithIfNoneMatchHeader(project, metric, response);
  171. }
  172. @Test
  173. public void display_deprecated_warning_quality_gate() {
  174. ComponentDto project = db.components().insertPublicProject();
  175. userSession.registerComponents(project);
  176. MetricDto metric = createQualityGateMetric();
  177. db.measures().insertLiveMeasure(project, metric, m -> m.setData(WARN.name()));
  178. TestResponse response = ws.newRequest()
  179. .setParam("project", project.getKey())
  180. .setParam("metric", metric.getKey())
  181. .execute();
  182. checkSvg(response, "quality gate", "warning", QUALITY_GATE_WARN);
  183. }
  184. @Test
  185. public void measure_on_non_main_branch() {
  186. ComponentDto project = db.components().insertPublicProject(p -> p.setPrivate(false));
  187. userSession.registerComponents(project);
  188. MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY).setValueType(INT.name()));
  189. db.measures().insertLiveMeasure(project, metric, m -> m.setValue(5_000d));
  190. ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH));
  191. db.measures().insertLiveMeasure(branch, metric, m -> m.setValue(10_000d));
  192. TestResponse response = ws.newRequest()
  193. .setParam("project", branch.getKey())
  194. .setParam("branch", branch.getBranch())
  195. .setParam("metric", metric.getKey())
  196. .execute();
  197. checkSvg(response, "bugs", "10k", DEFAULT);
  198. // Second call with If-None-Match must return 304
  199. response = ws.newRequest()
  200. .setHeader("If-None-Match", response.getHeader("ETag"))
  201. .setParam("project", branch.getKey())
  202. .setParam("branch", branch.getBranch())
  203. .setParam("metric", metric.getKey())
  204. .execute();
  205. assertThat(response.getInput()).isEmpty();
  206. assertThat(response.getStatus()).isEqualTo(304);
  207. }
  208. @Test
  209. public void measure_on_application() {
  210. ComponentDto application = db.components().insertPublicApplication();
  211. userSession.registerComponents(application);
  212. MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY).setValueType(INT.name()));
  213. db.measures().insertLiveMeasure(application, metric, m -> m.setValue(10_000d));
  214. TestResponse response = ws.newRequest()
  215. .setParam("project", application.getKey())
  216. .setParam("metric", metric.getKey())
  217. .execute();
  218. checkSvg(response, "bugs", "10k", DEFAULT);
  219. // Second call with If-None-Match must return 304
  220. checkWithIfNoneMatchHeader(application, metric, response);
  221. }
  222. @Test
  223. public void return_error_if_project_does_not_exist() throws ParseException {
  224. MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY));
  225. TestResponse response = ws.newRequest()
  226. .setParam("project", "unknown")
  227. .setParam("metric", metric.getKey())
  228. .execute();
  229. checkError(response, "Project has not been found");
  230. }
  231. @Test
  232. public void return_error_if_branch_does_not_exist() throws ParseException {
  233. ComponentDto project = db.components().insertPublicProject();
  234. ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH));
  235. userSession.registerComponents(project);
  236. MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY));
  237. TestResponse response = ws.newRequest()
  238. .setParam("project", project.getKey())
  239. .setParam("branch", "unknown")
  240. .setParam("metric", metric.getKey())
  241. .execute();
  242. checkError(response, "Project has not been found");
  243. }
  244. @Test
  245. public void return_error_if_measure_not_found() throws ParseException {
  246. ComponentDto project = db.components().insertPublicProject();
  247. userSession.registerComponents(project);
  248. MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY));
  249. TestResponse response = ws.newRequest()
  250. .setParam("project", project.getKey())
  251. .setParam("metric", metric.getKey())
  252. .execute();
  253. checkError(response, "Measure has not been found");
  254. }
  255. @Test
  256. public void return_error_on_directory() throws ParseException {
  257. ComponentDto project = db.components().insertPublicProject();
  258. ComponentDto directory = db.components().insertComponent(ComponentTesting.newDirectory(project, "path"));
  259. userSession.registerComponents(project);
  260. MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY).setValueType(INT.name()));
  261. TestResponse response = ws.newRequest()
  262. .setParam("project", directory.getKey())
  263. .setParam("metric", metric.getKey())
  264. .execute();
  265. checkError(response, "Project has not been found");
  266. }
  267. @Test
  268. public void return_error_on_private_project() throws ParseException {
  269. ComponentDto project = db.components().insertPrivateProject();
  270. UserDto user = db.users().insertUser();
  271. userSession.logIn(user).addProjectPermission(USER, project);
  272. MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY).setValueType(INT.name()));
  273. TestResponse response = ws.newRequest()
  274. .setParam("project", project.getKey())
  275. .setParam("metric", metric.getKey())
  276. .execute();
  277. checkError(response, "Project is invalid");
  278. }
  279. @Test
  280. public void return_error_on_provisioned_project() throws ParseException {
  281. ComponentDto project = db.components().insertPublicProject();
  282. userSession.registerComponents(project);
  283. MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY).setValueType(INT.name()));
  284. TestResponse response = ws.newRequest()
  285. .setParam("project", project.getKey())
  286. .setParam("metric", metric.getKey())
  287. .execute();
  288. checkError(response, "Measure has not been found");
  289. }
  290. @Test
  291. public void return_error_if_unauthorized() throws ParseException {
  292. ComponentDto project = db.components().insertPublicProject();
  293. MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY));
  294. TestResponse response = ws.newRequest()
  295. .setParam("project", project.getKey())
  296. .setParam("metric", metric.getKey())
  297. .execute();
  298. checkError(response, "Insufficient privileges");
  299. }
  300. @Test
  301. public void fail_on_invalid_quality_gate() {
  302. ComponentDto project = db.components().insertPublicProject();
  303. userSession.registerComponents(project);
  304. MetricDto metric = createQualityGateMetric();
  305. db.measures().insertLiveMeasure(project, metric, m -> m.setData("UNKNOWN"));
  306. expectedException.expect(IllegalArgumentException.class);
  307. expectedException.expectMessage("No enum constant org.sonar.api.measures.Metric.Level.UNKNOWN");
  308. ws.newRequest()
  309. .setParam("project", project.getKey())
  310. .setParam("metric", metric.getKey())
  311. .execute();
  312. }
  313. @Test
  314. public void fail_when_measure_value_is_null() {
  315. ComponentDto project = db.components().insertPublicProject();
  316. userSession.registerComponents(project);
  317. MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY).setValueType(INT.name()));
  318. db.measures().insertLiveMeasure(project, metric, m -> m.setValue(null));
  319. expectedException.expect(IllegalStateException.class);
  320. expectedException.expectMessage("Measure has not been found");
  321. ws.newRequest()
  322. .setParam("project", project.getKey())
  323. .setParam("metric", metric.getKey())
  324. .execute();
  325. }
  326. @Test
  327. public void fail_when_metric_not_found() {
  328. ComponentDto project = db.components().insertPublicProject();
  329. userSession.registerComponents(project);
  330. expectedException.expect(IllegalStateException.class);
  331. expectedException.expectMessage("Metric 'bugs' hasn't been found");
  332. ws.newRequest()
  333. .setParam("project", project.getKey())
  334. .setParam("metric", BUGS_KEY)
  335. .execute();
  336. }
  337. @Test
  338. public void test_definition() {
  339. WebService.Action def = ws.getDef();
  340. assertThat(def.key()).isEqualTo("measure");
  341. assertThat(def.isInternal()).isFalse();
  342. assertThat(def.isPost()).isFalse();
  343. assertThat(def.since()).isEqualTo("7.1");
  344. assertThat(def.responseExampleAsString()).isNotEmpty();
  345. assertThat(def.params())
  346. .extracting(Param::key, Param::isRequired)
  347. .containsExactlyInAnyOrder(
  348. tuple("project", true),
  349. tuple("branch", false),
  350. tuple("metric", true));
  351. }
  352. private void checkSvg(TestResponse response, String expectedLabel, String expectedValue, Color expectedColorValue) {
  353. assertThat(response.getHeader("ETag")).startsWith("W/");
  354. assertThat(response.getHeader("Cache-Control")).contains("no-cache");
  355. assertThat(response.getHeader("Expires")).isNull();
  356. assertThat(response.getInput()).contains(
  357. "<text", expectedLabel + "</text>",
  358. "<text", expectedValue + "</text>",
  359. "rect fill=\"" + expectedColorValue.getValue() + "\"");
  360. }
  361. private void checkError(TestResponse response, String expectedError) throws ParseException {
  362. SimpleDateFormat expiresDateFormat = new SimpleDateFormat(ETagUtils.RFC1123_DATE, Locale.US);
  363. assertThat(response.getHeader("Cache-Control")).contains("no-cache");
  364. assertThat(response.getHeader("Expires")).isNotNull();
  365. assertThat(response.getHeader("ETag")).isNull();
  366. assertThat(expiresDateFormat.parse(response.getHeader("Expires"))).isBeforeOrEqualsTo(new Date());
  367. assertThat(response.getInput()).contains("<text", ">" + expectedError + "</text>");
  368. }
  369. private void checkWithIfNoneMatchHeader(ComponentDto application, MetricDto metric, TestResponse response) {
  370. TestResponse newResponse = ws.newRequest()
  371. .setHeader("If-None-Match", response.getHeader("ETag"))
  372. .setParam("project", application.getKey())
  373. .setParam("metric", metric.getKey())
  374. .execute();
  375. assertThat(newResponse.getInput()).isEmpty();
  376. assertThat(newResponse.getStatus()).isEqualTo(304);
  377. }
  378. private MetricDto createQualityGateMetric() {
  379. return db.measures().insertMetric(m -> m.setKey(CoreMetrics.ALERT_STATUS_KEY).setValueType(LEVEL.name()));
  380. }
  381. }