]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-10134 Remove creation of built-in QG in DbTester
authorJulien Lancelot <julien.lancelot@sonarsource.com>
Mon, 11 Dec 2017 15:01:48 +0000 (16:01 +0100)
committerJulien Lancelot <julien.lancelot@sonarsource.com>
Thu, 14 Dec 2017 16:03:35 +0000 (17:03 +0100)
server/sonar-db-dao/src/test/java/org/sonar/db/DbTester.java
server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentDbTester.java
server/sonar-db-dao/src/test/java/org/sonar/db/organization/OrganizationTesting.java
server/sonar-db-dao/src/test/java/org/sonar/db/qualitygate/QualityGateDbTester.java
server/sonar-server/src/test/java/org/sonar/server/organization/OrganizationCreationImplTest.java
server/sonar-server/src/test/java/org/sonar/server/organization/ws/CreateActionTest.java
server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java
server/sonar-server/src/test/java/org/sonar/server/qualitygate/RegisterQualityGatesTest.java
server/sonar-server/src/test/java/org/sonar/server/qualitygate/ws/DestroyActionTest.java
server/sonar-server/src/test/java/org/sonar/server/ui/ws/ComponentActionTest.java

index e0d9e2322a281754ff2d3fcafb0c595ad410aada..8d923cec5f5015feaafed37fafd4390c4fc3bf40 100644 (file)
@@ -21,7 +21,6 @@ package org.sonar.db;
 
 import java.sql.Connection;
 import java.sql.SQLException;
-import java.util.Date;
 import java.util.List;
 import java.util.Map;
 import javax.annotation.Nullable;
@@ -30,7 +29,6 @@ import org.apache.commons.lang.StringUtils;
 import org.picocontainer.containers.TransientPicoContainer;
 import org.sonar.api.utils.System2;
 import org.sonar.core.util.SequenceUuidFactory;
-import org.sonar.core.util.Uuids;
 import org.sonar.db.component.ComponentDbTester;
 import org.sonar.db.event.EventDbTester;
 import org.sonar.db.favorite.FavoriteDbTester;
@@ -157,29 +155,12 @@ public class DbTester extends AbstractDbTester<TestDb> {
     db.start();
     db.truncateTables();
     initDbClient();
-    insertBuiltInQualityGateIfTableExists();
-
     if (!disableDefaultOrganization) {
       insertDefaultOrganization();
     }
     started = true;
   }
 
