예제 #1
0
  @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");
  }
예제 #2
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");
  }
예제 #3
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);
  }
예제 #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 activate_rule_override_severity() throws Exception {
    QualityProfileDto profile = createProfile("java");
    RuleDto rule = createRule(profile.getLanguage(), "toto");
    session.commit();
    ruIndexer.index();

    // 0. Assert No Active Rule for profile
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).isEmpty();

    // 1. Activate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, RuleActivationActions.ACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, profile.getKey());
    request.setParam(RuleActivationActions.RULE_KEY, rule.getKey().toString());
    request.setParam(RuleActivationActions.SEVERITY, "MINOR");
    WsTester.Result result = request.execute();
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    ActiveRuleKey activeRuleKey = ActiveRuleKey.of(profile.getKey(), rule.getKey());

    assertThat(db.activeRuleDao().selectOrFailByKey(session, activeRuleKey).getSeverityString())
        .isEqualTo("MINOR");
  }
예제 #6
0
  @Test
  public void update_description_only() throws Exception {
    MetricDto metric = insertNewMetric(ValueType.STRING);
    ComponentDto component = insertNewProject("project-uuid");
    CustomMeasureDto customMeasure =
        newCustomMeasure(component, metric)
            .setMetricId(metric.getId())
            .setComponentUuid(component.uuid())
            .setCreatedAt(system.now())
            .setDescription("custom-measure-description")
            .setTextValue("text-measure-value");
    dbClient.customMeasureDao().insert(dbSession, customMeasure);
    dbSession.commit();
    when(system.now()).thenReturn(123_456_789L);

    ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
        .setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
        .setParam(PARAM_VALUE, "new-text-measure-value")
        .execute();

    CustomMeasureDto updatedCustomMeasure =
        dbClient.customMeasureDao().selectOrFail(dbSession, customMeasure.getId());
    assertThat(updatedCustomMeasure.getTextValue()).isEqualTo("new-text-measure-value");
    assertThat(updatedCustomMeasure.getDescription()).isEqualTo("custom-measure-description");
    assertThat(updatedCustomMeasure.getUpdatedAt()).isEqualTo(123_456_789L);
    assertThat(customMeasure.getCreatedAt()).isEqualTo(updatedCustomMeasure.getCreatedAt());
  }
예제 #7
0
  @Test
  public void returns_full_object_in_response() throws Exception {
    MetricDto metric =
        MetricTesting.newMetricDto()
            .setEnabled(true)
            .setValueType(ValueType.STRING.name())
            .setKey("metric-key");
    dbClient.metricDao().insert(dbSession, metric);
    ComponentDto component = ComponentTesting.newProjectDto("project-uuid").setKey("project-key");
    dbClient.componentDao().insert(dbSession, component);
    CustomMeasureDto customMeasure =
        newCustomMeasure(component, metric)
            .setCreatedAt(100_000_000L)
            .setDescription("custom-measure-description")
            .setTextValue("text-measure-value");
    dbClient.customMeasureDao().insert(dbSession, customMeasure);
    dbSession.commit();
    when(system.now()).thenReturn(123_456_789L);

    WsTester.Result response =
        ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
            .setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
            .setParam(PARAM_DESCRIPTION, "new-custom-measure-description")
            .setParam(PARAM_VALUE, "new-text-measure-value")
            .execute();

    response.assertJson(getClass(), "custom-measure.json");
    String responseAsString = response.outputAsString();
    assertThat(responseAsString)
        .matches(String.format(".*\"id\"\\s*:\\s*\"%s\".*", customMeasure.getId()));
    assertThat(responseAsString)
        .matches(String.format(".*\"id\"\\s*:\\s*\"%s\".*", metric.getId()));
    assertThat(responseAsString).matches(".*createdAt.*updatedAt.*");
  }
 @Test(expected = IllegalArgumentException.class)
 public void add_project_missing_project() throws Exception {
   wsTester
       .newPostRequest(QProfilesWs.API_ENDPOINT, "add_project")
       .setParam("profileKey", "plouf")
       .execute();
 }
  @Test
  public void reset() throws Exception {
    QualityProfileDto profile = QProfileTesting.newXooP1();
    QualityProfileDto subProfile =
        QProfileTesting.newXooP2().setParentKee(QProfileTesting.XOO_P1_KEY);
    db.qualityProfileDao().insert(session, profile, subProfile);

    RuleDto rule = createRule(profile.getLanguage(), "rule");
    ActiveRuleDto active1 =
        ActiveRuleDto.createFor(profile, rule).setSeverity(rule.getSeverityString());
    ActiveRuleDto active2 = ActiveRuleDto.createFor(subProfile, rule).setSeverity("MINOR");
    db.activeRuleDao().insert(session, active1);
    db.activeRuleDao().insert(session, active2);

    session.commit();
    ruIndexer.index();
    activeRuIndexer.index();

    // 0. assert rule child rule is minor
    assertThat(db.activeRuleDao().selectOrFailByKey(session, active2.getKey()).getSeverityString())
        .isEqualTo("MINOR");

    // 1. reset child rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, RuleActivationActions.ACTIVATE_ACTION);
    request.setParam("profile_key", subProfile.getKey());
    request.setParam("rule_key", rule.getKey().toString());
    request.setParam("reset", "true");
    request.execute();
    session.clearCache();

    // 2. assert rule child rule is NOT minor
    assertThat(db.activeRuleDao().selectOrFailByKey(session, active2.getKey()).getSeverityString())
        .isNotEqualTo("MINOR");
  }
  @Test
  public void fail_to_update_custom_when_description_is_empty() {
    // Template rule
    RuleDto templateRule =
        ruleDao.insert(session, RuleTesting.newTemplateRule(RuleKey.of("java", "S001")));

    // Custom rule
    RuleDto customRule = RuleTesting.newCustomRule(templateRule);
    ruleDao.insert(session, customRule);
    session.commit();
    session.clearCache();

    WsTester.TestRequest request =
        wsTester
            .newPostRequest("api/rules", "update")
            .setParam("key", customRule.getKey().toString())
            .setParam("name", "My custom rule")
            .setParam("markdown_description", "");

    try {
      request.execute();
      fail();
    } catch (Exception e) {
      assertThat(e)
          .isInstanceOf(IllegalArgumentException.class)
          .hasMessage("The description is missing");
    }
  }
