]> source.dussan.org Git - sonarqube.git/commitdiff
Complete DeactivateRuleActionTest, InheritanceActionTest, QProfilesWsMediumTest,...
authorEric Hartmann <hartmann.eric@gmail.com>
Thu, 15 Jun 2017 07:40:49 +0000 (09:40 +0200)
committerEric Hartmann <hartmann.eric@gmail.Com>
Mon, 19 Jun 2017 07:48:28 +0000 (09:48 +0200)
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionTest.java
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/InheritanceActionTest.java
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/QProfilesWsMediumTest.java
server/sonar-server/src/test/java/org/sonar/server/rule/ws/ShowActionMediumTest.java
server/sonar-server/src/test/java/org/sonar/server/rule/ws/ShowActionTest.java

index dd637e67badcf930fc6eef5325795f6717557c2f..aea31bf43490bb58854a023b7a52c3f54eabfe85 100644 (file)
  */
 package org.sonar.server.qualityprofile.ws;
 
+import java.net.HttpURLConnection;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+import org.sonar.api.rule.RuleKey;
+import org.sonar.api.server.ws.WebService;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
+import org.sonar.db.DbTester;
+import org.sonar.db.organization.OrganizationDto;
+import org.sonar.db.permission.OrganizationPermission;
+import org.sonar.db.qualityprofile.QProfileDto;
+import org.sonar.db.rule.RuleTesting;
+import org.sonar.server.exceptions.BadRequestException;
+import org.sonar.server.exceptions.ForbiddenException;
+import org.sonar.server.exceptions.UnauthorizedException;
+import org.sonar.server.organization.TestDefaultOrganizationProvider;
+import org.sonar.server.qualityprofile.RuleActivator;
+import org.sonar.server.tester.UserSessionRule;
+import org.sonar.server.ws.TestRequest;
+import org.sonar.server.ws.TestResponse;
+import org.sonar.server.ws.WsActionTester;
+
+import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.UUID_SIZE;
+
 public class DeactivateRuleActionTest {
+  @Rule
+  public DbTester db = DbTester.create();
+  @Rule
+  public UserSessionRule userSession = UserSessionRule.standalone();
+  @Rule
+  public ExpectedException thrown = ExpectedException.none();
+
+  private DbClient dbClient = db.getDbClient();
+  private RuleActivator ruleActivator = mock(RuleActivator.class);
+  private QProfileWsSupport wsSupport = new QProfileWsSupport(dbClient, userSession, TestDefaultOrganizationProvider.from(db));
+  private DeactivateRuleAction underTest = new DeactivateRuleAction(dbClient, ruleActivator, userSession, wsSupport);
+  private WsActionTester wsActionTester = new WsActionTester(underTest);
+  private OrganizationDto defaultOrganization;
+  private OrganizationDto organization;
+
+  @Before
+  public void before() {
+    defaultOrganization = db.getDefaultOrganization();
+    organization = db.organizations().insert();
+  }
+
+  @Test
+  public void define_deactivate_rule_action() {
+    WebService.Action definition = wsActionTester.getDef();
+    assertThat(definition).isNotNull();
+    assertThat(definition.isPost()).isTrue();
+    assertThat(definition.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("profile_key", "rule_key");
+  }
+
+  @Test
+  public void should_fail_if_not_logged_in() {
+    TestRequest request = wsActionTester.newRequest()
+      .setMethod("POST")
+      .setParam("rule_key", RuleTesting.newRuleDto().getKey().toString())
+      .setParam("profile_key", randomAlphanumeric(UUID_SIZE));
+
+    thrown.expect(UnauthorizedException.class);
+    request.execute();
+  }
+
+  @Test
+  public void should_fail_if_not_organization_quality_profile_administrator() {
+    userSession.logIn().addPermission(OrganizationPermission.ADMINISTER_QUALITY_PROFILES, defaultOrganization);
+    QProfileDto qualityProfile = db.qualityProfiles().insert(organization);
+    TestRequest request = wsActionTester.newRequest()
+      .setMethod("POST")
+      .setParam("rule_key", RuleTesting.newRuleDto().getKey().toString())
+      .setParam("profile_key", qualityProfile.getKee());
+
+    thrown.expect(ForbiddenException.class);
+    request.execute();
+  }
+
+  @Test
+  public void fail_deactivate_if_built_in_profile() {
+    userSession.logIn().addPermission(OrganizationPermission.ADMINISTER_QUALITY_PROFILES, defaultOrganization);
+
+    QProfileDto qualityProfile = db.qualityProfiles().insert(defaultOrganization, profile -> profile.setIsBuiltIn(true));
+    TestRequest request = wsActionTester.newRequest()
+      .setMethod("POST")
+      .setParam("rule_key", RuleTesting.newRuleDto().getKey().toString())
+      .setParam("profile_key", qualityProfile.getKee());
+
+    thrown.expect(BadRequestException.class);
+
+    request.execute();
+  }
+
+  @Test
+  public void deactivate_rule_in_default_organization() {
+    userSession.logIn().addPermission(OrganizationPermission.ADMINISTER_QUALITY_PROFILES, defaultOrganization);
+    QProfileDto qualityProfile = db.qualityProfiles().insert(defaultOrganization);
+    RuleKey ruleKey = RuleTesting.randomRuleKey();
+    TestRequest request = wsActionTester.newRequest()
+      .setMethod("POST")
+      .setParam("rule_key", ruleKey.toString())
+      .setParam("profile_key", qualityProfile.getKee());
+
+    TestResponse response = request.execute();
+
+    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
+    ArgumentCaptor<RuleKey> ruleKeyCaptor = ArgumentCaptor.forClass(RuleKey.class);
+    ArgumentCaptor<QProfileDto> qProfileDtoCaptor = ArgumentCaptor.forClass(QProfileDto.class);
+    Mockito.verify(ruleActivator).deactivateAndUpdateIndex(any(DbSession.class), qProfileDtoCaptor.capture(), ruleKeyCaptor.capture());
+    assertThat(ruleKeyCaptor.getValue()).isEqualTo(ruleKey);
+    assertThat(qProfileDtoCaptor.getValue().getKee()).isEqualTo(qualityProfile.getKee());
+  }
+
+  @Test
+  public void deactivate_rule_in_specific_organization() {
+    userSession.logIn().addPermission(OrganizationPermission.ADMINISTER_QUALITY_PROFILES, organization);
+    QProfileDto qualityProfile = db.qualityProfiles().insert(organization);
+    RuleKey ruleKey = RuleTesting.randomRuleKey();
+    TestRequest request = wsActionTester.newRequest()
+      .setMethod("POST")
+      .setParam("organization", organization.getKey())
+      .setParam("rule_key", ruleKey.toString())
+      .setParam("profile_key", qualityProfile.getKee());
+
+    TestResponse response = request.execute();
 
-//  @Rule
-//  public DbTester db = DbTester.create();
-//  @Rule
-//  public UserSessionRule userSession = UserSessionRule.standalone();
-//  @Rule
-//  public ExpectedException thrown = ExpectedException.none();
-//
-//  private DbClient dbClient = db.getDbClient();
-//  private RuleActivator ruleActivator = mock(RuleActivator.class);
-//  private QProfileWsSupport wsSupport = new QProfileWsSupport(dbClient, userSession, TestDefaultOrganizationProvider.from(db));
-//  private DeactivateRuleAction underTest = new DeactivateRuleAction(dbClient, ruleActivator, userSession, wsSupport);
-//  private WsActionTester wsActionTester = new WsActionTester(underTest);
-//  private OrganizationDto defaultOrganization;
-//  private OrganizationDto organization;
-//
-//  @Before
-//  public void before() {
-//    defaultOrganization = db.getDefaultOrganization();
-//    organization = db.organizations().insert();
-//  }
-//
-//  @Test
-//  public void define_deactivate_rule_action() {
-//    WebService.Action definition = wsActionTester.getDef();
-//    assertThat(definition).isNotNull();
-//    assertThat(definition.isPost()).isTrue();
-//    assertThat(definition.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("profile_key", "rule_key");
-//  }
-//
-//  @Test
-//  public void should_fail_if_not_logged_in() {
-//    TestRequest request = wsActionTester.newRequest()
-//      .setMethod("POST")
-//      .setParam("rule_key", RuleTesting.newRuleDto().getKey().toString())
-//      .setParam("profile_key", randomAlphanumeric(UUID_SIZE));
-//
-//    thrown.expect(UnauthorizedException.class);
-//    request.execute();
-//  }
-//
-//  @Test
-//  public void should_fail_if_not_organization_quality_profile_administrator() {
-//    userSession.logIn().addPermission(OrganizationPermission.ADMINISTER_QUALITY_PROFILES, defaultOrganization);
-//    QProfileDto qualityProfile = db.qualityProfiles().insert(organization);
-//    TestRequest request = wsActionTester.newRequest()
-//      .setMethod("POST")
-//      .setParam("rule_key", RuleTesting.newRuleDto().getKey().toString())
-//      .setParam("profile_key", qualityProfile.getKee());
-//
-//    thrown.expect(ForbiddenException.class);
-//    request.execute();
-//  }
-//
-//  @Test
-//  public void fail_deactivate_if_built_in_profile() {
-//    userSession.logIn().addPermission(OrganizationPermission.ADMINISTER_QUALITY_PROFILES, defaultOrganization);
-//
-//    QProfileDto qualityProfile = db.qualityProfiles().insert(defaultOrganization, profile -> profile.setIsBuiltIn(true));
-//    TestRequest request = wsActionTester.newRequest()
-//      .setMethod("POST")
-//      .setParam("rule_key", RuleTesting.newRuleDto().getKey().toString())
-//      .setParam("profile_key", qualityProfile.getKee());
-//
-//    thrown.expect(BadRequestException.class);
-//
-//    request.execute();
-//  }
-//
-//  @Test
-//  public void deactivate_rule_in_default_organization() {
-//    userSession.logIn().addPermission(OrganizationPermission.ADMINISTER_QUALITY_PROFILES, defaultOrganization);
-//    QProfileDto qualityProfile = db.qualityProfiles().insert(defaultOrganization);
-//    RuleKey ruleKey = RuleTesting.randomRuleKey();
-//    TestRequest request = wsActionTester.newRequest()
-//      .setMethod("POST")
-//      .setParam("rule_key", ruleKey.toString())
-//      .setParam("profile_key", qualityProfile.getKee());
-//
-//    TestResponse response = request.execute();
-//
-//    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
-//    ArgumentCaptor<ActiveRuleKey> captor = ArgumentCaptor.forClass(ActiveRuleKey.class);
-//    Mockito.verify(ruleActivator).deactivateAndUpdateIndex(any(DbSession.class), captor.capture());
-//    assertThat(captor.getValue().getRuleKey()).isEqualTo(ruleKey);
-//    assertThat(captor.getValue().getRuleProfileUuid()).isEqualTo(qualityProfile.getKee());
-//  }
-//
-//  @Test
-//  public void deactivate_rule_in_specific_organization() {
-//    userSession.logIn().addPermission(OrganizationPermission.ADMINISTER_QUALITY_PROFILES, organization);
-//    QProfileDto qualityProfile = db.qualityProfiles().insert(organization);
-//    RuleKey ruleKey = RuleTesting.randomRuleKey();
-//    TestRequest request = wsActionTester.newRequest()
-//      .setMethod("POST")
-//      .setParam("organization", organization.getKey())
-//      .setParam("rule_key", ruleKey.toString())
-//      .setParam("profile_key", qualityProfile.getKee());
-//
-//    TestResponse response = request.execute();
-//
-//    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
-//    ArgumentCaptor<ActiveRuleKey> captor = ArgumentCaptor.forClass(ActiveRuleKey.class);
-//    Mockito.verify(ruleActivator).deactivateAndUpdateIndex(any(DbSession.class), captor.capture());
-//    assertThat(captor.getValue().getRuleKey()).isEqualTo(ruleKey);
-//    assertThat(captor.getValue().getRuleProfileUuid()).isEqualTo(qualityProfile.getKee());
-//  }
+    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
+    ArgumentCaptor<RuleKey> captor = ArgumentCaptor.forClass(RuleKey.class);
+    ArgumentCaptor<QProfileDto> qProfileDtoCaptor = ArgumentCaptor.forClass(QProfileDto.class);
+    Mockito.verify(ruleActivator).deactivateAndUpdateIndex(any(DbSession.class), qProfileDtoCaptor.capture(), captor.capture());
+    assertThat(captor.getValue()).isEqualTo(ruleKey);
+    assertThat(qProfileDtoCaptor.getValue().getKee()).isEqualTo(qualityProfile.getKee());
+  }
 }
index 71417481629c3281a5e29acca413e32ed33b229b..b8a0ebcee8e41bd610b02e67b63f9dccfa5b7b03 100644 (file)
  */
 package org.sonar.server.qualityprofile.ws;
 
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Date;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.sonar.api.config.MapSettings;
+import org.sonar.api.resources.Languages;
+import org.sonar.api.rule.RuleKey;
+import org.sonar.api.rule.RuleStatus;
+import org.sonar.api.rule.Severity;
+import org.sonar.api.utils.System2;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
+import org.sonar.db.DbTester;
+import org.sonar.db.organization.OrganizationDto;
+import org.sonar.db.qualityprofile.ActiveRuleDto;
+import org.sonar.db.qualityprofile.QProfileDto;
+import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleTesting;
+import org.sonar.server.es.EsClient;
+import org.sonar.server.es.EsTester;
+import org.sonar.server.exceptions.NotFoundException;
+import org.sonar.server.organization.TestDefaultOrganizationProvider;
+import org.sonar.server.qualityprofile.QProfileLookup;
+import org.sonar.server.qualityprofile.QProfileName;
+import org.sonar.server.qualityprofile.RuleActivation;
+import org.sonar.server.qualityprofile.RuleActivator;
+import org.sonar.server.qualityprofile.RuleActivatorContextFactory;
+import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
+import org.sonar.server.qualityprofile.index.ActiveRuleIteratorFactory;
+import org.sonar.server.rule.index.RuleIndex;
+import org.sonar.server.rule.index.RuleIndexDefinition;
+import org.sonar.server.rule.index.RuleIndexer;
+import org.sonar.server.tester.UserSessionRule;
+import org.sonar.server.util.TypeValidations;
+import org.sonar.server.ws.WsActionTester;
+import org.sonar.test.JsonAssert;
+import org.sonarqube.ws.QualityProfiles.InheritanceWsResponse;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.sonar.server.qualityprofile.QProfileTesting.newQProfileDto;
+import static org.sonarqube.ws.MediaTypes.PROTOBUF;
+
 public class InheritanceActionTest {
 
-//  @Rule
-//  public DbTester dbTester = DbTester.create();
-//  @Rule
-//  public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings()));
-//  @Rule
-//  public UserSessionRule userSession = UserSessionRule.standalone();
-//
-//  private DbClient dbClient;
-//  private DbSession dbSession;
-//  private EsClient esClient;
-//  private RuleIndexer ruleIndexer;
-//  private ActiveRuleIndexer activeRuleIndexer;
-//  private InheritanceAction underTest;
-//  private WsActionTester wsActionTester;
-//  private RuleActivator ruleActivator;
-//  private OrganizationDto organization;
-//
-//  @Before
-//  public void setUp() {
-//    dbClient = dbTester.getDbClient();
-//    dbSession = dbTester.getSession();
-//    esClient = esTester.client();
-//    ruleIndexer = new RuleIndexer(esClient, dbClient);
-//    activeRuleIndexer = new ActiveRuleIndexer(dbClient, esClient, , new ActiveRuleIteratorFactory(dbClient));
-//    TestDefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(dbTester);
-//    underTest = new InheritanceAction(
-//      dbClient,
-//      new QProfileLookup(dbClient),
-//      new QProfileWsSupport(dbClient, userSession, defaultOrganizationProvider),
-//      new Languages());
-//    wsActionTester = new WsActionTester(underTest);
-//    ruleActivator = new RuleActivator(
-//      System2.INSTANCE,
-//      dbClient,
-//      new RuleIndex(esClient),
-//      new RuleActivatorContextFactory(dbClient),
-//      new TypeValidations(new ArrayList<>()),
-//      activeRuleIndexer,
-//      userSession);
-//    organization = dbTester.organizations().insert();
-//  }
-//
-//  @Test
-//  public void inheritance_nominal() throws Exception {
-//    RuleDefinitionDto rule1 = createRule("xoo", "rule1");
-//    RuleDefinitionDto rule2 = createRule("xoo", "rule2");
-//    RuleDefinitionDto rule3 = createRule("xoo", "rule3");
-//
-//    /*
-//     * sonar way (2) <- companyWide (2) <- buWide (2, 1 overriding) <- (forProject1 (2), forProject2 (2))
-//     */
-//    QProfileDto sonarway = dbTester.qualityProfiles().insert(organization, p ->
-//      p.setKee("xoo-sonar-way").setLanguage("xoo").setName("Sonar way").setIsBuiltIn(true));
-//    createActiveRule(rule1, sonarway);
-//    createActiveRule(rule2, sonarway);
-//
-//    dbSession.commit();
-//    activeRuleIndexer.index();
-//
-//    QProfileDto companyWide = createProfile("xoo", "My Company Profile", "xoo-my-company-profile-12345");
-//    setParent(sonarway, companyWide);
-//
-//    QProfileDto buWide = createProfile("xoo", "My BU Profile", "xoo-my-bu-profile-23456");
-//    setParent(companyWide, buWide);
-//    overrideActiveRuleSeverity(rule1, buWide, Severity.CRITICAL);
-//
-//    QProfileDto forProject1 = createProfile("xoo", "For Project One", "xoo-for-project-one-34567");
-//    setParent(buWide, forProject1);
-//    createActiveRule(rule3, forProject1);
-//    dbSession.commit();
-//    activeRuleIndexer.index();
-//
-//    QProfileDto forProject2 = createProfile("xoo", "For Project Two", "xoo-for-project-two-45678");
-//    setParent(buWide, forProject2);
-//    overrideActiveRuleSeverity(rule2, forProject2, Severity.CRITICAL);
-//
-//    String response = wsActionTester.newRequest()
-//      .setMethod("GET")
-//      .setParam("profileKey", buWide.getKee())
-//      .execute()
-//      .getInput();
-//
-//    JsonAssert.assertJson(response).isSimilarTo(getClass().getResource("InheritanceActionTest/inheritance-buWide.json"));
-//  }
-//
-//  @Test
-//  public void inheritance_parent_child() throws Exception {
-//    RuleDefinitionDto rule1 = dbTester.rules().insert();
-//    ruleIndexer.indexRuleDefinition(rule1.getKey());
-//
-//    RuleDefinitionDto rule2 = dbTester.rules().insert();
-//    ruleIndexer.indexRuleDefinition(rule1.getKey());
-//
-//    RuleDefinitionDto rule3 = dbTester.rules().insert();
-//    ruleIndexer.indexRuleDefinition(rule1.getKey());
-//
-//    QProfileDto parent = dbTester.qualityProfiles().insert(organization);
-//    dbTester.qualityProfiles().activateRule(parent, rule1);
-//    dbTester.qualityProfiles().activateRule(parent, rule2);
-//    long parentRules = 2;
-//
-//    QProfileDto child = dbTester.qualityProfiles().insert(organization, q -> q.setParentKee(parent.getKee()));
-//    dbTester.qualityProfiles().activateRule(child, rule3);
-//    long childRules = 1;
-//
-//    activeRuleIndexer.index();
-//
-//    InputStream response = wsActionTester.newRequest()
-//      .setMethod("GET")
-//      .setMediaType(PROTOBUF)
-//      .setParam("profileKey", child.getKee())
-//      .execute()
-//      .getInputStream();
-//
-//    InheritanceWsResponse result = InheritanceWsResponse.parseFrom(response);
-//
-//    assertThat(result.getProfile().getKey()).isEqualTo(child.getKee());
-//    assertThat(result.getProfile().getActiveRuleCount()).isEqualTo(childRules);
-//
-//    assertThat(result.getAncestorsList()).extracting(InheritanceWsResponse.QualityProfile::getKey).containsExactly(parent.getKee());
-//    assertThat(result.getAncestorsList()).extracting(InheritanceWsResponse.QualityProfile::getActiveRuleCount).containsExactly(parentRules);
-//  }
-//
-//  @Test
-//  public void inheritance_ignores_removed_rules() throws Exception {
-//    RuleDefinitionDto rule = dbTester.rules().insert(r -> r.setStatus(RuleStatus.REMOVED));
-//    ruleIndexer.indexRuleDefinition(rule.getKey());
-//
-//    QProfileDto profile = dbTester.qualityProfiles().insert(organization);
-//    dbTester.qualityProfiles().activateRule(profile, rule);
-//    long activeRules = 0;
-//
-//    activeRuleIndexer.index();
-//
-//    InputStream response = wsActionTester.newRequest()
-//      .setMethod("GET")
-//      .setMediaType(PROTOBUF)
-//      .setParam("profileKey", profile.getKee())
-//      .execute()
-//      .getInputStream();
-//
-//    InheritanceWsResponse result = InheritanceWsResponse.parseFrom(response);
-//    assertThat(result.getProfile().getKey()).isEqualTo(profile.getKee());
-//    assertThat(result.getProfile().getActiveRuleCount()).isEqualTo(activeRules);
-//  }
-//
-//  @Test
-//  public void inheritance_no_family() throws Exception {
-//    // Simple profile, no parent, no child
-//    QProfileDto remi = createProfile("xoo", "Nobodys Boy", "xoo-nobody-s-boy-01234");
-//
-//    String response = wsActionTester.newRequest()
-//      .setMethod("GET")
-//      .setParam("profileKey", remi.getKee())
-//      .execute()
-//      .getInput();
-//
-//    JsonAssert.assertJson(response).isSimilarTo(getClass().getResource("InheritanceActionTest/inheritance-simple.json"));
-//  }
-//
-//  @Test(expected = NotFoundException.class)
-//  public void fail_if_not_found() throws Exception {
-//    wsActionTester.newRequest()
-//      .setMethod("GET").setParam("profileKey", "polop").execute();
-//  }
-//
-//  private QProfileDto createProfile(String lang, String name, String key) {
-//    QProfileDto profile = newQProfileDto(organization, new QProfileName(lang, name), key);
-//    dbClient.qualityProfileDao().insert(dbSession, profile);
-//    dbSession.commit();
-//    return profile;
-//  }
-//
-//  private void setParent(QProfileDto profile, QProfileDto parent) {
-//    ruleActivator.setParent(dbSession, parent, profile);
-//  }
-//
-//  private RuleDefinitionDto createRule(String lang, String id) {
-//    long now = new Date().getTime();
-//    RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("blah", id))
-//      .setLanguage(lang)
-//      .setSeverity(Severity.BLOCKER)
-//      .setStatus(RuleStatus.READY)
-//      .setUpdatedAt(now)
-//      .setCreatedAt(now);
-//    dbClient.ruleDao().insert(dbSession, rule);
-//    dbSession.commit();
-//    ruleIndexer.indexRuleDefinition(rule.getKey());
-//    return rule;
-//  }
-//
-//  private ActiveRuleDto createActiveRule(RuleDefinitionDto rule, QProfileDto profile) {
-//    long now = new Date().getTime();
-//    ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
-//      .setSeverity(rule.getSeverityString())
-//      .setUpdatedAt(now)
-//      .setCreatedAt(now);
-//    dbClient.activeRuleDao().insert(dbSession, activeRule);
-//    return activeRule;
-//  }
-//
-//  private void overrideActiveRuleSeverity(RuleDefinitionDto rule, QProfileDto profile, String severity) {
-//    ruleActivator.activate(dbSession, new RuleActivation(rule.getKey()).setSeverity(severity), profile.getKee());
-//    dbSession.commit();
-//    activeRuleIndexer.index();
-//  }
+  @Rule
+  public DbTester dbTester = DbTester.create();
+  @Rule
+  public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings()));
+  @Rule
+  public UserSessionRule userSession = UserSessionRule.standalone();
+
+  private DbClient dbClient;
+  private DbSession dbSession;
+  private EsClient esClient;
+  private RuleIndexer ruleIndexer;
+  private ActiveRuleIndexer activeRuleIndexer;
+  private InheritanceAction underTest;
+  private WsActionTester wsActionTester;
+  private RuleActivator ruleActivator;
+  private OrganizationDto organization;
+
+  @Before
+  public void setUp() {
+    dbClient = dbTester.getDbClient();
+    dbSession = dbTester.getSession();
+    esClient = esTester.client();
+    ruleIndexer = new RuleIndexer(esClient, dbClient);
+    activeRuleIndexer = new ActiveRuleIndexer(dbClient, esClient, new ActiveRuleIteratorFactory(dbClient));
+    TestDefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(dbTester);
+    underTest = new InheritanceAction(
+      dbClient,
+      new QProfileLookup(dbClient),
+      new QProfileWsSupport(dbClient, userSession, defaultOrganizationProvider),
+      new Languages());
+    wsActionTester = new WsActionTester(underTest);
+    ruleActivator = new RuleActivator(
+      System2.INSTANCE,
+      dbClient,
+      new RuleIndex(esClient),
+      new RuleActivatorContextFactory(dbClient),
+      new TypeValidations(new ArrayList<>()),
+      activeRuleIndexer,
+      userSession);
+    organization = dbTester.organizations().insert();
+  }
+
+  @Test
+  public void inheritance_nominal() throws Exception {
+    RuleDefinitionDto rule1 = createRule("xoo", "rule1");
+    RuleDefinitionDto rule2 = createRule("xoo", "rule2");
+    RuleDefinitionDto rule3 = createRule("xoo", "rule3");
+
+    /*
+     * sonar way (2) <- companyWide (2) <- buWide (2, 1 overriding) <- (forProject1 (2), forProject2 (2))
+     */
+    QProfileDto sonarway = dbTester.qualityProfiles().insert(organization, p ->
+      p.setKee("xoo-sonar-way").setLanguage("xoo").setName("Sonar way").setIsBuiltIn(true));
+    ActiveRuleDto activeRule1 = createActiveRule(rule1, sonarway);
+    ActiveRuleDto activeRule2 = createActiveRule(rule2, sonarway);
+
+    dbSession.commit();
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    QProfileDto companyWide = createProfile("xoo", "My Company Profile", "xoo-my-company-profile-12345");
+    setParent(sonarway, companyWide);
+
+    QProfileDto buWide = createProfile("xoo", "My BU Profile", "xoo-my-bu-profile-23456");
+    setParent(companyWide, buWide);
+    overrideActiveRuleSeverity(rule1, buWide, Severity.CRITICAL);
+
+    QProfileDto forProject1 = createProfile("xoo", "For Project One", "xoo-for-project-one-34567");
+    setParent(buWide, forProject1);
+    createActiveRule(rule3, forProject1);
+    dbSession.commit();
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    QProfileDto forProject2 = createProfile("xoo", "For Project Two", "xoo-for-project-two-45678");
+    setParent(buWide, forProject2);
+    overrideActiveRuleSeverity(rule2, forProject2, Severity.CRITICAL);
+
+    String response = wsActionTester.newRequest()
+      .setMethod("GET")
+      .setParam("profileKey", buWide.getKee())
+      .execute()
+      .getInput();
+
+    JsonAssert.assertJson(response).isSimilarTo(getClass().getResource("InheritanceActionTest/inheritance-buWide.json"));
+  }
+
+  @Test
+  public void inheritance_parent_child() throws Exception {
+    RuleDefinitionDto rule1 = dbTester.rules().insert();
+    ruleIndexer.indexRuleDefinition(rule1.getKey());
+
+    RuleDefinitionDto rule2 = dbTester.rules().insert();
+    ruleIndexer.indexRuleDefinition(rule1.getKey());
+
+    RuleDefinitionDto rule3 = dbTester.rules().insert();
+    ruleIndexer.indexRuleDefinition(rule1.getKey());
+
+    QProfileDto parent = dbTester.qualityProfiles().insert(organization);
+    dbTester.qualityProfiles().activateRule(parent, rule1);
+    dbTester.qualityProfiles().activateRule(parent, rule2);
+    long parentRules = 2;
+
+    QProfileDto child = dbTester.qualityProfiles().insert(organization, q -> q.setParentKee(parent.getKee()));
+    dbTester.qualityProfiles().activateRule(child, rule3);
+    long childRules = 1;
+
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    InputStream response = wsActionTester.newRequest()
+      .setMethod("GET")
+      .setMediaType(PROTOBUF)
+      .setParam("profileKey", child.getKee())
+      .execute()
+      .getInputStream();
+
+    InheritanceWsResponse result = InheritanceWsResponse.parseFrom(response);
+
+    assertThat(result.getProfile().getKey()).isEqualTo(child.getKee());
+    assertThat(result.getProfile().getActiveRuleCount()).isEqualTo(childRules);
+
+    assertThat(result.getAncestorsList()).extracting(InheritanceWsResponse.QualityProfile::getKey).containsExactly(parent.getKee());
+    assertThat(result.getAncestorsList()).extracting(InheritanceWsResponse.QualityProfile::getActiveRuleCount).containsExactly(parentRules);
+  }
+
+  @Test
+  public void inheritance_ignores_removed_rules() throws Exception {
+    RuleDefinitionDto rule = dbTester.rules().insert(r -> r.setStatus(RuleStatus.REMOVED));
+    ruleIndexer.indexRuleDefinition(rule.getKey());
+
+    QProfileDto profile = dbTester.qualityProfiles().insert(organization);
+    dbTester.qualityProfiles().activateRule(profile, rule);
+    long activeRules = 0;
+
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    InputStream response = wsActionTester.newRequest()
+      .setMethod("GET")
+      .setMediaType(PROTOBUF)
+      .setParam("profileKey", profile.getKee())
+      .execute()
+      .getInputStream();
+
+    InheritanceWsResponse result = InheritanceWsResponse.parseFrom(response);
+    assertThat(result.getProfile().getKey()).isEqualTo(profile.getKee());
+    assertThat(result.getProfile().getActiveRuleCount()).isEqualTo(activeRules);
+  }
+
+  @Test
+  public void inheritance_no_family() throws Exception {
+    // Simple profile, no parent, no child
+    QProfileDto remi = createProfile("xoo", "Nobodys Boy", "xoo-nobody-s-boy-01234");
+
+    String response = wsActionTester.newRequest()
+      .setMethod("GET")
+      .setParam("profileKey", remi.getKee())
+      .execute()
+      .getInput();
+
+    JsonAssert.assertJson(response).isSimilarTo(getClass().getResource("InheritanceActionTest/inheritance-simple.json"));
+  }
+
+  @Test(expected = NotFoundException.class)
+  public void fail_if_not_found() throws Exception {
+    wsActionTester.newRequest()
+      .setMethod("GET").setParam("profileKey", "polop").execute();
+  }
+
+  private QProfileDto createProfile(String lang, String name, String key) {
+    QProfileDto profile = newQProfileDto(organization, new QProfileName(lang, name), key);
+    dbClient.qualityProfileDao().insert(dbSession, profile);
+    dbSession.commit();
+    return profile;
+  }
+
+  private void setParent(QProfileDto profile, QProfileDto parent) {
+    ruleActivator.setParent(dbSession, parent, profile);
+  }
+
+  private RuleDefinitionDto createRule(String lang, String id) {
+    long now = new Date().getTime();
+    RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("blah", id))
+      .setLanguage(lang)
+      .setSeverity(Severity.BLOCKER)
+      .setStatus(RuleStatus.READY)
+      .setUpdatedAt(now)
+      .setCreatedAt(now);
+    dbClient.ruleDao().insert(dbSession, rule);
+    dbSession.commit();
+    ruleIndexer.indexRuleDefinition(rule.getKey());
+    return rule;
+  }
+
+  private ActiveRuleDto createActiveRule(RuleDefinitionDto rule, QProfileDto profile) {
+    long now = new Date().getTime();
+    ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
+      .setSeverity(rule.getSeverityString())
+      .setUpdatedAt(now)
+      .setCreatedAt(now);
+    dbClient.activeRuleDao().insert(dbSession, activeRule);
+    return activeRule;
+  }
+
+  private void overrideActiveRuleSeverity(RuleDefinitionDto rule, QProfileDto profile, String severity) {
+    ruleActivator.activate(dbSession, RuleActivation.create(rule.getKey(), severity, null), profile);
+    dbSession.commit();
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+  }
 }