-  private void insertBuiltInQualityGateIfTableExists() {
-    try (DbSession dbSession = db.getMyBatis().openSession(false)) {
-      if (DatabaseUtils.tableExists("quality_gates", dbSession.getConnection())) {
-        builtInQualityGate = new QualityGateDto()
-          .setUuid(Uuids.createFast())
-          .setName("Sonar way")
-          .setBuiltIn(true)
-          .setCreatedAt(new Date(system2.now()))
-          .setCreatedAt(new Date(system2.now()));
-        client.qualityGateDao().insert(dbSession, builtInQualityGate);
-        dbSession.commit();
-      }
-    }
-  }
-
   private void insertDefaultOrganization() {
     defaultOrganization = OrganizationTesting.newOrganizationDto().setUuid(defaultOrganizationUuid);
     try (DbSession dbSession = db.getMyBatis().openSession(false)) {
index cb0349e386846380e0fdd354f64ade8ed570890b..5c3e55023577c5b719a0c6f2ac4e102dbcc6164c 100644 (file)
@@ -115,6 +115,11 @@ public class ComponentDbTester {
     return insertComponentImpl(newPublicProjectDto(organizationDto, uuid), false, noExtraConfiguration());
   }
 
+  @SafeVarargs
+  public final ComponentDto insertPrivateProject(OrganizationDto organizationDto, String uuid, Consumer<ComponentDto>... dtoPopulators) {
+    return insertComponentImpl(newPrivateProjectDto(organizationDto, uuid), true, dtoPopulators);
+  }
+
   /**
    * @deprecated since 6.6
    * @see #insertPublicPortfolio(OrganizationDto, Consumer[])
index be98e22154bb8a27a0916457a632cf9e7af1892c..b6633257bcb9628344886eec278bc8fd7d1d4a49 100644 (file)
@@ -37,6 +37,7 @@ public class OrganizationTesting {
       .setName(randomAlphanumeric(64))
       .setDescription(randomAlphanumeric(256))
       .setAvatarUrl(randomAlphanumeric(256))
+      // Default quality gate should be set explicitly when needed in tests
       .setDefaultQualityGateUuid("_NOT_SET_")
       .setUrl(randomAlphanumeric(256));
   }
index bf96e855297e1d05231a65ca8b1e48eea9d51fea..7bae477af3a88aa7655e53e9d95fefaef86ce9b7 100644 (file)
@@ -60,7 +60,8 @@ public class QualityGateDbTester {
     QualityGateDto builtinQG = dbClient.qualityGateDao().selectBuiltIn(dbSession);
     dbClient.organizationDao().update(dbSession, organizationDto.setDefaultQualityGateUuid(builtinQG.getUuid()));
     if (dbClient.qualityGateDao().selectByOrganizationAndUuid(dbSession, organizationDto, builtinQG.getUuid()) == null) {
-      associateQualityGateToOrganization(builtinQG, organizationDto);
+      dbClient.qualityGateDao().associate(dbSession, Uuids.createFast(), organizationDto, builtinQG);
+      dbSession.commit();
     }
     dbSession.commit();
   }
@@ -86,11 +87,6 @@ public class QualityGateDbTester {
     db.commit();
   }
 
-  public void associateQualityGateToOrganization(QualityGateDto qualityGate, OrganizationDto organization) {
-    dbClient.qualityGateDao().associate(dbSession, Uuids.createFast(), organization, qualityGate);
-    dbSession.commit();
-  }
-
   @SafeVarargs
   public final QualityGateDto createDefaultQualityGate(OrganizationDto organization, Consumer<QualityGateDto>... dtoPopulators) {
     QualityGateDto defaultQGate = insertQualityGate(organization, dtoPopulators);
index 34be4e997388ccc6c955ba8de92478850a1e1adc..eb583965ac62b3bb3e8656adfe9e23923bd99fd3 100644 (file)
@@ -169,6 +169,7 @@ public class OrganizationCreationImplTest {
   @Test
   public void create_fails_with_ISE_if_BuiltInQProfileRepository_has_not_been_initialized() throws OrganizationCreation.KeyConflictException {
     UserDto user = db.users().insertUser();
+    db.qualityGates().insertBuiltInQualityGate();
 
     expectedException.expect(IllegalStateException.class);
     expectedException.expectMessage("initialize must be called first");
@@ -191,6 +192,7 @@ public class OrganizationCreationImplTest {
   public void create_creates_unguarded_organization_with_properties_from_NewOrganization_arg() throws OrganizationCreation.KeyConflictException {
     builtInQProfileRepositoryRule.initialize();
     UserDto user = db.users().insertUser();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.create(dbSession, user, FULL_POPULATED_NEW_ORGANIZATION);
 
@@ -211,6 +213,7 @@ public class OrganizationCreationImplTest {
   public void create_creates_owners_group_with_all_permissions_for_new_organization_and_add_current_user_to_it() throws OrganizationCreation.KeyConflictException {
     UserDto user = db.users().insertUser();
     builtInQProfileRepositoryRule.initialize();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.create(dbSession, user, FULL_POPULATED_NEW_ORGANIZATION);
 
@@ -221,6 +224,7 @@ public class OrganizationCreationImplTest {
   public void create_creates_members_group_and_add_current_user_to_it() throws OrganizationCreation.KeyConflictException {
     UserDto user = db.users().insertUser();
     builtInQProfileRepositoryRule.initialize();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.create(dbSession, user, FULL_POPULATED_NEW_ORGANIZATION);
 
@@ -231,6 +235,7 @@ public class OrganizationCreationImplTest {
   public void create_does_not_require_description_url_and_avatar_to_be_non_null() throws OrganizationCreation.KeyConflictException {
     builtInQProfileRepositoryRule.initialize();
     UserDto user = db.users().insertUser();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.create(dbSession, user, newOrganizationBuilder()
       .setKey("key")
@@ -251,6 +256,7 @@ public class OrganizationCreationImplTest {
   public void create_creates_default_template_for_new_organization() throws OrganizationCreation.KeyConflictException {
     builtInQProfileRepositoryRule.initialize();
     UserDto user = db.users().insertUser();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.create(dbSession, user, FULL_POPULATED_NEW_ORGANIZATION);
 
@@ -274,6 +280,7 @@ public class OrganizationCreationImplTest {
   public void create_add_current_user_as_member_of_organization() throws OrganizationCreation.KeyConflictException {
     UserDto user = db.users().insertUser();
     builtInQProfileRepositoryRule.initialize();
+    db.qualityGates().insertBuiltInQualityGate();
 
     OrganizationDto result = underTest.create(dbSession, user, FULL_POPULATED_NEW_ORGANIZATION);
 
@@ -289,6 +296,7 @@ public class OrganizationCreationImplTest {
     insertRulesProfile(builtIn1);
     insertRulesProfile(builtIn2);
     UserDto user = db.users().insertUser();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.create(dbSession, user, FULL_POPULATED_NEW_ORGANIZATION);
 
@@ -312,7 +320,7 @@ public class OrganizationCreationImplTest {
 
   @Test
   public void create_associates_to_built_in_quality_gate() throws OrganizationCreation.KeyConflictException {
-    QualityGateDto builtInQualityGate = qualityGateFinder.getBuiltInQualityGate(dbSession);
+    QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate();
     builtInQProfileRepositoryRule.initialize();
     UserDto user = db.users().insertUser();
 
@@ -357,6 +365,7 @@ public class OrganizationCreationImplTest {
     when(organizationValidation.generateKeyFrom(A_LOGIN)).thenReturn(SLUG_OF_A_LOGIN);
     enableCreatePersonalOrg(true);
     builtInQProfileRepositoryRule.initialize();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.createForUser(dbSession, user);
 
@@ -393,6 +402,7 @@ public class OrganizationCreationImplTest {
     when(organizationValidation.generateKeyFrom(A_LOGIN)).thenReturn(SLUG_OF_A_LOGIN);
     enableCreatePersonalOrg(true);
     builtInQProfileRepositoryRule.initialize();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.createForUser(dbSession, user);
 
@@ -407,6 +417,7 @@ public class OrganizationCreationImplTest {
     when(organizationValidation.generateKeyFrom(A_LOGIN)).thenReturn(SLUG_OF_A_LOGIN);
     enableCreatePersonalOrg(true);
     builtInQProfileRepositoryRule.initialize();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.createForUser(dbSession, user);
 
@@ -419,6 +430,7 @@ public class OrganizationCreationImplTest {
     when(organizationValidation.generateKeyFrom(A_LOGIN)).thenReturn(SLUG_OF_A_LOGIN);
     enableCreatePersonalOrg(true);
     builtInQProfileRepositoryRule.initialize();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.createForUser(dbSession, user);
 
@@ -446,6 +458,7 @@ public class OrganizationCreationImplTest {
     when(organizationValidation.generateKeyFrom(A_LOGIN)).thenReturn(SLUG_OF_A_LOGIN);
     enableCreatePersonalOrg(true);
     builtInQProfileRepositoryRule.initialize();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.createForUser(dbSession, user);
 
@@ -460,6 +473,7 @@ public class OrganizationCreationImplTest {
     when(organizationValidation.generateKeyFrom(A_LOGIN)).thenReturn(SLUG_OF_A_LOGIN);
     enableCreatePersonalOrg(true);
     builtInQProfileRepositoryRule.initialize();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.createForUser(dbSession, user);
 
@@ -475,6 +489,7 @@ public class OrganizationCreationImplTest {
     when(organizationValidation.generateKeyFrom(login)).thenReturn(SLUG_OF_A_LOGIN);
     enableCreatePersonalOrg(true);
     builtInQProfileRepositoryRule.initialize();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.createForUser(dbSession, user);
 
@@ -490,6 +505,7 @@ public class OrganizationCreationImplTest {
     when(organizationValidation.generateKeyFrom(login)).thenReturn(SLUG_OF_A_LOGIN);
     enableCreatePersonalOrg(true);
     builtInQProfileRepositoryRule.initialize();
+    db.qualityGates().insertBuiltInQualityGate();
 
     underTest.createForUser(dbSession, user);
 
@@ -503,7 +519,7 @@ public class OrganizationCreationImplTest {
     UserDto user = db.users().insertUser(A_LOGIN);
     when(organizationValidation.generateKeyFrom(A_LOGIN)).thenReturn(SLUG_OF_A_LOGIN);
     enableCreatePersonalOrg(true);
-
+    db.qualityGates().insertBuiltInQualityGate();
     BuiltInQProfile builtIn1 = builtInQProfileRepositoryRule.add(newLanguage("foo"), "qp1");
     BuiltInQProfile builtIn2 = builtInQProfileRepositoryRule.add(newLanguage("foo"), "qp2");
     builtInQProfileRepositoryRule.initialize();
@@ -520,7 +536,7 @@ public class OrganizationCreationImplTest {
 
   @Test
   public void createForUser_associates_to_built_in_quality_gate() {
-    QualityGateDto builtInQualityGate = qualityGateFinder.getBuiltInQualityGate(dbSession);
+    QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate();
     UserDto user = db.users().insertUser(A_LOGIN);
     when(organizationValidation.generateKeyFrom(A_LOGIN)).thenReturn(SLUG_OF_A_LOGIN);
     enableCreatePersonalOrg(true);
index 6a22e8d4ec160c7004311eed0008f150959e22e3..bc64b63b1e92d5f7fd6bc3ecb4b0347e2d9c95ab 100644 (file)
@@ -155,6 +155,7 @@ public class CreateActionTest {
   public void verify_response_example() throws URISyntaxException, IOException {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(Uuids.UUID_EXAMPLE_01, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     String response = executeJsonRequest("Foo Company", "foo-company", "The Foo company produces quality software for Bar.", "https://www.foo.com", "https://www.foo.com/foo.png");
 
@@ -196,6 +197,7 @@ public class CreateActionTest {
   public void request_succeeds_if_user_is_system_administrator_and_logged_in_users_cannot_create_organizations() {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     verifyResponseAndDb(executeRequest("foo"), SOME_UUID, "foo", "foo", SOME_DATE);
   }
@@ -205,6 +207,7 @@ public class CreateActionTest {
     logInAsSystemAdministrator();
     settings.setProperty(ORGANIZATIONS_ANYONE_CAN_CREATE, true);
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     verifyResponseAndDb(executeRequest("foo"), SOME_UUID, "foo", "foo", SOME_DATE);
   }
@@ -214,6 +217,7 @@ public class CreateActionTest {
     userSession.logIn(user);
     settings.setProperty(ORGANIZATIONS_ANYONE_CAN_CREATE, true);
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     verifyResponseAndDb(executeRequest("foo"), SOME_UUID, "foo", "foo", SOME_DATE);
   }
@@ -242,6 +246,7 @@ public class CreateActionTest {
   public void request_succeeds_if_name_is_two_chars_long() {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     verifyResponseAndDb(executeRequest("ab"), SOME_UUID, "ab", "ab", SOME_DATE);
   }
@@ -260,6 +265,7 @@ public class CreateActionTest {
   public void request_succeeds_if_name_is_64_char_long() {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     String name = STRING_65_CHARS_LONG.substring(0, 64);
 
@@ -292,6 +298,7 @@ public class CreateActionTest {
   public void request_succeeds_if_key_is_2_chars_long() {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     verifyResponseAndDb(executeRequest("foo", "ab"), SOME_UUID, "foo", "ab", SOME_DATE);
   }
@@ -300,6 +307,7 @@ public class CreateActionTest {
   public void requests_succeeds_if_key_is_32_chars_long() {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     String key = STRING_65_CHARS_LONG.substring(0, 32);
 
@@ -370,6 +378,7 @@ public class CreateActionTest {
   public void request_succeeds_if_description_url_and_avatar_are_not_specified() {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     CreateWsResponse response = executeRequest("foo", "bar", null, null, null);
     verifyResponseAndDb(response, SOME_UUID, "foo", "bar", null, null, null, SOME_DATE);
@@ -379,6 +388,7 @@ public class CreateActionTest {
   public void request_succeeds_if_description_url_and_avatar_are_specified() {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     CreateWsResponse response = executeRequest("foo", "bar", "moo", "doo", "boo");
     verifyResponseAndDb(response, SOME_UUID, "foo", "bar", "moo", "doo", "boo", SOME_DATE);
@@ -388,6 +398,7 @@ public class CreateActionTest {
   public void request_succeeds_to_generate_key_from_name_more_then_32_chars_long() {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     String name = STRING_65_CHARS_LONG.substring(0, 33);
 
@@ -399,6 +410,7 @@ public class CreateActionTest {
   public void request_generates_key_ignoring_multiple_following_spaces() {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     String name = "ab   cd";
 
@@ -421,6 +433,7 @@ public class CreateActionTest {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
     String description = STRING_257_CHARS_LONG.substring(0, 256);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     CreateWsResponse response = executeRequest("foo", "bar", description, null, null);
     verifyResponseAndDb(response, SOME_UUID, "foo", "bar", description, null, null, SOME_DATE);
@@ -441,6 +454,7 @@ public class CreateActionTest {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
     String url = STRING_257_CHARS_LONG.substring(0, 256);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     CreateWsResponse response = executeRequest("foo", "bar", null, url, null);
     verifyResponseAndDb(response, SOME_UUID, "foo", "bar", null, url, null, SOME_DATE);
@@ -461,6 +475,7 @@ public class CreateActionTest {
     logInAsSystemAdministrator();
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
     String avatar = STRING_257_CHARS_LONG.substring(0, 256);
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     CreateWsResponse response = executeRequest("foo", "bar", null, null, avatar);
     verifyResponseAndDb(response, SOME_UUID, "foo", "bar", null, null, avatar, SOME_DATE);
@@ -471,6 +486,7 @@ public class CreateActionTest {
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
     UserDto user = dbTester.users().insertUser();
     userSession.logIn(user).setSystemAdministrator();
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     executeRequest("orgFoo");
 
@@ -499,6 +515,7 @@ public class CreateActionTest {
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
     UserDto user = dbTester.users().insertUser();
     userSession.logIn(user).setSystemAdministrator();
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     executeRequest("orgFoo");
 
@@ -526,6 +543,7 @@ public class CreateActionTest {
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
     UserDto user = dbTester.users().insertUser();
     userSession.logIn(user).setSystemAdministrator();
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     executeRequest("orgFoo");
 
@@ -550,6 +568,7 @@ public class CreateActionTest {
     mockForSuccessfulInsert(SOME_UUID, SOME_DATE);
     UserDto user = dbTester.users().insertUser();
     userSession.logIn(user).setSystemAdministrator();
+    dbTester.qualityGates().insertBuiltInQualityGate();
 
     executeRequest("orgFoo");
 
index e8da7431e3d8c745c4e0dca0762ac3a0874b8610..b8e037b600b60426487c12de50ccd9caf605696a 100644 (file)
@@ -356,6 +356,7 @@ public class DeleteActionTest {
     OrganizationDto otherOrg = db.organizations().insert();
     QGateWithOrgDto qualityGate = db.qualityGates().insertQualityGate(org);
     QGateWithOrgDto qualityGateInOtherOrg = db.qualityGates().insertQualityGate(otherOrg);
+    db.qualityGates().insertBuiltInQualityGate();
     logInAsAdministrator(org);
 
     sendRequest(org);
index 8a848f2bd9fac3a2efedf0f254227e7c430618b1..c28a5ea95384fceaa8b08292a87930bd488ce5d8 100644 (file)
 package org.sonar.server.qualitygate;
 
 import java.util.ArrayList;
+import java.util.Date;
 import java.util.List;
 import java.util.Random;
-import org.junit.After;
-import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.utils.System2;
@@ -72,33 +71,18 @@ public class RegisterQualityGatesTest {
   private QualityGateConditionDao gateConditionDao = dbClient.gateConditionDao();
   private MetricDao metricDao = dbClient.metricDao();
   private QualityGateConditionsUpdater qualityGateConditionsUpdater = new QualityGateConditionsUpdater(dbClient);
-  private QualityGateUpdater qualityGateUpdater = new QualityGateUpdater(dbClient, UuidFactoryFast.getInstance());
   private QualityGateFinder qualityGateFinder = new QualityGateFinder(dbClient);
 
   private RegisterQualityGates underTest = new RegisterQualityGates(dbClient, qualityGateConditionsUpdater,
     UuidFactoryFast.getInstance(), System2.INSTANCE);
-  private QualityGateDto builtInQG;
-
-  @Before
-  public void setup() {
-    insertMetrics();
-    builtInQG = qualityGateFinder.getBuiltInQualityGate(dbSession);
-  }
-
-  @After
-  public void after() {
-    underTest.stop();
-  }
 
   @Test
   public void register_default_gate() {
-    dbClient.qualityGateDao().delete(builtInQG, dbSession);
-    dbSession.commit();
+    insertMetrics();
 
     underTest.start();
 
     verifyCorrectBuiltInQualityGate();
-
     assertThat(
       logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate [Sonar way] has been created")).isTrue();
     assertThat(
@@ -107,27 +91,28 @@ public class RegisterQualityGatesTest {
 
   @Test
   public void upgrade_empty_quality_gate() {
-    dbSession.commit();
+    insertMetrics();
 
     underTest.start();
+
     assertThat(db.countRowsOfTable("quality_gates")).isEqualTo(1);
     verifyCorrectBuiltInQualityGate();
-
     assertThat(
       logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate's conditions of [Sonar way] has been updated")).isTrue();
   }
 
   @Test
   public void upgrade_should_remove_deleted_condition() {
-    createBuiltInConditions(builtInQG);
-
+    insertMetrics();
+    QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate();
+    createBuiltInConditions(builtInQualityGate);
     // Add another condition
-    qualityGateConditionsUpdater.createCondition(dbSession, builtInQG,
+    qualityGateConditionsUpdater.createCondition(dbSession, builtInQualityGate,
       NEW_SECURITY_REMEDIATION_EFFORT_KEY, OPERATOR_GREATER_THAN, null, "5", LEAK_PERIOD);
-
     dbSession.commit();
 
     underTest.start();
+
     assertThat(db.countRowsOfTable("quality_gates")).isEqualTo(1);
     verifyCorrectBuiltInQualityGate();
     assertThat(
@@ -136,47 +121,53 @@ public class RegisterQualityGatesTest {
 
   @Test
   public void upgrade_should_add_missing_condition() {
-    List<QualityGateConditionDto> builtInConditions = createBuiltInConditions(builtInQG);
-
+    insertMetrics();
+    QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate();
+    List<QualityGateConditionDto> builtInConditions = createBuiltInConditions(builtInQualityGate);
     // Remove a condition
     QualityGateConditionDto conditionToBeDeleted = builtInConditions.get(new Random().nextInt(builtInConditions.size()));
     gateConditionDao.delete(conditionToBeDeleted, dbSession);
-
     dbSession.commit();
 
     underTest.start();
+
     assertThat(db.countRowsOfTable("quality_gates")).isEqualTo(1);
     verifyCorrectBuiltInQualityGate();
-
     assertThat(
       logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate's conditions of [Sonar way] has been updated")).isTrue();
   }
 
   @Test
   public void should_set_SonarWay_as_builtin_when_not_set() {
-    dbClient.qualityGateDao().delete(builtInQG, dbSession);
-    QualityGateDto builtin = new QualityGateDto().setName(BUILT_IN_NAME).setBuiltIn(false).setUuid(Uuids.createFast());
-    qualityGateDao.insert(dbSession, builtin);
-    createBuiltInConditions(builtin);
+    insertMetrics();
+    QualityGateDto qualityGate = dbClient.qualityGateDao().insert(dbSession, new QualityGateDto()
+      .setName("Sonar way")
+      .setUuid(Uuids.createFast())
+      .setBuiltIn(false)
+      .setCreatedAt(new Date()));
+    dbSession.commit();
+    createBuiltInConditions(qualityGate);
     dbSession.commit();
 
     underTest.start();
+
     assertThat(db.countRowsOfTable("quality_gates")).isEqualTo(1);
     verifyCorrectBuiltInQualityGate();
-
     assertThat(
       logTester.logs(LoggerLevel.INFO).contains("Quality gate [Sonar way] has been set as built-in")).isTrue();
   }
 
   @Test
   public void should_not_update_builtin_quality_gate_if_already_uptodate() {
-    createBuiltInConditions(builtInQG);
+    insertMetrics();
+    QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate();
+    createBuiltInConditions(builtInQualityGate);
     dbSession.commit();
 
     underTest.start();
+
     assertThat(db.countRowsOfTable("quality_gates")).isEqualTo(1);
     verifyCorrectBuiltInQualityGate();
-
     // Log must not be present
     assertThat(
       logTester.logs(LoggerLevel.INFO).contains("Quality gate [Sonar way] has been set as built-in")).isFalse();
@@ -188,7 +179,7 @@ public class RegisterQualityGatesTest {
 
   @Test
   public void ensure_only_one_built_in_quality_gate() {
-    dbClient.qualityGateDao().delete(builtInQG, dbSession);
+    insertMetrics();
     String qualityGateName = "IncorrectQualityGate";
     QualityGateDto builtin = new QualityGateDto().setName(qualityGateName).setBuiltIn(true).setUuid(Uuids.createFast());
     qualityGateDao.insert(dbSession, builtin);
@@ -199,11 +190,9 @@ public class RegisterQualityGatesTest {
     QualityGateDto oldQualityGate = qualityGateDao.selectByName(dbSession, qualityGateName);
     assertThat(oldQualityGate).isNotNull();
     assertThat(oldQualityGate.isBuiltIn()).isFalse();
-
     assertThat(db.select("select name as \"name\" from quality_gates where is_built_in is true"))
       .extracting(column -> column.get("name"))
       .containsExactly(BUILT_IN_NAME);
-
     assertThat(
       logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate [Sonar way] has been created")).isTrue();
     assertThat(
@@ -212,15 +201,18 @@ public class RegisterQualityGatesTest {
 
   @Test
   public void ensure_only_that_builtin_is_set_as_default_when_no_default_quality_gate() {
+    insertMetrics();
+    QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate();
 
     underTest.start();
 
     assertThat(qualityGateFinder.getBuiltInQualityGate(dbSession)).isNotNull();
-    assertThat(qualityGateFinder.getBuiltInQualityGate(dbSession).getId()).isEqualTo(builtInQG.getId());
+    assertThat(qualityGateFinder.getBuiltInQualityGate(dbSession).getId()).isEqualTo(builtInQualityGate.getId());
   }
 
   @Test
   public void builtin_quality_gate_with_incorrect_metricId_should_not_throw_an_exception() {
+    insertMetrics();
     QualityGateConditionDto conditionDto = new QualityGateConditionDto()
       .setMetricId(-1) // This Id does not exist
       .setOperator(OPERATOR_GREATER_THAN)
@@ -233,7 +225,6 @@ public class RegisterQualityGatesTest {
 
     // No exception thrown
     verifyCorrectBuiltInQualityGate();
-
     assertThat(
       logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate's conditions of [Sonar way] has been updated")).isTrue();
   }
index 65feb0d94f332bb10363c0ad9e819c9de90b1a65..e51ccc1780184f18396547ac17032227a89ad39e 100644 (file)
@@ -24,6 +24,7 @@ import org.junit.Test;
 import org.junit.rules.ExpectedException;
 import org.sonar.api.server.ws.WebService;
 import org.sonar.api.utils.System2;
+import org.sonar.core.util.Uuids;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.DbTester;
@@ -60,7 +61,6 @@ public class DestroyActionTest {
   private DbClient dbClient = db.getDbClient();
   private TestDefaultOrganizationProvider organizationProvider = TestDefaultOrganizationProvider.from(db);
   private QualityGateFinder qualityGateFinder = new QualityGateFinder(dbClient);
-  private QualityGateDbTester qualityGateDbTester = new QualityGateDbTester(db);
   private QualityGatesWsSupport wsSupport = new QualityGatesWsSupport(db.getDbClient(), userSession, organizationProvider);
 
   private DbSession dbSession = db.getSession();
@@ -70,10 +70,9 @@ public class DestroyActionTest {
   @Test
   public void delete_quality_gate() {
     OrganizationDto organization = db.organizations().insert();
-    userSession.addPermission(ADMINISTER_QUALITY_GATES, organization);
+    db.qualityGates().createDefaultQualityGate(organization);
     QGateWithOrgDto qualityGate = db.qualityGates().insertQualityGate(organization);
-
-    qualityGateDbTester.setBuiltInAsDefaultOn(organization);
+    userSession.addPermission(ADMINISTER_QUALITY_GATES, organization);
 
     ws.newRequest()
       .setParam(PARAM_ID, qualityGate.getId().toString())
@@ -81,19 +80,14 @@ public class DestroyActionTest {
       .execute();
 
     assertThat(db.getDbClient().qualityGateDao().selectByOrganizationAndId(dbSession, organization, qualityGate.getId())).isNull();
-    assertThat(db.countRowsOfTable(dbSession, "org_quality_gates")).isEqualTo(1); // built-in quality gate
   }
 
   @Test
   public void delete_quality_gate_if_non_default_when_a_default_exist() {
     OrganizationDto organization = db.organizations().insert();
-    userSession.addPermission(ADMINISTER_QUALITY_GATES, organization);
+    db.qualityGates().createDefaultQualityGate(organization);
     QGateWithOrgDto qualityGate = db.qualityGates().insertQualityGate(organization);
-
-    qualityGateDbTester.setBuiltInAsDefaultOn(organization);
-
-    QualityGateDto defaultQualityGate = db.qualityGates().insertQualityGate(organization);
-    db.qualityGates().setDefaultQualityGate(organization, defaultQualityGate);
+    userSession.addPermission(ADMINISTER_QUALITY_GATES, organization);
 
     ws.newRequest()
       .setParam(PARAM_ID, valueOf(qualityGate.getId()))
@@ -106,27 +100,27 @@ public class DestroyActionTest {
   @Test
   public void does_not_delete_built_in_quality_gate() {
     OrganizationDto organization = db.organizations().insert();
-    qualityGateDbTester.setBuiltInAsDefaultOn(organization);
-
+    db.qualityGates().createDefaultQualityGate(organization);
+    QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate();
+    db.getDbClient().qualityGateDao().associate(db.getSession(), Uuids.createFast(), organization, builtInQualityGate);
+    db.commit();
     userSession.addPermission(ADMINISTER_QUALITY_GATES, organization);
-    QGateWithOrgDto qualityGate = db.qualityGates().insertQualityGate(organization, qg -> qg.setBuiltIn(true));
 
     expectedException.expect(IllegalArgumentException.class);
-    expectedException.expectMessage(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName()));
+    expectedException.expectMessage(format("Operation forbidden for built-in Quality Gate '%s'", builtInQualityGate.getName()));
 
     ws.newRequest()
-      .setParam(PARAM_ID, valueOf(qualityGate.getId()))
+      .setParam(PARAM_ID, valueOf(builtInQualityGate.getId()))
       .setParam(PARAM_ORGANIZATION, organization.getKey())
       .execute();
   }
 
   @Test
   public void default_organization_is_used_when_no_organization_parameter() {
-    userSession.addPermission(ADMINISTER_QUALITY_GATES, db.getDefaultOrganization());
-
-    qualityGateDbTester.setBuiltInAsDefaultOn(db.getDefaultOrganization());
-
-    QGateWithOrgDto qualityGate = db.qualityGates().insertQualityGate(db.getDefaultOrganization());
+    OrganizationDto defaultOrganization = db.getDefaultOrganization();
+    db.qualityGates().createDefaultQualityGate(defaultOrganization);
+    userSession.addPermission(ADMINISTER_QUALITY_GATES, defaultOrganization);
+    QGateWithOrgDto qualityGate = db.qualityGates().insertQualityGate(defaultOrganization);
     OrganizationDto otherOrganization = db.organizations().insert();
     QGateWithOrgDto otherQualityGate = db.qualityGates().insertQualityGate(otherOrganization);
 
@@ -134,7 +128,7 @@ public class DestroyActionTest {
       .setParam(PARAM_ID, valueOf(qualityGate.getId()))
       .execute();
 
-    assertThat(db.getDbClient().qualityGateDao().selectByOrganizationAndId(dbSession, db.getDefaultOrganization(), qualityGate.getId())).isNull();
+    assertThat(db.getDbClient().qualityGateDao().selectByOrganizationAndId(dbSession, defaultOrganization, qualityGate.getId())).isNull();
   }
 
   @Test
@@ -169,15 +163,14 @@ public class DestroyActionTest {
   @Test
   public void fail_to_delete_default_quality_gate() {
     OrganizationDto organization = db.organizations().insert();
+    QualityGateDto defaultQualityGate = db.qualityGates().createDefaultQualityGate(organization);
     userSession.addPermission(ADMINISTER_QUALITY_GATES, organization);
-    QGateWithOrgDto qualityGate = db.qualityGates().insertQualityGate(organization);
-    db.qualityGates().setDefaultQualityGate(organization, qualityGate);
 
     expectedException.expect(IllegalArgumentException.class);
     expectedException.expectMessage("The default quality gate cannot be removed");
 
     ws.newRequest()
-      .setParam(PARAM_ID, valueOf(qualityGate.getId()))
+      .setParam(PARAM_ID, valueOf(defaultQualityGate.getId()))
       .setParam(PARAM_ORGANIZATION, organization.getKey())
       .execute();
   }
@@ -198,11 +191,9 @@ public class DestroyActionTest {
   @Test
   public void fail_when_not_quality_gates_administer() {
     OrganizationDto organization = db.organizations().insert();
-
-    qualityGateDbTester.setBuiltInAsDefaultOn(organization);
-
-    userSession.logIn("john").addPermission(ADMINISTER_QUALITY_PROFILES, organization);
     QGateWithOrgDto qualityGate = db.qualityGates().insertQualityGate(organization);
+    db.qualityGates().createDefaultQualityGate(organization);
+    userSession.logIn("john").addPermission(ADMINISTER_QUALITY_PROFILES, organization);
 
     expectedException.expect(ForbiddenException.class);
 
index 1492e5840ea94c874f4924aa63d6abb5f312b79d..9a45de0e026c51ed2f214eaeb8156b6f4c973eb3 100644 (file)
@@ -22,7 +22,6 @@ package org.sonar.server.ui.ws;
 import java.util.Arrays;
 import java.util.Date;
 import java.util.List;
-import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
@@ -30,7 +29,6 @@ import org.sonar.api.resources.ResourceType;
 import org.sonar.api.resources.ResourceTypes;
 import org.sonar.api.server.ws.Change;
 import org.sonar.api.server.ws.WebService;
-import org.sonar.api.utils.DateUtils;
 import org.sonar.api.utils.System2;
 import org.sonar.api.web.UserRole;
 import org.sonar.api.web.page.Page;
@@ -70,6 +68,7 @@ import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.sonar.api.measures.CoreMetrics.QUALITY_PROFILES_KEY;
+import static org.sonar.api.utils.DateUtils.parseDateTime;
 import static org.sonar.api.web.page.Page.Scope.COMPONENT;
 import static org.sonar.db.component.ComponentTesting.newDirectory;
 import static org.sonar.db.component.ComponentTesting.newFileDto;
@@ -102,132 +101,72 @@ public class ComponentActionTest {
   private WsActionTester ws;
   private OrganizationDto organization;
 
-  @Before
-  public void before() {
-    organization = dbTester.organizations().insertForKey("my-org");
-    project = newPrivateProjectDto(organization, "abcd")
-      .setDbKey("polop")
-      .setName("Polop")
-      .setDescription("test project")
-      .setLanguage("xoo");
-    dbTester.qualityGates().setBuiltInAsDefaultOn(organization);
-    dbTester.qualityGates().setBuiltInAsDefaultOn(dbTester.getDefaultOrganization());
-  }
-
-  @Test
-  public void check_definition() {
-    init();
-    WebService.Action action = ws.getDef();
-
-    assertThat(action.since()).isEqualTo("5.2");
-    assertThat(action.isPost()).isFalse();
-    assertThat(action.isInternal()).isTrue();
-    assertThat(action.description()).isNotNull();
-    assertThat(action.responseExample()).isNotNull();
-    assertThat(action.changelog()).extracting(Change::getVersion, Change::getDescription).containsExactlyInAnyOrder(
-      tuple("6.4", "The 'visibility' field is added"));
-
-    WebService.Param componentId = action.param(PARAM_COMPONENT);
-    assertThat(componentId.isRequired()).isFalse();
-    assertThat(componentId.description()).isNotNull();
-    assertThat(componentId.exampleValue()).isNotNull();
-    assertThat(componentId.deprecatedKey()).isEqualTo("componentKey");
-    assertThat(componentId.deprecatedKeySince()).isEqualTo("6.4");
-  }
-
-  @Test
-  public void fail_on_missing_parameters() {
-    init();
-
-    expectedException.expect(IllegalArgumentException.class);
-    ws.newRequest().execute();
-  }
-
-  @Test
-  public void fail_on_unknown_component_key() {
-    init();
-
-    expectedException.expect(NotFoundException.class);
-    execute(project.getDbKey());
-  }
-
-  @Test
-  public void throw_ForbiddenException_if_required_permission_is_not_granted() {
-    init();
-    componentDbTester.insertComponent(project);
-    userSession.logIn();
-
-    expectedException.expect(ForbiddenException.class);
-    execute(project.getDbKey());
-  }
-
   @Test
   public void return_info_if_user_has_browse_permission_on_project() {
-    init();
-    componentDbTester.insertComponent(project);
+    ComponentDto project = insertOrganizationAndProject();
     userSession.logIn().addProjectPermission(UserRole.USER, project);
+    init();
 
-    verifySuccess(project.getDbKey());
+    verifySuccess(project.getKey());
   }
 
   @Test
   public void return_info_if_user_has_administration_permission_on_project() {
-    init();
-    componentDbTester.insertComponent(project);
+    ComponentDto project = insertOrganizationAndProject();
     userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
+    init();
 
     verifySuccess(project.getDbKey());
   }
 
   @Test
   public void return_info_if_user_is_system_administrator() {
-    init();
-    componentDbTester.insertComponent(project);
+    ComponentDto project = insertOrganizationAndProject();
     userSession.logIn().setSystemAdministrator();
+    init();
 
     verifySuccess(project.getDbKey());
   }
 
   @Test
   public void return_component_info_when_anonymous_no_snapshot() {
-    init();
-    componentDbTester.insertComponent(project);
+    ComponentDto project = insertOrganizationAndProject();
     userSession.addProjectPermission(UserRole.USER, project);
+    init();
 
     executeAndVerify(project.getDbKey(), "return_component_info_when_anonymous_no_snapshot.json");
   }
 
   @Test
   public void return_component_info_with_favourite() {
-    init();
+    ComponentDto project = insertOrganizationAndProject();
     UserDto user = dbTester.users().insertUser("obiwan");
-    componentDbTester.insertComponent(project);
     propertyDbTester.insertProperty(new PropertyDto().setKey("favourite").setResourceId(project.getId()).setUserId(user.getId()));
     userSession.logIn(user).addProjectPermission(UserRole.USER, project);
+    init();
 
     executeAndVerify(project.getDbKey(), "return_component_info_with_favourite.json");
   }
 
   @Test
   public void return_component_info_when_snapshot() {
-    init();
-    componentDbTester.insertComponent(project);
-    componentDbTester.insertSnapshot(newAnalysis(project)
-      .setCreatedAt(DateUtils.parseDateTime("2015-04-22T11:44:00+0200").getTime())
-      .setVersion("3.14")
-      .setLast(true));
+    ComponentDto project = insertOrganizationAndProject();
+    dbTester.components().insertSnapshot(project, snapshot -> snapshot
+      .setCreatedAt(parseDateTime("2015-04-22T11:44:00+0200").getTime())
+      .setVersion("3.14"));
     userSession.addProjectPermission(UserRole.USER, project);
+    init();
 
     executeAndVerify(project.getDbKey(), "return_component_info_when_snapshot.json");
   }
 
   @Test
   public void return_component_info_when_file_on_master() {
-    init();
-    OrganizationDto organization = dbTester.organizations().insertForKey("my-org2");
-    dbTester.qualityGates().setBuiltInAsDefaultOn(organization);
+    OrganizationDto organization = dbTester.organizations().insert(o -> o.setKey("my-org2"));
+    dbTester.qualityGates().createDefaultQualityGate(organization);
     ComponentDto main = componentDbTester.insertMainBranch(organization, p -> p.setName("Sample"), p -> p.setDbKey("sample"));
     userSession.addProjectPermission(UserRole.USER, main);
+    init();
 
     ComponentDto dirDto = componentDbTester.insertComponent(newDirectory(main, "src"));
 
@@ -241,12 +180,12 @@ public class ComponentActionTest {
 
   @Test
   public void return_component_info_when_file_on_branch() {
-    init();
     OrganizationDto organization = dbTester.organizations().insertForKey("my-org2");
-    dbTester.qualityGates().setBuiltInAsDefaultOn(organization);
+    dbTester.qualityGates().createDefaultQualityGate(organization);
     ComponentDto project = componentDbTester.insertMainBranch(organization, p -> p.setName("Sample"), p -> p.setDbKey("sample"));
     ComponentDto branch = componentDbTester.insertProjectBranch(project, b -> b.setKey("feature1"));
     userSession.addProjectPermission(UserRole.USER, project);
+    init();
 
     ComponentDto dirDto = componentDbTester.insertComponent(newDirectory(branch, "src"));
 
@@ -265,68 +204,73 @@ public class ComponentActionTest {
 
   @Test
   public void return_quality_profiles() {
-    init();
-    componentDbTester.insertComponent(project);
+    ComponentDto project = insertOrganizationAndProject();
     addQualityProfiles(project,
       createQProfile("qp1", "Sonar Way Java", "java"),
       createQProfile("qp2", "Sonar Way Xoo", "xoo"));
     userSession.addProjectPermission(UserRole.USER, project);
+    init();
 
     executeAndVerify(project.getDbKey(), "return_quality_profiles.json");
   }
 
   @Test
   public void return_empty_quality_profiles_when_no_measure() {
-    init();
-    componentDbTester.insertComponent(project);
+    ComponentDto project = insertOrganizationAndProject();
     userSession.addProjectPermission(UserRole.USER, project);
+    init();
 
     executeAndVerify(project.getDbKey(), "return_empty_quality_profiles_when_no_measure.json");
   }
 
   @Test
   public void return_quality_gate_defined_on_project() {
-    init();
-    componentDbTester.insertComponent(project);
-    QualityGateDto qualityGateDto = dbTester.qualityGates().insertQualityGate(dbTester.getDefaultOrganization(), qg -> qg.setName("Sonar way"));
+    OrganizationDto organization = dbTester.organizations().insert(o -> o.setKey("my-org"));
+    dbTester.qualityGates().createDefaultQualityGate(organization);
+    ComponentDto project = dbTester.components().insertPrivateProject(organization);
+    QualityGateDto qualityGateDto = dbTester.qualityGates().insertQualityGate(organization, qg -> qg.setName("Sonar way"));
     dbTester.qualityGates().associateProjectToQualityGate(project, qualityGateDto);
     userSession.addProjectPermission(UserRole.USER, project);
+    init();
 
     executeAndVerify(project.getDbKey(), "return_quality_gate.json");
   }
 
   @Test
   public void return_default_quality_gate() {
-    init();
-    componentDbTester.insertComponent(project);
+    OrganizationDto organization = dbTester.organizations().insert(o -> o.setKey("my-org"));
+    ComponentDto project = dbTester.components().insertPrivateProject(organization);
     dbTester.qualityGates().createDefaultQualityGate(organization, qg -> qg.setName("Sonar way"));
     userSession.addProjectPermission(UserRole.USER, project);
+    init();
 
     executeAndVerify(project.getDbKey(), "return_default_quality_gate.json");
   }
 
   @Test
   public void return_extensions() {
-    init(createPages());
-    componentDbTester.insertComponent(project);
+    ComponentDto project = insertOrganizationAndProject();
     userSession.anonymous().addProjectPermission(UserRole.USER, project);
+    init(createPages());
 
     executeAndVerify(project.getDbKey(), "return_extensions.json");
   }
 
   @Test
   public void return_extensions_for_application() {
+    OrganizationDto organization = dbTester.organizations().insert(o -> o.setKey("my-org"));
+    dbTester.qualityGates().createDefaultQualityGate(organization);
+    ComponentDto project = dbTester.components().insertPrivateProject(organization);
     Page page = Page.builder("my_plugin/app_page")
       .setName("App Page")
       .setScope(COMPONENT)
       .setComponentQualifiers(Qualifier.VIEW, Qualifier.APP)
       .build();
-
-    init(page);
-    ComponentDto application = componentDbTester.insertPublicApplication(dbTester.getDefaultOrganization());
-    QualityGateDto qualityGateDto = dbTester.qualityGates().insertQualityGate(dbTester.getDefaultOrganization(), qg -> qg.setName("Sonar way"));
+    ComponentDto application = componentDbTester.insertPublicApplication(organization);
+    QualityGateDto qualityGateDto = dbTester.qualityGates().insertQualityGate(organization, qg -> qg.setName("Sonar way"));
     dbTester.qualityGates().associateProjectToQualityGate(project, qualityGateDto);
     userSession.registerComponents(application);
+    init(page);
 
     String result = ws.newRequest()
       .setParam(PARAM_COMPONENT, application.getDbKey())
@@ -337,23 +281,22 @@ public class ComponentActionTest {
 
   @Test
   public void return_extensions_for_admin() {
-    init(createPages());
-    componentDbTester.insertComponent(project);
+    ComponentDto project = insertOrganizationAndProject();
     userSession.anonymous()
       .addProjectPermission(UserRole.USER, project)
       .addProjectPermission(UserRole.ADMIN, project);
+    init(createPages());
 
     executeAndVerify(project.getDbKey(), "return_extensions_for_admin.json");
   }
 
   @Test
   public void return_configuration_for_admin() {
+    ComponentDto project = insertOrganizationAndProject();
     UserDto user = dbTester.users().insertUser();
-    componentDbTester.insertComponent(project);
     userSession.logIn(user)
       .addProjectPermission(UserRole.USER, project)
       .addProjectPermission(UserRole.ADMIN, project);
-
     Page page1 = Page.builder("my_plugin/first_page")
       .setName("First Page")
       .setAdmin(true)
@@ -366,19 +309,17 @@ public class ComponentActionTest {
       .setScope(COMPONENT)
       .setComponentQualifiers(Qualifier.PROJECT)
       .build();
-
     init(page1, page2);
+
     executeAndVerify(project.getDbKey(), "return_configuration_for_admin.json");
   }
 
   @Test
   public void return_configuration_with_all_properties() {
-    init();
-    componentDbTester.insertComponent(project);
+    ComponentDto project = insertOrganizationAndProject();
     userSession.anonymous()
       .addProjectPermission(UserRole.USER, project)
       .addProjectPermission(UserRole.ADMIN, project);
-
     ResourceType projectResourceType = ResourceType.builder(project.qualifier())
       .setProperty("comparable", true)
       .setProperty("configurable", true)
@@ -389,103 +330,74 @@ public class ComponentActionTest {
       .build();
     when(resourceTypes.get(project.qualifier()))
       .thenReturn(projectResourceType);
+    init();
 
     executeAndVerify(project.getDbKey(), "return_configuration_with_all_properties.json");
   }
 
   @Test
   public void return_breadcrumbs_on_module() {
-    init();
-    ComponentDto project = componentDbTester.insertComponent(this.project);
+    ComponentDto project = insertOrganizationAndProject();
     ComponentDto module = componentDbTester.insertComponent(newModuleDto("bcde", project).setDbKey("palap").setName("Palap"));
     userSession.anonymous()
       .addProjectPermission(UserRole.USER, project)
       .addProjectPermission(UserRole.ADMIN, project);
+    init();
 
     executeAndVerify(module.getDbKey(), "return_breadcrumbs_on_module.json");
   }
 
   @Test
   public void return_configuration_for_quality_profile_admin() {
-    init();
-    componentDbTester.insertComponent(project);
+    ComponentDto project = insertOrganizationAndProject();
     userSession.logIn()
       .addProjectPermission(UserRole.USER, project)
       .addPermission(ADMINISTER_QUALITY_PROFILES, project.getOrganizationUuid());
+    init();
 
     executeAndVerify(project.getDbKey(), "return_configuration_for_quality_profile_admin.json");
   }
 
   @Test
   public void return_configuration_for_quality_gate_admin() {
-    init();
-    componentDbTester.insertComponent(project);
+    ComponentDto project = insertOrganizationAndProject();
     userSession.logIn()
       .addProjectPermission(UserRole.USER, project)
       .addPermission(ADMINISTER_QUALITY_GATES, project.getOrganizationUuid());
+    init();
 
     executeAndVerify(project.getDbKey(), "return_configuration_for_quality_gate_admin.json");
   }
 
   @Test
   public void return_bread_crumbs_on_several_levels() {
-    init();
-    ComponentDto project = componentDbTester.insertComponent(this.project);
+    ComponentDto project = insertOrganizationAndProject();
     ComponentDto module = componentDbTester.insertComponent(newModuleDto("bcde", project).setDbKey("palap").setName("Palap"));
     ComponentDto directory = componentDbTester.insertComponent(newDirectory(module, "src/main/xoo"));
     ComponentDto file = componentDbTester.insertComponent(newFileDto(directory, directory, "cdef").setName("Source.xoo")
       .setDbKey("palap:src/main/xoo/Source.xoo")
       .setPath(directory.path()));
     userSession.addProjectPermission(UserRole.USER, project);
+    init();
 
     executeAndVerify(file.getDbKey(), "return_bread_crumbs_on_several_levels.json");
   }
 
   @Test
   public void project_administrator_is_allowed_to_get_information() {
-    init(createPages());
-    componentDbTester.insertProjectAndSnapshot(project);
+    ComponentDto project = insertOrganizationAndProject();
     userSession.addProjectPermission(UserRole.ADMIN, project);
-
-    execute(project.getDbKey());
-  }
-
-  @Test
-  public void test_example_response() {
     init(createPages());
-    OrganizationDto organizationDto = dbTester.organizations().insertForKey("my-org-1");
-    ComponentDto project = newPrivateProjectDto(organizationDto, "ABCD")
-      .setDbKey("org.codehaus.sonar:sonar")
-      .setName("Sonarqube")
-      .setDescription("Open source platform for continuous inspection of code quality");
-    componentDbTester.insertComponent(project);
-    SnapshotDto analysis = newAnalysis(project)
-      .setCreatedAt(DateUtils.parseDateTime("2016-12-06T11:44:00+0200").getTime())
-      .setVersion("6.3")
-      .setLast(true);
-    componentDbTester.insertSnapshot(analysis);
-    when(resourceTypes.get(project.qualifier())).thenReturn(DefaultResourceTypes.get().getRootType());
-    UserDto user = dbTester.users().insertUser("obiwan");
-    propertyDbTester.insertProperty(new PropertyDto().setKey("favourite").setResourceId(project.getId()).setUserId(user.getId()));
-    addQualityProfiles(project,
-      createQProfile("qp1", "Sonar Way Java", "java"),
-      createQProfile("qp2", "Sonar Way Xoo", "xoo"));
-    QualityGateDto qualityGateDto = dbTester.qualityGates().insertQualityGate(dbTester.getDefaultOrganization(), qg -> qg.setName("Sonar way"));
-    dbTester.qualityGates().associateProjectToQualityGate(project, qualityGateDto);
-    userSession.logIn(user)
-      .addProjectPermission(UserRole.USER, project)
-      .addProjectPermission(UserRole.ADMIN, project);
 
-    String result = execute(project.getDbKey());
-    assertJson(result).ignoreFields("snapshotDate", "key", "qualityGate.key").isSimilarTo(ws.getDef().responseExampleAsString());
+    execute(project.getDbKey());
   }
 
   @Test
   public void should_return_private_flag_for_project() {
-    init();
     OrganizationDto org = dbTester.organizations().insert();
-    dbTester.qualityGates().setBuiltInAsDefaultOn(org);
+    dbTester.qualityGates().createDefaultQualityGate(org);
     ComponentDto project = dbTester.components().insertPrivateProject(org);
+    init();
 
     userSession.logIn()
       .addProjectPermission(UserRole.ADMIN, project)
@@ -495,10 +407,10 @@ public class ComponentActionTest {
 
   @Test
   public void should_return_public_flag_for_project() {
-    init();
     OrganizationDto org = dbTester.organizations().insert();
-    dbTester.qualityGates().setBuiltInAsDefaultOn(org);
+    dbTester.qualityGates().createDefaultQualityGate(org);
     ComponentDto project = dbTester.components().insertPublicProject(org);
+    init();
 
     userSession.logIn()
       .addProjectPermission(UserRole.ADMIN, project)
@@ -508,11 +420,11 @@ public class ComponentActionTest {
 
   @Test
   public void should_not_return_private_flag_for_module() {
-    init();
     OrganizationDto org = dbTester.organizations().insert();
-    dbTester.qualityGates().setBuiltInAsDefaultOn(org);
+    dbTester.qualityGates().createDefaultQualityGate(org);
     ComponentDto project = dbTester.components().insertPrivateProject(org);
     ComponentDto module = dbTester.components().insertComponent(ComponentTesting.newModuleDto(project));
+    init();
 
     userSession.logIn()
       .addProjectPermission(UserRole.ADMIN, project)
@@ -523,10 +435,10 @@ public class ComponentActionTest {
 
   @Test
   public void canApplyPermissionTemplate_is_true_if_logged_in_as_organization_administrator() {
-    init(createPages());
     OrganizationDto org = dbTester.organizations().insert();
-    dbTester.qualityGates().setBuiltInAsDefaultOn(org);
+    dbTester.qualityGates().createDefaultQualityGate(org);
     ComponentDto project = dbTester.components().insertPrivateProject(org);
+    init(createPages());
 
     userSession.logIn()
       .addProjectPermission(UserRole.ADMIN, project)
@@ -541,10 +453,10 @@ public class ComponentActionTest {
 
   @Test
   public void canUpdateProjectVisibilityToPrivate_is_true_if_logged_in_as_project_administrator_and_extension_returns_false() {
-    init(createPages());
     OrganizationDto org = dbTester.organizations().insert();
-    dbTester.qualityGates().setBuiltInAsDefaultOn(org);
+    dbTester.qualityGates().createDefaultQualityGate(org);
     ComponentDto project = dbTester.components().insertPublicProject(org);
+    init(createPages());
 
     userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
     when(billingValidations.canUpdateProjectVisibilityToPrivate(any(BillingValidations.Organization.class))).thenReturn(false);
@@ -555,6 +467,91 @@ public class ComponentActionTest {
     assertJson(execute(project.getDbKey())).isSimilarTo("{\"configuration\": {\"canUpdateProjectVisibilityToPrivate\": true}}");
   }
 
+  @Test
+  public void fail_on_missing_parameters() {
+    insertOrganizationAndProject();
+    init();
+
+    expectedException.expect(IllegalArgumentException.class);
+    ws.newRequest().execute();
+  }
+
+  @Test
+  public void fail_on_unknown_component_key() {
+    insertOrganizationAndProject();
+    init();
+
+    expectedException.expect(NotFoundException.class);
+    execute("unknoen");
+  }
+
+  @Test
+  public void throw_ForbiddenException_if_required_permission_is_not_granted() {
+    ComponentDto project = insertOrganizationAndProject();
+    init();
+    userSession.logIn();
+
+    expectedException.expect(ForbiddenException.class);
+    execute(project.getDbKey());
+  }
+
+  @Test
+  public void test_example_response() {
+    init(createPages());
+    OrganizationDto organizationDto = dbTester.organizations().insertForKey("my-org-1");
+    ComponentDto project = newPrivateProjectDto(organizationDto, "ABCD")
+      .setDbKey("org.codehaus.sonar:sonar")
+      .setName("Sonarqube")
+      .setDescription("Open source platform for continuous inspection of code quality");
+    componentDbTester.insertComponent(project);
+    SnapshotDto analysis = newAnalysis(project)
+      .setCreatedAt(parseDateTime("2016-12-06T11:44:00+0200").getTime())
+      .setVersion("6.3")
+      .setLast(true);
+    componentDbTester.insertSnapshot(analysis);
+    when(resourceTypes.get(project.qualifier())).thenReturn(DefaultResourceTypes.get().getRootType());
+    UserDto user = dbTester.users().insertUser("obiwan");
+    propertyDbTester.insertProperty(new PropertyDto().setKey("favourite").setResourceId(project.getId()).setUserId(user.getId()));
+    addQualityProfiles(project,
+      createQProfile("qp1", "Sonar Way Java", "java"),
+      createQProfile("qp2", "Sonar Way Xoo", "xoo"));
+    QualityGateDto qualityGateDto = dbTester.qualityGates().insertQualityGate(dbTester.getDefaultOrganization(), qg -> qg.setName("Sonar way"));
+    dbTester.qualityGates().associateProjectToQualityGate(project, qualityGateDto);
+    userSession.logIn(user)
+      .addProjectPermission(UserRole.USER, project)
+      .addProjectPermission(UserRole.ADMIN, project);
+
+    String result = execute(project.getDbKey());
+    assertJson(result).ignoreFields("snapshotDate", "key", "qualityGate.key").isSimilarTo(ws.getDef().responseExampleAsString());
+  }
+
+  @Test
+  public void definition() {
+    init();
+    WebService.Action action = ws.getDef();
+
+    assertThat(action.since()).isEqualTo("5.2");
+    assertThat(action.isPost()).isFalse();
+    assertThat(action.isInternal()).isTrue();
+    assertThat(action.description()).isNotNull();
+    assertThat(action.responseExample()).isNotNull();
+    assertThat(action.changelog()).extracting(Change::getVersion, Change::getDescription).containsExactlyInAnyOrder(
+      tuple("6.4", "The 'visibility' field is added"));
+
+    WebService.Param componentId = action.param(PARAM_COMPONENT);
+    assertThat(componentId.isRequired()).isFalse();
+    assertThat(componentId.description()).isNotNull();
+    assertThat(componentId.exampleValue()).isNotNull();
+    assertThat(componentId.deprecatedKey()).isEqualTo("componentKey");
+    assertThat(componentId.deprecatedKeySince()).isEqualTo("6.4");
+  }
+
+  private ComponentDto insertOrganizationAndProject(){
+    OrganizationDto organization = dbTester.organizations().insert(o -> o.setKey("my-org"));
+    dbTester.qualityGates().createDefaultQualityGate(organization);
+    return dbTester.components().insertPrivateProject(organization, "abcd", p -> p.setDbKey("polop").setName("Polop").setDescription("test project"));
+  }
+
   private void init(Page... pages) {
     PluginRepository pluginRepository = mock(PluginRepository.class);
     when(pluginRepository.hasPlugin(anyString())).thenReturn(true);