예제 #11
0
 @Test
 public void define_controller() throws Exception {
   WebService.Controller controller = tester.controller("api/action_plans");
   assertThat(controller).isNotNull();
   assertThat(controller.description()).isNotEmpty();
   assertThat(controller.actions()).hasSize(6);
 }
  @Test
  public void change_project_association_with_key_and_uuid() throws Exception {
    ComponentDto project = ComponentTesting.newProjectDto("ABCD").setId(1L);
    db.componentDao().insert(session, project);
    QualityProfileDto profile1 = QProfileTesting.newXooP1();
    QualityProfileDto profile2 = QProfileTesting.newXooP2();
    db.qualityProfileDao().insert(session, profile1, profile2);
    db.qualityProfileDao()
        .insertProjectProfileAssociation(project.uuid(), profile1.getKey(), session);

    session.commit();

    wsTester
        .newPostRequest(QProfilesWs.API_ENDPOINT, "add_project")
        .setParam("profileKey", profile2.getKee())
        .setParam("projectUuid", project.uuid())
        .execute()
        .assertNoContent();
    assertThat(
            tester
                .get(QProfileFactory.class)
                .getByProjectAndLanguage(session, project.getKey(), "xoo")
                .getKee())
        .isEqualTo(profile2.getKee());
  }
  @Test
  public void bulk_activate_rule_not_all() throws Exception {
    QualityProfileDto java = createProfile("java");
    QualityProfileDto php = createProfile("php");
    createRule(java.getLanguage(), "toto");
    createRule(java.getLanguage(), "tata");
    createRule(php.getLanguage(), "hello");
    createRule(php.getLanguage(), "world");
    session.commit();
    ruIndexer.index();

    // 0. Assert No Active Rule for profile
    assertThat(db.activeRuleDao().selectByProfileKey(session, php.getKey())).isEmpty();

    // 1. Activate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_ACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, php.getKey());
    request.setParam(PARAM_LANGUAGES, "php");
    request.execute().assertJson(getClass(), "bulk_activate_rule_not_all.json");
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, php.getKey())).hasSize(2);
  }
  @Test
  public void
      does_not_return_warnings_when_bulk_activate_on_profile_and_rules_exist_on_another_language_than_profile()
          throws Exception {
    QualityProfileDto javaProfile = createProfile("java");
    createRule(javaProfile.getLanguage(), "toto");
    createRule(javaProfile.getLanguage(), "tata");
    QualityProfileDto phpProfile = createProfile("php");
    createRule(phpProfile.getLanguage(), "hello");
    createRule(phpProfile.getLanguage(), "world");
    session.commit();
    ruIndexer.index();

    // 1. Activate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_ACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, javaProfile.getKey());
    request.setParam(PARAM_QPROFILE, javaProfile.getKey());
    request.setParam("activation", "false");
    request
        .execute()
        .assertJson(
            getClass(),
            "does_not_return_warnings_when_bulk_activate_on_profile_and_rules_exist_on_another_language_than_profile.json");
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, javaProfile.getKey())).hasSize(2);
  }
