Example #1
0
  @Test
  public void app_with_measures() throws Exception {
    userSessionRule.addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
    ComponentDto project = newProject();
    newComponent(project);

    addMeasure(CoreMetrics.LINES_KEY, 200);
    addMeasure(CoreMetrics.COVERAGE_KEY, 95.4);
    addMeasure(CoreMetrics.DUPLICATED_LINES_DENSITY_KEY, 7.4);
    addMeasure(CoreMetrics.SQALE_RATING_KEY, "C");
    addMeasure(CoreMetrics.SQALE_DEBT_RATIO_KEY, 35d);

    measures.add(
        new MeasureDto()
            .setComponentKey(COMPONENT_KEY)
            .setMetricKey(CoreMetrics.TECHNICAL_DEBT_KEY)
            .setValue(182.0));
    when(durations.format(
            any(Locale.class), any(Duration.class), eq(Durations.DurationFormat.SHORT)))
        .thenReturn("3h 2min");

    WsTester.TestRequest request =
        tester.newGetRequest("api/components", "app").setParam("uuid", COMPONENT_UUID);
    request.execute().assertJson(getClass(), "app_with_measures.json");

    verify(measureDao)
        .selectByComponentKeyAndMetricKeys(
            eq(session), eq(COMPONENT_KEY), measureKeysCaptor.capture());
    assertThat(measureKeysCaptor.getValue())
        .contains(
            CoreMetrics.LINES_KEY,
            CoreMetrics.COVERAGE_KEY,
            CoreMetrics.DUPLICATED_LINES_DENSITY_KEY,
            CoreMetrics.TECHNICAL_DEBT_KEY);
  }
  @Test
  public void covered_files() throws Exception {
    userSessionRule.addComponentUuidPermission(UserRole.CODEVIEWER, "SonarQube", "test-file-uuid");

    when(testIndex.searchByTestUuid(anyString()).fileUuid()).thenReturn("test-file-uuid");
    when(testIndex.coveredFiles("test-uuid"))
        .thenReturn(
            Arrays.asList(
                new CoveredFileDoc()
                    .setFileUuid("bar-uuid")
                    .setCoveredLines(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
                new CoveredFileDoc()
                    .setFileUuid("file-uuid")
                    .setCoveredLines(Arrays.asList(1, 2, 3))));
    when(dbClient.componentDao().selectByUuids(any(DbSession.class), anyList()))
        .thenReturn(
            Arrays.asList(
                newFileDto(newProjectDto(), "bar-uuid")
                    .setKey("org.foo.Bar.java")
                    .setLongName("src/main/java/org/foo/Bar.java"),
                newFileDto(newProjectDto(), "file-uuid")
                    .setKey("org.foo.File.java")
                    .setLongName("src/main/java/org/foo/File.java")));

    WsTester.TestRequest request =
        ws.newGetRequest("api/tests", "covered_files").setParam(TEST_UUID, "test-uuid");

    request.execute().assertJson(getClass(), "tests-covered-files.json");
  }
Example #3
0
  @Test
  public void list_based_on_source_file_key_and_line_number() throws Exception {
    String sourceFileUuid = "MAIN-FILE-UUID";
    String sourceFileKey = "MAIN-FILE-KEY";
    userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, TestFile1.PROJECT_UUID);
    dbClient
        .componentDao()
        .insert(
            db.getSession(),
            TestFile1.dto(),
            TestFile2.dto(),
            new ComponentDto()
                .setUuid(sourceFileUuid)
                .setUuidPath(TestFile1.PROJECT_UUID + "." + sourceFileUuid + ".")
                .setRootUuid(TestFile1.PROJECT_UUID)
                .setKey(sourceFileKey)
                .setProjectUuid(TestFile1.PROJECT_UUID));
    db.getSession().commit();

    es.putDocuments(
        TestIndexDefinition.INDEX, TestIndexDefinition.TYPE, TestFile1.doc(), TestFile2.doc());

    WsTester.TestRequest request =
        ws.newGetRequest("api/tests", "list")
            .setParam(ListAction.SOURCE_FILE_KEY, sourceFileKey)
            .setParam(ListAction.SOURCE_FILE_LINE_NUMBER, "10");

    request.execute().assertJson(getClass(), "list-main-file.json");
  }