index 918c7c04e4d4209d70aa93f6068a69888abf2f8e..09d17df346992e4457c5cf2991f2845ca328de92 100644 (file)
  */
 package org.sonar.server.qualityprofile.ws;
 
+import com.google.common.collect.ImmutableSet;
+import java.util.Collections;
+import java.util.Optional;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.sonar.api.rule.RuleKey;
+import org.sonar.api.rule.RuleStatus;
+import org.sonar.api.rule.Severity;
+import org.sonar.api.server.ws.WebService;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
+import org.sonar.db.organization.OrganizationDto;
+import org.sonar.db.organization.OrganizationTesting;
+import org.sonar.db.qualityprofile.ActiveRuleDao;
+import org.sonar.db.qualityprofile.ActiveRuleDto;
+import org.sonar.db.qualityprofile.ActiveRuleKey;
+import org.sonar.db.qualityprofile.QProfileDto;
+import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleTesting;
+import org.sonar.server.es.SearchOptions;
+import org.sonar.server.exceptions.BadRequestException;
+import org.sonar.server.qualityprofile.QProfileName;
+import org.sonar.server.qualityprofile.QProfileTesting;
+import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
+import org.sonar.server.rule.index.RuleIndex;
+import org.sonar.server.rule.index.RuleIndexer;
+import org.sonar.server.rule.index.RuleQuery;
+import org.sonar.server.tester.ServerTester;
+import org.sonar.server.tester.UserSessionRule;
+import org.sonar.server.ws.WsTester;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.fail;
+import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_ACTIVATE_RULE;
+import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_DEACTIVATE_RULE;
+import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ActivateActionParameters.PARAM_PROFILE_KEY;
+import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ActivateActionParameters.PARAM_RULE_KEY;
+import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ActivateActionParameters.PARAM_SEVERITY;
+import static org.sonarqube.ws.client.rule.RulesWsParameters.PARAM_LANGUAGES;
+import static org.sonarqube.ws.client.rule.RulesWsParameters.PARAM_QPROFILE;
+
 public class QProfilesWsMediumTest {
 
-//  @ClassRule
-//  public static ServerTester tester = new ServerTester().withEsIndexes();
-//
-//  @Rule
-//  public UserSessionRule userSessionRule = UserSessionRule.forServerTester(tester)
-//    .logIn().setRoot();
-//
-//  private DbClient db;
-//  private DbSession session;
-//  private WsTester wsTester;
-//  private RuleIndexer ruleIndexer = tester.get(RuleIndexer.class);
-//  private ActiveRuleIndexer activeRuIndexer = tester.get(ActiveRuleIndexer.class);
-//  private OrganizationDto organization;
-//
-//  @Before
-//  public void setUp() {
-//    tester.clearDbAndIndexes();
-//    db = tester.get(DbClient.class);
-//    wsTester = tester.get(WsTester.class);
-//    session = db.openSession(false);
-//
-//    ruleIndexer = tester.get(RuleIndexer.class);
-//    activeRuIndexer = tester.get(ActiveRuleIndexer.class);
-//    organization = OrganizationTesting.newOrganizationDto().setKey("org-123");
-//    db.organizationDao().insert(session, organization, false);
-//  }
-//
-//  @After
-//  public void after() {
-//    session.close();
-//  }
-//
-//  @Test
-//  public void deactivate_rule() throws Exception {
-//    QProfileDto profile = createProfile("java");
-//    RuleDefinitionDto rule = createRule(profile.getLanguage(), "toto");
-//    createActiveRule(rule, profile);
-//    session.commit();
-//    ruleIndexer.indexRuleDefinition(rule.getKey());
-//    activeRuIndexer.index();
-//
-//    // 0. Assert No Active Rule for profile
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(1);
-//
-//    // 1. Deactivate Rule
-//    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ACTION_DEACTIVATE_RULE);
-//    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
-//    request.setParam(PARAM_RULE_KEY, rule.getKey().toString());
-//    request.execute();
-//    session.clearCache();
-//
-//    // 2. Assert ActiveRule in DAO
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
-//  }
-//
-//  @Test
-//  public void bulk_deactivate_rule() throws Exception {
-//    QProfileDto profile = createProfile("java");
-//    RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "toto1");
-//    RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "toto2");
-//    RuleDefinitionDto rule2 = createRule(profile.getLanguage(), "toto3");
-//    RuleDefinitionDto rule3 = createRule(profile.getLanguage(), "toto4");
-//    createActiveRule(rule0, profile);
-//    createActiveRule(rule2, profile);
-//    createActiveRule(rule3, profile);
-//    createActiveRule(rule1, profile);
-//    session.commit();
-//    activeRuIndexer.index();
-//
-//    // 0. Assert No Active Rule for profile
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(4);
-//
-//    // 1. Deactivate Rule
-//    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, DeactivateRulesAction.DEACTIVATE_RULES_ACTION);
-//    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
-//    WsTester.Result result = request.execute();
-//    session.clearCache();
-//
-//    // 2. Assert ActiveRule in DAO
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
-//  }
-//
-//  @Test
-//  public void bulk_deactivate_rule_not_all() throws Exception {
-//    QProfileDto profile = createProfile("java");
-//    QProfileDto php = createProfile("php");
-//    RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "toto1");
-//    RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "toto2");
-//    createActiveRule(rule0, profile);
-//    createActiveRule(rule1, profile);
-//    createActiveRule(rule0, php);
-//    createActiveRule(rule1, php);
-//    session.commit();
-//    activeRuIndexer.index();
-//
-//    // 0. Assert No Active Rule for profile
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(2);
-//
-//    // 1. Deactivate Rule
-//    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, DeactivateRulesAction.DEACTIVATE_RULES_ACTION);
-//    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
-//    WsTester.Result result = request.execute();
-//    session.clearCache();
-//
-//    // 2. Assert ActiveRule in DAO
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(0);
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, php.getKee())).hasSize(2);
-//  }
-//
-//  @Test
-//  public void bulk_deactivate_rule_by_profile() throws Exception {
-//    QProfileDto profile = createProfile("java");
-//    RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "hello");
-//    RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "world");
-//    createActiveRule(rule0, profile);
-//    createActiveRule(rule1, profile);
-//    session.commit();
-//    activeRuIndexer.index();
-//
-//    // 0. Assert No Active Rule for profile
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(2);
-//
-//    // 1. Deactivate Rule
-//    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, DeactivateRulesAction.DEACTIVATE_RULES_ACTION);
-//    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
-//    request.setParam(WebService.Param.TEXT_QUERY, "hello");
-//    WsTester.Result result = request.execute();
-//    session.clearCache();
-//
-//    // 2. Assert ActiveRule in DAO
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(1);
-//  }
-//
-//  @Test
-//  public void activate_rule() throws Exception {
-//    QProfileDto profile = createProfile("java");
-//    RuleDefinitionDto rule = createRule(profile.getLanguage(), "toto");
-//    session.commit();
-//    ruleIndexer.indexRuleDefinition(rule.getKey());
-//
-//    // 0. Assert No Active Rule for profile
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
-//
-//    // 1. Activate Rule
-//    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ACTION_ACTIVATE_RULE);
-//    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
-//    request.setParam(PARAM_RULE_KEY, rule.getKey().toString());
-//    WsTester.Result result = request.execute();
-//    session.clearCache();
-//
-//    // 2. Assert ActiveRule in DAO
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(1);
-//  }
-//
-//  @Test
-//  public void activate_rule_diff_languages() throws Exception {
-//    QProfileDto profile = createProfile("java");
-//    RuleDefinitionDto rule = createRule("php", "toto");
-//    session.commit();
-//    ruleIndexer.indexRuleDefinition(rule.getKey());
-//
-//    // 0. Assert No Active Rule for profile
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
-//
-//    try {
-//      // 1. Activate Rule
-//      WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ACTION_ACTIVATE_RULE);
-//      request.setParam(PARAM_PROFILE_KEY, profile.getKee());
-//      request.setParam(PARAM_RULE_KEY, rule.getKey().toString());
-//      request.execute();
-//      session.clearCache();
-//      fail();
-//    } catch (BadRequestException e) {
-//      assertThat(e.getMessage()).isEqualTo("Rule blah:toto and profile pjava have different languages");
-//    }
-//  }
-//
-//  @Test
-//  public void activate_rule_override_severity() throws Exception {
-//    QProfileDto profile = createProfile("java");
-//    RuleDefinitionDto rule = createRule(profile.getLanguage(), "toto");
-//    session.commit();
-//    ruleIndexer.indexRuleDefinition(rule.getKey());
-//
-//    // 0. Assert No Active Rule for profile
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
-//
-//    // 1. Activate Rule
-//    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ACTION_ACTIVATE_RULE);
-//    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
-//    request.setParam(PARAM_RULE_KEY, rule.getKey().toString());
-//    request.setParam(PARAM_SEVERITY, "MINOR");
-//    WsTester.Result result = request.execute();
-//    session.clearCache();
-//
-//    // 2. Assert ActiveRule in DAO
-//    ActiveRuleKey activeRuleKey = ActiveRuleKey.of(profile.getKee(), rule.getKey());
-//
-//    assertThat(db.activeRuleDao().selectOrFailByKey(session, activeRuleKey).getSeverityString())
-//      .isEqualTo("MINOR");
-//  }
-//
-//  @Test
-//  public void bulk_activate_rule() throws Exception {
-//    QProfileDto profile = createProfile("java");
-//    createRule(profile.getLanguage(), "toto");
-//    createRule(profile.getLanguage(), "tata");
-//    createRule(profile.getLanguage(), "hello");
-//    createRule(profile.getLanguage(), "world");
-//    session.commit();
-//
-//    // 0. Assert No Active Rule for profile
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
-//
-//    // 1. Activate Rule
-//    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
-//    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
-//    request.setParam(PARAM_LANGUAGES, "java");
-//    request.execute().assertJson(getClass(), "bulk_activate_rule.json");
-//    session.clearCache();
-//
-//    // 2. Assert ActiveRule in DAO
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(4);
-//  }
-//
-//  @Test
-//  public void bulk_activate_rule_not_all() throws Exception {
-//    QProfileDto java = createProfile("java");
-//    QProfileDto php = createProfile("php");
-//    createRule(java.getLanguage(), "toto");
-//    createRule(java.getLanguage(), "tata");
-//    createRule(php.getLanguage(), "hello");
-//    createRule(php.getLanguage(), "world");
-//    session.commit();
-//
-//    // 0. Assert No Active Rule for profile
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, php.getKee())).isEmpty();
-//
-//    // 1. Activate Rule
-//    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
-//    request.setParam(PARAM_PROFILE_KEY, php.getKee());
-//    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().selectByProfileUuid(session, php.getKee())).hasSize(2);
-//  }
-//
-//  @Test
-//  public void bulk_activate_rule_by_query() throws Exception {
-//    QProfileDto profile = createProfile("java");
-//    createRule(profile.getLanguage(), "toto");
-//    createRule(profile.getLanguage(), "tata");
-//    createRule(profile.getLanguage(), "hello");
-//    createRule(profile.getLanguage(), "world");
-//    session.commit();
-//
-//    // 0. Assert No Active Rule for profile
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
-//
-//    // 1. Activate Rule with query returning 0 hits
-//    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
-//    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
-//    request.setParam(WebService.Param.TEXT_QUERY, "php");
-//    request.execute();
-//    session.clearCache();
-//
-//    // 2. Assert ActiveRule in DAO
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(0);
-//
-//    // 1. Activate Rule with query returning 1 hits
-//    request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
-//    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
-//    request.setParam(WebService.Param.TEXT_QUERY, "world");
-//    request.execute();
-//    session.commit();
-//
-//    // 2. Assert ActiveRule in DAO
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(1);
-//  }
-//
-//  @Test
-//  public void bulk_activate_rule_by_query_with_severity() throws Exception {
-//    QProfileDto profile = createProfile("java");
-//    RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "toto");
-//    RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "tata");
-//    session.commit();
-//
-//    // 0. Assert No Active Rule for profile
-//    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
-//
-//    // 2. Assert ActiveRule with BLOCKER severity
-//    assertThat(tester.get(RuleIndex.class).search(
-//      new RuleQuery().setSeverities(ImmutableSet.of("BLOCKER")),
-//      new SearchOptions()).getIds()).hasSize(2);
-//
-//    // 1. Activate Rule with query returning 2 hits
-//    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
-//    request.setParam(ActivateRulesAction.PROFILE_KEY, profile.getKee());
-//    request.setParam(ActivateRulesAction.SEVERITY, "MINOR");
-//    request.execute();
-//    session.commit();
-//
-//    // 2. Assert ActiveRule with MINOR severity
-//    assertThat(tester.get(ActiveRuleDao.class).selectByRuleId(session, organization, rule0.getId()).get(0).getSeverityString()).isEqualTo("MINOR");
-//    assertThat(tester.get(RuleIndex.class).searchAll(new RuleQuery()
-//      .setQProfileKey(profile.getKee())
-//      .setKey(rule0.getKey().toString())
-//      .setActiveSeverities(Collections.singleton("MINOR"))
-//      .setActivation(true))).hasSize(1);
-//  }
-//
-//  @Test
-//  public void does_not_return_warnings_when_bulk_activate_on_profile_and_rules_exist_on_another_language_than_profile() throws Exception {
-//    QProfileDto javaProfile = createProfile("java");
-//    createRule(javaProfile.getLanguage(), "toto");
-//    createRule(javaProfile.getLanguage(), "tata");
-//    QProfileDto phpProfile = createProfile("php");
-//    createRule(phpProfile.getLanguage(), "hello");
-//    createRule(phpProfile.getLanguage(), "world");
-//    session.commit();
-//
-//    // 1. Activate Rule
-//    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
-//    request.setParam(PARAM_PROFILE_KEY, javaProfile.getKee());
-//    request.setParam(PARAM_QPROFILE, javaProfile.getKee());
-//    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().selectByProfileUuid(session, javaProfile.getKee())).hasSize(2);
-//  }
-//
-//  @Test
-//  public void reset() throws Exception {
-//    QProfileDto profile = QProfileTesting.newXooP1(organization);
-//    QProfileDto subProfile = QProfileTesting.newXooP2(organization).setParentKee(QProfileTesting.XOO_P1_KEY);
-//    db.qualityProfileDao().insert(session, profile, subProfile);
-//
-//    RuleDefinitionDto 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();
-//    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, ACTION_ACTIVATE_RULE);
-//    request.setParam("profile_key", subProfile.getKee());
-//    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");
-//  }
-//
-//  private QProfileDto createProfile(String lang) {
-//    QProfileDto profile = QProfileTesting.newQProfileDto(organization, new QProfileName(lang, "P" + lang), "p" + lang);
-//    db.qualityProfileDao().insert(session, profile);
-//    return profile;
-//  }
-//
-//  private RuleDefinitionDto createRule(String lang, String id) {
-//    RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("blah", id))
-//      .setLanguage(lang)
-//      .setSeverity(Severity.BLOCKER)
-//      .setStatus(RuleStatus.READY);
-//    db.ruleDao().insert(session, rule);
-//    session.commit();
-//    ruleIndexer.indexRuleDefinition(rule.getKey());
-//    return rule;
-//  }
-//
-//  private ActiveRuleDto createActiveRule(RuleDefinitionDto rule, QProfileDto profile) {
-//    ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
-//      .setSeverity(rule.getSeverityString());
-//    db.activeRuleDao().insert(session, activeRule);
-//    return activeRule;
-//  }
+  @ClassRule
+  public static ServerTester tester = new ServerTester().withEsIndexes();
+
+  @Rule
+  public UserSessionRule userSessionRule = UserSessionRule.forServerTester(tester)
+    .logIn().setRoot();
+
+  private DbClient db;
+  private DbSession session;
+  private WsTester wsTester;
+  private RuleIndexer ruleIndexer = tester.get(RuleIndexer.class);
+  private ActiveRuleIndexer activeRuleIndexer = tester.get(ActiveRuleIndexer.class);
+  private OrganizationDto organization;
+
+  @Before
+  public void setUp() {
+    tester.clearDbAndIndexes();
+    db = tester.get(DbClient.class);
+    wsTester = tester.get(WsTester.class);
+    session = db.openSession(false);
+
+    ruleIndexer = tester.get(RuleIndexer.class);
+    activeRuleIndexer = tester.get(ActiveRuleIndexer.class);
+    organization = OrganizationTesting.newOrganizationDto().setKey("org-123");
+    db.organizationDao().insert(session, organization, false);
+  }
+
+  @After
+  public void after() {
+    session.close();
+  }
+
+  @Test
+  public void deactivate_rule() throws Exception {
+    QProfileDto profile = createProfile("java");
+    RuleDefinitionDto rule = createRule(profile.getLanguage(), "toto");
+    createActiveRule(rule, profile);
+    session.commit();
+    ruleIndexer.indexRuleDefinition(rule.getKey());
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    // 0. Assert No Active Rule for profile
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(1);
+
+    // 1. Deactivate Rule
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ACTION_DEACTIVATE_RULE);
+    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
+    request.setParam(PARAM_RULE_KEY, rule.getKey().toString());
+    request.execute();
+    session.clearCache();
+
+    // 2. Assert ActiveRule in DAO
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
+  }
+
+  @Test
+  public void bulk_deactivate_rule() throws Exception {
+    QProfileDto profile = createProfile("java");
+    RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "toto1");
+    RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "toto2");
+    RuleDefinitionDto rule2 = createRule(profile.getLanguage(), "toto3");
+    RuleDefinitionDto rule3 = createRule(profile.getLanguage(), "toto4");
+    createActiveRule(rule0, profile);
+    createActiveRule(rule2, profile);
+    createActiveRule(rule3, profile);
+    createActiveRule(rule1, profile);
+    session.commit();
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    // 0. Assert No Active Rule for profile
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(4);
+
+    // 1. Deactivate Rule
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, DeactivateRulesAction.DEACTIVATE_RULES_ACTION);
+    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
+    WsTester.Result result = request.execute();
+    session.clearCache();
+
+    // 2. Assert ActiveRule in DAO
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
+  }
+
+  @Test
+  public void bulk_deactivate_rule_not_all() throws Exception {
+    QProfileDto profile = createProfile("java");
+    QProfileDto php = createProfile("php");
+    RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "toto1");
+    RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "toto2");
+    createActiveRule(rule0, profile);
+    createActiveRule(rule1, profile);
+    createActiveRule(rule0, php);
+    createActiveRule(rule1, php);
+    session.commit();
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    // 0. Assert No Active Rule for profile
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(2);
+
+    // 1. Deactivate Rule
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, DeactivateRulesAction.DEACTIVATE_RULES_ACTION);
+    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
+    WsTester.Result result = request.execute();
+    session.clearCache();
+
+    // 2. Assert ActiveRule in DAO
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(0);
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, php.getKee())).hasSize(2);
+  }
+
+  @Test
+  public void bulk_deactivate_rule_by_profile() throws Exception {
+    QProfileDto profile = createProfile("java");
+    RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "hello");
+    RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "world");
+    createActiveRule(rule0, profile);
+    createActiveRule(rule1, profile);
+    session.commit();
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    // 0. Assert No Active Rule for profile
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(2);
+
+    // 1. Deactivate Rule
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, DeactivateRulesAction.DEACTIVATE_RULES_ACTION);
+    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
+    request.setParam(WebService.Param.TEXT_QUERY, "hello");
+    WsTester.Result result = request.execute();
+    session.clearCache();
+
+    // 2. Assert ActiveRule in DAO
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(1);
+  }
+
+  @Test
+  public void activate_rule() throws Exception {
+    QProfileDto profile = createProfile("java");
+    RuleDefinitionDto rule = createRule(profile.getLanguage(), "toto");
+    session.commit();
+    ruleIndexer.indexRuleDefinition(rule.getKey());
+
+    // 0. Assert No Active Rule for profile
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
+
+    // 1. Activate Rule
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ACTION_ACTIVATE_RULE);
+    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
+    request.setParam(PARAM_RULE_KEY, rule.getKey().toString());
+    WsTester.Result result = request.execute();
+    session.clearCache();
+
+    // 2. Assert ActiveRule in DAO
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(1);
+  }
+
+  @Test
+  public void activate_rule_diff_languages() throws Exception {
+    QProfileDto profile = createProfile("java");
+    RuleDefinitionDto rule = createRule("php", "toto");
+    session.commit();
+    ruleIndexer.indexRuleDefinition(rule.getKey());
+
+    // 0. Assert No Active Rule for profile
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
+
+    try {
+      // 1. Activate Rule
+      WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ACTION_ACTIVATE_RULE);
+      request.setParam(PARAM_PROFILE_KEY, profile.getKee());
+      request.setParam(PARAM_RULE_KEY, rule.getKey().toString());
+      request.execute();
+      session.clearCache();
+      fail();
+    } catch (BadRequestException e) {
+      assertThat(e.getMessage()).isEqualTo("Rule blah:toto and profile pjava have different languages");
+    }
+  }
+
+  @Test
+  public void activate_rule_override_severity() throws Exception {
+    QProfileDto profile = createProfile("java");
+    RuleDefinitionDto rule = createRule(profile.getLanguage(), "toto");
+    session.commit();
+    ruleIndexer.indexRuleDefinition(rule.getKey());
+
+    // 0. Assert No Active Rule for profile
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
+
+    // 1. Activate Rule
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ACTION_ACTIVATE_RULE);
+    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
+    request.setParam(PARAM_RULE_KEY, rule.getKey().toString());
+    request.setParam(PARAM_SEVERITY, "MINOR");
+    WsTester.Result result = request.execute();
+    session.clearCache();
+
+    // 2. Assert ActiveRule in DAO
+    ActiveRuleKey activeRuleKey = ActiveRuleKey.of(profile, rule.getKey());
+
+    Optional<ActiveRuleDto> activeRuleDto = db.activeRuleDao().selectByKey(session, activeRuleKey);
+    assertThat(activeRuleDto.isPresent()).isTrue();
+    assertThat(activeRuleDto.get().getSeverityString()).isEqualTo(Severity.MINOR);
+  }
+
+  @Test
+  public void bulk_activate_rule() throws Exception {
+    QProfileDto profile = createProfile("java");
+    createRule(profile.getLanguage(), "toto");
+    createRule(profile.getLanguage(), "tata");
+    createRule(profile.getLanguage(), "hello");
+    createRule(profile.getLanguage(), "world");
+    session.commit();
+
+    // 0. Assert No Active Rule for profile
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
+
+    // 1. Activate Rule
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
+    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
+    request.setParam(PARAM_LANGUAGES, "java");
+    request.execute().assertJson(getClass(), "bulk_activate_rule.json");
+    session.clearCache();
+
+    // 2. Assert ActiveRule in DAO
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(4);
+  }
+
+  @Test
+  public void bulk_activate_rule_not_all() throws Exception {
+    QProfileDto java = createProfile("java");
+    QProfileDto php = createProfile("php");
+    createRule(java.getLanguage(), "toto");
+    createRule(java.getLanguage(), "tata");
+    createRule(php.getLanguage(), "hello");
+    createRule(php.getLanguage(), "world");
+    session.commit();
+
+    // 0. Assert No Active Rule for profile
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, php.getKee())).isEmpty();
+
+    // 1. Activate Rule
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
+    request.setParam(PARAM_PROFILE_KEY, php.getKee());
+    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().selectByProfileUuid(session, php.getKee())).hasSize(2);
+  }
+
+  @Test
+  public void bulk_activate_rule_by_query() throws Exception {
+    QProfileDto profile = createProfile("java");
+    createRule(profile.getLanguage(), "toto");
+    createRule(profile.getLanguage(), "tata");
+    createRule(profile.getLanguage(), "hello");
+    createRule(profile.getLanguage(), "world");
+    session.commit();
+
+    // 0. Assert No Active Rule for profile
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
+
+    // 1. Activate Rule with query returning 0 hits
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
+    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
+    request.setParam(WebService.Param.TEXT_QUERY, "php");
+    request.execute();
+    session.clearCache();
+
+    // 2. Assert ActiveRule in DAO
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(0);
+
+    // 1. Activate Rule with query returning 1 hits
+    request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
+    request.setParam(PARAM_PROFILE_KEY, profile.getKee());
+    request.setParam(WebService.Param.TEXT_QUERY, "world");
+    request.execute();
+    session.commit();
+
+    // 2. Assert ActiveRule in DAO
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).hasSize(1);
+  }
+
+  @Test
+  public void bulk_activate_rule_by_query_with_severity() throws Exception {
+    QProfileDto profile = createProfile("java");
+    RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "toto");
+    RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "tata");
+    session.commit();
+
+    // 0. Assert No Active Rule for profile
+    assertThat(db.activeRuleDao().selectByProfileUuid(session, profile.getKee())).isEmpty();
+
+    // 2. Assert ActiveRule with BLOCKER severity
+    assertThat(tester.get(RuleIndex.class).search(
+      new RuleQuery().setSeverities(ImmutableSet.of("BLOCKER")),
+      new SearchOptions()).getIds()).hasSize(2);
+
+    // 1. Activate Rule with query returning 2 hits
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
+    request.setParam(ActivateRulesAction.PROFILE_KEY, profile.getKee());
+    request.setParam(ActivateRulesAction.SEVERITY, "MINOR");
+    request.execute();
+    session.commit();
+
+    // 2. Assert ActiveRule with MINOR severity
+    assertThat(tester.get(ActiveRuleDao.class).selectByRuleId(session, organization, rule0.getId()).get(0).getSeverityString()).isEqualTo("MINOR");
+    assertThat(tester.get(RuleIndex.class).searchAll(new RuleQuery()
+      .setQProfile(profile)
+      .setKey(rule0.getKey().toString())
+      .setActiveSeverities(Collections.singleton("MINOR"))
+      .setActivation(true))).hasSize(1);
+  }
+
+  @Test
+  public void does_not_return_warnings_when_bulk_activate_on_profile_and_rules_exist_on_another_language_than_profile() throws Exception {
+    QProfileDto javaProfile = createProfile("java");
+    createRule(javaProfile.getLanguage(), "toto");
+    createRule(javaProfile.getLanguage(), "tata");
+    QProfileDto phpProfile = createProfile("php");
+    createRule(phpProfile.getLanguage(), "hello");
+    createRule(phpProfile.getLanguage(), "world");
+    session.commit();
+
+    // 1. Activate Rule
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ActivateRulesAction.ACTIVATE_RULES_ACTION);
+    request.setParam(PARAM_PROFILE_KEY, javaProfile.getKee());
+    request.setParam(PARAM_QPROFILE, javaProfile.getKee());
+    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().selectByProfileUuid(session, javaProfile.getKee())).hasSize(2);
+  }
+
+  @Test
+  public void reset() throws Exception {
+    QProfileDto profile = QProfileTesting.newXooP1(organization);
+    QProfileDto subProfile = QProfileTesting.newXooP2(organization).setParentKee(QProfileTesting.XOO_P1_KEY);
+    db.qualityProfileDao().insert(session, profile, subProfile);
+
+    RuleDefinitionDto 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();
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    // 0. assert rule child rule is minor
+    Optional<ActiveRuleDto> activeRuleDto = db.activeRuleDao().selectByKey(session, active2.getKey());
+    assertThat(activeRuleDto.isPresent()).isTrue();
+    assertThat(activeRuleDto.get().getSeverityString()).isEqualTo(Severity.MINOR);
+
+    // 1. reset child rule
+    WsTester.TestRequest request = wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, ACTION_ACTIVATE_RULE);
+    request.setParam("profile_key", subProfile.getKee());
+    request.setParam("rule_key", rule.getKey().toString());
+    request.setParam("reset", "true");
+    request.execute();
+    session.clearCache();
+
+    // 2. assert rule child rule is NOT minor
+    activeRuleDto = db.activeRuleDao().selectByKey(session, active2.getKey());
+    assertThat(activeRuleDto.isPresent()).isTrue();
+    assertThat(activeRuleDto.get().getSeverityString()).isNotEqualTo(Severity.MINOR);
+  }
+
+  private QProfileDto createProfile(String lang) {
+    QProfileDto profile = QProfileTesting.newQProfileDto(organization, new QProfileName(lang, "P" + lang), "p" + lang);
+    db.qualityProfileDao().insert(session, profile);
+    return profile;
+  }
+
+  private RuleDefinitionDto createRule(String lang, String id) {
+    RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("blah", id))
+      .setLanguage(lang)
+      .setSeverity(Severity.BLOCKER)
+      .setStatus(RuleStatus.READY);
+    db.ruleDao().insert(session, rule);
+    session.commit();
+    ruleIndexer.indexRuleDefinition(rule.getKey());
+    return rule;
+  }
+
+  private ActiveRuleDto createActiveRule(RuleDefinitionDto rule, QProfileDto profile) {
+    ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
+      .setSeverity(rule.getSeverityString());
+    db.activeRuleDao().insert(session, activeRule);
+    return activeRule;
+  }
 }