예제 #15
0
  @Test
  public void fail_if_not_logged_in() throws Exception {
    userSessionRule.anonymous();
    expectedException.expect(UnauthorizedException.class);
    MetricDto metric =
        MetricTesting.newMetricDto().setEnabled(true).setValueType(ValueType.STRING.name());
    dbClient.metricDao().insert(dbSession, metric);
    ComponentDto component = ComponentTesting.newProjectDto("project-uuid");
    dbClient.componentDao().insert(dbSession, component);
    CustomMeasureDto customMeasure =
        newCustomMeasureDto()
            .setMetricId(metric.getId())
            .setComponentUuid(component.uuid())
            .setCreatedAt(system.now())
            .setDescription("custom-measure-description")
            .setTextValue("text-measure-value");
    dbClient.customMeasureDao().insert(dbSession, customMeasure);
    dbSession.commit();

    ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
        .setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
        .setParam(PARAM_DESCRIPTION, "new-custom-measure-description")
        .setParam(PARAM_VALUE, "1984")
        .execute();
  }
  @Test
  public void bulk_deactivate_rule_by_profile() throws Exception {
    QualityProfileDto profile = createProfile("java");
    RuleDto rule0 = createRule(profile.getLanguage(), "hello");
    RuleDto rule1 = createRule(profile.getLanguage(), "world");
    createActiveRule(rule0, profile);
    createActiveRule(rule1, profile);
    session.commit();
    ruIndexer.index();
    activeRuIndexer.index();

    // 0. Assert No Active Rule for profile
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).hasSize(2);

    // 1. Deactivate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_DEACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, profile.getKey());
    request.setParam(WebService.Param.TEXT_QUERY, "hello");
    WsTester.Result result = request.execute();
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).hasSize(1);
  }
  @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");
  }
예제 #18
0
  @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();
  }
예제 #19
0
  @Test
  public void fail_when_permission_is_missing() throws Exception {
    expectedException.expect(IllegalArgumentException.class);

    ws.newPostRequest(PermissionsWs.ENDPOINT, ACTION)
        .setParam(PARAM_USER_LOGIN, "jrr.tolkien")
        .execute();
  }
예제 #20
0
  @Test
  public void action_pending_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("pending");

    WebService.Action action = controller.actions().iterator().next();
    assertThat(action.isPost()).isFalse();
    assertThat(action.description()).isNotEmpty();
    assertThat(action.responseExample()).isNotNull();
  }
예제 #21
0
  @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();
  }
예제 #22
0
  @Test
  public void fail_when_user_login_is_missing() throws Exception {
    expectedException.expect(IllegalArgumentException.class);

    ws.newPostRequest(PermissionsWs.ENDPOINT, ACTION)
        .setParam(PARAM_PERMISSION, SYSTEM_ADMIN)
        .execute();
  }
예제 #23
0
 @Test
 public void define_controller() throws Exception {
   WebService.Controller controller = tester.controller("api/permissions");
   assertThat(controller).isNotNull();
   assertThat(controller.description()).isNotEmpty();
   assertThat(controller.since()).isEqualTo("3.7");
   assertThat(controller.actions()).hasSize(2);
 }
예제 #24
0
  @Test
  public void define() {
    WebService.Controller controller = ws.controller("api/computation");

    assertThat(controller).isNotNull();
    assertThat(controller.description()).isNotEmpty();
    assertThat(controller.actions()).hasSize(3);
  }
예제 #25
0
  @Test
  public void define_close_action() throws Exception {
    WebService.Controller controller = tester.controller("api/action_plans");

    WebService.Action action = controller.action("close");
    assertThat(action).isNotNull();
    assertThat(action.handler()).isInstanceOf(RailsHandler.class);
    assertThat(action.params()).hasSize(2);
  }
 @Test(expected = IllegalArgumentException.class)
 public void add_project_too_many_project_parameters() throws Exception {
   wsTester
       .newPostRequest(QProfilesWs.API_ENDPOINT, "add_project")
       .setParam("profileKey", "plouf")
       .setParam("projectUuid", "polop")
       .setParam("projectKey", "palap")
       .execute();
 }
예제 #27
0
  @Test
  public void define_remove_action() throws Exception {
    WebService.Controller controller = tester.controller("api/permissions");

    WebService.Action action = controller.action("remove");
    assertThat(action).isNotNull();
    assertThat(action.handler()).isInstanceOf(RailsHandler.INSTANCE.getClass());
    assertThat(action.params()).hasSize(5);
  }
 @Test(expected = NotFoundException.class)
 public void add_project_unknown_profile() throws Exception {
   wsTester
       .newPostRequest(QProfilesWs.API_ENDPOINT, "add_project")
       .setParam("projectUuid", "plouf")
       .setParam("profileName", "polop")
       .setParam("language", "xoo")
       .execute();
 }
예제 #29
0
  @Test
  public void fail_if_custom_measure_value_and_description_are_missing_in_request()
      throws Exception {
    expectedException.expect(IllegalArgumentException.class);

    ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
        .setParam(PARAM_ID, "42")
        .execute();
  }
예제 #30
0
  @Test
  public void fail_if_custom_measure_id_is_missing_in_request() throws Exception {
    expectedException.expect(IllegalArgumentException.class);

    ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
        .setParam(PARAM_DESCRIPTION, "new-custom-measure-description")
        .setParam(PARAM_VALUE, "1984")
        .execute();
  }