Example #4
0
  @Test
  public void app() throws Exception {
    userSessionRule
        .login("john")
        .addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
    ComponentDto project = newProject();

    ComponentDto file =
        ComponentTesting.newFileDto(project)
            .setId(10L)
            .setKey(COMPONENT_KEY)
            .setUuid(COMPONENT_UUID)
            .setName("Plugin.java")
            .setProjectUuid("THE_PROJECT")
            .setLongName("src/main/java/org/sonar/api/Plugin.java")
            .setPath("src/main/java/org/sonar/api/Plugin.java")
            .setParentProjectId(5L);
    when(componentDao.selectByUuid(session, COMPONENT_UUID)).thenReturn(Optional.of(file));
    when(componentDao.selectOrFailById(session, 5L))
        .thenReturn(
            new ComponentDto()
                .setId(5L)
                .setLongName("SonarQube :: Plugin API")
                .setKey(SUB_PROJECT_KEY));
    when(componentDao.selectOrFailByUuid(session, project.uuid())).thenReturn(project);
    when(propertiesDao.selectByQuery(any(PropertyQuery.class), eq(session)))
        .thenReturn(newArrayList(new PropertyDto()));

    WsTester.TestRequest request =
        tester.newGetRequest("api/components", "app").setParam("uuid", COMPONENT_UUID);
    request.execute().assertJson(getClass(), "app.json");
  }
  @Test
  public void fail_when_no_uuid_or_key_param() throws Exception {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Either 'uuid' or 'key' must be provided, not both");

    WsTester.TestRequest request = wsTester.newGetRequest("api/sources", "lines");
    request.execute();
  }
  @Test(expected = ForbiddenException.class)
  public void should_check_permission() throws Exception {
    newFile();

    userSessionRule.login("login");

    wsTester.newGetRequest("api/sources", "lines").setParam("uuid", FILE_UUID).execute();
  }
Example #7
0
 @Test(expected = ForbiddenException.class)
 public void fail_when_no_sufficent_privilege_on_file_key() throws Exception {
   userSessionRule.addProjectUuidPermissions(UserRole.USER, TestFile1.PROJECT_UUID);
   dbClient.componentDao().insert(db.getSession(), TestFile1.dto());
   db.getSession().commit();
   ws.newGetRequest("api/tests", "list")
       .setParam(ListAction.TEST_FILE_KEY, TestFile1.KEY)
       .execute();
 }
Example #8
0
  @Test
  public void fail_when_test_uuid_is_unknown() throws Exception {
    expectedException.expect(NotFoundException.class);
    expectedException.expectMessage("Test with id 'unknown-test-uuid' is not found");

    ws.newGetRequest("api/tests", "list")
        .setParam(ListAction.TEST_ID, "unknown-test-uuid")
        .execute();
  }
  @Test
  public void fail_when_file_key_does_not_exist() throws Exception {
    thrown.expect(NotFoundException.class);
    thrown.expectMessage("Component key 'Foo.java' not found");

    WsTester.TestRequest request =
        wsTester.newGetRequest("api/sources", "lines").setParam("key", FILE_KEY);
    request.execute();
  }
  @Test
  public void fail_when_file_uuid_does_not_exist() throws Exception {
    thrown.expect(NotFoundException.class);
    thrown.expectMessage("Component id 'ABCD' not found");

    WsTester.TestRequest request =
        wsTester.newGetRequest("api/sources", "lines").setParam("uuid", "ABCD");
    request.execute();
  }
  @Test
  public void validate_content() throws Exception {
    String result = ws.newGetRequest(MetricsWs.ENDPOINT, "types").execute().outputAsString();

    assertThat(result)
        .contains(
            ValueType.INT.name(), ValueType.INT.description(),
            ValueType.PERCENT.name(), ValueType.PERCENT.description());
  }
  @Test
  public void fail_when_get_request() throws Exception {
    expectedException.expect(ServerException.class);

    ws.newGetRequest(PermissionsWs.ENDPOINT, ACTION)
        .setParam(PARAM_USER_LOGIN, "george.orwell")
        .setParam(PARAM_PERMISSION, SYSTEM_ADMIN)
        .execute();
  }