index 0c26b3c2f9c0339f997d33be93ea733344f6a982..38ed5a92b2caf77d49a4c0e0264cce80c611d6bc 100644 (file)
  */
 package org.sonar.server.rule.ws;
 
+import java.util.Date;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.sonar.api.rule.RuleKey;
+import org.sonar.api.rule.RuleStatus;
+import org.sonar.api.rules.RuleType;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
+import org.sonar.db.organization.OrganizationDto;
+import org.sonar.db.qualityprofile.ActiveRuleDao;
+import org.sonar.db.qualityprofile.ActiveRuleDto;
+import org.sonar.db.qualityprofile.ActiveRuleParamDto;
+import org.sonar.db.qualityprofile.QualityProfileDao;
+import org.sonar.db.qualityprofile.QProfileDto;
+import org.sonar.db.rule.RuleDao;
+import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
+import org.sonar.db.rule.RuleDto.Format;
+import org.sonar.db.rule.RuleParamDto;
+import org.sonar.db.rule.RuleTesting;
+import org.sonar.server.organization.DefaultOrganizationProvider;
+import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
+import org.sonar.server.rule.NewCustomRule;
+import org.sonar.server.rule.RuleCreator;
+import org.sonar.server.rule.index.RuleIndexer;
+import org.sonar.server.tester.ServerTester;
+import org.sonar.server.tester.UserSessionRule;
+import org.sonar.server.ws.WsTester;
+
+import static com.google.common.collect.Sets.newHashSet;
+import static org.sonar.api.rule.Severity.MINOR;
+import static org.sonar.db.permission.OrganizationPermission.ADMINISTER_QUALITY_PROFILES;
+
 public class ShowActionMediumTest {
 
-//  @ClassRule
-//  public static ServerTester tester = new ServerTester().withEsIndexes();
-//
-//  DefaultOrganizationProvider defaultOrganizationProvider = tester.get(DefaultOrganizationProvider.class);
-//
-//  @Rule
-//  public UserSessionRule userSessionRule = UserSessionRule.forServerTester(tester).logIn()
-//    .addPermission(ADMINISTER_QUALITY_PROFILES, defaultOrganizationProvider.get().getUuid());
-//
-//  private WsTester wsTester;
-//  private RuleIndexer ruleIndexer;
-//  private RuleDao ruleDao;
-//  private DbSession session;
-//  private OrganizationDto defaultOrganization;
-//
-//  @Before
-//  public void setUp() {
-//    tester.clearDbAndIndexes();
-//    wsTester = tester.get(WsTester.class);
-//    ruleIndexer = tester.get(RuleIndexer.class);
-//    ruleDao = tester.get(RuleDao.class);
-//    session = tester.get(DbClient.class).openSession(false);
-//    defaultOrganization = tester.get(DbClient.class).organizationDao().selectByUuid(session, defaultOrganizationProvider.get().getUuid()).get();
-//  }
-//
-//  @After
-//  public void after() {
-//    session.close();
-//  }
-//
-//  @Test
-//  public void show_rule() throws Exception {
-//    RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("java", "S001"), defaultOrganization)
-//      .setName("Rule S001")
-//      .setDescription("Rule S001 <b>description</b>")
-//      .setDescriptionFormat(Format.HTML)
-//      .setSeverity(MINOR)
-//      .setStatus(RuleStatus.BETA)
-//      .setConfigKey("InternalKeyS001")
-//      .setLanguage("xoo")
-//      .setTags(newHashSet("tag1", "tag2"))
-//      .setSystemTags(newHashSet("systag1", "systag2"))
-//      .setType(RuleType.BUG);
-//    RuleDefinitionDto definition = ruleDto.getDefinition();
-//    ruleDao.insert(session, definition);
-//    ruleDao.insertOrUpdate(session, ruleDto.getMetadata().setRuleId(ruleDto.getId()));
-//    RuleParamDto param = RuleParamDto.createFor(definition).setName("regex").setType("STRING").setDescription("Reg *exp*").setDefaultValue(".*");
-//    ruleDao.insertRuleParam(session, definition, param);
-//    session.commit();
-//    session.clearCache();
-//
-//    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
-//      .setParam("key", ruleDto.getKey().toString());
-//    request.execute().assertJson(getClass(), "show_rule.json");
-//  }
-//
-//  @Test
-//  public void show_rule_with_default_debt_infos() throws Exception {
-//    RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("java", "S001"), defaultOrganization)
-//      .setName("Rule S001")
-//      .setDescription("Rule S001 <b>description</b>")
-//      .setSeverity(MINOR)
-//      .setStatus(RuleStatus.BETA)
-//      .setConfigKey("InternalKeyS001")
-//      .setLanguage("xoo")
-//      .setDefRemediationFunction("LINEAR_OFFSET")
-//      .setDefRemediationGapMultiplier("5d")
-//      .setDefRemediationBaseEffort("10h")
-//      .setRemediationFunction(null)
-//      .setRemediationGapMultiplier(null)
-//      .setRemediationBaseEffort(null);
-//    ruleDao.insert(session, ruleDto.getDefinition());
-//    ruleDao.insertOrUpdate(session, ruleDto.getMetadata());
-//    session.commit();
-//    session.clearCache();
-//
-//    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
-//      .setParam("key", ruleDto.getKey().toString());
-//    WsTester.Result response = request.execute();
-//
-//    response.assertJson(getClass(), "show_rule_with_default_debt_infos.json");
-//  }
-//
-//  @Test
-//  public void show_rule_with_overridden_debt() throws Exception {
-//    RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("java", "S001"), defaultOrganization)
-//      .setName("Rule S001")
-//      .setDescription("Rule S001 <b>description</b>")
-//      .setSeverity(MINOR)
-//      .setStatus(RuleStatus.BETA)
-//      .setConfigKey("InternalKeyS001")
-//      .setLanguage("xoo")
-//      .setDefRemediationFunction(null)
-//      .setDefRemediationGapMultiplier(null)
-//      .setDefRemediationBaseEffort(null)
-//      .setRemediationFunction("LINEAR_OFFSET")
-//      .setRemediationGapMultiplier("5d")
-//      .setRemediationBaseEffort("10h");
-//    ruleDao.insert(session, ruleDto.getDefinition());
-//    ruleDao.insertOrUpdate(session, ruleDto.getMetadata().setRuleId(ruleDto.getId()));
-//    session.commit();
-//    session.clearCache();
-//
-//    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
-//      .setParam("key", ruleDto.getKey().toString());
-//    request.execute().assertJson(getClass(), "show_rule_with_overridden_debt_infos.json");
-//  }
-//
-//  @Test
-//  public void show_rule_with_default_and_overridden_debt_infos() throws Exception {
-//    RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("java", "S001"), defaultOrganization)
-//      .setName("Rule S001")
-//      .setDescription("Rule S001 <b>description</b>")
-//      .setSeverity(MINOR)
-//      .setStatus(RuleStatus.BETA)
-//      .setConfigKey("InternalKeyS001")
-//      .setLanguage("xoo")
-//      .setDefRemediationFunction("LINEAR")
-//      .setDefRemediationGapMultiplier("5min")
-//      .setDefRemediationBaseEffort(null)
-//      .setRemediationFunction("LINEAR_OFFSET")
-//      .setRemediationGapMultiplier("5d")
-//      .setRemediationBaseEffort("10h");
-//    ruleDao.insert(session, ruleDto.getDefinition());
-//    ruleDao.insertOrUpdate(session, ruleDto.getMetadata().setRuleId(ruleDto.getId()));
-//    session.commit();
-//    session.clearCache();
-//
-//    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
-//      .setParam("key", ruleDto.getKey().toString());
-//    request.execute().assertJson(getClass(), "show_rule_with_default_and_overridden_debt_infos.json");
-//  }
-//
-//  @Test
-//  public void show_rule_with_no_default_and_no_overridden_debt() throws Exception {
-//    RuleDefinitionDto ruleDto = RuleTesting.newRule(RuleKey.of("java", "S001"))
-//      .setName("Rule S001")
-//      .setDescription("Rule S001 <b>description</b>")
-//      .setDescriptionFormat(Format.HTML)
-//      .setSeverity(MINOR)
-//      .setStatus(RuleStatus.BETA)
-//      .setConfigKey("InternalKeyS001")
-//      .setLanguage("xoo")
-//      .setDefRemediationFunction(null)
-//      .setDefRemediationGapMultiplier(null)
-//      .setDefRemediationBaseEffort(null);
-//    ruleDao.insert(session, ruleDto);
-//    session.commit();
-//    session.clearCache();
-//
-//    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
-//      .setParam("key", ruleDto.getKey().toString());
-//    request.execute().assertJson(getClass(), "show_rule_with_no_default_and_no_overridden_debt.json");
-//  }
-//
-//  @Test
-//  public void encode_html_description_of_custom_rule() throws Exception {
-//    // Template rule
-//    RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
-//    ruleDao.insert(session, templateRule.getDefinition());
-//    session.commit();
-//
-//    // Custom rule
-//    NewCustomRule customRule = NewCustomRule.createForCustomRule("MY_CUSTOM", templateRule.getKey())
-//      .setName("My custom")
-//      .setSeverity(MINOR)
-//      .setStatus(RuleStatus.READY)
-//      .setMarkdownDescription("<div>line1\nline2</div>");
-//    RuleKey customRuleKey = tester.get(RuleCreator.class).create(session, customRule);
-//    session.clearCache();
-//
-//    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
-//      .setParam("key", customRuleKey.toString());
-//    request.execute().assertJson(getClass(), "encode_html_description_of_custom_rule.json");
-//  }
-//
-//  @Test
-//  public void show_deprecated_rule_rem_function_fields() throws Exception {
-//    RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("java", "S001"), defaultOrganization)
-//      .setName("Rule S001")
-//      .setDescription("Rule S001 <b>description</b>")
-//      .setSeverity(MINOR)
-//      .setStatus(RuleStatus.BETA)
-//      .setConfigKey("InternalKeyS001")
-//      .setLanguage("xoo")
-//      .setDefRemediationFunction("LINEAR_OFFSET")
-//      .setDefRemediationGapMultiplier("6d")
-//      .setDefRemediationBaseEffort("11h")
-//      .setRemediationFunction("LINEAR_OFFSET")
-//      .setRemediationGapMultiplier("5d")
-//      .setRemediationBaseEffort("10h");
-//    ruleDao.insert(session, ruleDto.getDefinition());
-//    ruleDao.insertOrUpdate(session, ruleDto.getMetadata().setRuleId(ruleDto.getId()));
-//    session.commit();
-//
-//    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
-//      .setParam("key", ruleDto.getKey().toString());
-//    request.execute().assertJson(getClass(), "show_deprecated_rule_rem_function_fields.json");
-//  }
-//
-//  @Test
-//  public void show_rule_when_activated() throws Exception {
-//    RuleDefinitionDto ruleDto = RuleTesting.newRule(RuleKey.of("java", "S001"))
-//      .setName("Rule S001")
-//      .setDescription("Rule S001 <b>description</b>")
-//      .setDescriptionFormat(Format.HTML)
-//      .setSeverity(MINOR)
-//      .setStatus(RuleStatus.BETA)
-//      .setLanguage("xoo")
-//      .setType(RuleType.BUG)
-//      .setCreatedAt(new Date().getTime())
-//      .setUpdatedAt(new Date().getTime());
-//    ruleDao.insert(session, ruleDto);
-//    session.commit();
-//    ruleIndexer.indexRuleDefinition(ruleDto.getKey());
-//    RuleParamDto regexParam = RuleParamDto.createFor(ruleDto).setName("regex").setType("STRING").setDescription("Reg *exp*").setDefaultValue(".*");
-//    ruleDao.insertRuleParam(session, ruleDto, regexParam);
-//
-//    QProfileDto profile = new QProfileDto()
-//      .setKee("profile")
-//      .setRulesProfileUuid("rp-profile")
-//      .setOrganizationUuid(defaultOrganizationProvider.get().getUuid())
-//      .setName("Profile")
-//      .setLanguage("xoo");
-//    tester.get(QualityProfileDao.class).insert(session, profile);
-//    ActiveRuleDto activeRuleDto = new ActiveRuleDto()
-//      .setProfileId(profile.getId())
-//      .setRuleId(ruleDto.getId())
-//      .setSeverity(MINOR)
-//      .setCreatedAt(new Date().getTime())
-//      .setUpdatedAt(new Date().getTime());
-//    tester.get(ActiveRuleDao.class).insert(session, activeRuleDto);
-//    tester.get(ActiveRuleDao.class).insertParam(session, activeRuleDto, new ActiveRuleParamDto()
-//      .setRulesParameterId(regexParam.getId())
-//      .setKey(regexParam.getName())
-//      .setValue(".*?"));
-//    session.commit();
-//
-//    tester.get(ActiveRuleIndexer.class).index();
-//
-//    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
-//      .setParam("key", ruleDto.getKey().toString())
-//      .setParam("actives", "true");
-//    request.execute().assertJson(getClass(), "show_rule_when_activated.json");
-//  }
+  @ClassRule
+  public static ServerTester tester = new ServerTester().withEsIndexes();
+
+  DefaultOrganizationProvider defaultOrganizationProvider = tester.get(DefaultOrganizationProvider.class);
+
+  @Rule
+  public UserSessionRule userSessionRule = UserSessionRule.forServerTester(tester).logIn()
+    .addPermission(ADMINISTER_QUALITY_PROFILES, defaultOrganizationProvider.get().getUuid());
+
+  private WsTester wsTester;
+  private RuleIndexer ruleIndexer;
+  private RuleDao ruleDao;
+  private DbSession session;
+  private OrganizationDto defaultOrganization;
+
+  @Before
+  public void setUp() {
+    tester.clearDbAndIndexes();
+    wsTester = tester.get(WsTester.class);
+    ruleIndexer = tester.get(RuleIndexer.class);
+    ruleDao = tester.get(RuleDao.class);
+    session = tester.get(DbClient.class).openSession(false);
+    defaultOrganization = tester.get(DbClient.class).organizationDao().selectByUuid(session, defaultOrganizationProvider.get().getUuid()).get();
+  }
+
+  @After
+  public void after() {
+    session.close();
+  }
+
+  @Test
+  public void show_rule() throws Exception {
+    RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("java", "S001"), defaultOrganization)
+      .setName("Rule S001")
+      .setDescription("Rule S001 <b>description</b>")
+      .setDescriptionFormat(Format.HTML)
+      .setSeverity(MINOR)
+      .setStatus(RuleStatus.BETA)
+      .setConfigKey("InternalKeyS001")
+      .setLanguage("xoo")
+      .setTags(newHashSet("tag1", "tag2"))
+      .setSystemTags(newHashSet("systag1", "systag2"))
+      .setType(RuleType.BUG);
+    RuleDefinitionDto definition = ruleDto.getDefinition();
+    ruleDao.insert(session, definition);
+    ruleDao.insertOrUpdate(session, ruleDto.getMetadata().setRuleId(ruleDto.getId()));
+    RuleParamDto param = RuleParamDto.createFor(definition).setName("regex").setType("STRING").setDescription("Reg *exp*").setDefaultValue(".*");
+    ruleDao.insertRuleParam(session, definition, param);
+    session.commit();
+    session.clearCache();
+
+    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
+      .setParam("key", ruleDto.getKey().toString());
+    request.execute().assertJson(getClass(), "show_rule.json");
+  }
+
+  @Test
+  public void show_rule_with_default_debt_infos() throws Exception {
+    RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("java", "S001"), defaultOrganization)
+      .setName("Rule S001")
+      .setDescription("Rule S001 <b>description</b>")
+      .setSeverity(MINOR)
+      .setStatus(RuleStatus.BETA)
+      .setConfigKey("InternalKeyS001")
+      .setLanguage("xoo")
+      .setDefRemediationFunction("LINEAR_OFFSET")
+      .setDefRemediationGapMultiplier("5d")
+      .setDefRemediationBaseEffort("10h")
+      .setRemediationFunction(null)
+      .setRemediationGapMultiplier(null)
+      .setRemediationBaseEffort(null);
+    ruleDao.insert(session, ruleDto.getDefinition());
+    ruleDao.insertOrUpdate(session, ruleDto.getMetadata());
+    session.commit();
+    session.clearCache();
+
+    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
+      .setParam("key", ruleDto.getKey().toString());
+    WsTester.Result response = request.execute();
+
+    response.assertJson(getClass(), "show_rule_with_default_debt_infos.json");
+  }
+
+  @Test
+  public void show_rule_with_overridden_debt() throws Exception {
+    RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("java", "S001"), defaultOrganization)
+      .setName("Rule S001")
+      .setDescription("Rule S001 <b>description</b>")
+      .setSeverity(MINOR)
+      .setStatus(RuleStatus.BETA)
+      .setConfigKey("InternalKeyS001")
+      .setLanguage("xoo")
+      .setDefRemediationFunction(null)
+      .setDefRemediationGapMultiplier(null)
+      .setDefRemediationBaseEffort(null)
+      .setRemediationFunction("LINEAR_OFFSET")
+      .setRemediationGapMultiplier("5d")
+      .setRemediationBaseEffort("10h");
+    ruleDao.insert(session, ruleDto.getDefinition());
+    ruleDao.insertOrUpdate(session, ruleDto.getMetadata().setRuleId(ruleDto.getId()));
+    session.commit();
+    session.clearCache();
+
+    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
+      .setParam("key", ruleDto.getKey().toString());
+    request.execute().assertJson(getClass(), "show_rule_with_overridden_debt_infos.json");
+  }
+
+  @Test
+  public void show_rule_with_default_and_overridden_debt_infos() throws Exception {
+    RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("java", "S001"), defaultOrganization)
+      .setName("Rule S001")
+      .setDescription("Rule S001 <b>description</b>")
+      .setSeverity(MINOR)
+      .setStatus(RuleStatus.BETA)
+      .setConfigKey("InternalKeyS001")
+      .setLanguage("xoo")
+      .setDefRemediationFunction("LINEAR")
+      .setDefRemediationGapMultiplier("5min")
+      .setDefRemediationBaseEffort(null)
+      .setRemediationFunction("LINEAR_OFFSET")
+      .setRemediationGapMultiplier("5d")
+      .setRemediationBaseEffort("10h");
+    ruleDao.insert(session, ruleDto.getDefinition());
+    ruleDao.insertOrUpdate(session, ruleDto.getMetadata().setRuleId(ruleDto.getId()));
+    session.commit();
+    session.clearCache();
+
+    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
+      .setParam("key", ruleDto.getKey().toString());
+    request.execute().assertJson(getClass(), "show_rule_with_default_and_overridden_debt_infos.json");
+  }
+
+  @Test
+  public void show_rule_with_no_default_and_no_overridden_debt() throws Exception {
+    RuleDefinitionDto ruleDto = RuleTesting.newRule(RuleKey.of("java", "S001"))
+      .setName("Rule S001")
+      .setDescription("Rule S001 <b>description</b>")
+      .setDescriptionFormat(Format.HTML)
+      .setSeverity(MINOR)
+      .setStatus(RuleStatus.BETA)
+      .setConfigKey("InternalKeyS001")
+      .setLanguage("xoo")
+      .setDefRemediationFunction(null)
+      .setDefRemediationGapMultiplier(null)
+      .setDefRemediationBaseEffort(null);
+    ruleDao.insert(session, ruleDto);
+    session.commit();
+    session.clearCache();
+
+    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
+      .setParam("key", ruleDto.getKey().toString());
+    request.execute().assertJson(getClass(), "show_rule_with_no_default_and_no_overridden_debt.json");
+  }
+
+  @Test
+  public void encode_html_description_of_custom_rule() throws Exception {
+    // Template rule
+    RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
+    ruleDao.insert(session, templateRule.getDefinition());
+    session.commit();
+
+    // Custom rule
+    NewCustomRule customRule = NewCustomRule.createForCustomRule("MY_CUSTOM", templateRule.getKey())
+      .setName("My custom")
+      .setSeverity(MINOR)
+      .setStatus(RuleStatus.READY)
+      .setMarkdownDescription("<div>line1\nline2</div>");
+    RuleKey customRuleKey = tester.get(RuleCreator.class).create(session, customRule);
+    session.clearCache();
+
+    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
+      .setParam("key", customRuleKey.toString());
+    request.execute().assertJson(getClass(), "encode_html_description_of_custom_rule.json");
+  }
+
+  @Test
+  public void show_deprecated_rule_rem_function_fields() throws Exception {
+    RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("java", "S001"), defaultOrganization)
+      .setName("Rule S001")
+      .setDescription("Rule S001 <b>description</b>")
+      .setSeverity(MINOR)
+      .setStatus(RuleStatus.BETA)
+      .setConfigKey("InternalKeyS001")
+      .setLanguage("xoo")
+      .setDefRemediationFunction("LINEAR_OFFSET")
+      .setDefRemediationGapMultiplier("6d")
+      .setDefRemediationBaseEffort("11h")
+      .setRemediationFunction("LINEAR_OFFSET")
+      .setRemediationGapMultiplier("5d")
+      .setRemediationBaseEffort("10h");
+    ruleDao.insert(session, ruleDto.getDefinition());
+    ruleDao.insertOrUpdate(session, ruleDto.getMetadata().setRuleId(ruleDto.getId()));
+    session.commit();
+
+    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
+      .setParam("key", ruleDto.getKey().toString());
+    request.execute().assertJson(getClass(), "show_deprecated_rule_rem_function_fields.json");
+  }
+
+  @Test
+  public void show_rule_when_activated() throws Exception {
+    RuleDefinitionDto ruleDto = RuleTesting.newRule(RuleKey.of("java", "S001"))
+      .setName("Rule S001")
+      .setDescription("Rule S001 <b>description</b>")
+      .setDescriptionFormat(Format.HTML)
+      .setSeverity(MINOR)
+      .setStatus(RuleStatus.BETA)
+      .setLanguage("xoo")
+      .setType(RuleType.BUG)
+      .setCreatedAt(new Date().getTime())
+      .setUpdatedAt(new Date().getTime());
+    ruleDao.insert(session, ruleDto);
+    session.commit();
+    ruleIndexer.indexRuleDefinition(ruleDto.getKey());
+    RuleParamDto regexParam = RuleParamDto.createFor(ruleDto).setName("regex").setType("STRING").setDescription("Reg *exp*").setDefaultValue(".*");
+    ruleDao.insertRuleParam(session, ruleDto, regexParam);
+
+    QProfileDto profile = new QProfileDto()
+      .setRulesProfileUuid("profile")
+      .setKee("profile")
+      .setOrganizationUuid(defaultOrganizationProvider.get().getUuid())
+      .setName("Profile")
+      .setLanguage("xoo");
+    tester.get(QualityProfileDao.class).insert(session, profile);
+    ActiveRuleDto activeRuleDto = new ActiveRuleDto()
+      .setProfileId(profile.getId())
+      .setRuleId(ruleDto.getId())
+      .setSeverity(MINOR)
+      .setCreatedAt(new Date().getTime())
+      .setUpdatedAt(new Date().getTime());
+    tester.get(ActiveRuleDao.class).insert(session, activeRuleDto);
+    tester.get(ActiveRuleDao.class).insertParam(session, activeRuleDto, new ActiveRuleParamDto()
+      .setRulesParameterId(regexParam.getId())
+      .setKey(regexParam.getName())
+      .setValue(".*?"));
+    session.commit();
+
+    ActiveRuleIndexer activeRuleIndexer = tester.get(ActiveRuleIndexer.class);
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "show")
+      .setParam("key", ruleDto.getKey().toString())
+      .setParam("actives", "true");
+    request.execute().assertJson(getClass(), "show_rule_when_activated.json");
+  }
 
 }