Example #13
0
  @Test
  public void fail_if_get_request() throws Exception {
    expectedException.expect(ServerException.class);

    ws.newGetRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
        .setParam(PARAM_ID, "42")
        .setParam(PARAM_DESCRIPTION, "new-custom-measure-description")
        .setParam(PARAM_VALUE, "1984")
        .execute();
  }
Example #14
0
  @Test
  public void app_with_it_measure() throws Exception {
    userSessionRule.addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
    ComponentDto project = newProject();
    newComponent(project);

    addMeasure(CoreMetrics.IT_COVERAGE_KEY, 85.2);

    WsTester.TestRequest request =
        tester.newGetRequest("api/components", "app").setParam("uuid", COMPONENT_UUID);
    request.execute().assertJson(getClass(), "app_with_it_measure.json");
  }
  @Test
  public void importers_nominal() throws Exception {
    WsTester wsTester =
        new WsTester(
            new QProfilesWs(
                mock(RuleActivationActions.class),
                mock(BulkRuleActivationActions.class),
                new ImportersAction(createImporters())));

    wsTester
        .newGetRequest("api/qualityprofiles", "importers")
        .execute()
        .assertJson(getClass(), "importers.json");
  }
Example #16
0
  @Test
  public void list_based_on_test_file_key() throws Exception {
    userSessionRule.addComponentPermission(
        UserRole.CODEVIEWER, TestFile1.PROJECT_UUID, TestFile1.KEY);
    dbClient.componentDao().insert(db.getSession(), TestFile1.dto());
    db.getSession().commit();

    es.putDocuments(TestIndexDefinition.INDEX, TestIndexDefinition.TYPE, TestFile1.doc());

    WsTester.TestRequest request =
        ws.newGetRequest("api/tests", "list").setParam(ListAction.TEST_FILE_KEY, TestFile1.KEY);

    request.execute().assertJson(getClass(), "list-test-uuid.json");
  }
  @Test
  public void access_forbidden_without_scan_and_preview_permission() throws Exception {
    userSessionRule.setGlobalPermissions();

    when(propertiesDao.selectGlobalProperties(session))
        .thenReturn(
            newArrayList(
                new PropertyDto().setKey("foo").setValue("bar"),
                new PropertyDto().setKey("foo.secured").setValue("1234"),
                new PropertyDto().setKey("foo.license.secured").setValue("5678")));

    thrown.expect(ForbiddenException.class);

    tester.newGetRequest("batch", "global").execute();
  }
  @Test
  public void return_global_settings() throws Exception {
    userSessionRule.setGlobalPermissions(
        GlobalPermissions.SCAN_EXECUTION, GlobalPermissions.PREVIEW_EXECUTION);

    when(propertiesDao.selectGlobalProperties(session))
        .thenReturn(
            newArrayList(
                new PropertyDto().setKey("foo").setValue("bar"),
                new PropertyDto().setKey("foo.secured").setValue("1234"),
                new PropertyDto().setKey("foo.license.secured").setValue("5678")));

    WsTester.TestRequest request = tester.newGetRequest("batch", "global");
    request.execute().assertJson(getClass(), "return_global_settings.json");
  }
  @Test
  public void fail_to_show_source_if_no_source_found() {
    newFile();

    userSessionRule.login("login").addProjectUuidPermissions(UserRole.CODEVIEWER, PROJECT_UUID);

    try {
      WsTester.TestRequest request =
          wsTester.newGetRequest("api/sources", "lines").setParam("uuid", FILE_UUID);
      request.execute();
      fail();
    } catch (Exception e) {
      assertThat(e).isInstanceOf(NotFoundException.class);
    }
  }
  @Test
  public void json_example_validated() throws Exception {
    insertNewMetricDto(newEnabledMetric("API Compatibility"));
    insertNewMetricDto(newEnabledMetric("Issues"));
    insertNewMetricDto(newEnabledMetric("Rules"));
    insertNewMetricDto(newEnabledMetric("Tests"));
    insertNewMetricDto(newEnabledMetric("Documentation"));
    insertNewMetricDto(newEnabledMetric(null));
    insertNewMetricDto(newEnabledMetric(""));
    insertNewMetricDto(newMetricDto().setDomain("Domain of Deactivated Metric").setEnabled(false));

    WsTester.Result result = ws.newGetRequest(MetricsWs.ENDPOINT, "domains").execute();

    JsonAssert.assertJson(result.outputAsString())
        .isSimilarTo(getClass().getResource("example-domains.json"));
  }
Example #21
0
  @Test
  public void fail_on_unknown_component() {
    userSessionRule
        .login("john")
        .addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
    when(componentDao.selectByUuid(session, COMPONENT_UUID))
        .thenReturn(Optional.<ComponentDto>absent());

    try {
      tester.newGetRequest("api/components", "app").setParam("uuid", COMPONENT_UUID).execute();
      fail();
    } catch (Exception e) {
      assertThat(e)
          .isInstanceOf(NotFoundException.class)
          .hasMessage("Component id 'ABCDE' not found");
    }
  }
  @Test
  public void show_source() throws Exception {
    newFile();

    dbTester
        .getDbClient()
        .fileSourceDao()
        .insert(
            new FileSourceDto()
                .setProjectUuid(PROJECT_UUID)
                .setFileUuid(FILE_UUID)
                .setSourceData(FileSourceTesting.newFakeData(3).build()));

    userSessionRule.login("login").addProjectUuidPermissions(UserRole.CODEVIEWER, PROJECT_UUID);

    WsTester.TestRequest request =
        wsTester.newGetRequest("api/sources", "lines").setParam("uuid", FILE_UUID);
    request.execute().assertJson(getClass(), "show_source.json");
  }
Example #23
0
  @Test(expected = ForbiddenException.class)
  public void fail_when_no_sufficient_privilege_on_main_file_uuid() throws Exception {
    userSessionRule.addProjectUuidPermissions(UserRole.USER, TestFile1.PROJECT_UUID);
    String mainFileUuid = "MAIN-FILE-UUID";
    dbClient
        .componentDao()
        .insert(
            db.getSession(),
            new ComponentDto()
                .setUuid(mainFileUuid)
                .setUuidPath(TestFile1.PROJECT_UUID + "." + mainFileUuid + ".")
                .setRootUuid(TestFile1.PROJECT_UUID)
                .setProjectUuid(TestFile1.PROJECT_UUID));
    db.getSession().commit();

    ws.newGetRequest("api/tests", "list")
        .setParam(ListAction.SOURCE_FILE_ID, mainFileUuid)
        .setParam(ListAction.SOURCE_FILE_LINE_NUMBER, "10")
        .execute();
  }
  @Test
  public void return_metrics() throws Exception {
    userSessionRule.setGlobalPermissions(
        GlobalPermissions.SCAN_EXECUTION, GlobalPermissions.PREVIEW_EXECUTION);

    when(metricDao.selectEnabled(session))
        .thenReturn(
            newArrayList(
                new MetricDto()
                    .setId(1)
                    .setKey("coverage")
                    .setDescription("Coverage by unit tests")
                    .setValueType("PERCENT")
                    .setQualitative(true)
                    .setWorstValue(0d)
                    .setBestValue(100d)
                    .setOptimizedBestValue(false)
                    .setDirection(1)
                    .setEnabled(true)));

    WsTester.TestRequest request = tester.newGetRequest("batch", "global");
    request.execute().assertJson(getClass(), "return_global_referentials.json");
  }
Example #25
0
public class UpdateActionTest {
  private static final String DUMMY_CONTROLLER_KEY = "dummy";
  private static final String CONTROLLER_KEY = "api/plugins";
  private static final String ACTION_KEY = "update";
  private static final String KEY_PARAM = "key";
  private static final String PLUGIN_KEY = "pluginKey";