index 32131dc6e06f9552225925679f8b4a8a5b972e90..c4e2e4266e9e92d626a6dde9cb416be48cb4b204 100644 (file)
 
 package org.sonar.server.rule.ws;
 
+import java.io.IOException;
+import java.util.List;
+import java.util.function.Consumer;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+import org.sonar.api.config.MapSettings;
+import org.sonar.api.resources.Languages;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
+import org.sonar.db.DbTester;
+import org.sonar.db.organization.OrganizationDto;
+import org.sonar.db.qualityprofile.QProfileDto;
+import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleMetadataDto;
+import org.sonar.server.es.EsClient;
+import org.sonar.server.es.EsTester;
+import org.sonar.server.exceptions.NotFoundException;
+import org.sonar.server.organization.DefaultOrganizationProvider;
+import org.sonar.server.organization.TestDefaultOrganizationProvider;
+import org.sonar.server.qualityprofile.QProfileTesting;
+import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
+import org.sonar.server.qualityprofile.index.ActiveRuleIteratorFactory;
+import org.sonar.server.rule.index.RuleIndexDefinition;
+import org.sonar.server.rule.index.RuleIndexer;
+import org.sonar.server.text.MacroInterpreter;
+import org.sonar.server.ws.TestResponse;
+import org.sonar.server.ws.WsAction;
+import org.sonar.server.ws.WsActionTester;
+import org.sonarqube.ws.Rules;
+import org.sonarqube.ws.Rules.Rule;
+
+import static java.util.Collections.singletonList;
+import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.sonar.db.rule.RuleTesting.setTags;
+import static org.sonar.server.rule.ws.ShowAction.PARAM_KEY;
+import static org.sonar.server.rule.ws.ShowAction.PARAM_ORGANIZATION;
+import static org.sonarqube.ws.MediaTypes.PROTOBUF;
+
 public class ShowActionTest {
-//
-//  @org.junit.Rule
-//  public DbTester dbTester = DbTester.create();
-//  @org.junit.Rule
-//  public EsTester esTester = new EsTester(
-//    new RuleIndexDefinition(new MapSettings()));
-//  @org.junit.Rule
-//  public ExpectedException thrown = ExpectedException.none();
-//
-//  private DbClient dbClient = dbTester.getDbClient();
-//  private EsClient esClient = esTester.client();
-//
-//  private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(dbTester);
-//  private MacroInterpreter macroInterpreter = mock(MacroInterpreter.class);
-//  private Languages languages = new Languages();
-//  private RuleMapper mapper = new RuleMapper(languages, macroInterpreter);
-//  private ActiveRuleCompleter activeRuleCompleter = mock(ActiveRuleCompleter.class);
-//  private WsAction underTest = new ShowAction(dbClient, mapper, activeRuleCompleter, defaultOrganizationProvider);
-//  private WsActionTester actionTester = new WsActionTester(underTest);
-//
-//  private RuleIndexer ruleIndexer = new RuleIndexer(esClient, dbClient);
-//
-//  @Before
-//  public void before() {
-//    doReturn("interpreted").when(macroInterpreter).interpret(anyString());
-//  }
-//
-//  @Test
-//  public void should_show_rule_key() throws IOException {
-//    RuleDefinitionDto rule = insertRule();
-//
-//    Rules.ShowResponse result = actionTester.newRequest()
-//      .setParam(PARAM_KEY, rule.getKey().toString())
-//      .executeProtobuf(Rules.ShowResponse.class);
-//    assertThat(result.getRule()).extracting(Rule::getKey).containsExactly(rule.getKey().toString());
-//  }
-//
-//  @Test
-//  public void should_show_rule_tags_in_default_organization() throws IOException {
-//    RuleDefinitionDto rule = insertRule();
-//    RuleMetadataDto metadata = insertMetadata(dbTester.getDefaultOrganization(), rule, setTags("tag1", "tag2"));
-//
-//    Rules.ShowResponse result = actionTester.newRequest()
-//      .setParam(PARAM_KEY, rule.getKey().toString())
-//      .executeProtobuf(Rules.ShowResponse.class);
-//    assertThat(result.getRule().getTags().getTagsList())
-//      .containsExactly(metadata.getTags().toArray(new String[0]));
-//  }
-//
-//  @Test
-//  public void should_show_rule_tags_in_specific_organization() throws IOException {
-//    RuleDefinitionDto rule = insertRule();
-//    OrganizationDto organization = dbTester.organizations().insert();
-//    RuleMetadataDto metadata = insertMetadata(organization, rule, setTags("tag1", "tag2"));
-//
-//    Rules.ShowResponse result = actionTester.newRequest()
-//        .setParam(PARAM_KEY, rule.getKey().toString())
-//        .setParam(PARAM_ORGANIZATION, organization.getKey())
-//        .executeProtobuf(Rules.ShowResponse.class);
-//    assertThat(result.getRule().getTags().getTagsList())
-//      .containsExactly(metadata.getTags().toArray(new String[0]));
-//  }
-//
-//  @Test
-//  public void show_rule_with_activation() throws Exception {
-//    OrganizationDto organization = dbTester.organizations().insert();
-//
-//    QProfileDto profile = QProfileTesting.newXooP1(organization);
-//    dbClient.qualityProfileDao().insert(dbTester.getSession(), profile);
-//    dbTester.commit();
-//
-//    RuleDefinitionDto rule = insertRule();
-//    RuleMetadataDto ruleMetadata = dbTester.rules().insertOrUpdateMetadata(rule, organization);
-//
-//    ArgumentCaptor<OrganizationDto> orgCaptor = ArgumentCaptor.forClass(OrganizationDto.class);
-//    ArgumentCaptor<RuleDefinitionDto> ruleCaptor = ArgumentCaptor.forClass(RuleDefinitionDto.class);
-//    Rules.Active active = Rules.Active.newBuilder()
-//      .setQProfile(randomAlphanumeric(5))
-//      .setInherit(randomAlphanumeric(5))
-//      .setSeverity(randomAlphanumeric(5))
-//      .build();
-//    Mockito.doReturn(singletonList(active)).when(activeRuleCompleter).completeShow(any(DbSession.class), orgCaptor.capture(), ruleCaptor.capture());
-
-//    new ActiveRuleIndexer(System2.INSTANCE, dbClient, esClient).index();
-//
-//    TestResponse response = actionTester.newRequest().setMethod("GET")
-//      .setMediaType(PROTOBUF)
-//      .setParam(ShowAction.PARAM_KEY, rule.getKey().toString())
-//      .setParam(ShowAction.PARAM_ACTIVES, "true")
-//      .setParam(ShowAction.PARAM_ORGANIZATION, organization.getKey())
-//      .execute();
-//
-//    assertThat(orgCaptor.getValue().getUuid()).isEqualTo(organization.getUuid());
-//    assertThat(ruleCaptor.getValue().getKey()).isEqualTo(rule.getKey());
-//
-//    Rules.ShowResponse result = response.getInputObject(Rules.ShowResponse.class);
-//    Rule resultRule = result.getRule();
-//    assertEqual(rule, ruleMetadata, resultRule);
-//
-//    List<Rules.Active> actives = result.getActivesList();
-//    assertThat(actives).extracting(Rules.Active::getQProfile).containsExactly(active.getQProfile());
-//    assertThat(actives).extracting(Rules.Active::getInherit).containsExactly(active.getInherit());
-//    assertThat(actives).extracting(Rules.Active::getSeverity).containsExactly(active.getSeverity());
-//  }
-//
-//  @Test
-//  public void show_rule_without_activation() throws Exception {
-//    OrganizationDto organization = dbTester.organizations().insert();
-//
-//    QProfileDto profile = QProfileTesting.newXooP1(organization);
-//    dbClient.qualityProfileDao().insert(dbTester.getSession(), profile);
-//    dbTester.commit();
-//
-//    RuleDefinitionDto rule = insertRule();
-//    RuleMetadataDto ruleMetadata = dbTester.rules().insertOrUpdateMetadata(rule, organization);
-//
-//    dbTester.qualityProfiles().activateRule(profile, rule, a -> a.setSeverity("BLOCKER"));
-//    new ActiveRuleIndexer(dbClient, esClient).index();
-//
-//    TestResponse response = actionTester.newRequest().setMethod("GET")
-//      .setParam(ShowAction.PARAM_KEY, rule.getKey().toString())
-//      .setParam(ShowAction.PARAM_ORGANIZATION, organization.getKey())
-//      .setMediaType(PROTOBUF)
-//      .execute();
-//
-//    Rules.ShowResponse result = response.getInputObject(Rules.ShowResponse.class);
-//    Rule resultRule = result.getRule();
-//    assertEqual(rule, ruleMetadata, resultRule);
-//
-//    List<Rules.Active> actives = result.getActivesList();
-//    assertThat(actives).isEmpty();
-//  }
-//
-//  @Test
-//  public void throw_NotFoundException_if_organization_cannot_be_found() throws Exception {
-//    RuleDefinitionDto rule = dbTester.rules().insert();
-//
-//    thrown.expect(NotFoundException.class);
-//
-//    actionTester.newRequest().setMethod("POST")
-//      .setParam("key", rule.getKey().toString())
-//      .setParam("organization", "foo")
-//      .execute();
-//  }
-//
-//  private void assertEqual(RuleDefinitionDto rule, RuleMetadataDto ruleMetadata, Rule resultRule) {
-//    assertThat(resultRule.getKey()).isEqualTo(rule.getKey().toString());
-//    assertThat(resultRule.getRepo()).isEqualTo(rule.getRepositoryKey());
-//    assertThat(resultRule.getName()).isEqualTo(rule.getName());
-//    assertThat(resultRule.getSeverity()).isEqualTo(rule.getSeverityString());
-//    assertThat(resultRule.getStatus().toString()).isEqualTo(rule.getStatus().toString());
-//    assertThat(resultRule.getInternalKey()).isEqualTo(rule.getConfigKey());
-//    assertThat(resultRule.getIsTemplate()).isEqualTo(rule.isTemplate());
-//    assertThat(resultRule.getTags().getTagsList()).containsExactlyInAnyOrder(ruleMetadata.getTags().toArray(new String[0]));
-//    assertThat(resultRule.getSysTags().getSysTagsList()).containsExactlyInAnyOrder(rule.getSystemTags().toArray(new String[0]));
-//    assertThat(resultRule.getLang()).isEqualTo(rule.getLanguage());
-//    assertThat(resultRule.getParams().getParamsList()).isEmpty();
-//  }
-//
-//  private RuleDefinitionDto insertRule() {
-//    RuleDefinitionDto rule = dbTester.rules().insert();
-//    ruleIndexer.indexRuleDefinition(rule.getKey());
-//    return rule;
-//  }
-//
-//  @SafeVarargs
-//  private final RuleMetadataDto insertMetadata(OrganizationDto organization, RuleDefinitionDto rule, Consumer<RuleMetadataDto>... populaters) {
-//    RuleMetadataDto metadata = dbTester.rules().insertOrUpdateMetadata(rule, organization, populaters);
-//    ruleIndexer.indexRuleExtension(organization, rule.getKey());
-//    return metadata;
-//  }
+
+  @org.junit.Rule
+  public DbTester dbTester = DbTester.create();
+  @org.junit.Rule
+  public EsTester esTester = new EsTester(
+    new RuleIndexDefinition(new MapSettings()));
+  @org.junit.Rule
+  public ExpectedException thrown = ExpectedException.none();
+
+  private DbClient dbClient = dbTester.getDbClient();
+  private EsClient esClient = esTester.client();
+
+  private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(dbTester);
+  private MacroInterpreter macroInterpreter = mock(MacroInterpreter.class);
+  private Languages languages = new Languages();
+  private RuleMapper mapper = new RuleMapper(languages, macroInterpreter);
+  private ActiveRuleCompleter activeRuleCompleter = mock(ActiveRuleCompleter.class);
+  private WsAction underTest = new ShowAction(dbClient, mapper, activeRuleCompleter, defaultOrganizationProvider);
+  private WsActionTester actionTester = new WsActionTester(underTest);
+
+  private RuleIndexer ruleIndexer = new RuleIndexer(esClient, dbClient);
+
+  @Before
+  public void before() {
+    doReturn("interpreted").when(macroInterpreter).interpret(anyString());
+  }
+
+  @Test
+  public void should_show_rule_key() throws IOException {
+    RuleDefinitionDto rule = insertRule();
+
+    Rules.ShowResponse result = actionTester.newRequest()
+      .setParam(PARAM_KEY, rule.getKey().toString())
+      .executeProtobuf(Rules.ShowResponse.class);
+    assertThat(result.getRule()).extracting(Rule::getKey).containsExactly(rule.getKey().toString());
+  }
+
+  @Test
+  public void should_show_rule_tags_in_default_organization() throws IOException {
+    RuleDefinitionDto rule = insertRule();
+    RuleMetadataDto metadata = insertMetadata(dbTester.getDefaultOrganization(), rule, setTags("tag1", "tag2"));
+
+    Rules.ShowResponse result = actionTester.newRequest()
+      .setParam(PARAM_KEY, rule.getKey().toString())
+      .executeProtobuf(Rules.ShowResponse.class);
+    assertThat(result.getRule().getTags().getTagsList())
+      .containsExactly(metadata.getTags().toArray(new String[0]));
+  }
+
+  @Test
+  public void should_show_rule_tags_in_specific_organization() throws IOException {
+    RuleDefinitionDto rule = insertRule();
+    OrganizationDto organization = dbTester.organizations().insert();
+    RuleMetadataDto metadata = insertMetadata(organization, rule, setTags("tag1", "tag2"));
+
+    Rules.ShowResponse result = actionTester.newRequest()
+        .setParam(PARAM_KEY, rule.getKey().toString())
+        .setParam(PARAM_ORGANIZATION, organization.getKey())
+        .executeProtobuf(Rules.ShowResponse.class);
+    assertThat(result.getRule().getTags().getTagsList())
+      .containsExactly(metadata.getTags().toArray(new String[0]));
+  }
+
+  @Test
+  public void show_rule_with_activation() throws Exception {
+    OrganizationDto organization = dbTester.organizations().insert();
+
+    QProfileDto profile = QProfileTesting.newXooP1(organization);
+    dbClient.qualityProfileDao().insert(dbTester.getSession(), profile);
+    dbTester.commit();
+
+    RuleDefinitionDto rule = insertRule();
+    RuleMetadataDto ruleMetadata = dbTester.rules().insertOrUpdateMetadata(rule, organization);
+
+    ArgumentCaptor<OrganizationDto> orgCaptor = ArgumentCaptor.forClass(OrganizationDto.class);
+    ArgumentCaptor<RuleDefinitionDto> ruleCaptor = ArgumentCaptor.forClass(RuleDefinitionDto.class);
+    Rules.Active active = Rules.Active.newBuilder()
+      .setQProfile(randomAlphanumeric(5))
+      .setInherit(randomAlphanumeric(5))
+      .setSeverity(randomAlphanumeric(5))
+      .build();
+    Mockito.doReturn(singletonList(active)).when(activeRuleCompleter).completeShow(any(DbSession.class), orgCaptor.capture(), ruleCaptor.capture());
+
+    ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(dbClient, esClient, new ActiveRuleIteratorFactory(dbClient));
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    TestResponse response = actionTester.newRequest().setMethod("GET")
+      .setMediaType(PROTOBUF)
+      .setParam(ShowAction.PARAM_KEY, rule.getKey().toString())
+      .setParam(ShowAction.PARAM_ACTIVES, "true")
+      .setParam(ShowAction.PARAM_ORGANIZATION, organization.getKey())
+      .execute();
+
+    assertThat(orgCaptor.getValue().getUuid()).isEqualTo(organization.getUuid());
+    assertThat(ruleCaptor.getValue().getKey()).isEqualTo(rule.getKey());
+
+    Rules.ShowResponse result = response.getInputObject(Rules.ShowResponse.class);
+    Rule resultRule = result.getRule();
+    assertEqual(rule, ruleMetadata, resultRule);
+
+    List<Rules.Active> actives = result.getActivesList();
+    assertThat(actives).extracting(Rules.Active::getQProfile).containsExactly(active.getQProfile());
+    assertThat(actives).extracting(Rules.Active::getInherit).containsExactly(active.getInherit());
+    assertThat(actives).extracting(Rules.Active::getSeverity).containsExactly(active.getSeverity());
+  }
+
+  @Test
+  public void show_rule_without_activation() throws Exception {
+    OrganizationDto organization = dbTester.organizations().insert();
+
+    QProfileDto profile = QProfileTesting.newXooP1(organization);
+    dbClient.qualityProfileDao().insert(dbTester.getSession(), profile);
+    dbTester.commit();
+
+    RuleDefinitionDto rule = insertRule();
+    RuleMetadataDto ruleMetadata = dbTester.rules().insertOrUpdateMetadata(rule, organization);
+
+    dbTester.qualityProfiles().activateRule(profile, rule, a -> a.setSeverity("BLOCKER"));
+    ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(dbClient, esClient, new ActiveRuleIteratorFactory(dbClient));
+    activeRuleIndexer.indexOnStartup(activeRuleIndexer.getIndexTypes());
+
+    TestResponse response = actionTester.newRequest().setMethod("GET")
+      .setParam(ShowAction.PARAM_KEY, rule.getKey().toString())
+      .setParam(ShowAction.PARAM_ORGANIZATION, organization.getKey())
+      .setMediaType(PROTOBUF)
+      .execute();
+
+    Rules.ShowResponse result = response.getInputObject(Rules.ShowResponse.class);
+    Rule resultRule = result.getRule();
+    assertEqual(rule, ruleMetadata, resultRule);
+
+    List<Rules.Active> actives = result.getActivesList();
+    assertThat(actives).isEmpty();
+  }
+
+  @Test
+  public void throw_NotFoundException_if_organization_cannot_be_found() throws Exception {
+    RuleDefinitionDto rule = dbTester.rules().insert();
+
+    thrown.expect(NotFoundException.class);
+
+    actionTester.newRequest().setMethod("POST")
+      .setParam("key", rule.getKey().toString())
+      .setParam("organization", "foo")
+      .execute();
+  }
+
+  private void assertEqual(RuleDefinitionDto rule, RuleMetadataDto ruleMetadata, Rule resultRule) {
+    assertThat(resultRule.getKey()).isEqualTo(rule.getKey().toString());
+    assertThat(resultRule.getRepo()).isEqualTo(rule.getRepositoryKey());
+    assertThat(resultRule.getName()).isEqualTo(rule.getName());
+    assertThat(resultRule.getSeverity()).isEqualTo(rule.getSeverityString());
+    assertThat(resultRule.getStatus().toString()).isEqualTo(rule.getStatus().toString());
+    assertThat(resultRule.getInternalKey()).isEqualTo(rule.getConfigKey());
+    assertThat(resultRule.getIsTemplate()).isEqualTo(rule.isTemplate());
+    assertThat(resultRule.getTags().getTagsList()).containsExactlyInAnyOrder(ruleMetadata.getTags().toArray(new String[0]));
+    assertThat(resultRule.getSysTags().getSysTagsList()).containsExactlyInAnyOrder(rule.getSystemTags().toArray(new String[0]));
+    assertThat(resultRule.getLang()).isEqualTo(rule.getLanguage());
+    assertThat(resultRule.getParams().getParamsList()).isEmpty();
+  }
+
+  private RuleDefinitionDto insertRule() {
+    RuleDefinitionDto rule = dbTester.rules().insert();
+    ruleIndexer.indexRuleDefinition(rule.getKey());
+    return rule;
+  }
+
+  @SafeVarargs
+  private final RuleMetadataDto insertMetadata(OrganizationDto organization, RuleDefinitionDto rule, Consumer<RuleMetadataDto>... populaters) {
+    RuleMetadataDto metadata = dbTester.rules().insertOrUpdateMetadata(rule, organization, populaters);
+    ruleIndexer.indexRuleExtension(organization, rule.getKey());
+    return metadata;
+  }
 }