  @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone();

  private UpdateCenterMatrixFactory updateCenterFactory = mock(UpdateCenterMatrixFactory.class);
  private UpdateCenter updateCenter = mock(UpdateCenter.class);
  private PluginDownloader pluginDownloader = mock(PluginDownloader.class);
  private UpdateAction underTest =
      new UpdateAction(updateCenterFactory, pluginDownloader, userSessionRule);

  private WsTester wsTester = new WsTester(new PluginsWs(underTest));
  private Request invalidRequest = wsTester.newGetRequest(CONTROLLER_KEY, ACTION_KEY);
  private Request validRequest =
      wsTester.newGetRequest(CONTROLLER_KEY, ACTION_KEY).setParam(KEY_PARAM, PLUGIN_KEY);
  private WsTester.TestResponse response = new WsTester.TestResponse();

  @Rule public ExpectedException expectedException = ExpectedException.none();

  @Before
  public void setUp() {
    when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.of(updateCenter));

    userSessionRule.setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
  }

  @Test
  public void user_must_have_system_admin_permission() throws Exception {
    expectedException.expect(ForbiddenException.class);
    expectedException.expectMessage("Insufficient privileges");

    // no permission on user
    userSessionRule.setGlobalPermissions();

    underTest.handle(validRequest, response);
  }

  @Test
  public void action_update_is_defined() {
    WsTester wsTester = new WsTester();
    WebService.NewController newController =
        wsTester.context().createController(DUMMY_CONTROLLER_KEY);

    underTest.define(newController);
    newController.done();

    WebService.Controller controller = wsTester.controller(DUMMY_CONTROLLER_KEY);
    assertThat(controller.actions()).extracting("key").containsExactly(ACTION_KEY);

    WebService.Action action = controller.actions().iterator().next();
    assertThat(action.isPost()).isTrue();
    assertThat(action.description()).isNotEmpty();
    assertThat(action.responseExample()).isNull();

    assertThat(action.params()).hasSize(1);
    WebService.Param key = action.param(KEY_PARAM);
    assertThat(key).isNotNull();
    assertThat(key.isRequired()).isTrue();
    assertThat(key.description()).isNotNull();
  }

  @Test
  public void IAE_is_raised_when_key_param_is_not_provided() throws Exception {
    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("Parameter 'key' is missing");

    underTest.handle(invalidRequest, response);
  }

  @Test
  public void IAE_is_raised_when_there_is_no_plugin_update_for_the_key() throws Exception {
    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("No plugin with key 'pluginKey'");

    underTest.handle(validRequest, response);
  }

  @Test
  public void IAE_is_raised_when_update_center_is_unavailable() throws Exception {
    when(updateCenterFactory.getUpdateCenter(anyBoolean()))
        .thenReturn(Optional.<UpdateCenter>absent());

    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("No plugin with key 'pluginKey'");

    underTest.handle(validRequest, response);
  }

  @Test
  public void if_plugin_has_an_update_download_is_triggered_with_latest_version_from_updatecenter()
      throws Exception {
    Version version = Version.create("1.0");
    when(updateCenter.findPluginUpdates())
        .thenReturn(
            ImmutableList.of(
                PluginUpdate.createWithStatus(
                    new Release(new Plugin(PLUGIN_KEY), version), Status.COMPATIBLE)));

    underTest.handle(validRequest, response);

    verify(pluginDownloader).download(PLUGIN_KEY, version);
    assertThat(response.outputAsString()).isEmpty();
  }
}
Example #26
0
 private TestRequest newUsersRequest() {
   return wsTester.newGetRequest("api/usergroups", "users");
 }
Example #27
0
 @Test(expected = IllegalArgumentException.class)
 public void fail_when_no_argument() throws Exception {
   ws.newGetRequest("api/tests", "list").execute();
 }
Example #28
0
 @Test(expected = IllegalArgumentException.class)
 public void fail_when_main_file_uuid_without_line_number() throws Exception {
   ws.newGetRequest("api/tests", "list").setParam(ListAction.SOURCE_FILE_ID, "ANY-UUID").execute();
 }