From: Sébastien Lesaint Date: Wed, 28 Aug 2019 15:57:49 +0000 (+0200) Subject: use testFixtures instead of test configuration of db-dao X-Git-Tag: 8.0~179 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=2b029d9b127be48da51a65a66103becbc5ab6fa9;p=sonarqube.git use testFixtures instead of test configuration of db-dao --- diff --git a/server/sonar-ce-common/build.gradle b/server/sonar-ce-common/build.gradle index fb674e92796..f346ac18aa1 100644 --- a/server/sonar-ce-common/build.gradle +++ b/server/sonar-ce-common/build.gradle @@ -35,7 +35,6 @@ dependencies { compile 'org.slf4j:jul-to-slf4j' compile 'org.slf4j:slf4j-api' compile project(':server:sonar-ce-task') - compile project(':server:sonar-db-dao') compile project(':server:sonar-server-common') compile project(':sonar-core') compile project(path: ':sonar-plugin-api', configuration: 'shadow') diff --git a/server/sonar-ce-task-projectanalysis/build.gradle b/server/sonar-ce-task-projectanalysis/build.gradle index 15226d64134..1052d12965a 100644 --- a/server/sonar-ce-task-projectanalysis/build.gradle +++ b/server/sonar-ce-task-projectanalysis/build.gradle @@ -38,7 +38,6 @@ dependencies { compile project(':sonar-core') compile project(':server:sonar-ce-task') - compile project(':server:sonar-db-dao') compile project(':server:sonar-db-migration') compile project(':server:sonar-process') compile project(':server:sonar-server-common') diff --git a/server/sonar-ce-task/build.gradle b/server/sonar-ce-task/build.gradle index ed02c72c1ca..4cf16892980 100644 --- a/server/sonar-ce-task/build.gradle +++ b/server/sonar-ce-task/build.gradle @@ -22,7 +22,6 @@ dependencies { compile 'org.slf4j:jul-to-slf4j' compile 'org.slf4j:slf4j-api' - compile project(':server:sonar-db-dao') compile project(':server:sonar-server-common') compile project(':sonar-core') compileOnly project(path: ':sonar-plugin-api', configuration: 'shadow') diff --git a/server/sonar-ce/build.gradle b/server/sonar-ce/build.gradle index c828f41e767..6ce9decb822 100644 --- a/server/sonar-ce/build.gradle +++ b/server/sonar-ce/build.gradle @@ -18,7 +18,6 @@ dependencies { compile project(':server:sonar-ce-common') compile project(':server:sonar-ce-task') compile project(':server:sonar-ce-task-projectanalysis') - compile project(':server:sonar-db-dao') compile project(':server:sonar-process') compile project(':server:sonar-ce-task') compile project(':server:sonar-server-common') diff --git a/server/sonar-ce/src/test/resources/logback-test.xml b/server/sonar-ce/src/test/resources/logback-test.xml new file mode 100644 index 00000000000..7cfba2985f6 --- /dev/null +++ b/server/sonar-ce/src/test/resources/logback-test.xml @@ -0,0 +1,22 @@ + + + + + + + + %d{yyyy.MM.dd HH:mm:ss} %-5level %msg%n + + + + + + + + + + + + + + diff --git a/server/sonar-db-dao/build.gradle b/server/sonar-db-dao/build.gradle index ac0c3db3aa8..6877e8d4eba 100644 --- a/server/sonar-db-dao/build.gradle +++ b/server/sonar-db-dao/build.gradle @@ -22,7 +22,6 @@ dependencies { compileOnly 'com.google.code.findbugs:jsr305' - testCompile 'com.h2database:h2' testCompile 'com.tngtech.java:junit-dataprovider' testCompile 'junit:junit' testCompile 'org.assertj:assertj-core' @@ -30,7 +29,6 @@ dependencies { testCompile 'org.mockito:mockito-core' testCompile 'org.sonarsource.orchestrator:sonar-orchestrator' testCompile project(':sonar-testing-harness') - testCompile testFixtures(project(':server:sonar-db-core')) testCompile project(':sonar-plugin-api-impl') testCompileOnly 'com.google.code.findbugs:jsr305' @@ -39,6 +37,12 @@ dependencies { testRuntime 'com.microsoft.sqlserver:mssql-jdbc' testRuntime 'com.oracle.jdbc:ojdbc8' testRuntime 'org.postgresql:postgresql' + + testFixturesApi testFixtures(project(':server:sonar-db-core')) + + testFixturesImplementation 'com.h2database:h2' + + testFixturesCompileOnly 'com.google.code.findbugs:jsr305' } test { diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/DbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/DbTester.java deleted file mode 100644 index ecccc986685..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/DbTester.java +++ /dev/null @@ -1,406 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; -import javax.annotation.Nullable; -import org.apache.commons.dbcp2.BasicDataSource; -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.db.alm.AlmDbTester; -import org.sonar.db.component.ComponentDbTester; -import org.sonar.db.component.ProjectLinkDbTester; -import org.sonar.db.event.EventDbTester; -import org.sonar.db.favorite.FavoriteDbTester; -import org.sonar.db.issue.IssueDbTester; -import org.sonar.db.measure.MeasureDbTester; -import org.sonar.db.notification.NotificationDbTester; -import org.sonar.db.organization.OrganizationDbTester; -import org.sonar.db.organization.OrganizationDto; -import org.sonar.db.organization.OrganizationTesting; -import org.sonar.db.permission.template.PermissionTemplateDbTester; -import org.sonar.db.plugin.PluginDbTester; -import org.sonar.db.property.InternalComponentPropertyDbTester; -import org.sonar.db.property.PropertyDbTester; -import org.sonar.db.qualitygate.QualityGateDbTester; -import org.sonar.db.qualityprofile.QualityProfileDbTester; -import org.sonar.db.rule.RuleDbTester; -import org.sonar.db.source.FileSourceTester; -import org.sonar.db.user.RootFlagAssertions; -import org.sonar.db.user.UserDbTester; -import org.sonar.db.webhook.WebhookDbTester; -import org.sonar.db.webhook.WebhookDeliveryDbTester; - -import static com.google.common.base.Preconditions.checkState; -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; - -/** - * This class should be called using @Rule. - * Data is truncated between each tests. The schema is created between each test. - */ -public class DbTester extends AbstractDbTester { - - private final System2 system2; - private DbClient client; - private DbSession session = null; - private boolean disableDefaultOrganization = false; - private boolean started = false; - private String defaultOrganizationUuid = randomAlphanumeric(40); - private OrganizationDto defaultOrganization; - - private final UserDbTester userTester; - private final ComponentDbTester componentTester; - private final ProjectLinkDbTester componentLinkTester; - private final FavoriteDbTester favoriteTester; - private final EventDbTester eventTester; - private final OrganizationDbTester organizationTester; - private final PermissionTemplateDbTester permissionTemplateTester; - private final PropertyDbTester propertyTester; - private final QualityGateDbTester qualityGateDbTester; - private final IssueDbTester issueDbTester; - private final RuleDbTester ruleDbTester; - private final NotificationDbTester notificationDbTester; - private final RootFlagAssertions rootFlagAssertions; - private final QualityProfileDbTester qualityProfileDbTester; - private final MeasureDbTester measureDbTester; - private final FileSourceTester fileSourceTester; - private final PluginDbTester pluginDbTester; - private final WebhookDbTester webhookDbTester; - private final WebhookDeliveryDbTester webhookDeliveryDbTester; - private final AlmDbTester almDbTester; - private final InternalComponentPropertyDbTester internalComponentPropertyTester; - - private DbTester(System2 system2, @Nullable String schemaPath, MyBatisConfExtension... confExtensions) { - super(TestDbImpl.create(schemaPath, confExtensions)); - this.system2 = system2; - - initDbClient(); - this.userTester = new UserDbTester(this); - this.componentTester = new ComponentDbTester(this); - this.componentLinkTester = new ProjectLinkDbTester(this); - this.favoriteTester = new FavoriteDbTester(this); - this.eventTester = new EventDbTester(this); - this.organizationTester = new OrganizationDbTester(this); - this.permissionTemplateTester = new PermissionTemplateDbTester(this); - this.propertyTester = new PropertyDbTester(this); - this.qualityGateDbTester = new QualityGateDbTester(this); - this.issueDbTester = new IssueDbTester(this); - this.ruleDbTester = new RuleDbTester(this); - this.notificationDbTester = new NotificationDbTester(this); - this.rootFlagAssertions = new RootFlagAssertions(this); - this.qualityProfileDbTester = new QualityProfileDbTester(this); - this.measureDbTester = new MeasureDbTester(this); - this.fileSourceTester = new FileSourceTester(this); - this.pluginDbTester = new PluginDbTester(this); - this.webhookDbTester = new WebhookDbTester(this); - this.webhookDeliveryDbTester = new WebhookDeliveryDbTester(this); - this.almDbTester = new AlmDbTester(this); - this.internalComponentPropertyTester = new InternalComponentPropertyDbTester(this); - } - - public static DbTester create() { - return new DbTester(System2.INSTANCE, null); - } - - public static DbTester create(System2 system2) { - return new DbTester(system2, null); - } - - public static DbTester createWithExtensionMappers(Class firstMapperClass, Class... otherMapperClasses) { - return new DbTester(System2.INSTANCE, null, new DbTesterMyBatisConfExtension(firstMapperClass, otherMapperClasses)); - } - - public static DbTester createWithExtensionMappers(System2 system2, Class firstMapperClass, Class... otherMapperClasses) { - return new DbTester(system2, null, new DbTesterMyBatisConfExtension(firstMapperClass, otherMapperClasses)); - } - - public static DbTester createForSchema(System2 system2, Class testClass, String filename) { - String path = StringUtils.replaceChars(testClass.getCanonicalName(), '.', '/'); - String schemaPath = path + "/" + filename; - return new DbTester(system2, schemaPath).setDisableDefaultOrganization(true); - } - - private void initDbClient() { - TransientPicoContainer ioc = new TransientPicoContainer(); - ioc.addComponent(db.getMyBatis()); - ioc.addComponent(system2); - ioc.addComponent(new SequenceUuidFactory()); - for (Class daoClass : DaoModule.classes()) { - ioc.addComponent(daoClass); - } - List daos = ioc.getComponents(Dao.class); - client = new DbClient(db.getDatabase(), db.getMyBatis(), new TestDBSessions(db.getMyBatis()), daos.toArray(new Dao[daos.size()])); - } - - public DbTester setDisableDefaultOrganization(boolean b) { - checkState(!started, "DbTester is already started"); - this.disableDefaultOrganization = b; - return this; - } - - public DbTester setDefaultOrganizationUuid(String uuid) { - checkState(!started, "DbTester is already started"); - this.defaultOrganizationUuid = uuid; - return this; - } - - public DbTester enableOrganizations() { - properties().insertInternal("organization.enabled", "true"); - return this; - } - - @Override - protected void before() { - db.start(); - db.truncateTables(); - initDbClient(); - if (!disableDefaultOrganization) { - insertDefaultOrganization(); - } - started = true; - } - - private void insertDefaultOrganization() { - defaultOrganization = OrganizationTesting.newOrganizationDto().setUuid(defaultOrganizationUuid); - try (DbSession dbSession = db.getMyBatis().openSession(false)) { - client.organizationDao().insert(dbSession, defaultOrganization, false); - client.internalPropertiesDao().save(dbSession, "organization.default", defaultOrganization.getUuid()); - dbSession.commit(); - } - } - - public boolean hasDefaultOrganization() { - return defaultOrganization != null; - } - - public OrganizationDto getDefaultOrganization() { - checkState(defaultOrganization != null, "Default organization has not been created"); - return defaultOrganization; - } - - public UserDbTester users() { - return userTester; - } - - public ComponentDbTester components() { - return componentTester; - } - - public ProjectLinkDbTester componentLinks() { - return componentLinkTester; - } - - public FavoriteDbTester favorites() { - return favoriteTester; - } - - public EventDbTester events() { - return eventTester; - } - - public OrganizationDbTester organizations() { - return organizationTester; - } - - public PermissionTemplateDbTester permissionTemplates() { - return permissionTemplateTester; - } - - public PropertyDbTester properties() { - return propertyTester; - } - - public QualityGateDbTester qualityGates() { - return qualityGateDbTester; - } - - public RootFlagAssertions rootFlag() { - return rootFlagAssertions; - } - - public IssueDbTester issues() { - return issueDbTester; - } - - public RuleDbTester rules() { - return ruleDbTester; - } - - public NotificationDbTester notifications() { - return notificationDbTester; - } - - public QualityProfileDbTester qualityProfiles() { - return qualityProfileDbTester; - } - - public MeasureDbTester measures() { - return measureDbTester; - } - - public FileSourceTester fileSources() { - return fileSourceTester; - } - - public PluginDbTester pluginDbTester() { - return pluginDbTester; - } - - public WebhookDbTester webhooks() { - return webhookDbTester; - } - - public WebhookDeliveryDbTester webhookDelivery() { - return webhookDeliveryDbTester; - } - - public AlmDbTester alm() { - return almDbTester; - } - - public InternalComponentPropertyDbTester internalComponentProperties() { - return internalComponentPropertyTester; - } - - @Override - protected void after() { - if (session != null) { - session.rollback(); - session.close(); - } - db.stop(); - started = false; - } - - public DbSession getSession() { - if (session == null) { - session = db.getMyBatis().openSession(false); - } - return session; - } - - public void commit() { - getSession().commit(); - } - - public DbClient getDbClient() { - return client; - } - - public int countRowsOfTable(DbSession dbSession, String tableName) { - return super.countRowsOfTable(tableName, new DbSessionConnectionSupplier(dbSession)); - } - - public int countSql(DbSession dbSession, String sql) { - return super.countSql(sql, new DbSessionConnectionSupplier(dbSession)); - } - - public List> select(DbSession dbSession, String selectSql) { - return super.select(selectSql, new DbSessionConnectionSupplier(dbSession)); - } - - public Map selectFirst(DbSession dbSession, String selectSql) { - return super.selectFirst(selectSql, new DbSessionConnectionSupplier(dbSession)); - } - - @Deprecated - public MyBatis myBatis() { - return db.getMyBatis(); - } - - @Deprecated - public Connection openConnection() throws SQLException { - return getConnection(); - } - - private Connection getConnection() throws SQLException { - return db.getDatabase().getDataSource().getConnection(); - } - - @Deprecated - public Database database() { - return db.getDatabase(); - } - - public String getUrl() { - return ((BasicDataSource) db.getDatabase().getDataSource()).getUrl(); - } - - private static class DbSessionConnectionSupplier implements ConnectionSupplier { - private final DbSession dbSession; - - public DbSessionConnectionSupplier(DbSession dbSession) { - this.dbSession = dbSession; - } - - @Override - public Connection get() { - return dbSession.getConnection(); - } - - @Override - public void close() { - // closing dbSession is not our responsability - } - } - - private static class DbTesterMyBatisConfExtension implements MyBatisConfExtension { - // do not replace with a lambda to allow cache of MyBatis instances in TestDbImpl to work - private final Class[] mapperClasses; - - public DbTesterMyBatisConfExtension(Class firstMapperClass, Class... otherMapperClasses) { - this.mapperClasses = Stream.concat( - Stream.of(firstMapperClass), - Arrays.stream(otherMapperClasses)) - .sorted(Comparator.comparing(Class::getName)) - .toArray(Class[]::new); - } - - @Override - public Stream> getMapperClasses() { - return Arrays.stream(mapperClasses); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DbTesterMyBatisConfExtension that = (DbTesterMyBatisConfExtension) o; - return Arrays.equals(mapperClasses, that.mapperClasses); - } - - @Override - public int hashCode() { - return Arrays.hashCode(mapperClasses); - } - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/OrchestratorSettingsUtils.java b/server/sonar-db-dao/src/test/java/org/sonar/db/OrchestratorSettingsUtils.java deleted file mode 100644 index b3f5e8f02ab..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/OrchestratorSettingsUtils.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.io.File; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.util.Map; -import java.util.Properties; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.text.StrSubstitutor; -import org.sonar.api.config.Settings; - -import static org.apache.commons.lang.StringUtils.isEmpty; - -public class OrchestratorSettingsUtils { - private OrchestratorSettingsUtils() { - // prevents instantiation - } - - public static void loadOrchestratorSettings(Settings settings) { - String url = settings.getString("orchestrator.configUrl"); - if (isEmpty(url)) { - return; - } - - InputStream input = null; - try { - URI uri = new URI(url); - - if (url.startsWith("file:")) { - File file = new File(uri); - input = FileUtils.openInputStream(file); - } else { - HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); - int responseCode = connection.getResponseCode(); - if (responseCode >= 400) { - throw new IllegalStateException("Fail to request: " + uri + ". Status code=" + responseCode); - } - - input = connection.getInputStream(); - } - - Properties props = new Properties(); - props.load(input); - settings.addProperties(props); - for (Map.Entry entry : settings.getProperties().entrySet()) { - String interpolatedValue = StrSubstitutor.replace(entry.getValue(), System.getenv(), "${", "}"); - settings.setProperty(entry.getKey(), interpolatedValue); - } - } catch (Exception e) { - throw new IllegalStateException("Cannot load Orchestrator properties from:" + url, e); - } finally { - IOUtils.closeQuietly(input); - } - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/SQDatabase.java b/server/sonar-db-dao/src/test/java/org/sonar/db/SQDatabase.java deleted file mode 100644 index 4a4fd2eae79..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/SQDatabase.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.io.PrintWriter; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.List; -import javax.sql.DataSource; -import org.apache.commons.dbutils.DbUtils; -import org.apache.commons.io.output.NullWriter; -import org.apache.ibatis.io.Resources; -import org.apache.ibatis.jdbc.ScriptRunner; -import org.sonar.api.SonarEdition; -import org.sonar.api.SonarQubeSide; -import org.sonar.api.config.Settings; -import org.sonar.api.config.internal.MapSettings; -import org.sonar.api.internal.SonarRuntimeImpl; -import org.sonar.api.utils.System2; -import org.sonar.api.utils.Version; -import org.sonar.api.utils.log.Loggers; -import org.sonar.core.platform.ComponentContainer; -import org.sonar.core.util.UuidFactoryFast; -import org.sonar.core.util.logs.Profiler; -import org.sonar.db.dialect.Dialect; -import org.sonar.process.logging.LogbackHelper; -import org.sonar.server.platform.db.migration.MigrationConfigurationModule; -import org.sonar.server.platform.db.migration.engine.MigrationContainer; -import org.sonar.server.platform.db.migration.engine.MigrationContainerImpl; -import org.sonar.server.platform.db.migration.engine.MigrationContainerPopulator; -import org.sonar.server.platform.db.migration.engine.MigrationContainerPopulatorImpl; -import org.sonar.server.platform.db.migration.history.MigrationHistoryTableImpl; -import org.sonar.server.platform.db.migration.step.MigrationStep; -import org.sonar.server.platform.db.migration.step.MigrationStepExecutionException; -import org.sonar.server.platform.db.migration.step.MigrationSteps; -import org.sonar.server.platform.db.migration.step.MigrationStepsExecutor; -import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep; -import org.sonar.server.platform.db.migration.version.DbVersion; - -import static com.google.common.base.Preconditions.checkState; - -public class SQDatabase extends DefaultDatabase { - private final boolean createSchema; - - private SQDatabase(Settings settings, boolean createSchema) { - super(new LogbackHelper(), settings); - this.createSchema = createSchema; - } - - public static SQDatabase newDatabase(Settings settings, boolean createSchema) { - return new SQDatabase(settings, createSchema); - } - - public static SQDatabase newH2Database(String name, boolean createSchema) { - MapSettings settings = new MapSettings() - .setProperty("sonar.jdbc.dialect", "h2") - .setProperty("sonar.jdbc.driverClassName", "org.h2.Driver") - .setProperty("sonar.jdbc.url", "jdbc:h2:mem:" + name) - .setProperty("sonar.jdbc.username", "sonar") - .setProperty("sonar.jdbc.password", "sonar"); - return new SQDatabase(settings, createSchema); - } - - @Override - public void start() { - super.start(); - if (createSchema) { - createSchema(); - } - } - - private void createSchema() { - Connection connection = null; - try { - connection = getDataSource().getConnection(); - NoopDatabase noopDatabase = new NoopDatabase(getDialect(), getDataSource()); - // create and populate schema - createMigrationHistoryTable(noopDatabase); - executeDbMigrations(noopDatabase); - } catch (SQLException e) { - throw new IllegalStateException("Fail to create schema", e); - } finally { - DbUtils.closeQuietly(connection); - } - } - - public static final class H2MigrationContainerPopulator extends MigrationContainerPopulatorImpl { - public H2MigrationContainerPopulator(DbVersion... dbVersions) { - super(H2StepExecutor.class, dbVersions); - } - } - - public static final class H2StepExecutor implements MigrationStepsExecutor { - private static final String STEP_START_PATTERN = "{}..."; - private static final String STEP_STOP_PATTERN = "{}: {}"; - - private final ComponentContainer componentContainer; - - public H2StepExecutor(ComponentContainer componentContainer) { - this.componentContainer = componentContainer; - } - - @Override - public void execute(List steps) { - steps.forEach(step -> execute(step, componentContainer)); - } - - private void execute(RegisteredMigrationStep step, ComponentContainer componentContainer) { - MigrationStep migrationStep = componentContainer.getComponentByType(step.getStepClass()); - checkState(migrationStep != null, "Can not find instance of " + step.getStepClass()); - - execute(step, migrationStep); - } - - private void execute(RegisteredMigrationStep step, MigrationStep migrationStep) { - Profiler stepProfiler = Profiler.create(Loggers.get(SQDatabase.class)); - stepProfiler.startInfo(STEP_START_PATTERN, step); - boolean done = false; - try { - migrationStep.execute(); - done = true; - } catch (Exception e) { - throw new MigrationStepExecutionException(step, e); - } finally { - if (done) { - stepProfiler.stopInfo(STEP_STOP_PATTERN, step, "success"); - } else { - stepProfiler.stopError(STEP_STOP_PATTERN, step, "failure"); - } - } - } - } - - private void executeDbMigrations(NoopDatabase noopDatabase) { - ComponentContainer parentContainer = new ComponentContainer(); - parentContainer.add(noopDatabase); - parentContainer.add(H2MigrationContainerPopulator.class); - MigrationConfigurationModule migrationConfigurationModule = new MigrationConfigurationModule(); - migrationConfigurationModule.configure(parentContainer); - - // dependencies required by DB migrations - parentContainer.add(SonarRuntimeImpl.forSonarQube(Version.create(8, 0), SonarQubeSide.SERVER, SonarEdition.COMMUNITY)); - parentContainer.add(UuidFactoryFast.getInstance()); - parentContainer.add(System2.INSTANCE); - - parentContainer.startComponents(); - - MigrationContainer migrationContainer = new MigrationContainerImpl(parentContainer, parentContainer.getComponentByType(MigrationContainerPopulator.class)); - MigrationSteps migrationSteps = migrationContainer.getComponentByType(MigrationSteps.class); - migrationContainer.getComponentByType(MigrationStepsExecutor.class) - .execute(migrationSteps.readAll()); - } - - private void createMigrationHistoryTable(NoopDatabase noopDatabase) { - new MigrationHistoryTableImpl(noopDatabase).start(); - } - - private class NoopDatabase implements Database { - private final Dialect dialect; - private final DataSource dataSource; - - private NoopDatabase(Dialect dialect, DataSource dataSource) { - this.dialect = dialect; - this.dataSource = dataSource; - } - - @Override - public DataSource getDataSource() { - return dataSource; - } - - @Override - public Dialect getDialect() { - return dialect; - } - - @Override - public void enableSqlLogging(boolean enable) { - - } - - @Override - public void start() { - // do nothing - } - - @Override - public void stop() { - // do nothing - } - } - - public void executeScript(String classloaderPath) { - try (Connection connection = getDataSource().getConnection()) { - executeScript(connection, classloaderPath); - } catch (SQLException e) { - throw new IllegalStateException("Fail to execute script: " + classloaderPath, e); - } - } - - private static void executeScript(Connection connection, String path) { - ScriptRunner scriptRunner = newScriptRunner(connection); - try { - scriptRunner.runScript(Resources.getResourceAsReader(path)); - connection.commit(); - - } catch (Exception e) { - throw new IllegalStateException("Fail to restore: " + path, e); - } - } - - private static ScriptRunner newScriptRunner(Connection connection) { - ScriptRunner scriptRunner = new ScriptRunner(connection); - scriptRunner.setDelimiter(";"); - scriptRunner.setStopOnError(true); - scriptRunner.setLogWriter(new PrintWriter(new NullWriter())); - return scriptRunner; - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/TestDBSessions.java b/server/sonar-db-dao/src/test/java/org/sonar/db/TestDBSessions.java deleted file mode 100644 index 34a4908bb9c..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/TestDBSessions.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -public final class TestDBSessions implements DBSessions { - private final MyBatis myBatis; - - public TestDBSessions(MyBatis myBatis) { - this.myBatis = myBatis; - } - - @Override - public DbSession openSession(boolean batch) { - return myBatis.openSession(false); - } - - @Override - public void enableCaching() { - // ignored - } - - @Override - public void disableCaching() { - // ignored - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/TestDbImpl.java b/server/sonar-db-dao/src/test/java/org/sonar/db/TestDbImpl.java deleted file mode 100644 index d984564bb08..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/TestDbImpl.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import java.util.function.Function; -import javax.annotation.Nullable; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang.StringUtils; -import org.junit.AssumptionViolatedException; -import org.sonar.api.config.Settings; -import org.sonar.db.dialect.H2; -import org.sonar.process.logging.LogbackHelper; - -class TestDbImpl extends CoreTestDb { - private static TestDbImpl defaultSchemaBaseTestDb; - // instantiating MyBatis objects is costly => we cache them for default schema - private static final Map defaultSchemaTestDbsWithExtensions = new HashMap<>(); - - private boolean isDefault; - private MyBatis myBatis; - - private TestDbImpl(@Nullable String schemaPath, MyBatisConfExtension... confExtensions) { - super(); - isDefault = (schemaPath == null); - init(schemaPath, confExtensions); - } - - private TestDbImpl(TestDbImpl base, MyBatis myBatis) { - super(base.getDatabase()); - this.isDefault = base.isDefault; - this.myBatis = myBatis; - } - - private void init(@Nullable String schemaPath, MyBatisConfExtension[] confExtensions) { - Consumer loadOrchestratorSettings = settings -> { - OrchestratorSettingsUtils.loadOrchestratorSettings(settings); - }; - Function databaseCreator = settings -> { - String dialect = settings.getString("sonar.jdbc.dialect"); - if (dialect != null && !"h2".equals(dialect)) { - return new DefaultDatabase(new LogbackHelper(), settings); - } - return SQDatabase.newH2Database("h2Tests" + DigestUtils.md5Hex(StringUtils.defaultString(schemaPath)), schemaPath == null); - }; - Consumer schemaPathExecutor = database -> { - if (schemaPath == null) { - return; - } - - // scripts are assumed to be using H2 specific syntax, ignore the test if not on H2 - if (!database.getDialect().getId().equals("h2")) { - database.stop(); - throw new AssumptionViolatedException("This test is intended to be run on H2 only"); - } - ((SQDatabase) database).executeScript(schemaPath); - }; - BiConsumer createMyBatis = (db, created) -> myBatis = newMyBatis(db, confExtensions); - init(loadOrchestratorSettings, databaseCreator, schemaPathExecutor, createMyBatis); - } - - private static MyBatis newMyBatis(Database db, MyBatisConfExtension[] extensions) { - MyBatis newMyBatis = new MyBatis(db, extensions); - newMyBatis.start(); - return newMyBatis; - } - - static TestDbImpl create(@Nullable String schemaPath, MyBatisConfExtension... confExtensions) { - MyBatisConfExtension[] extensionArray = confExtensions.length == 0 ? null : confExtensions; - if (schemaPath == null) { - if (defaultSchemaBaseTestDb == null) { - defaultSchemaBaseTestDb = new TestDbImpl((String) null); - } - if (extensionArray != null) { - return defaultSchemaTestDbsWithExtensions.computeIfAbsent( - extensionArray, - extensions -> new TestDbImpl(defaultSchemaBaseTestDb, newMyBatis(defaultSchemaBaseTestDb.getDatabase(), extensions))); - } - return defaultSchemaBaseTestDb; - } - return new TestDbImpl(schemaPath, confExtensions); - } - - @Override - public void start() { - if (!isDefault && !H2.ID.equals(getDatabase().getDialect().getId())) { - throw new AssumptionViolatedException("Test disabled because it supports only H2"); - } - } - - @Override - public void stop() { - if (!isDefault) { - super.stop(); - } - } - - MyBatis getMyBatis() { - return myBatis; - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/alm/AlmDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/alm/AlmDbTester.java deleted file mode 100644 index 579f505a602..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/alm/AlmDbTester.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.alm; - -import java.util.Arrays; -import java.util.function.Consumer; -import org.apache.commons.lang.math.RandomUtils; -import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.organization.OrganizationDto; -import org.sonar.db.user.UserDto; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.sonar.db.alm.ALM.GITHUB; - -public class AlmDbTester { - - private final DbTester db; - - public AlmDbTester(DbTester db) { - this.db = db; - } - - public OrganizationAlmBindingDto insertOrganizationAlmBinding(OrganizationDto organization, AlmAppInstallDto almAppInstall, boolean membersSync) { - UserDto user = db.users().insertUser(); - db.getDbClient().organizationAlmBindingDao().insert(db.getSession(), organization, almAppInstall, randomAlphabetic(10), user.getUuid(), membersSync); - db.commit(); - return db.getDbClient().organizationAlmBindingDao().selectByOrganization(db.getSession(), organization).get(); - } - - public ProjectAlmBindingDto insertProjectAlmBinding(ALM alm, ComponentDto componentDto, String repositoryUuid) { - db.getDbClient().projectAlmBindingsDao().insertOrUpdate(db.getSession(), alm, repositoryUuid, componentDto.uuid(), - "some_org/some_repo", "http://alm/some_org_some_repo"); - db.commit(); - return db.getDbClient().projectAlmBindingsDao().selectByProjectUuid(db.getSession(), componentDto.uuid()).get(); - } - - @SafeVarargs - public final AlmAppInstallDto insertAlmAppInstall(Consumer... dtoPopulators) { - AlmAppInstallDto dto = new AlmAppInstallDto() - .setAlm(GITHUB) - .setInstallId(randomAlphanumeric(10)) - .setOrganizationAlmId(Integer.toString(RandomUtils.nextInt())) - .setIsOwnerUser(false) - .setUserExternalId(randomAlphanumeric(10)); - Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(dto)); - db.getDbClient().almAppInstallDao().insertOrUpdate(db.getSession(), dto.getAlm(), dto.getOrganizationAlmId(), dto.isOwnerUser(), dto.getInstallId(), dto.getUserExternalId()); - db.commit(); - return db.getDbClient().almAppInstallDao().selectByOrganizationAlmId(db.getSession(), dto.getAlm(), dto.getOrganizationAlmId()).get(); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeQueueTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeQueueTesting.java deleted file mode 100644 index 07b8074a0d9..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeQueueTesting.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.ce; - -import java.util.stream.Stream; -import org.sonar.db.DbSession; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang.math.RandomUtils.nextLong; -import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.db.ce.CeQueueDto.Status.IN_PROGRESS; -import static org.sonar.db.ce.CeQueueDto.Status.PENDING; - -public class CeQueueTesting { - private CeQueueTesting() { - // static methods only - } - - public static CeQueueDto newCeQueueDto(String uuid) { - return new CeQueueDto() - .setUuid(uuid) - .setComponentUuid(randomAlphanumeric(40)) - .setMainComponentUuid(randomAlphanumeric(39)) - .setStatus(CeQueueDto.Status.PENDING) - .setTaskType(CeTaskTypes.REPORT) - .setSubmitterUuid(randomAlphanumeric(255)) - .setCreatedAt(nextLong()) - .setUpdatedAt(nextLong()); - } - - public static void makeInProgress(DbSession dbSession, String workerUuid, long now, CeQueueDto... ceQueueDtos) { - Stream.of(ceQueueDtos).forEach(ceQueueDto -> { - CeQueueMapper mapper = dbSession.getMapper(CeQueueMapper.class); - int touchedRows = mapper.updateIf(ceQueueDto.getUuid(), - new UpdateIf.NewProperties(IN_PROGRESS, workerUuid, now, now), - new UpdateIf.OldProperties(PENDING)); - assertThat(touchedRows).isEqualTo(1); - }); - } - - public static void reset(DbSession dbSession, long now, CeQueueDto... ceQueueDtos) { - Stream.of(ceQueueDtos).forEach(ceQueueDto -> { - checkArgument(ceQueueDto.getStatus() == IN_PROGRESS); - checkArgument(ceQueueDto.getWorkerUuid() != null); - - CeQueueMapper mapper = dbSession.getMapper(CeQueueMapper.class); - int touchedRows = mapper.updateIf(ceQueueDto.getUuid(), - new UpdateIf.NewProperties(PENDING, ceQueueDto.getUuid(), now, now), - new UpdateIf.OldProperties(IN_PROGRESS)); - assertThat(touchedRows).isEqualTo(1); - }); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentDbTester.java deleted file mode 100644 index d8ed910582f..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentDbTester.java +++ /dev/null @@ -1,333 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import java.util.Arrays; -import java.util.function.Consumer; -import javax.annotation.Nullable; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; -import org.sonar.db.organization.OrganizationDto; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; -import static java.util.Arrays.asList; -import static org.sonar.db.component.BranchType.LONG; -import static org.sonar.db.component.ComponentTesting.newApplication; -import static org.sonar.db.component.ComponentTesting.newBranchDto; -import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; -import static org.sonar.db.component.ComponentTesting.newProjectBranch; -import static org.sonar.db.component.ComponentTesting.newPublicProjectDto; -import static org.sonar.db.component.ComponentTesting.newSubView; -import static org.sonar.db.component.ComponentTesting.newView; -import static org.sonar.db.component.SnapshotTesting.newAnalysis; - -public class ComponentDbTester { - private final DbTester db; - private final DbClient dbClient; - private final DbSession dbSession; - - public ComponentDbTester(DbTester db) { - this.db = db; - this.dbClient = db.getDbClient(); - this.dbSession = db.getSession(); - } - - public SnapshotDto insertProjectAndSnapshot(ComponentDto component) { - return insertComponentAndSnapshot(component); - } - - public SnapshotDto insertViewAndSnapshot(ComponentDto component) { - return insertComponentAndSnapshot(component); - } - - private SnapshotDto insertComponentAndSnapshot(ComponentDto component) { - dbClient.componentDao().insert(dbSession, component); - SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(component)); - db.commit(); - - return snapshot; - } - - public ComponentDto insertComponent(ComponentDto component) { - return insertComponentImpl(component, null, noExtraConfiguration()); - } - - public ComponentDto insertPrivateProject() { - return insertComponentImpl(newPrivateProjectDto(db.getDefaultOrganization()), true, noExtraConfiguration()); - } - - public ComponentDto insertPublicProject() { - return insertComponentImpl(ComponentTesting.newPublicProjectDto(db.getDefaultOrganization()), false, noExtraConfiguration()); - } - - @SafeVarargs - public final ComponentDto insertPrivateProject(Consumer... dtoPopulators) { - return insertComponentImpl(newPrivateProjectDto(db.getDefaultOrganization()), true, dtoPopulators); - } - - @SafeVarargs - public final ComponentDto insertPublicProject(Consumer... dtoPopulators) { - return insertComponentImpl(newPublicProjectDto(db.getDefaultOrganization()), false, dtoPopulators); - } - - @SafeVarargs - public final ComponentDto insertPrivateProject(OrganizationDto organizationDto, Consumer... dtoPopulators) { - return insertComponentImpl(newPrivateProjectDto(organizationDto), true, dtoPopulators); - } - - @SafeVarargs - public final ComponentDto insertPublicProject(OrganizationDto organizationDto, Consumer... dtoPopulators) { - return insertComponentImpl(newPublicProjectDto(organizationDto), false, dtoPopulators); - } - - public ComponentDto insertPrivateProject(OrganizationDto organizationDto) { - return insertComponentImpl(newPrivateProjectDto(organizationDto), true, noExtraConfiguration()); - } - - public ComponentDto insertPublicProject(OrganizationDto organizationDto) { - return insertComponentImpl(newPublicProjectDto(organizationDto), false, noExtraConfiguration()); - } - - public ComponentDto insertPrivateProject(OrganizationDto organizationDto, String uuid) { - return insertComponentImpl(newPrivateProjectDto(organizationDto, uuid), true, noExtraConfiguration()); - } - - public ComponentDto insertPublicProject(OrganizationDto organizationDto, String uuid) { - return insertComponentImpl(newPublicProjectDto(organizationDto, uuid), false, noExtraConfiguration()); - } - - @SafeVarargs - public final ComponentDto insertPrivateProject(OrganizationDto organizationDto, String uuid, Consumer... dtoPopulators) { - return insertComponentImpl(newPrivateProjectDto(organizationDto, uuid), true, dtoPopulators); - } - - /** - * @deprecated since 6.6 - * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) - */ - @Deprecated - public ComponentDto insertView() { - return insertComponentImpl(newView(db.getDefaultOrganization()), false, noExtraConfiguration()); - } - - /** - * @deprecated since 6.6 - * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) - */ - public ComponentDto insertView(Consumer dtoPopulator) { - return insertComponentImpl(newView(db.getDefaultOrganization()), false, dtoPopulator); - } - - /** - * @deprecated since 6.6 - * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) - */ - public ComponentDto insertView(OrganizationDto organizationDto) { - return insertComponentImpl(newView(organizationDto), false, noExtraConfiguration()); - } - - /** - * @deprecated since 6.6 - * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) - */ - public ComponentDto insertView(OrganizationDto organizationDto, Consumer dtoPopulator) { - return insertComponentImpl(newView(organizationDto), false, dtoPopulator); - } - - /** - * @deprecated since 6.6 - * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) - */ - public ComponentDto insertView(String uuid) { - return insertComponentImpl(newView(db.getDefaultOrganization(), uuid), false, noExtraConfiguration()); - } - - /** - * @deprecated since 6.6 - * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) - */ - public ComponentDto insertView(OrganizationDto organizationDto, String uuid) { - return insertComponentImpl(newView(organizationDto, uuid), false, noExtraConfiguration()); - } - - @SafeVarargs - public final ComponentDto insertPublicPortfolio(OrganizationDto organization, Consumer... dtoPopulators) { - return insertComponentImpl(newView(organization).setPrivate(false), false, dtoPopulators); - } - - @SafeVarargs - public final ComponentDto insertPrivatePortfolio(OrganizationDto organization, Consumer... dtoPopulators) { - return insertComponentImpl(newView(organization).setPrivate(true), true, dtoPopulators); - } - - @SafeVarargs - public final ComponentDto insertPublicApplication(OrganizationDto organization, Consumer... dtoPopulators) { - return insertComponentImpl(newApplication(organization).setPrivate(false), false, dtoPopulators); - } - - @SafeVarargs - public final ComponentDto insertPrivateApplication(OrganizationDto organization, Consumer... dtoPopulators) { - return insertComponentImpl(newApplication(organization).setPrivate(true), true, dtoPopulators); - } - - /** - * @deprecated since 6.6 - * @see #insertPublicApplication(OrganizationDto, Consumer[]) - */ - @SafeVarargs - public final ComponentDto insertApplication(OrganizationDto organizationDto, Consumer... dtoPopulators) { - return insertComponentImpl(newApplication(organizationDto), false, dtoPopulators); - } - - @SafeVarargs - public final ComponentDto insertSubView(ComponentDto view, Consumer... dtoPopulators) { - return insertComponentImpl(newSubView(view), view.isPrivate(), dtoPopulators); - } - - private static Consumer noExtraConfiguration() { - return (t) -> { - }; - } - - @SafeVarargs - private final ComponentDto insertComponentImpl(ComponentDto component, @Nullable Boolean isPrivate, Consumer... dtoPopulators) { - Arrays.stream(dtoPopulators) - .forEach(dtoPopulator -> dtoPopulator.accept(component)); - checkState(isPrivate == null || component.isPrivate() == isPrivate, "Illegal modification of private flag"); - dbClient.componentDao().insert(dbSession, component); - db.commit(); - - return component; - } - - public void insertComponents(ComponentDto... components) { - dbClient.componentDao().insert(dbSession, asList(components)); - db.commit(); - } - - public SnapshotDto insertSnapshot(SnapshotDto snapshotDto) { - SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, snapshotDto); - db.commit(); - return snapshot; - } - - public SnapshotDto insertSnapshot(ComponentDto componentDto) { - return insertSnapshot(componentDto, noExtraConfiguration()); - } - - public SnapshotDto insertSnapshot(ComponentDto componentDto, Consumer consumer) { - SnapshotDto snapshotDto = SnapshotTesting.newAnalysis(componentDto); - consumer.accept(snapshotDto); - SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, snapshotDto); - db.commit(); - return snapshot; - } - - public void insertSnapshots(SnapshotDto... snapshotDtos) { - dbClient.snapshotDao().insert(dbSession, asList(snapshotDtos)); - db.commit(); - } - - @SafeVarargs - public final ComponentDto insertMainBranch(Consumer... dtoPopulators) { - return insertMainBranch(db.getDefaultOrganization(), dtoPopulators); - } - - @SafeVarargs - public final ComponentDto insertMainBranch(OrganizationDto organization, Consumer... dtoPopulators) { - ComponentDto project = newPrivateProjectDto(organization); - Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(project)); - return insertMainBranch(project); - } - - public final ComponentDto insertMainBranch(ComponentDto project) { - BranchDto branchDto = newBranchDto(project, LONG); - insertComponent(project); - dbClient.branchDao().insert(dbSession, branchDto); - db.commit(); - return project; - } - - @SafeVarargs - public final ComponentDto insertMainBranch(OrganizationDto organization, String mainBranchName, Consumer... dtoPopulators) { - ComponentDto project = newPrivateProjectDto(organization); - BranchDto branchDto = newBranchDto(project, LONG).setKey(mainBranchName); - Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(project)); - insertComponent(project); - dbClient.branchDao().insert(dbSession, branchDto); - db.commit(); - return project; - } - - @SafeVarargs - public final ComponentDto insertProjectBranch(ComponentDto project, Consumer... dtoPopulators) { - // MainBranchProjectUuid will be null if it's a main branch - BranchDto branchDto = newBranchDto(firstNonNull(project.getMainBranchProjectUuid(), project.projectUuid()), LONG); - Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(branchDto)); - ComponentDto branch = newProjectBranch(project, branchDto); - insertComponent(branch); - dbClient.branchDao().insert(dbSession, branchDto); - db.commit(); - return branch; - } - - @SafeVarargs - public final ComponentDto insertProjectBranch(OrganizationDto organization, Consumer... dtoPopulators) { - ComponentDto project = newPrivateProjectDto(organization); - return insertProjectBranch(project, dtoPopulators); - } - - public final ComponentDto insertProjectBranch(ComponentDto project, BranchDto branchDto) { - // MainBranchProjectUuid will be null if it's a main branch - checkArgument(branchDto.getProjectUuid().equals(firstNonNull(project.getMainBranchProjectUuid(), project.projectUuid()))); - ComponentDto branch = newProjectBranch(project, branchDto); - insertComponent(branch); - dbClient.branchDao().insert(dbSession, branchDto); - db.commit(); - return branch; - } - - public final void setManualBaseline(ComponentDto longOrMainBranchOfProject, SnapshotDto analysis) { - checkArgument(longOrMainBranchOfProject.isRoot()); - - BranchDto branchDto = db.getDbClient().branchDao().selectByUuid(dbSession, longOrMainBranchOfProject.uuid()) - .orElseThrow(() -> new IllegalArgumentException("BranchDto not found for component " + longOrMainBranchOfProject)); - checkArgument(branchDto.getBranchType() == LONG, "must be a main or a Long Living branch"); - db.getDbClient().branchDao().updateManualBaseline(dbSession, longOrMainBranchOfProject.uuid(), analysis.getUuid()); - db.commit(); - } - - public final void unsetManualBaseline(ComponentDto longOrMainBranchOfProject) { - checkArgument(longOrMainBranchOfProject.isRoot()); - - BranchDto branchDto = db.getDbClient().branchDao().selectByUuid(dbSession, longOrMainBranchOfProject.uuid()) - .orElseThrow(() -> new IllegalArgumentException("BranchDto not found for component " + longOrMainBranchOfProject)); - checkArgument(branchDto.getBranchType() == LONG, "must be a main or a Long Living branch"); - db.getDbClient().branchDao().updateManualBaseline(dbSession, longOrMainBranchOfProject.uuid(), null); - db.commit(); - } - - private static T firstNonNull(@Nullable T first, T second) { - return (first != null) ? first : second; - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentTesting.java deleted file mode 100644 index de911e71fe3..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentTesting.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import java.util.Date; -import javax.annotation.Nullable; -import org.sonar.api.resources.Qualifiers; -import org.sonar.api.resources.Scopes; -import org.sonar.core.util.Uuids; -import org.sonar.db.organization.OrganizationDto; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.sonar.db.component.BranchType.PULL_REQUEST; -import static org.sonar.db.component.ComponentDto.BRANCH_KEY_SEPARATOR; -import static org.sonar.db.component.ComponentDto.PULL_REQUEST_SEPARATOR; -import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT; -import static org.sonar.db.component.ComponentDto.UUID_PATH_SEPARATOR; -import static org.sonar.db.component.ComponentDto.formatUuidPathFromParent; -import static org.sonar.db.component.ComponentDto.generateBranchKey; -import static org.sonar.db.component.ComponentDto.generatePullRequestKey; - -public class ComponentTesting { - - public static ComponentDto newFileDto(ComponentDto subProjectOrProject) { - return newFileDto(subProjectOrProject, null); - } - - public static ComponentDto newFileDto(ComponentDto subProjectOrProject, @Nullable ComponentDto directory) { - return newFileDto(subProjectOrProject, directory, Uuids.createFast()); - } - - public static ComponentDto newFileDto(ComponentDto module, @Nullable ComponentDto directory, String fileUuid) { - String filename = "NAME_" + fileUuid; - String path = directory != null ? directory.path() + "/" + filename : module.path() + "/" + filename; - return newChildComponent(fileUuid, module, directory == null ? module : directory) - .setDbKey(generateKey("FILE_KEY_" + fileUuid, module)) - .setName(filename) - .setLongName(path) - .setScope(Scopes.FILE) - .setQualifier(Qualifiers.FILE) - .setPath(path) - .setCreatedAt(new Date()) - .setLanguage("xoo"); - } - - public static ComponentDto newDirectory(ComponentDto module, String path) { - return newDirectory(module, Uuids.createFast(), path); - } - - public static ComponentDto newDirectory(ComponentDto module, String uuid, String path) { - String key = !path.equals("/") ? module.getKey() + ":" + path : module.getKey() + ":/"; - return newChildComponent(uuid, module, module) - .setDbKey(generateKey(key, module)) - .setName(path) - .setLongName(path) - .setPath(path) - .setScope(Scopes.DIRECTORY) - .setQualifier(Qualifiers.DIRECTORY); - } - - public static ComponentDto newSubView(ComponentDto viewOrSubView, String uuid, String key) { - return newModuleDto(uuid, viewOrSubView) - .setDbKey(key) - .setName(key) - .setLongName(key) - .setScope(Scopes.PROJECT) - .setQualifier(Qualifiers.SUBVIEW) - .setPath(null); - } - - public static ComponentDto newSubView(ComponentDto viewOrSubView) { - String uuid = Uuids.createFast(); - return newSubView(viewOrSubView, uuid, "KEY_" + uuid); - } - - public static ComponentDto newModuleDto(String uuid, ComponentDto parentModuleOrProject) { - return newChildComponent(uuid, parentModuleOrProject, parentModuleOrProject) - .setModuleUuidPath(parentModuleOrProject.moduleUuidPath() + uuid + UUID_PATH_SEPARATOR) - .setDbKey(generateKey("MODULE_KEY_" + uuid, parentModuleOrProject)) - .setName("NAME_" + uuid) - .setLongName("LONG_NAME_" + uuid) - .setPath("module") - .setScope(Scopes.PROJECT) - .setQualifier(Qualifiers.MODULE) - .setLanguage(null); - } - - private static String generateKey(String key, ComponentDto parentModuleOrProject) { - String branch = parentModuleOrProject.getBranch(); - if (branch != null) { - return generateBranchKey(key, branch); - } - String pullRequest = parentModuleOrProject.getPullRequest(); - if (pullRequest != null) { - return generatePullRequestKey(key, pullRequest); - } - - return key; - } - - public static ComponentDto newModuleDto(ComponentDto subProjectOrProject) { - return newModuleDto(Uuids.createFast(), subProjectOrProject); - } - - public static ComponentDto newPrivateProjectDto(OrganizationDto organizationDto) { - return newProjectDto(organizationDto.getUuid(), Uuids.createFast(), true); - } - - public static ComponentDto newPrivateProjectDto(OrganizationDto organizationDto, String uuid) { - return newProjectDto(organizationDto.getUuid(), uuid, true); - } - - public static ComponentDto newPublicProjectDto(OrganizationDto organizationDto) { - return newProjectDto(organizationDto.getUuid(), Uuids.createFast(), false); - } - - public static ComponentDto newPublicProjectDto(OrganizationDto organizationDto, String uuid) { - return newProjectDto(organizationDto.getUuid(), uuid, false); - } - - private static ComponentDto newProjectDto(String organizationUuid, String uuid, boolean isPrivate) { - return new ComponentDto() - .setOrganizationUuid(organizationUuid) - .setUuid(uuid) - .setUuidPath(UUID_PATH_OF_ROOT) - .setProjectUuid(uuid) - .setModuleUuidPath(UUID_PATH_SEPARATOR + uuid + UUID_PATH_SEPARATOR) - .setRootUuid(uuid) - .setDbKey("KEY_" + uuid) - .setName("NAME_" + uuid) - .setLongName("LONG_NAME_" + uuid) - .setDescription("DESCRIPTION_" + uuid) - .setScope(Scopes.PROJECT) - .setQualifier(Qualifiers.PROJECT) - .setPath(null) - .setLanguage(null) - .setEnabled(true) - .setPrivate(isPrivate); - } - - public static ComponentDto newView(OrganizationDto organizationDto) { - return newView(organizationDto.getUuid(), Uuids.createFast()); - } - - public static ComponentDto newView(OrganizationDto organizationDto, String uuid) { - return newPrivateProjectDto(organizationDto, uuid) - .setUuid(uuid) - .setScope(Scopes.PROJECT) - .setQualifier(Qualifiers.VIEW) - .setPrivate(false); - } - - private static ComponentDto newView(String organizationUuid, String uuid) { - return newProjectDto(organizationUuid, uuid, false) - .setUuid(uuid) - .setScope(Scopes.PROJECT) - .setQualifier(Qualifiers.VIEW); - } - - public static ComponentDto newApplication(OrganizationDto organizationDto) { - return newView(organizationDto.getUuid(), Uuids.createFast()) - .setQualifier(Qualifiers.APP); - } - - public static ComponentDto newProjectCopy(ComponentDto project, ComponentDto view) { - return newProjectCopy(Uuids.createFast(), project, view); - } - - public static ComponentDto newProjectCopy(String uuid, ComponentDto project, ComponentDto view) { - checkNotNull(project.getId(), "The project need to be persisted before creating this technical project."); - return newChildComponent(uuid, view, view) - .setDbKey(view.getDbKey() + project.getDbKey()) - .setName(project.name()) - .setLongName(project.longName()) - .setCopyComponentUuid(project.uuid()) - .setScope(Scopes.FILE) - .setQualifier(Qualifiers.PROJECT) - .setPath(null) - .setLanguage(null); - } - - public static ComponentDto newChildComponent(String uuid, ComponentDto moduleOrProject, ComponentDto parent) { - checkArgument(moduleOrProject.isPrivate() == parent.isPrivate(), - "private flag inconsistent between moduleOrProject (%s) and parent (%s)", - moduleOrProject.isPrivate(), parent.isPrivate()); - return new ComponentDto() - .setOrganizationUuid(parent.getOrganizationUuid()) - .setUuid(uuid) - .setUuidPath(formatUuidPathFromParent(parent)) - .setProjectUuid(moduleOrProject.projectUuid()) - .setRootUuid(moduleOrProject.uuid()) - .setModuleUuid(moduleOrProject.uuid()) - .setModuleUuidPath(moduleOrProject.moduleUuidPath()) - .setMainBranchProjectUuid(moduleOrProject.getMainBranchProjectUuid()) - .setCreatedAt(new Date()) - .setEnabled(true) - .setPrivate(moduleOrProject.isPrivate()); - } - - public static BranchDto newBranchDto(@Nullable String projectUuid, BranchType branchType) { - String key = projectUuid == null ? null : "branch_" + randomAlphanumeric(248); - return new BranchDto() - .setKey(key) - .setUuid(Uuids.createFast()) - // MainBranchProjectUuid will be null if it's a main branch - .setProjectUuid(projectUuid) - .setBranchType(branchType); - } - - public static BranchDto newBranchDto(ComponentDto project) { - return newBranchDto(project.projectUuid(), BranchType.LONG); - } - - public static BranchDto newBranchDto(ComponentDto branchComponent, BranchType branchType) { - boolean isMain = branchComponent.getMainBranchProjectUuid() == null; - String projectUuid = isMain ? branchComponent.uuid() : branchComponent.getMainBranchProjectUuid(); - String key = isMain ? "master" : "branch_" + randomAlphanumeric(248); - - return new BranchDto() - .setKey(key) - .setUuid(branchComponent.uuid()) - .setProjectUuid(projectUuid) - .setBranchType(branchType); - } - - public static ComponentDto newProjectBranch(ComponentDto project, BranchDto branchDto) { - checkArgument(project.qualifier().equals(Qualifiers.PROJECT) || project.qualifier().equals(Qualifiers.APP)); - checkArgument(project.getMainBranchProjectUuid() == null); - String branchName = branchDto.getKey(); - String branchSeparator = branchDto.getBranchType() == PULL_REQUEST ? PULL_REQUEST_SEPARATOR : BRANCH_KEY_SEPARATOR; - String uuid = branchDto.getUuid(); - return new ComponentDto() - .setUuid(uuid) - .setOrganizationUuid(project.getOrganizationUuid()) - .setUuidPath(UUID_PATH_OF_ROOT) - .setProjectUuid(uuid) - .setModuleUuidPath(UUID_PATH_SEPARATOR + uuid + UUID_PATH_SEPARATOR) - .setRootUuid(uuid) - // name of the branch is not mandatory on the main branch - .setDbKey(branchName != null ? project.getDbKey() + branchSeparator + branchName : project.getKey()) - .setMainBranchProjectUuid(project.uuid()) - .setName(project.name()) - .setLongName(project.longName()) - .setDescription(project.description()) - .setScope(project.scope()) - .setQualifier(project.qualifier()) - .setPath(null) - .setLanguage(null) - .setEnabled(true) - .setPrivate(project.isPrivate()); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ProjectLinkDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ProjectLinkDbTester.java deleted file mode 100644 index 86c9a7adfb8..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ProjectLinkDbTester.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import java.util.Arrays; -import java.util.function.Consumer; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; - -import static org.sonar.db.component.ProjectLinkTesting.newCustomLinkDto; -import static org.sonar.db.component.ProjectLinkTesting.newProvidedLinkDto; - -public class ProjectLinkDbTester { - private final DbTester db; - private final DbClient dbClient; - private final DbSession dbSession; - - public ProjectLinkDbTester(DbTester db) { - this.db = db; - this.dbClient = db.getDbClient(); - this.dbSession = db.getSession(); - } - - @SafeVarargs - public final ProjectLinkDto insertProvidedLink(ComponentDto project, Consumer... dtoPopulators) { - return insertLink(project, newProvidedLinkDto(), dtoPopulators); - } - - @SafeVarargs - public final ProjectLinkDto insertCustomLink(ComponentDto project, Consumer... dtoPopulators) { - return insertLink(project, newCustomLinkDto(), dtoPopulators); - } - - @SafeVarargs - private final ProjectLinkDto insertLink(ComponentDto project, ProjectLinkDto componentLink, Consumer... dtoPopulators) { - Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(componentLink)); - dbClient.projectLinkDao().insert(dbSession, componentLink.setProjectUuid(project.uuid())); - db.commit(); - return componentLink; - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ProjectLinkTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ProjectLinkTesting.java deleted file mode 100644 index 08170f8855c..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ProjectLinkTesting.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import org.apache.commons.lang.math.RandomUtils; -import org.sonar.core.util.Uuids; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; - -public class ProjectLinkTesting { - - public static ProjectLinkDto newProvidedLinkDto() { - return newCommonLinkDto() - .setName(null) - .setType(ProjectLinkDto.PROVIDED_TYPES.get(RandomUtils.nextInt(ProjectLinkDto.PROVIDED_TYPES.size() - 1))); - } - - public static ProjectLinkDto newCustomLinkDto() { - String nameAndType = randomAlphabetic(20); - return newCommonLinkDto() - .setName(nameAndType) - .setType(nameAndType); - } - - private static ProjectLinkDto newCommonLinkDto() { - return new ProjectLinkDto() - .setUuid(Uuids.createFast()) - .setProjectUuid(Uuids.createFast()) - .setHref(randomAlphanumeric(128)) - .setCreatedAt(System.currentTimeMillis()) - .setUpdatedAt(System.currentTimeMillis()); - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ResourceTypesRule.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ResourceTypesRule.java deleted file mode 100644 index 25945d9848f..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ResourceTypesRule.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import org.sonar.api.resources.ResourceType; -import org.sonar.api.resources.ResourceTypeTree; -import org.sonar.api.resources.ResourceTypes; - -import static java.util.Collections.emptyList; -import static java.util.Collections.emptySet; - -public class ResourceTypesRule extends ResourceTypes { - private Set allResourceTypes = emptySet(); - private Set rootResourceTypes = emptySet(); - private List leavesQualifiers = emptyList(); - - public ResourceTypesRule() { - super(new ResourceTypeTree[0]); - } - - - @Override - public Collection getAll() { - return allResourceTypes; - } - - @Override - public Collection getRoots() { - return rootResourceTypes; - } - - public ResourceTypesRule setRootQualifiers(String... qualifiers) { - Set resourceTypes = new LinkedHashSet<>(); - for (String qualifier : qualifiers) { - resourceTypes.add(ResourceType.builder(qualifier).setProperty("deletable", true).build()); - } - rootResourceTypes = ImmutableSet.copyOf(resourceTypes); - - return this; - } - - public ResourceTypesRule setLeavesQualifiers(String... qualifiers) { - leavesQualifiers = ImmutableList.copyOf(qualifiers); - return this; - } - - public ResourceTypesRule setAllQualifiers(String... qualifiers) { - Set resourceTypes = new HashSet<>(); - for (String qualifier : qualifiers) { - resourceTypes.add(ResourceType.builder(qualifier).setProperty("deletable", true).build()); - } - allResourceTypes = ImmutableSet.copyOf(resourceTypes); - - return this; - } - - @Override - public ResourceType get(String qualifier) { - return allResourceTypes.stream() - .filter(resourceType -> qualifier.equals(resourceType.getQualifier())) - .findAny().orElse(null); - } - - @Override - public boolean isQualifierPresent(String qualifier) { - return rootResourceTypes.stream() - .anyMatch(resourceType -> qualifier.equals(resourceType.getQualifier())); - } - - @Override - public List getLeavesQualifiers(String qualifier) { - return this.leavesQualifiers; - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotTesting.java deleted file mode 100644 index 1f65b38e2b2..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotTesting.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.component; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang.RandomStringUtils.randomAscii; - -public class SnapshotTesting { - - public static SnapshotDto newAnalysis(ComponentDto rootComponent) { - checkNotNull(rootComponent.uuid(), "Project UUID must be set"); - checkArgument(rootComponent.uuid().equals(rootComponent.projectUuid()), "Component is not a tree root"); - return new SnapshotDto() - .setUuid(randomAlphanumeric(40)) - .setComponentUuid(rootComponent.uuid()) - .setStatus(SnapshotDto.STATUS_PROCESSED) - .setCreatedAt(System.currentTimeMillis()) - .setBuildDate(System.currentTimeMillis()) - .setRevision(randomAlphanumeric(50)) - .setLast(true); - } - - public static SnapshotDto newSnapshot() { - return new SnapshotDto() - .setUuid(randomAlphanumeric(40)) - .setComponentUuid(randomAlphanumeric(40)) - .setStatus(randomAscii(1)) - .setCreatedAt(System.currentTimeMillis()) - .setBuildDate(System.currentTimeMillis()) - .setLast(true); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventDbTester.java deleted file mode 100644 index bc97784ed3b..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventDbTester.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.event; - -import java.util.Optional; -import javax.annotation.Nullable; -import org.sonar.core.util.UuidFactoryFast; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; -import org.sonar.db.component.BranchDto; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.component.SnapshotDto; -import org.sonar.db.event.EventComponentChangeDto.ChangeCategory; - -public class EventDbTester { - private final DbTester db; - private final DbClient dbClient; - private final DbSession dbSession; - - public EventDbTester(DbTester db) { - this.db = db; - this.dbClient = db.getDbClient(); - this.dbSession = db.getSession(); - } - - public EventDto insertEvent(EventDto event) { - dbClient.eventDao().insert(dbSession, event); - db.commit(); - - return event; - } - - public EventDto insertEvent(SnapshotDto analysis) { - EventDto event = EventTesting.newEvent(analysis); - dbClient.eventDao().insert(dbSession, event); - db.commit(); - - return event; - } - - public EventComponentChangeDto insertEventComponentChanges(EventDto event, SnapshotDto analysis, - ChangeCategory changeCategory, ComponentDto component, @Nullable BranchDto branch) { - - EventComponentChangeDto eventComponentChange = new EventComponentChangeDto() - .setUuid(UuidFactoryFast.getInstance().create()) - .setCategory(changeCategory) - .setEventUuid(event.getUuid()) - .setComponentUuid(component.uuid()) - .setComponentKey(component.getKey()) - .setComponentName(component.name()) - .setComponentBranchKey(Optional.ofNullable(branch).map(BranchDto::getKey).orElse(null)); - EventPurgeData eventPurgeData = new EventPurgeData(analysis.getComponentUuid(), analysis.getUuid()); - - dbClient.eventComponentChangeDao().insert(dbSession, eventComponentChange, eventPurgeData); - db.commit(); - - return eventComponentChange; - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventTesting.java deleted file mode 100644 index b3a4c135e65..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventTesting.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.event; - -import org.sonar.db.component.SnapshotDto; - -import static java.util.Objects.requireNonNull; -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; - -public class EventTesting { - - public static EventDto newEvent(SnapshotDto analysis) { - requireNonNull(analysis.getUuid()); - requireNonNull(analysis.getComponentUuid()); - - return new EventDto() - .setAnalysisUuid(analysis.getUuid()) - .setComponentUuid(analysis.getComponentUuid()) - .setUuid(randomAlphanumeric(40)) - .setName(randomAlphanumeric(400)) - .setDescription(null) - .setCategory("Other") - .setCreatedAt(System.currentTimeMillis()) - .setDate(System.currentTimeMillis()); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/favorite/FavoriteDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/favorite/FavoriteDbTester.java deleted file mode 100644 index feb803c5f0d..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/favorite/FavoriteDbTester.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.favorite; - -import java.util.List; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.property.PropertyDto; -import org.sonar.db.property.PropertyQuery; - -public class FavoriteDbTester { - private static final String PROP_FAVORITE_KEY = "favourite"; - - private final DbClient dbClient; - private final DbSession dbSession; - - public FavoriteDbTester(DbTester db) { - this.dbClient = db.getDbClient(); - this.dbSession = db.getSession(); - } - - public void add(ComponentDto componentDto, int userId) { - dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto() - .setKey(PROP_FAVORITE_KEY) - .setUserId(userId) - .setResourceId(componentDto.getId())); - dbSession.commit(); - } - - public boolean hasFavorite(ComponentDto componentDto, int userId) { - List result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() - .setKey(PROP_FAVORITE_KEY) - .setComponentId(componentDto.getId()) - .setUserId(userId) - .build(), dbSession); - - return !result.isEmpty(); - } - - public boolean hasNoFavorite(ComponentDto componentDto) { - List result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() - .setKey(PROP_FAVORITE_KEY) - .setComponentId(componentDto.getId()) - .build(), dbSession); - return result.isEmpty(); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDbTester.java deleted file mode 100644 index a7c5c0c7355..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDbTester.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.issue; - -import java.util.Arrays; -import java.util.function.Consumer; -import javax.annotation.Nullable; -import org.sonar.core.issue.DefaultIssueComment; -import org.sonar.core.issue.FieldDiffs; -import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.organization.OrganizationDto; -import org.sonar.db.rule.RuleDefinitionDto; -import org.sonar.db.user.UserDto; - -import static java.util.Arrays.stream; -import static org.sonar.db.component.ComponentTesting.newFileDto; -import static org.sonar.db.issue.IssueTesting.newIssue; - -public class IssueDbTester { - - private final DbTester db; - - public IssueDbTester(DbTester db) { - this.db = db; - } - - @SafeVarargs - public final IssueDto insert(RuleDefinitionDto rule, ComponentDto project, ComponentDto file, Consumer... populators) { - IssueDto issue = newIssue(rule, project, file); - stream(populators).forEach(p -> p.accept(issue)); - return insertIssue(issue); - } - - public IssueDto insertIssue(IssueDto issueDto) { - db.getDbClient().issueDao().insert(db.getSession(), issueDto); - db.commit(); - return issueDto; - } - - @SafeVarargs - public final IssueDto insertIssue(Consumer... populateIssueDto) { - return insertIssue(db.getDefaultOrganization(), populateIssueDto); - } - - @SafeVarargs - public final IssueDto insertIssue(OrganizationDto organizationDto, Consumer... populators) { - RuleDefinitionDto rule = db.rules().insert(); - ComponentDto project = db.components().insertMainBranch(organizationDto); - ComponentDto file = db.components().insertComponent(newFileDto(project)); - IssueDto issue = newIssue(rule, project, file); - stream(populators).forEach(p -> p.accept(issue)); - return insertIssue(issue); - } - - @SafeVarargs - public final IssueChangeDto insertChange(IssueDto issueDto, Consumer... populators) { - IssueChangeDto dto = IssueTesting.newIssuechangeDto(issueDto); - stream(populators).forEach(p -> p.accept(dto)); - return insertChange(dto); - } - - public IssueChangeDto insertChange(IssueChangeDto issueChangeDto) { - db.getDbClient().issueChangeDao().insert(db.getSession(), issueChangeDto); - db.commit(); - return issueChangeDto; - } - - public IssueChangeDto insertComment(IssueDto issueDto, @Nullable UserDto user, String text) { - IssueChangeDto issueChangeDto = IssueChangeDto.of(DefaultIssueComment.create(issueDto.getKey(), user == null ? null : user.getUuid(), text)); - return insertChange(issueChangeDto); - } - - public void insertFieldDiffs(IssueDto issueDto, FieldDiffs... diffs) { - Arrays.stream(diffs).forEach(diff -> db.getDbClient().issueChangeDao().insert(db.getSession(), IssueChangeDto.of(issueDto.getKey(), diff))); - db.commit(); - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureDbTester.java deleted file mode 100644 index 59b8c3160bd..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureDbTester.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure; - -import com.google.common.base.Preconditions; -import java.util.Arrays; -import java.util.function.Consumer; -import javax.annotation.Nullable; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.component.SnapshotDto; -import org.sonar.db.measure.custom.CustomMeasureDto; -import org.sonar.db.metric.MetricDto; -import org.sonar.db.user.UserDto; - -import static org.sonar.db.measure.MeasureTesting.newLiveMeasure; -import static org.sonar.db.measure.MeasureTesting.newMeasureDto; -import static org.sonar.db.measure.custom.CustomMeasureTesting.newCustomMeasureDto; -import static org.sonar.db.metric.MetricTesting.newMetricDto; - -public class MeasureDbTester { - private final DbClient dbClient; - private final DbSession dbSession; - - public MeasureDbTester(DbTester db) { - this.dbClient = db.getDbClient(); - this.dbSession = db.getSession(); - } - - @SafeVarargs - public final MeasureDto insertMeasure(ComponentDto component, SnapshotDto analysis, MetricDto metricDto, Consumer... consumers) { - MeasureDto measureDto = newMeasureDto(metricDto, component, analysis); - Arrays.stream(consumers).forEach(c -> c.accept(measureDto)); - dbClient.measureDao().insert(dbSession, measureDto); - dbSession.commit(); - return measureDto; - } - - @SafeVarargs - public final LiveMeasureDto insertLiveMeasure(ComponentDto component, MetricDto metric, Consumer... consumers) { - LiveMeasureDto dto = newLiveMeasure(component, metric); - Arrays.stream(consumers).forEach(c -> c.accept(dto)); - dbClient.liveMeasureDao().insert(dbSession, dto); - dbSession.commit(); - return dto; - } - - @SafeVarargs - public final CustomMeasureDto insertCustomMeasure(@Nullable UserDto user, ComponentDto component, MetricDto metricDto, Consumer... consumers) { - Preconditions.checkArgument(metricDto.isUserManaged(),"Custom measure must be created from a custom metric"); - CustomMeasureDto dto = newCustomMeasureDto() - .setComponentUuid(component.uuid()) - .setMetricId(metricDto.getId()); - if (user != null) { - dto.setUserUuid(user.getUuid()); - } - Arrays.stream(consumers).forEach(c -> c.accept(dto)); - dbClient.customMeasureDao().insert(dbSession, dto); - dbSession.commit(); - return dto; - } - - @SafeVarargs - public final MetricDto insertMetric(Consumer... consumers) { - MetricDto metricDto = newMetricDto(); - Arrays.stream(consumers).forEach(c -> c.accept(metricDto)); - dbClient.metricDao().insert(dbSession, metricDto); - dbSession.commit(); - return metricDto; - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureTesting.java deleted file mode 100644 index 60b0c188757..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureTesting.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure; - -import org.apache.commons.lang.math.RandomUtils; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.component.SnapshotDto; -import org.sonar.db.metric.MetricDto; - -import static com.google.common.base.Preconditions.checkNotNull; - -public class MeasureTesting { - - private static int cursor = RandomUtils.nextInt(100); - - private MeasureTesting() { - // static methods only - } - - public static MeasureDto newMeasureDto(MetricDto metricDto, ComponentDto component, SnapshotDto analysis) { - checkNotNull(metricDto.getId()); - checkNotNull(metricDto.getKey()); - checkNotNull(component.uuid()); - checkNotNull(analysis.getUuid()); - return new MeasureDto() - .setMetricId(metricDto.getId()) - .setComponentUuid(component.uuid()) - .setAnalysisUuid(analysis.getUuid()); - } - - public static MeasureDto newMeasure() { - return new MeasureDto() - .setMetricId(cursor++) - .setComponentUuid(String.valueOf(cursor++)) - .setAnalysisUuid(String.valueOf(cursor++)) - .setData(String.valueOf(cursor++)) - .setAlertStatus(String.valueOf(cursor++)) - .setAlertText(String.valueOf(cursor++)) - .setValue((double) cursor++); - } - - public static LiveMeasureDto newLiveMeasure() { - return new LiveMeasureDto() - .setMetricId(cursor++) - .setComponentUuid(String.valueOf(cursor++)) - .setProjectUuid(String.valueOf(cursor++)) - .setData(String.valueOf(cursor++)) - .setValue((double) cursor++) - .setVariation((double) cursor++); - } - - public static LiveMeasureDto newLiveMeasure(ComponentDto component, MetricDto metric) { - return new LiveMeasureDto() - .setMetricId(metric.getId()) - .setComponentUuid(component.uuid()) - .setProjectUuid(component.projectUuid()) - .setData(String.valueOf(cursor++)) - .setValue((double) cursor++) - .setVariation((double) cursor++); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/custom/CustomMeasureTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/measure/custom/CustomMeasureTesting.java deleted file mode 100644 index 318633e316b..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/custom/CustomMeasureTesting.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.measure.custom; - -import org.apache.commons.lang.RandomStringUtils; -import org.apache.commons.lang.math.RandomUtils; -import org.sonar.api.utils.System2; - -public class CustomMeasureTesting { - private CustomMeasureTesting() { - // static stuff only - } - - public static CustomMeasureDto newCustomMeasureDto() { - return new CustomMeasureDto() - .setDescription(RandomStringUtils.randomAlphanumeric(255)) - .setTextValue(RandomStringUtils.randomAlphanumeric(255)) - .setUserUuid("userUuid" + RandomStringUtils.randomAlphanumeric(100)) - .setValue(RandomUtils.nextDouble()) - .setMetricId(RandomUtils.nextInt()) - .setComponentUuid(RandomStringUtils.randomAlphanumeric(50)) - .setCreatedAt(System2.INSTANCE.now()) - .setUpdatedAt(System2.INSTANCE.now()); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricTesting.java deleted file mode 100644 index 2158cc56dba..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricTesting.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.metric; - -import org.apache.commons.lang.RandomStringUtils; -import org.apache.commons.lang.math.RandomUtils; -import org.sonar.api.measures.Metric; - -public class MetricTesting { - private MetricTesting() { - // static stuff only - } - - public static MetricDto newMetricDto() { - Metric.ValueType[] metricTypes = Metric.ValueType.values(); - return new MetricDto() - .setId(RandomUtils.nextInt()) - .setKey(RandomStringUtils.randomAlphanumeric(64)) - .setShortName(RandomStringUtils.randomAlphanumeric(64)) - .setValueType(metricTypes[RandomUtils.nextInt(metricTypes.length - 1)].name()) - .setDomain(RandomStringUtils.randomAlphanumeric(64)) - .setDescription(RandomStringUtils.randomAlphanumeric(250)) - .setBestValue(RandomUtils.nextDouble()) - .setDeleteHistoricalData(RandomUtils.nextBoolean()) - .setDirection(RandomUtils.nextInt()) - .setHidden(RandomUtils.nextBoolean()) - .setEnabled(true) - .setOptimizedBestValue(RandomUtils.nextBoolean()) - .setQualitative(RandomUtils.nextBoolean()) - .setUserManaged(RandomUtils.nextBoolean()) - .setWorstValue(RandomUtils.nextDouble()); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/notification/NotificationDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/notification/NotificationDbTester.java deleted file mode 100644 index 4449bbaafc2..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/notification/NotificationDbTester.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.notification; - -import java.util.List; -import javax.annotation.Nullable; -import org.sonar.core.util.stream.MoreCollectors; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.property.PropertyDto; -import org.sonar.db.property.PropertyQuery; - -import static org.assertj.core.api.Assertions.assertThat; - -public class NotificationDbTester { - private static final String PROP_NOTIFICATION_PREFIX = "notification"; - - private final DbTester db; - private final DbClient dbClient; - private final DbSession dbSession; - - public NotificationDbTester(DbTester db) { - this.db = db; - this.dbClient = db.getDbClient(); - this.dbSession = db.getSession(); - } - - public void assertExists(String channel, String dispatcher, int userId, @Nullable ComponentDto component) { - List result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() - .setKey(String.join(".", PROP_NOTIFICATION_PREFIX, dispatcher, channel)) - .setComponentId(component == null ? null : component.getId()) - .setUserId(userId) - .build(), dbSession).stream() - .filter(prop -> component == null ? prop.getResourceId() == null : prop.getResourceId() != null) - .collect(MoreCollectors.toList()); - assertThat(result).hasSize(1); - assertThat(result.get(0).getValue()).isEqualTo("true"); - } - - public void assertDoesNotExist(String channel, String dispatcher, int userId, @Nullable ComponentDto component) { - List result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() - .setKey(String.join(".", PROP_NOTIFICATION_PREFIX, dispatcher, channel)) - .setComponentId(component == null ? null : component.getId()) - .setUserId(userId) - .build(), dbSession); - assertThat(result).isEmpty(); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/organization/OrganizationDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/organization/OrganizationDbTester.java deleted file mode 100644 index 5daf1ff867d..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/organization/OrganizationDbTester.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.organization; - -import java.util.Arrays; -import java.util.function.Consumer; -import javax.annotation.Nullable; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; -import org.sonar.db.permission.template.PermissionTemplateDto; -import org.sonar.db.user.GroupMembershipDto; -import org.sonar.db.user.GroupMembershipQuery; -import org.sonar.db.user.UserDto; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.db.user.GroupMembershipQuery.IN; - -public class OrganizationDbTester { - private final DbTester db; - - public OrganizationDbTester(DbTester db) { - this.db = db; - } - - /** - * Insert an {@link OrganizationDto} and commit the session - */ - public OrganizationDto insert() { - return insert(OrganizationTesting.newOrganizationDto()); - } - - public OrganizationDto insert(Consumer populator) { - OrganizationDto dto = OrganizationTesting.newOrganizationDto(); - populator.accept(dto); - return insert(dto); - } - - public OrganizationDto insertForKey(String key) { - return insert(dto -> dto.setKey(key)); - } - - public OrganizationDto insertForUuid(String organizationUuid) { - return insert(dto -> dto.setUuid(organizationUuid)); - } - - /** - * Insert the provided {@link OrganizationDto} and commit the session - */ - public OrganizationDto insert(OrganizationDto dto) { - DbSession dbSession = db.getSession(); - db.getDbClient().organizationDao().insert(dbSession, dto, false); - dbSession.commit(); - return dto; - } - - public void setDefaultTemplates(PermissionTemplateDto projectDefaultTemplate, @Nullable PermissionTemplateDto applicationDefaultTemplate, - @Nullable PermissionTemplateDto portfolioDefaultTemplate) { - checkArgument(portfolioDefaultTemplate == null - || portfolioDefaultTemplate.getOrganizationUuid().equals(projectDefaultTemplate.getOrganizationUuid()), - "default template for project and portfolio must belong to the same organization"); - checkArgument(applicationDefaultTemplate == null - || applicationDefaultTemplate.getOrganizationUuid().equals(projectDefaultTemplate.getOrganizationUuid()), - "default template for project and application must belong to the same organization"); - - DbSession dbSession = db.getSession(); - db.getDbClient().organizationDao().setDefaultTemplates(dbSession, projectDefaultTemplate.getOrganizationUuid(), - new DefaultTemplates() - .setProjectUuid(projectDefaultTemplate.getUuid()) - .setPortfoliosUuid(portfolioDefaultTemplate == null ? null : portfolioDefaultTemplate.getUuid()) - .setApplicationsUuid(applicationDefaultTemplate == null ? null : applicationDefaultTemplate.getUuid())); - dbSession.commit(); - } - - public void setDefaultTemplates(OrganizationDto defaultOrganization, String projectDefaultTemplateUuid, - @Nullable String applicationDefaultTemplateUuid, @Nullable String portfoliosDefaultTemplateUuid) { - DbSession dbSession = db.getSession(); - db.getDbClient().organizationDao().setDefaultTemplates(dbSession, defaultOrganization.getUuid(), - new DefaultTemplates() - .setProjectUuid(projectDefaultTemplateUuid) - .setApplicationsUuid(applicationDefaultTemplateUuid) - .setPortfoliosUuid(portfoliosDefaultTemplateUuid)); - dbSession.commit(); - } - - public void addMember(OrganizationDto organization, UserDto... users) { - Arrays.stream(users) - .forEach(u -> db.getDbClient().organizationMemberDao().insert(db.getSession(), new OrganizationMemberDto().setOrganizationUuid(organization.getUuid()).setUserId(u.getId()))); - db.commit(); - } - - public void setNewProjectPrivate(OrganizationDto organization, boolean newProjectPrivate) { - db.getDbClient().organizationDao().setNewProjectPrivate(db.getSession(), organization, newProjectPrivate); - db.commit(); - } - - public boolean getNewProjectPrivate(OrganizationDto organization) { - return db.getDbClient().organizationDao().getNewProjectPrivate(db.getSession(), organization); - } - - public void assertUserIsMemberOfOrganization(OrganizationDto organization, UserDto user) { - assertThat(db.getDbClient().organizationMemberDao().select(db.getSession(), organization.getUuid(), user.getId())).as("User is not member of the organization").isPresent(); - Integer defaultGroupId = db.getDbClient().organizationDao().getDefaultGroupId(db.getSession(), organization.getUuid()).get(); - assertThat(db.getDbClient().groupMembershipDao().selectGroups( - db.getSession(), - GroupMembershipQuery.builder().membership(IN).organizationUuid(organization.getUuid()).build(), - user.getId(), 0, 10)) - .extracting(GroupMembershipDto::getId) - .as("User is not member of the default group of the organization") - .containsOnly(defaultGroupId.longValue()); - } - - public void assertUserIsNotMemberOfOrganization(OrganizationDto organization, UserDto user) { - assertThat(db.getDbClient().organizationMemberDao().select(db.getSession(), organization.getUuid(), user.getId())).as("User is still member of the organization") - .isNotPresent(); - assertThat(db.getDbClient().groupMembershipDao().countGroups(db.getSession(), - GroupMembershipQuery.builder().membership(IN).organizationUuid(organization.getUuid()).build(), - user.getId())).isZero(); - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/organization/OrganizationTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/organization/OrganizationTesting.java deleted file mode 100644 index 57f1b59a289..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/organization/OrganizationTesting.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.organization; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.sonar.db.organization.OrganizationDto.Subscription.FREE; - -public class OrganizationTesting { - - private OrganizationTesting() { - // only statics - } - - /** - * Creates a new {@link OrganizationDto} with randomly generated field values. - */ - public static OrganizationDto newOrganizationDto() { - return new OrganizationDto() - .setKey(randomAlphanumeric(32)) - .setUuid(randomAlphanumeric(40)) - .setName(randomAlphanumeric(64)) - .setDescription(randomAlphanumeric(256)) - .setAvatarUrl(randomAlphanumeric(256)) - // Default quality gate should be set explicitly when needed in tests - .setDefaultQualityGateUuid("_NOT_SET_") - .setSubscription(FREE) - .setUrl(randomAlphanumeric(256)); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/PermissionsTestHelper.java b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/PermissionsTestHelper.java deleted file mode 100644 index 3eb75f13258..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/PermissionsTestHelper.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission; - -import com.google.common.collect.ImmutableSet; -import java.util.Set; -import org.sonar.api.web.UserRole; -import org.sonar.core.permission.GlobalPermissions; - -public class PermissionsTestHelper { - - public static final Set ALL_PERMISSIONS = ImmutableSet.of(UserRole.ADMIN, UserRole.CODEVIEWER, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, - GlobalPermissions.SCAN_EXECUTION, UserRole.USER, OrganizationPermission.APPLICATION_CREATOR.getKey(), OrganizationPermission.PORTFOLIO_CREATOR.getKey()); - - private PermissionsTestHelper() { - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateDbTester.java deleted file mode 100644 index 35e48b0d6f7..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateDbTester.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission.template; - -import javax.annotation.Nullable; -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.user.GroupDto; -import org.sonar.db.user.UserDto; - -import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateCharacteristicDto; -import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto; - -public class PermissionTemplateDbTester { - private final DbTester db; - private final DbClient dbClient; - private final DbSession dbSession; - - public PermissionTemplateDbTester(DbTester db) { - this.db = db; - this.dbClient = db.getDbClient(); - this.dbSession = db.getSession(); - } - - public PermissionTemplateDto insertTemplate() { - return insertTemplate(newPermissionTemplateDto()); - } - - public PermissionTemplateDto insertTemplate(OrganizationDto organizationDto) { - return insertTemplate(newPermissionTemplateDto().setOrganizationUuid(organizationDto.getUuid())); - } - - public PermissionTemplateDto insertTemplate(PermissionTemplateDto template) { - PermissionTemplateDto templateInDb = dbClient.permissionTemplateDao().insert(dbSession, template); - db.commit(); - - return templateInDb; - } - - public void addGroupToTemplate(PermissionTemplateDto permissionTemplate, GroupDto group, String permission) { - addGroupToTemplate(permissionTemplate.getId(), group.getId(), permission); - } - - public void addGroupToTemplate(long templateId, @Nullable Integer groupId, String permission) { - dbClient.permissionTemplateDao().insertGroupPermission(dbSession, templateId, groupId, permission); - db.commit(); - } - - public void addAnyoneToTemplate(PermissionTemplateDto permissionTemplate, String permission) { - addGroupToTemplate(permissionTemplate.getId(), null, permission); - } - - public void addUserToTemplate(PermissionTemplateDto permissionTemplate, UserDto user, String permission) { - addUserToTemplate(permissionTemplate.getId(), user.getId(), permission); - } - - public void addUserToTemplate(long templateId, int userId, String permission) { - dbClient.permissionTemplateDao().insertUserPermission(dbSession, templateId, userId, permission); - db.commit(); - } - - public void addProjectCreatorToTemplate(PermissionTemplateDto permissionTemplate, String permission) { - addProjectCreatorToTemplate(permissionTemplate.getId(), permission); - } - - public void addProjectCreatorToTemplate(long templateId, String permission) { - dbClient.permissionTemplateCharacteristicDao().insert(dbSession, newPermissionTemplateCharacteristicDto() - .setWithProjectCreator(true) - .setTemplateId(templateId) - .setPermission(permission)); - db.commit(); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateTesting.java deleted file mode 100644 index a029200457e..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateTesting.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.permission.template; - -import java.util.Date; -import org.apache.commons.lang.math.RandomUtils; -import org.sonar.core.util.Uuids; -import org.sonar.db.permission.PermissionsTestHelper; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang.RandomStringUtils.randomAscii; - -public class PermissionTemplateTesting { - public static PermissionTemplateDto newPermissionTemplateDto() { - return new PermissionTemplateDto() - .setName(randomAlphanumeric(60)) - .setDescription(randomAscii(500)) - .setOrganizationUuid(randomAlphanumeric(40)) - .setUuid(Uuids.create()) - .setCreatedAt(new Date()) - .setUpdatedAt(new Date()); - } - - public static PermissionTemplateUserDto newPermissionTemplateUserDto() { - return new PermissionTemplateUserDto() - .setPermission(PermissionsTestHelper.ALL_PERMISSIONS.toArray(new String[0])[RandomUtils.nextInt(PermissionsTestHelper.ALL_PERMISSIONS.size())]) - .setCreatedAt(new Date()) - .setUpdatedAt(new Date()); - } - - public static PermissionTemplateGroupDto newPermissionTemplateGroupDto() { - return new PermissionTemplateGroupDto() - .setPermission(PermissionsTestHelper.ALL_PERMISSIONS.toArray(new String[0])[RandomUtils.nextInt(PermissionsTestHelper.ALL_PERMISSIONS.size())]) - .setCreatedAt(new Date()) - .setUpdatedAt(new Date()); - } - - public static PermissionTemplateCharacteristicDto newPermissionTemplateCharacteristicDto() { - return new PermissionTemplateCharacteristicDto() - .setPermission(PermissionsTestHelper.ALL_PERMISSIONS.toArray(new String[0])[RandomUtils.nextInt(PermissionsTestHelper.ALL_PERMISSIONS.size())]) - .setWithProjectCreator(RandomUtils.nextBoolean()) - .setCreatedAt(System.currentTimeMillis()) - .setUpdatedAt(System.currentTimeMillis()); - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginDbTester.java deleted file mode 100644 index 5fc1afab4e8..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginDbTester.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.plugin; - -import java.util.Arrays; -import java.util.function.Consumer; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; - -public class PluginDbTester { - private final DbClient dbClient; - private final DbSession dbSession; - - public PluginDbTester(DbTester db) { - this.dbClient = db.getDbClient(); - this.dbSession = db.getSession(); - } - - @SafeVarargs - public final PluginDto insertPlugin(Consumer... consumers) { - PluginDto pluginDto = PluginTesting.newPluginDto(); - Arrays.stream(consumers).forEach(c -> c.accept(pluginDto)); - dbClient.pluginDao().insert(dbSession, pluginDto); - dbSession.commit(); - return pluginDto; - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginTesting.java deleted file mode 100644 index e42b939864d..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginTesting.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.plugin; - -import org.sonar.core.util.Uuids; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang.math.RandomUtils.nextLong; - -public class PluginTesting { - - private PluginTesting() { - // prevent instantiation - } - - /** - * Create an instance of {@link PluginDto} with random field values. - */ - public static PluginDto newPluginDto() { - String uuid = Uuids.createFast(); - return new PluginDto() - .setUuid(uuid) - .setKee(uuid) - .setFileHash(randomAlphanumeric(32)) - .setCreatedAt(nextLong()) - .setUpdatedAt(nextLong()); - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertyDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertyDbTester.java deleted file mode 100644 index 4588ad91853..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertyDbTester.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -import java.util.Optional; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; - -public class InternalComponentPropertyDbTester { - private final DbTester db; - private final DbClient dbClient; - private final DbSession dbSession; - - public InternalComponentPropertyDbTester(DbTester db) { - this.db = db; - this.dbClient = db.getDbClient(); - this.dbSession = db.getSession(); - } - - public void insertProperty(String componentUuid, String key, String value) { - dbClient.internalComponentPropertiesDao().insertOrUpdate(dbSession, componentUuid, key, value); - db.commit(); - } - - public Optional getProperty(String componentUuid, String key) { - return dbClient.internalComponentPropertiesDao().selectByComponentUuidAndKey(dbSession, componentUuid, key); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertyDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertyDbTester.java deleted file mode 100644 index b00cc9f1964..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertyDbTester.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -import com.google.common.base.Joiner; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import javax.annotation.Nullable; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDto; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.db.property.PropertyTesting.newComponentPropertyDto; -import static org.sonar.db.property.PropertyTesting.newGlobalPropertyDto; - -public class PropertyDbTester { - private final DbTester db; - private final DbClient dbClient; - private final DbSession dbSession; - - public PropertyDbTester(DbTester db) { - this.db = db; - this.dbClient = db.getDbClient(); - this.dbSession = db.getSession(); - } - - public PropertyDto insertProperty(PropertyDto property) { - dbClient.propertiesDao().saveProperty(dbSession, property); - db.commit(); - - return property; - } - - public void insertProperties(PropertyDto... properties) { - insertProperties(asList(properties)); - } - - public void insertProperties(List properties) { - for (PropertyDto propertyDto : properties) { - dbClient.propertiesDao().saveProperty(dbSession, propertyDto); - } - dbSession.commit(); - } - - public void insertPropertySet(String settingBaseKey, @Nullable ComponentDto componentDto, Map... fieldValues) { - int index = 1; - List propertyDtos = new ArrayList<>(); - List ids = new ArrayList<>(); - for (Map fieldValue : fieldValues) { - for (Map.Entry entry : fieldValue.entrySet()) { - String key = settingBaseKey + "." + index + "." + entry.getKey(); - if (componentDto != null) { - propertyDtos.add(newComponentPropertyDto(componentDto).setKey(key).setValue(entry.getValue())); - } else { - propertyDtos.add(newGlobalPropertyDto().setKey(key).setValue(entry.getValue())); - } - } - ids.add(Integer.toString(index)); - index++; - } - String idsValue = Joiner.on(",").join(ids); - if (componentDto != null) { - propertyDtos.add(newComponentPropertyDto(componentDto).setKey(settingBaseKey).setValue(idsValue)); - } else { - propertyDtos.add(newGlobalPropertyDto().setKey(settingBaseKey).setValue(idsValue)); - } - insertProperties(propertyDtos); - } - - public PropertyDbTester verifyInternal(String key, @Nullable String expectedValue) { - Optional value = dbClient.internalPropertiesDao().selectByKey(dbSession, key); - if (expectedValue == null) { - assertThat(value).isEmpty(); - } else { - assertThat(value).hasValue(expectedValue); - } - return this; - } - - public PropertyDbTester insertInternal(String key, String value) { - dbClient.internalPropertiesDao().save(dbSession, key, value); - dbSession.commit(); - return this; - } - - public PropertyDbTester insertEmptyInternal(String key) { - dbClient.internalPropertiesDao().saveAsEmpty(dbSession, key); - dbSession.commit(); - return this; - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertyTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertyTesting.java deleted file mode 100644 index 904f350cf9a..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertyTesting.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.property; - -import javax.annotation.Nullable; -import org.apache.commons.lang.math.RandomUtils; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.user.UserDto; - -import static com.google.common.base.Preconditions.checkNotNull; - -public class PropertyTesting { - - private static int cursor = RandomUtils.nextInt(100); - - private PropertyTesting() { - // static methods only - } - - public static PropertyDto newGlobalPropertyDto(String key, String value) { - return newPropertyDto(key, value, (Long) null, null); - } - - public static PropertyDto newGlobalPropertyDto() { - return newPropertyDto((Long) null, null); - } - - public static PropertyDto newComponentPropertyDto(String key, String value, ComponentDto component) { - checkNotNull(component.getId()); - return newPropertyDto(key, value, component.getId(), null); - } - - public static PropertyDto newComponentPropertyDto(ComponentDto component) { - checkNotNull(component.getId()); - return newPropertyDto(component.getId(), null); - } - - public static PropertyDto newUserPropertyDto(String key, String value, UserDto user) { - checkNotNull(user.getId()); - return newPropertyDto(key, value, null, user.getId()); - } - - public static PropertyDto newUserPropertyDto(UserDto user) { - checkNotNull(user.getId()); - return newPropertyDto(null, user.getId()); - } - - public static PropertyDto newPropertyDto(String key, String value, ComponentDto component, UserDto user) { - checkNotNull(component.getId()); - checkNotNull(user.getId()); - return newPropertyDto(key, value, component.getId(), user.getId()); - } - - public static PropertyDto newPropertyDto(ComponentDto component, UserDto user) { - checkNotNull(component.getId()); - checkNotNull(user.getId()); - return newPropertyDto(component.getId(), user.getId()); - } - - private static PropertyDto newPropertyDto(@Nullable Long componentId, @Nullable Integer userId) { - String key = String.valueOf(cursor); - cursor++; - String value = String.valueOf(cursor); - cursor++; - return newPropertyDto(key, value, componentId, userId); - } - - private static PropertyDto newPropertyDto(String key, String value, @Nullable Long componentId, @Nullable Integer userId) { - PropertyDto propertyDto = new PropertyDto() - .setKey(key) - .setValue(value); - if (componentId != null) { - propertyDto.setResourceId(componentId); - } - if (userId != null) { - propertyDto.setUserId(userId); - } - return propertyDto; - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/qualitygate/QualityGateDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/qualitygate/QualityGateDbTester.java deleted file mode 100644 index 6b72f94b4a2..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/qualitygate/QualityGateDbTester.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualitygate; - -import java.util.Arrays; -import java.util.Date; -import java.util.Optional; -import java.util.function.Consumer; -import org.sonar.core.util.Uuids; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.metric.MetricDto; -import org.sonar.db.organization.OrganizationDto; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang.RandomStringUtils.randomNumeric; - -public class QualityGateDbTester { - - private final DbTester db; - private final DbClient dbClient; - private final DbSession dbSession; - - public QualityGateDbTester(DbTester db) { - this.db = db; - this.dbClient = db.getDbClient(); - this.dbSession = db.getSession(); - } - - public QualityGateDto insertBuiltInQualityGate() { - QualityGateDto builtin = dbClient.qualityGateDao().insert(dbSession, new QualityGateDto() - .setName("Sonar way") - .setUuid(Uuids.createFast()) - .setBuiltIn(true) - .setCreatedAt(new Date())); - dbSession.commit(); - return builtin; - } - - @SafeVarargs - public final QGateWithOrgDto insertQualityGate(OrganizationDto organization, Consumer... dtoPopulators) { - QualityGateDto qualityGate = new QualityGateDto() - .setName(randomAlphanumeric(30)) - .setUuid(Uuids.createFast()) - .setBuiltIn(false); - Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(qualityGate)); - dbClient.qualityGateDao().insert(dbSession, qualityGate); - dbClient.qualityGateDao().associate(dbSession, Uuids.createFast(), organization, qualityGate); - db.commit(); - return dbClient.qualityGateDao().selectByOrganizationAndUuid(dbSession, organization, qualityGate.getUuid()); - } - - public void associateProjectToQualityGate(ComponentDto component, QualityGateDto qualityGate) { - dbClient.projectQgateAssociationDao().insertProjectQGateAssociation(dbSession, component.uuid(), qualityGate.getUuid()); - db.commit(); - } - - public void associateQualityGateToOrganization(QualityGateDto qualityGate, OrganizationDto organization) { - dbClient.qualityGateDao().associate(dbSession, Uuids.createFast(), organization, qualityGate); - db.commit(); - } - - @SafeVarargs - public final QualityGateDto createDefaultQualityGate(OrganizationDto organization, Consumer... dtoPopulators) { - QualityGateDto defaultQGate = insertQualityGate(organization, dtoPopulators); - setDefaultQualityGate(organization, defaultQGate); - return defaultQGate; - } - - public void setDefaultQualityGate(OrganizationDto organization, QualityGateDto qualityGate) { - dbClient.organizationDao().update(dbSession, organization.setDefaultQualityGateUuid(qualityGate.getUuid())); - dbSession.commit(); - } - - @SafeVarargs - public final QualityGateConditionDto addCondition(QualityGateDto qualityGate, MetricDto metric, Consumer... dtoPopulators) { - QualityGateConditionDto condition = new QualityGateConditionDto().setQualityGateId(qualityGate.getId()) - .setMetricId(metric.getId()) - .setOperator("GT") - .setErrorThreshold(randomNumeric(10)); - Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(condition)); - dbClient.gateConditionDao().insert(condition, dbSession); - db.commit(); - return condition; - } - - public Optional selectQGateUuidByComponentUuid(String componentUuid) { - return dbClient.projectQgateAssociationDao().selectQGateUuidByComponentUuid(dbSession, componentUuid); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QualityProfileDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QualityProfileDbTester.java deleted file mode 100644 index d2ba860709e..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QualityProfileDbTester.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import java.util.Arrays; -import java.util.Optional; -import java.util.function.Consumer; -import org.sonar.api.rule.Severity; -import org.sonar.core.util.Uuids; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.organization.OrganizationDto; -import org.sonar.db.rule.RuleDefinitionDto; -import org.sonar.db.user.GroupDto; -import org.sonar.db.user.UserDto; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.apache.commons.lang.math.RandomUtils.nextInt; -import static org.apache.commons.lang.math.RandomUtils.nextLong; -import static org.sonar.db.qualityprofile.ActiveRuleDto.createFor; - -public class QualityProfileDbTester { - private final DbClient dbClient; - private final DbSession dbSession; - - public QualityProfileDbTester(DbTester dbTester) { - this.dbClient = dbTester.getDbClient(); - this.dbSession = dbTester.getSession(); - } - - public Optional selectByUuid(String uuid) { - return Optional.ofNullable(dbClient.qualityProfileDao().selectByUuid(dbSession, uuid)); - } - - /** - * Create a profile with random field values on the specified organization. - */ - public QProfileDto insert(OrganizationDto organization) { - return insert(organization, c -> { - }); - } - - /** - * Create a profile with random field values on the specified organization. - */ - public QProfileDto insert(OrganizationDto organization, Consumer consumer) { - QProfileDto profile = QualityProfileTesting.newQualityProfileDto() - .setOrganizationUuid(organization.getUuid()); - consumer.accept(profile); - - dbClient.qualityProfileDao().insert(dbSession, profile); - dbSession.commit(); - return profile; - } - - public QualityProfileDbTester insert(QProfileDto profile, QProfileDto... others) { - dbClient.qualityProfileDao().insert(dbSession, profile); - Arrays.stream(others).forEach(p -> dbClient.qualityProfileDao().insert(dbSession, p)); - dbSession.commit(); - return this; - } - - public QualityProfileDbTester associateWithProject(ComponentDto project, QProfileDto profile, QProfileDto... otherProfiles) { - dbClient.qualityProfileDao().insertProjectProfileAssociation(dbSession, project, profile); - for (QProfileDto p : otherProfiles) { - dbClient.qualityProfileDao().insertProjectProfileAssociation(dbSession, project, p); - } - dbSession.commit(); - return this; - } - - public ActiveRuleDto activateRule(QProfileDto profile, RuleDefinitionDto rule) { - return activateRule(profile, rule, ar -> { - }); - } - - public ActiveRuleDto activateRule(QProfileDto profile, RuleDefinitionDto rule, Consumer consumer) { - ActiveRuleDto activeRule = createFor(profile, rule) - .setSeverity(Severity.ALL.get(nextInt(Severity.ALL.size()))) - .setCreatedAt(nextLong()) - .setUpdatedAt(nextLong()); - consumer.accept(activeRule); - dbClient.activeRuleDao().insert(dbSession, activeRule); - dbSession.commit(); - return activeRule; - } - - public QualityProfileDbTester setAsDefault(QProfileDto profile, QProfileDto... others) { - dbClient.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(profile)); - for (QProfileDto other : others) { - dbClient.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(other)); - } - dbSession.commit(); - return this; - } - - public void addUserPermission(QProfileDto profile, UserDto user){ - checkArgument(!profile.isBuiltIn(), "Built-In profile cannot be used"); - dbClient.qProfileEditUsersDao().insert(dbSession, new QProfileEditUsersDto() - .setUuid(Uuids.createFast()) - .setUserId(user.getId()) - .setQProfileUuid(profile.getKee()) - ); - dbSession.commit(); - } - - public void addGroupPermission(QProfileDto profile, GroupDto group){ - checkArgument(!profile.isBuiltIn(), "Built-In profile cannot be used"); - dbClient.qProfileEditGroupsDao().insert(dbSession, new QProfileEditGroupsDto() - .setUuid(Uuids.createFast()) - .setGroupId(group.getId()) - .setQProfileUuid(profile.getKee()) - ); - dbSession.commit(); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QualityProfileTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QualityProfileTesting.java deleted file mode 100644 index 0ef23d5ad99..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QualityProfileTesting.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.qualityprofile; - -import java.util.function.Consumer; -import org.sonar.core.util.Uuids; - -import static java.util.Arrays.stream; -import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang.math.RandomUtils.nextLong; - -public class QualityProfileTesting { - - private QualityProfileTesting() { - // prevent instantiation - } - - /** - * Create an instance of {@link QProfileDto} with random field values. - */ - public static QProfileDto newQualityProfileDto() { - String uuid = Uuids.createFast(); - return new QProfileDto() - .setKee(uuid) - .setRulesProfileUuid(Uuids.createFast()) - .setOrganizationUuid(randomAlphanumeric(40)) - .setName(uuid) - .setLanguage(randomAlphanumeric(20)) - .setLastUsed(nextLong()); - } - - /** - * Create an instance of {@link QProfileChangeDto} with random field values, - * except changeType which is always {@code "ACTIVATED"}. - */ - public static QProfileChangeDto newQProfileChangeDto() { - return new QProfileChangeDto() - .setUuid(randomAlphanumeric(40)) - .setRulesProfileUuid(randomAlphanumeric(40)) - .setCreatedAt(nextLong()) - .setChangeType("ACTIVATED") - .setUserUuid("userUuid_" + randomAlphanumeric(10)); - } - - /** - * Create an instance of {@link RulesProfileDto} with most of random field values. - */ - public static RulesProfileDto newRuleProfileDto(Consumer... populators) { - RulesProfileDto dto = new RulesProfileDto() - .setKee("uuid" + randomAlphabetic(10)) - .setName("name" + randomAlphabetic(10)) - .setLanguage("lang" + randomAlphabetic(5)) - .setIsBuiltIn(false); - stream(populators).forEach(p -> p.accept(dto)); - return dto; - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDbTester.java deleted file mode 100644 index 5e1c497f11f..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDbTester.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.rule; - -import java.util.function.Consumer; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.server.rule.RuleParamType; -import org.sonar.db.DbTester; -import org.sonar.db.organization.OrganizationDto; -import org.sonar.db.user.UserDto; - -import static java.util.Arrays.asList; -import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; -import static org.sonar.db.rule.RuleTesting.newDeprecatedRuleKey; -import static org.sonar.db.rule.RuleTesting.newRule; -import static org.sonar.db.rule.RuleTesting.newRuleDto; - -public class RuleDbTester { - - private final DbTester db; - - public RuleDbTester(DbTester db) { - this.db = db; - } - - public RuleDefinitionDto insert() { - return insert(newRule()); - } - - public RuleDefinitionDto insert(RuleKey key) { - return insert(newRule(key)); - } - - @SafeVarargs - public final RuleDefinitionDto insert(Consumer... populaters) { - RuleDefinitionDto rule = newRule(); - asList(populaters).forEach(populater -> populater.accept(rule)); - return insert(rule); - } - - public RuleDefinitionDto insert(RuleKey key, Consumer populater) { - RuleDefinitionDto rule = newRule(key); - populater.accept(rule); - return insert(rule); - } - - public RuleDefinitionDto insert(RuleDefinitionDto rule) { - db.getDbClient().ruleDao().insert(db.getSession(), rule); - db.commit(); - return rule; - } - - public RuleDefinitionDto update(RuleDefinitionDto rule) { - db.getDbClient().ruleDao().update(db.getSession(), rule); - db.commit(); - return rule; - } - - @SafeVarargs - public final RuleMetadataDto insertOrUpdateMetadata(RuleDefinitionDto rule, OrganizationDto organization, Consumer... populaters) { - RuleMetadataDto dto = RuleTesting.newRuleMetadata(rule, organization); - asList(populaters).forEach(populater -> populater.accept(dto)); - return insertOrUpdateMetadata(dto); - } - - @SafeVarargs - public final RuleMetadataDto insertOrUpdateMetadata(RuleDefinitionDto rule, UserDto noteUser, OrganizationDto organization, Consumer... populaters) { - RuleMetadataDto dto = RuleTesting.newRuleMetadata(rule, noteUser, organization); - asList(populaters).forEach(populater -> populater.accept(dto)); - return insertOrUpdateMetadata(dto); - } - - public RuleMetadataDto insertOrUpdateMetadata(RuleMetadataDto metadata) { - db.getDbClient().ruleDao().insertOrUpdate(db.getSession(), metadata); - db.commit(); - return metadata; - } - - public RuleParamDto insertRuleParam(RuleDefinitionDto rule) { - return insertRuleParam(rule, p -> { - }); - } - - @SafeVarargs - public final RuleParamDto insertRuleParam(RuleDefinitionDto rule, Consumer... populaters) { - RuleParamDto param = RuleTesting.newRuleParam(rule); - asList(populaters).forEach(populater -> populater.accept(param)); - db.getDbClient().ruleDao().insertRuleParam(db.getSession(), rule, param); - db.commit(); - return param; - } - - public RuleDto insertRule(RuleDto ruleDto) { - insert(ruleDto.getDefinition()); - RuleMetadataDto metadata = ruleDto.getMetadata(); - if (metadata.getOrganizationUuid() != null) { - db.getDbClient().ruleDao().insertOrUpdate(db.getSession(), metadata.setRuleId(ruleDto.getId())); - db.commit(); - } - return ruleDto; - } - - /** - * Create and persist a rule with random values. - */ - public RuleDto insertRule() { - return insertRule(rule -> { - }); - } - - @SafeVarargs - public final RuleDto insertRule(OrganizationDto organization, Consumer... populaters) { - RuleDto ruleDto = newRuleDto(organization); - asList(populaters).forEach(populater -> populater.accept(ruleDto)); - return insertRule(ruleDto); - } - - public RuleDto insertRule(Consumer populateRuleDto) { - RuleDto ruleDto = newRuleDto(); - populateRuleDto.accept(ruleDto); - return insertRule(ruleDto); - } - - @SafeVarargs - public final DeprecatedRuleKeyDto insertDeprecatedKey(Consumer... deprecatedRuleKeyDtoConsumers) { - DeprecatedRuleKeyDto deprecatedRuleKeyDto = newDeprecatedRuleKey(); - asList(deprecatedRuleKeyDtoConsumers).forEach(c -> c.accept(deprecatedRuleKeyDto)); - db.getDbClient().ruleDao().insert(db.getSession(), deprecatedRuleKeyDto); - return deprecatedRuleKeyDto; - } - - public RuleParamDto insertRuleParam(RuleDto rule) { - RuleParamDto param = new RuleParamDto(); - param.setRuleId(rule.getId()); - param.setName(randomAlphabetic(10)); - param.setType(RuleParamType.STRING.type()); - db.getDbClient().ruleDao().insertRuleParam(db.getSession(), rule.getDefinition(), param); - db.commit(); - return param; - } - - public RuleDto insertRule(RuleDefinitionDto ruleDefinition, RuleMetadataDto ruleMetadata) { - db.getDbClient().ruleDao().insertOrUpdate(db.getSession(), ruleMetadata.setRuleId(ruleDefinition.getId())); - db.commit(); - return new RuleDto(ruleDefinition, ruleMetadata); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleTesting.java deleted file mode 100644 index 9df18d86726..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleTesting.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.rule; - -import com.google.common.collect.ImmutableSet; -import java.util.Date; -import java.util.Set; -import java.util.function.Consumer; -import javax.annotation.Nullable; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.rule.Severity; -import org.sonar.api.rules.RuleType; -import org.sonar.api.server.rule.RuleParamType; -import org.sonar.core.util.UuidFactory; -import org.sonar.core.util.UuidFactoryFast; -import org.sonar.db.organization.OrganizationDto; -import org.sonar.db.rule.RuleDto.Format; -import org.sonar.db.rule.RuleDto.Scope; -import org.sonar.db.user.UserDto; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Sets.newHashSet; -import static java.util.Objects.requireNonNull; -import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang.math.RandomUtils.nextInt; -import static org.sonar.api.rule.RuleKey.EXTERNAL_RULE_REPO_PREFIX; - -/** - * Utility class for tests involving rules - */ -public class RuleTesting { - - public static final RuleKey EXTERNAL_XOO = RuleKey.of(EXTERNAL_RULE_REPO_PREFIX + "xoo", "x1"); - public static final RuleKey XOO_X1 = RuleKey.of("xoo", "x1"); - public static final RuleKey XOO_X2 = RuleKey.of("xoo", "x2"); - public static final RuleKey XOO_X3 = RuleKey.of("xoo", "x3"); - - private static final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); - - private RuleTesting() { - // only static helpers - } - - public static RuleDefinitionDto newRule() { - return newRule(randomRuleKey()); - } - - public static RuleDefinitionDto newRule(RuleKey key) { - return new RuleDefinitionDto() - .setRepositoryKey(key.repository()) - .setRuleKey(key.rule()) - .setId(nextInt(100_000)) - .setName("name_" + randomAlphanumeric(5)) - .setDescription("description_" + randomAlphanumeric(5)) - .setDescriptionFormat(Format.HTML) - .setType(RuleType.values()[nextInt(RuleType.values().length)]) - .setStatus(RuleStatus.READY) - .setConfigKey("configKey_" + randomAlphanumeric(5)) - .setSeverity(Severity.ALL.get(nextInt(Severity.ALL.size()))) - .setIsTemplate(false) - .setIsExternal(false) - .setIsAdHoc(false) - .setSystemTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5))) - .setLanguage("lang_" + randomAlphanumeric(3)) - .setGapDescription("gapDescription_" + randomAlphanumeric(5)) - .setDefRemediationBaseEffort(nextInt(10) + "h") - .setDefRemediationGapMultiplier(nextInt(10) + "h") - .setDefRemediationFunction("LINEAR_OFFSET") - .setCreatedAt(System.currentTimeMillis()) - .setUpdatedAt(System.currentTimeMillis()) - .setScope(Scope.MAIN); - } - - public static RuleMetadataDto newRuleMetadata() { - return new RuleMetadataDto() - .setRuleId(nextInt(100_000)) - .setOrganizationUuid("org_" + randomAlphanumeric(5)) - .setRemediationBaseEffort(nextInt(10) + "h") - .setRemediationGapMultiplier(nextInt(10) + "h") - .setRemediationFunction("LINEAR_OFFSET") - .setTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5))) - .setNoteData("noteData_" + randomAlphanumeric(5)) - .setNoteUserUuid("noteUserUuid_" + randomAlphanumeric(5)) - .setNoteCreatedAt(System.currentTimeMillis() - 200) - .setNoteUpdatedAt(System.currentTimeMillis() - 150) - .setAdHocName("adHocName_" + randomAlphanumeric(5)) - .setAdHocDescription("adHocDescription_" + randomAlphanumeric(5)) - .setAdHocSeverity(Severity.ALL.get(nextInt(Severity.ALL.size()))) - .setAdHocType(RuleType.values()[nextInt(RuleType.values().length - 1)]) - .setCreatedAt(System.currentTimeMillis() - 100) - .setUpdatedAt(System.currentTimeMillis() - 50); - } - - public static RuleMetadataDto newRuleMetadata(RuleDefinitionDto rule, OrganizationDto organization) { - return newRuleMetadata() - .setRuleId(rule.getId()) - .setOrganizationUuid(organization.getUuid()); - } - - public static RuleMetadataDto newRuleMetadata(RuleDefinitionDto rule, UserDto noteUser, OrganizationDto organization) { - return newRuleMetadata(rule, organization) - .setNoteUserUuid(noteUser.getUuid()); - } - - public static RuleParamDto newRuleParam(RuleDefinitionDto rule) { - return new RuleParamDto() - .setRuleId(rule.getId()) - .setName("name_" + randomAlphabetic(5)) - .setDefaultValue("default_" + randomAlphabetic(5)) - .setDescription("description_" + randomAlphabetic(5)) - .setType(RuleParamType.STRING.type()); - } - - public static DeprecatedRuleKeyDto newDeprecatedRuleKey() { - return new DeprecatedRuleKeyDto() - .setUuid(uuidFactory.create()) - .setOldRepositoryKey(randomAlphanumeric(50)) - .setOldRuleKey(randomAlphanumeric(50)) - .setRuleId(nextInt(100_000)) - .setCreatedAt(System.currentTimeMillis()); - } - - /** - * @deprecated use newRule(...) - */ - @Deprecated - public static RuleDto newXooX1() { - return newDto(XOO_X1).setLanguage("xoo"); - } - - /** - * @deprecated use newRule(...) - */ - @Deprecated - public static RuleDto newXooX1(OrganizationDto organization) { - return newDto(XOO_X1, requireNonNull(organization, "organization can't be null")).setLanguage("xoo"); - } - - /** - * @deprecated use newRule(...) - */ - @Deprecated - public static RuleDto newXooX2() { - return newDto(XOO_X2).setLanguage("xoo"); - } - - /** - * @deprecated use newRule(...) - */ - @Deprecated - public static RuleDto newXooX2(OrganizationDto organization) { - return newDto(XOO_X2, requireNonNull(organization, "organization can't be null")).setLanguage("xoo"); - } - - /** - * @deprecated use newRule(...) - */ - @Deprecated - public static RuleDto newXooX3() { - return newDto(XOO_X3).setLanguage("xoo"); - } - - /** - * @deprecated use newRule(...) - */ - @Deprecated - public static RuleDto newXooX3(OrganizationDto organization) { - return newDto(XOO_X3, requireNonNull(organization, "organization can't be null")).setLanguage("xoo"); - } - - /** - * @deprecated use newRule(...) - */ - @Deprecated - public static RuleDto newDto(RuleKey ruleKey) { - return newDto(ruleKey, null); - } - - /** - * @deprecated use newRule(...) - */ - @Deprecated - public static RuleDto newDto(RuleKey ruleKey, @Nullable OrganizationDto organization) { - RuleDto res = new RuleDto() - .setRuleKey(ruleKey.rule()) - .setRepositoryKey(ruleKey.repository()) - .setName("Rule " + ruleKey.rule()) - .setDescription("Description " + ruleKey.rule()) - .setDescriptionFormat(Format.HTML) - .setStatus(RuleStatus.READY) - .setConfigKey("InternalKey" + ruleKey.rule()) - .setSeverity(Severity.INFO) - .setIsTemplate(false) - .setSystemTags(ImmutableSet.of("systag1", "systag2")) - .setLanguage("js") - .setDefRemediationFunction("LINEAR_OFFSET") - .setDefRemediationGapMultiplier("5d") - .setDefRemediationBaseEffort("10h") - .setGapDescription(ruleKey.repository() + "." + ruleKey.rule() + ".effortToFix") - .setType(RuleType.CODE_SMELL) - .setCreatedAt(new Date().getTime()) - .setUpdatedAt(new Date().getTime()) - .setScope(Scope.MAIN); - if (organization != null) { - res - .setOrganizationUuid(organization.getUuid()) - .setTags(ImmutableSet.of("tag1", "tag2")) - .setRemediationFunction("LINEAR") - .setRemediationGapMultiplier("1h"); - } - return res; - } - - /** - * @deprecated use newRule(...) - */ - @Deprecated - public static RuleDto newRuleDto() { - return newDto(RuleKey.of(randomAlphanumeric(30), randomAlphanumeric(30))); - } - - /** - * @deprecated use newRule(...) - */ - @Deprecated - public static RuleDto newRuleDto(OrganizationDto organization) { - return newDto(RuleKey.of(randomAlphanumeric(30), randomAlphanumeric(30)), organization); - } - - public static RuleDto newTemplateRule(RuleKey ruleKey) { - return newDto(ruleKey) - .setIsTemplate(true); - } - - public static RuleDto newTemplateRule(RuleKey ruleKey, OrganizationDto organization) { - return newDto(ruleKey, organization) - .setIsTemplate(true); - } - - /** - * @deprecated use {@link #newCustomRule(RuleDefinitionDto)} - */ - @Deprecated - public static RuleDto newCustomRule(RuleDto templateRule) { - checkNotNull(templateRule.getId(), "The template rule need to be persisted before creating this custom rule."); - return newDto(RuleKey.of(templateRule.getRepositoryKey(), templateRule.getRuleKey() + "_" + System.currentTimeMillis())) - .setLanguage(templateRule.getLanguage()) - .setTemplateId(templateRule.getId()) - .setType(templateRule.getType()); - } - - public static RuleDefinitionDto newCustomRule(RuleDefinitionDto templateRule) { - checkNotNull(templateRule.getId(), "The template rule need to be persisted before creating this custom rule."); - return newRule(RuleKey.of(templateRule.getRepositoryKey(), templateRule.getRuleKey() + "_" + System.currentTimeMillis())) - .setLanguage(templateRule.getLanguage()) - .setTemplateId(templateRule.getId()) - .setType(templateRule.getType()); - } - - public static RuleKey randomRuleKey() { - return RuleKey.of("repo_" + randomAlphanumeric(3), "rule_" + randomAlphanumeric(3)); - } - - public static RuleKey randomRuleKeyOfMaximumLength() { - return RuleKey.of(randomAlphabetic(255), randomAlphabetic(200)); - } - - public static Consumer setRepositoryKey(String repositoryKey) { - return rule -> rule.setRepositoryKey(repositoryKey); - } - - public static Consumer setCreatedAt(long createdAt) { - return rule -> rule.setCreatedAt(createdAt); - } - - public static Consumer setUpdatedAt(long updatedtAt) { - return rule -> rule.setUpdatedAt(updatedtAt); - } - - public static Consumer setRuleKey(String ruleKey) { - return rule -> rule.setRuleKey(ruleKey); - } - - public static Consumer setName(String name) { - return rule -> rule.setName(name); - } - - public static Consumer setLanguage(String language) { - return rule -> rule.setLanguage(language); - } - - public static Consumer setSeverity(String severity) { - return rule -> rule.setSeverity(severity); - } - - public static Consumer setStatus(RuleStatus status) { - return rule -> rule.setStatus(status); - } - - public static Consumer setType(RuleType type) { - return rule -> rule.setType(type); - } - - public static Consumer setIsExternal(boolean isExternal) { - return rule -> rule.setIsExternal(isExternal); - } - - public static Consumer setSecurityStandards(Set securityStandards) { - return rule -> rule.setSecurityStandards(securityStandards); - } - - public static Consumer setIsTemplate(boolean isTemplate) { - return rule -> rule.setIsTemplate(isTemplate); - } - - public static Consumer setTemplateId(@Nullable Integer templateId) { - return rule -> rule.setTemplateId(templateId); - } - - public static Consumer setSystemTags(String... tags) { - return rule -> rule.setSystemTags(copyOf(tags)); - } - - public static Consumer setOrganization(OrganizationDto organization) { - return rule -> rule.setOrganizationUuid(organization.getUuid()); - } - - public static Consumer setTags(String... tags) { - return rule -> rule.setTags(copyOf(tags)); - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/source/FileSourceTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/source/FileSourceTester.java deleted file mode 100644 index e450b0d8c63..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/source/FileSourceTester.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.source; - -import java.util.Arrays; -import java.util.Date; -import java.util.Random; -import java.util.function.Consumer; -import java.util.stream.IntStream; -import org.apache.commons.lang.math.RandomUtils; -import org.sonar.core.util.stream.MoreCollectors; -import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.protobuf.DbFileSources; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; - -public class FileSourceTester { - - private final DbTester db; - - public FileSourceTester(DbTester db) { - this.db = db; - } - - @SafeVarargs - public final FileSourceDto insertFileSource(ComponentDto file, Consumer... dtoPopulators) { - FileSourceDto dto = new FileSourceDto() - .setProjectUuid(file.projectUuid()) - .setFileUuid(file.uuid()) - .setSrcHash(randomAlphanumeric(50)) - .setDataHash(randomAlphanumeric(50)) - .setLineHashes(IntStream.range(0, new Random().nextInt(21)).mapToObj(String::valueOf).collect(MoreCollectors.toList())) - .setRevision(randomAlphanumeric(100)) - .setSourceData(newRandomData(3).build()) - .setCreatedAt(new Date().getTime()) - .setUpdatedAt(new Date().getTime()); - Arrays.stream(dtoPopulators).forEach(c -> c.accept(dto)); - db.getDbClient().fileSourceDao().insert(db.getSession(), dto); - db.commit(); - dto.setId(db.getDbClient().fileSourceDao().selectByFileUuid(db.getSession(), dto.getFileUuid()).getId()); - return dto; - } - - @SafeVarargs - public final FileSourceDto insertFileSource(ComponentDto file, int numLines, Consumer... dtoPopulators) { - FileSourceDto dto = new FileSourceDto() - .setProjectUuid(file.projectUuid()) - .setFileUuid(file.uuid()) - .setSrcHash(randomAlphanumeric(50)) - .setDataHash(randomAlphanumeric(50)) - .setLineHashes(IntStream.range(0, numLines).mapToObj(String::valueOf).collect(MoreCollectors.toList())) - .setRevision(randomAlphanumeric(100)) - .setSourceData(newRandomData(numLines).build()) - .setCreatedAt(new Date().getTime()) - .setUpdatedAt(new Date().getTime()); - Arrays.stream(dtoPopulators).forEach(c -> c.accept(dto)); - db.getDbClient().fileSourceDao().insert(db.getSession(), dto); - db.commit(); - return dto; - } - - private static DbFileSources.Data.Builder newRandomData(int numberOfLines) { - DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder(); - for (int i = 1; i <= numberOfLines; i++) { - dataBuilder.addLinesBuilder() - .setLine(i) - .setScmRevision(randomAlphanumeric(15)) - .setScmAuthor(randomAlphanumeric(10)) - .setScmDate(RandomUtils.nextLong()) - .setSource(randomAlphanumeric(20)) - .setLineHits(RandomUtils.nextInt(4)) - .setConditions(RandomUtils.nextInt(4)) - .setCoveredConditions(RandomUtils.nextInt(4)) - .setHighlighting(randomAlphanumeric(40)) - .setSymbols(randomAlphanumeric(30)) - .addAllDuplication(Arrays.asList(RandomUtils.nextInt(200), RandomUtils.nextInt(200))) - .build(); - } - return dataBuilder; - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/GroupTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/GroupTesting.java deleted file mode 100644 index cfb6379e188..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/GroupTesting.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.Date; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang.math.RandomUtils.nextInt; -import static org.apache.commons.lang.math.RandomUtils.nextLong; - -public class GroupTesting { - - private GroupTesting() { - // only statics - } - - public static GroupDto newGroupDto() { - GroupDto group = new GroupDto() - .setId(nextInt()) - .setOrganizationUuid(randomAlphanumeric(40)) - .setName(randomAlphanumeric(255)) - .setDescription(randomAlphanumeric(200)) - .setCreatedAt(new Date(nextLong())) - .setUpdatedAt(new Date(nextLong())); - return group; - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/RootFlagAssertions.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/RootFlagAssertions.java deleted file mode 100644 index 0b84443f834..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/RootFlagAssertions.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import java.util.Map; -import org.sonar.db.DbTester; - -import static org.assertj.core.api.Assertions.assertThat; - -public class RootFlagAssertions { - private final DbTester db; - - public RootFlagAssertions(DbTester db) { - this.db = db; - } - - public void verify(UserDto userDto, boolean root, long updatedAt) { - Map row = db.selectFirst("select is_root as \"isRoot\", updated_at as \"updatedAt\" from users where login = '" + userDto.getLogin() + "'"); - Object isRoot = row.get("isRoot"); - assertThat(isRoot) - .as("Root flag of user '%s' is same as when created", userDto.getLogin()) - .isEqualTo(isRoot instanceof Long ? toLong(root) : root); - assertThat(row.get("updatedAt")) - .as("UpdatedAt of user '%s' has not changed since created") - .isEqualTo(updatedAt); - } - - public void verify(UserDto userDto, boolean root) { - Map row = db.selectFirst("select is_root as \"isRoot\", updated_at as \"updatedAt\" from users where login = '" + userDto.getLogin() + "'"); - Object isRoot = row.get("isRoot"); - assertThat(isRoot) - .as("Root flag of user '%s' is '%s'", userDto.getLogin(), root) - .isEqualTo(isRoot instanceof Long ? toLong(root) : root); - assertThat(row.get("updatedAt")) - .as("UpdatedAt of user '%s' has changed since insertion", userDto.getLogin()) - .isNotEqualTo(userDto.getUpdatedAt()); - } - - private static Long toLong(boolean root) { - return root ? 1L : 0L; - } - - public void verify(String login, boolean root) { - assertThat(db.getDbClient().userDao().selectByLogin(db.getSession(), login).isRoot()) - .as("Root flag of user '%s' is '%s'", login, root) - .isEqualTo(root); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserDbTester.java deleted file mode 100644 index 138f9f85395..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserDbTester.java +++ /dev/null @@ -1,378 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import com.google.common.collect.ImmutableSet; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.function.Consumer; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.api.web.UserRole; -import org.sonar.core.util.stream.MoreCollectors; -import org.sonar.db.DbClient; -import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.organization.OrganizationDto; -import org.sonar.db.permission.GroupPermissionDto; -import org.sonar.db.permission.OrganizationPermission; -import org.sonar.db.permission.UserPermissionDto; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.lang.String.format; -import static java.util.Arrays.stream; -import static org.sonar.db.permission.OrganizationPermission.ADMINISTER; -import static org.sonar.db.user.GroupTesting.newGroupDto; -import static org.sonar.db.user.UserTesting.newDisabledUser; -import static org.sonar.db.user.UserTesting.newUserDto; -import static org.sonar.db.user.UserTesting.newUserSettingDto; -import static org.sonar.db.user.UserTokenTesting.newUserToken; - -public class UserDbTester { - private static final Set PUBLIC_PERMISSIONS = ImmutableSet.of(UserRole.USER, UserRole.CODEVIEWER); // FIXME to check with Simon - - private final DbTester db; - private final DbClient dbClient; - - public UserDbTester(DbTester db) { - this.db = db; - this.dbClient = db.getDbClient(); - } - - // USERS - - public UserDto insertUser() { - return insertUser(newUserDto()); - } - - public UserDto insertUser(String login) { - UserDto dto = newUserDto().setLogin(login).setActive(true); - return insertUser(dto); - } - - @SafeVarargs - public final UserDto insertUser(Consumer... populators) { - UserDto dto = newUserDto().setActive(true); - stream(populators).forEach(p -> p.accept(dto)); - return insertUser(dto); - } - - @SafeVarargs - public final UserDto insertDisabledUser(Consumer... populators) { - UserDto dto = newDisabledUser(); - stream(populators).forEach(p -> p.accept(dto)); - return insertUser(dto); - } - - public UserDto insertUser(UserDto userDto) { - UserDto updatedUser = dbClient.userDao().insert(db.getSession(), userDto); - db.commit(); - return updatedUser; - } - - public UserDto makeRoot(UserDto userDto) { - dbClient.userDao().setRoot(db.getSession(), userDto.getLogin(), true); - db.commit(); - return dbClient.userDao().selectByLogin(db.getSession(), userDto.getLogin()); - } - - public UserDto makeNotRoot(UserDto userDto) { - dbClient.userDao().setRoot(db.getSession(), userDto.getLogin(), false); - db.commit(); - return dbClient.userDao().selectByLogin(db.getSession(), userDto.getLogin()); - } - - public UserDto insertAdminByUserPermission(OrganizationDto org) { - UserDto user = insertUser(); - insertPermissionOnUser(org, user, ADMINISTER); - return user; - } - - public UserDto updateLastConnectionDate(UserDto user, long lastConnectionDate) { - db.getDbClient().userDao().update(db.getSession(), user.setLastConnectionDate(lastConnectionDate)); - db.getSession().commit(); - return user; - } - - public Optional selectUserByLogin(String login) { - return Optional.ofNullable(dbClient.userDao().selectByLogin(db.getSession(), login)); - } - - // USER SETTINGS - - @SafeVarargs - public final UserPropertyDto insertUserSetting(UserDto user, Consumer... populators) { - UserPropertyDto dto = newUserSettingDto(user); - stream(populators).forEach(p -> p.accept(dto)); - dbClient.userPropertiesDao().insertOrUpdate(db.getSession(), dto); - db.commit(); - return dto; - } - - // GROUPS - - public GroupDto insertGroup(OrganizationDto organization, String name) { - GroupDto group = newGroupDto().setName(name).setOrganizationUuid(organization.getUuid()); - return insertGroup(group); - } - - /** - * Create group in default organization - */ - public GroupDto insertGroup() { - GroupDto group = newGroupDto().setOrganizationUuid(db.getDefaultOrganization().getUuid()); - return insertGroup(group); - } - - /** - * Create group in specified organization - */ - public GroupDto insertGroup(OrganizationDto organizationDto) { - GroupDto group = newGroupDto().setOrganizationUuid(organizationDto.getUuid()); - return insertGroup(group); - } - - public GroupDto insertGroup(GroupDto dto) { - db.getDbClient().groupDao().insert(db.getSession(), dto); - db.commit(); - return dto; - } - - public GroupDto insertDefaultGroup(GroupDto dto) { - String organizationUuid = dto.getOrganizationUuid(); - db.getDbClient().organizationDao().getDefaultGroupId(db.getSession(), organizationUuid) - .ifPresent(groupId -> { - throw new IllegalArgumentException(format("Organization '%s' has already a default group", organizationUuid)); - }); - db.getDbClient().groupDao().insert(db.getSession(), dto); - db.getDbClient().organizationDao().setDefaultGroupId(db.getSession(), organizationUuid, dto); - db.commit(); - return dto; - } - - public GroupDto insertDefaultGroup(OrganizationDto organization, String name) { - return insertDefaultGroup(newGroupDto().setName(name).setOrganizationUuid(organization.getUuid())); - } - - public GroupDto insertDefaultGroup(OrganizationDto organization) { - return insertDefaultGroup(newGroupDto().setOrganizationUuid(organization.getUuid())); - } - - @CheckForNull - public GroupDto selectGroupById(int groupId) { - return db.getDbClient().groupDao().selectById(db.getSession(), groupId); - } - - public Optional selectGroup(OrganizationDto org, String name) { - return db.getDbClient().groupDao().selectByName(db.getSession(), org.getUuid(), name); - } - - public List selectGroups(OrganizationDto org) { - return db.getDbClient().groupDao().selectByOrganizationUuid(db.getSession(), org.getUuid()); - } - - // GROUP MEMBERSHIP - - public UserGroupDto insertMember(GroupDto group, UserDto user) { - UserGroupDto dto = new UserGroupDto().setGroupId(group.getId()).setUserId(user.getId()); - db.getDbClient().userGroupDao().insert(db.getSession(), dto); - db.commit(); - return dto; - } - - public void insertMembers(GroupDto group, UserDto... users) { - Arrays.stream(users).forEach(user -> { - UserGroupDto dto = new UserGroupDto().setGroupId(group.getId()).setUserId(user.getId()); - db.getDbClient().userGroupDao().insert(db.getSession(), dto); - }); - db.commit(); - } - - public List selectGroupIdsOfUser(UserDto user) { - return db.getDbClient().groupMembershipDao().selectGroupIdsByUserId(db.getSession(), user.getId()); - } - - // GROUP PERMISSIONS - - public GroupPermissionDto insertPermissionOnAnyone(OrganizationDto org, String permission) { - GroupPermissionDto dto = new GroupPermissionDto() - .setOrganizationUuid(org.getUuid()) - .setGroupId(null) - .setRole(permission); - db.getDbClient().groupPermissionDao().insert(db.getSession(), dto); - db.commit(); - return dto; - } - - public GroupPermissionDto insertPermissionOnAnyone(OrganizationDto org, OrganizationPermission permission) { - return insertPermissionOnAnyone(org, permission.getKey()); - } - - public GroupPermissionDto insertPermissionOnGroup(GroupDto group, String permission) { - GroupPermissionDto dto = new GroupPermissionDto() - .setOrganizationUuid(group.getOrganizationUuid()) - .setGroupId(group.getId()) - .setRole(permission); - db.getDbClient().groupPermissionDao().insert(db.getSession(), dto); - db.commit(); - return dto; - } - - public GroupPermissionDto insertPermissionOnGroup(GroupDto group, OrganizationPermission permission) { - return insertPermissionOnGroup(group, permission.getKey()); - } - - public void deletePermissionFromGroup(GroupDto group, String permission) { - db.getDbClient().groupPermissionDao().delete(db.getSession(), permission, group.getOrganizationUuid(), group.getId(), null); - db.commit(); - } - - public GroupPermissionDto insertProjectPermissionOnAnyone(String permission, ComponentDto project) { - checkArgument(!project.isPrivate(), "No permission to group AnyOne can be granted on a private project"); - checkArgument(!PUBLIC_PERMISSIONS.contains(permission), - "permission %s can't be granted on a public project", permission); - checkArgument(project.getMainBranchProjectUuid() == null, "Permissions can't be granted on branches"); - GroupPermissionDto dto = new GroupPermissionDto() - .setOrganizationUuid(project.getOrganizationUuid()) - .setGroupId(null) - .setRole(permission) - .setResourceId(project.getId()); - db.getDbClient().groupPermissionDao().insert(db.getSession(), dto); - db.commit(); - return dto; - } - - public void deleteProjectPermissionFromAnyone(ComponentDto project, String permission) { - db.getDbClient().groupPermissionDao().delete(db.getSession(), permission, project.getOrganizationUuid(), null, project.getId()); - db.commit(); - } - - public GroupPermissionDto insertProjectPermissionOnGroup(GroupDto group, String permission, ComponentDto project) { - checkArgument(group.getOrganizationUuid().equals(project.getOrganizationUuid()), "Different organizations"); - checkArgument(project.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission), - "%s can't be granted on a public project", permission); - checkArgument(project.getMainBranchProjectUuid() == null, "Permissions can't be granted on branches"); - GroupPermissionDto dto = new GroupPermissionDto() - .setOrganizationUuid(group.getOrganizationUuid()) - .setGroupId(group.getId()) - .setRole(permission) - .setResourceId(project.getId()); - db.getDbClient().groupPermissionDao().insert(db.getSession(), dto); - db.commit(); - return dto; - } - - public List selectGroupPermissions(GroupDto group, @Nullable ComponentDto project) { - if (project == null) { - return db.getDbClient().groupPermissionDao().selectGlobalPermissionsOfGroup(db.getSession(), - group.getOrganizationUuid(), group.getId()); - } - return db.getDbClient().groupPermissionDao().selectProjectPermissionsOfGroup(db.getSession(), - group.getOrganizationUuid(), group.getId(), project.getId()); - } - - public List selectAnyonePermissions(OrganizationDto org, @Nullable ComponentDto project) { - if (project == null) { - return db.getDbClient().groupPermissionDao().selectGlobalPermissionsOfGroup(db.getSession(), - org.getUuid(), null); - } - checkArgument(org.getUuid().equals(project.getOrganizationUuid()), "Different organizations"); - return db.getDbClient().groupPermissionDao().selectProjectPermissionsOfGroup(db.getSession(), org.getUuid(), null, project.getId()); - } - - // USER PERMISSIONS - - /** - * Grant permission on default organization - */ - public UserPermissionDto insertPermissionOnUser(UserDto user, OrganizationPermission permission) { - return insertPermissionOnUser(db.getDefaultOrganization(), user, permission); - } - - /** - * Grant global permission - * @deprecated use {@link #insertPermissionOnUser(OrganizationDto, UserDto, OrganizationPermission)} - */ - @Deprecated - public UserPermissionDto insertPermissionOnUser(OrganizationDto org, UserDto user, String permission) { - UserPermissionDto dto = new UserPermissionDto(org.getUuid(), permission, user.getId(), null); - db.getDbClient().userPermissionDao().insert(db.getSession(), dto); - db.commit(); - return dto; - } - - /** - * Grant organization permission to user - */ - public UserPermissionDto insertPermissionOnUser(OrganizationDto org, UserDto user, OrganizationPermission permission) { - return insertPermissionOnUser(org, user, permission.getKey()); - } - - public void deletePermissionFromUser(OrganizationDto org, UserDto user, OrganizationPermission permission) { - db.getDbClient().userPermissionDao().deleteGlobalPermission(db.getSession(), user.getId(), permission.getKey(), org.getUuid()); - db.commit(); - } - - public void deletePermissionFromUser(ComponentDto project, UserDto user, String permission) { - db.getDbClient().userPermissionDao().deleteProjectPermission(db.getSession(), user.getId(), permission, project.getId()); - db.commit(); - } - - /** - * Grant permission on given project - */ - public UserPermissionDto insertProjectPermissionOnUser(UserDto user, String permission, ComponentDto project) { - checkArgument(project.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission), - "%s can't be granted on a public project", permission); - checkArgument(project.getMainBranchProjectUuid() == null, "Permissions can't be granted on branches"); - UserPermissionDto dto = new UserPermissionDto(project.getOrganizationUuid(), permission, user.getId(), project.getId()); - db.getDbClient().userPermissionDao().insert(db.getSession(), dto); - db.commit(); - return dto; - } - - public List selectPermissionsOfUser(UserDto user, OrganizationDto organization) { - return toListOfOrganizationPermissions(db.getDbClient().userPermissionDao() - .selectGlobalPermissionsOfUser(db.getSession(), user.getId(), organization.getUuid())); - } - - public List selectProjectPermissionsOfUser(UserDto user, ComponentDto project) { - return db.getDbClient().userPermissionDao().selectProjectPermissionsOfUser(db.getSession(), user.getId(), project.getId()); - } - - private static List toListOfOrganizationPermissions(List keys) { - return keys - .stream() - .map(OrganizationPermission::fromKey) - .collect(MoreCollectors.toList()); - } - - @SafeVarargs - public final UserTokenDto insertToken(UserDto user, Consumer... populators) { - UserTokenDto dto = newUserToken().setUserUuid(user.getUuid()); - stream(populators).forEach(p -> p.accept(dto)); - db.getDbClient().userTokenDao().insert(db.getSession(), dto); - db.commit(); - return dto; - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTesting.java deleted file mode 100644 index 65e76738293..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTesting.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import javax.annotation.Nullable; -import org.sonar.core.util.Uuids; - -import static java.util.Collections.singletonList; -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang.math.RandomUtils.nextBoolean; -import static org.apache.commons.lang.math.RandomUtils.nextInt; -import static org.apache.commons.lang.math.RandomUtils.nextLong; - -public class UserTesting { - - public static UserDto newUserDto() { - return new UserDto() - .setId(nextInt()) - .setUuid(randomAlphanumeric(40)) - .setActive(true) - .setLocal(nextBoolean()) - .setLogin(randomAlphanumeric(30)) - .setName(randomAlphanumeric(30)) - .setEmail(randomAlphanumeric(30)) - .setOnboarded(nextBoolean()) - .setScmAccounts(singletonList(randomAlphanumeric(40))) - .setExternalId(randomAlphanumeric(40)) - .setExternalLogin(randomAlphanumeric(40)) - .setExternalIdentityProvider(randomAlphanumeric(40)) - .setSalt(randomAlphanumeric(40)) - .setCryptedPassword(randomAlphanumeric(40)) - .setCreatedAt(nextLong()) - .setUpdatedAt(nextLong()); - } - - public static UserDto newUserDto(String login, String name, @Nullable String email) { - return newUserDto() - .setName(name) - .setEmail(email) - .setLogin(login); - } - - public static UserDto newLocalUser(String login, String name, @Nullable String email) { - return newUserDto() - .setLocal(true) - .setName(name) - .setEmail(email) - .setLogin(login) - .setExternalId(login) - .setExternalLogin(login) - .setExternalIdentityProvider("sonarqube"); - } - - public static UserDto newExternalUser(String login, String name, @Nullable String email) { - return newUserDto() - .setLocal(false) - .setName(name) - .setEmail(email) - .setLogin(login) - .setExternalId(randomAlphanumeric(40)) - .setExternalLogin(randomAlphanumeric(40)) - .setExternalIdentityProvider(randomAlphanumeric(40)); - } - - public static UserDto newDisabledUser() { - return newUserDto() - .setActive(false) - // All these fields are reset when disabling a user - .setScmAccounts((String) null) - .setEmail(null) - .setCryptedPassword(null) - .setSalt(null); - } - - public static UserPropertyDto newUserSettingDto(UserDto user) { - return new UserPropertyDto() - .setUuid(Uuids.createFast()) - .setUserUuid(user.getUuid()) - .setKey(randomAlphanumeric(20)) - .setValue(randomAlphanumeric(100)); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenTesting.java deleted file mode 100644 index 3d83071824f..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenTesting.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.user; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang.math.RandomUtils.nextLong; - -public class UserTokenTesting { - public static UserTokenDto newUserToken() { - return new UserTokenDto() - .setUserUuid("userUuid_" + randomAlphanumeric(40)) - .setName("name_" + randomAlphanumeric(20)) - .setTokenHash("hash_" + randomAlphanumeric(30)) - .setCreatedAt(nextLong()); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDbTester.java deleted file mode 100644 index 24b823aa981..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDbTester.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.webhook; - -import java.util.Optional; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.organization.OrganizationDto; - -import static org.sonar.db.webhook.WebhookTesting.newWebhook; - -public class WebhookDbTester { - - private final DbTester dbTester; - - public WebhookDbTester(DbTester dbTester) { - this.dbTester = dbTester; - } - - public WebhookDto insertWebhook(OrganizationDto organizationDto) { - return insert(newWebhook(organizationDto)); - } - - public WebhookDto insertWebhook(ComponentDto project) { - return insert(newWebhook(project)); - } - - public WebhookDto insert(WebhookDto dto) { - DbSession dbSession = dbTester.getSession(); - dbTester.getDbClient().webhookDao().insert(dbSession, dto); - dbSession.commit(); - return dto; - } - - public Optional selectWebhook(String uuid) { - DbSession dbSession = dbTester.getSession(); - return dbTester.getDbClient().webhookDao().selectByUuid(dbSession, uuid); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDeliveryDbTester.java b/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDeliveryDbTester.java deleted file mode 100644 index 2bd8a385975..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDeliveryDbTester.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.webhook; - -import java.util.Objects; -import java.util.function.Consumer; -import org.sonar.db.DbTester; - -import static java.util.Arrays.stream; -import static org.sonar.db.webhook.WebhookDeliveryTesting.newDto; - -public class WebhookDeliveryDbTester { - - private final DbTester dbTester; - - public WebhookDeliveryDbTester(DbTester dbTester) { - this.dbTester = dbTester; - } - - public WebhookDeliveryLiteDto insert(WebhookDeliveryDto dto) { - dbTester.getDbClient().webhookDeliveryDao().insert(dbTester.getSession(), dto); - dbTester.getSession().commit(); - return dto; - } - - @SafeVarargs - public final WebhookDeliveryLiteDto insert(Consumer... dtoPopulators) { - WebhookDeliveryDto dto = newDto(); - stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(dto)); - dbTester.getDbClient().webhookDeliveryDao().insert(dbTester.getSession(), dto); - dbTester.getSession().commit(); - return dto; - } - - @SafeVarargs - public final WebhookDeliveryLiteDto insert(WebhookDto webhook, Consumer... dtoPopulators) { - WebhookDeliveryDto dto = newDto(); - stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(dto)); - String projectUuid = webhook.getProjectUuid(); - dto.setComponentUuid(Objects.requireNonNull(projectUuid, "Project uuid of webhook cannot be null")); - dto.setWebhookUuid(webhook.getUuid()); - dbTester.getDbClient().webhookDeliveryDao().insert(dbTester.getSession(), dto); - dbTester.getSession().commit(); - return dto; - } - -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDeliveryTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDeliveryTesting.java deleted file mode 100644 index edefc760292..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDeliveryTesting.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.webhook; - -import java.util.List; -import java.util.stream.Collectors; -import org.sonar.core.util.Uuids; -import org.sonar.db.DbSession; -import org.sonar.db.DbTester; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang.math.RandomUtils.nextBoolean; -import static org.apache.commons.lang.math.RandomUtils.nextInt; -import static org.apache.commons.lang.math.RandomUtils.nextLong; - -public class WebhookDeliveryTesting { - - private WebhookDeliveryTesting() { - // only statics - } - - /** - * Build a {@link WebhookDeliveryDto} with all mandatory fields. - * Optional fields are kept null. - */ - public static WebhookDeliveryDto newDto(String uuid, String webhookUuid, String componentUuid, String ceTaskUuid) { - return newDto() - .setUuid(uuid) - .setWebhookUuid(webhookUuid) - .setComponentUuid(componentUuid) - .setCeTaskUuid(ceTaskUuid); - } - - public static WebhookDeliveryDto newDto() { - return new WebhookDeliveryDto() - .setUuid(Uuids.createFast()) - .setWebhookUuid(randomAlphanumeric(40)) - .setComponentUuid(randomAlphanumeric(40)) - .setCeTaskUuid(randomAlphanumeric(40)) - .setAnalysisUuid(randomAlphanumeric(40)) - .setName(randomAlphanumeric(10)) - .setUrl(randomAlphanumeric(10)) - .setDurationMs(nextInt()) - .setHttpStatus(nextInt()) - .setSuccess(nextBoolean()) - .setPayload(randomAlphanumeric(10)) - .setCreatedAt(nextLong()); - } - - public static List selectAllDeliveryUuids(DbTester dbTester, DbSession dbSession) { - return dbTester.select(dbSession, "select uuid as \"uuid\" from webhook_deliveries") - .stream() - .map(columns -> (String) columns.get("uuid")) - .collect(Collectors.toList()); - } -} diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookTesting.java b/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookTesting.java deleted file mode 100644 index 52e532b70b0..00000000000 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookTesting.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2019 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.db.webhook; - -import java.util.Arrays; -import java.util.function.Consumer; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.organization.OrganizationDto; - -import java.util.Calendar; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; - -public class WebhookTesting { - - private WebhookTesting() { - // only statics - } - - public static WebhookDto newWebhook(ComponentDto project) { - return getWebhookDto() - .setProjectUuid(project.uuid()); - } - - public static WebhookDto newProjectWebhook(String projectUuid) { - return getWebhookDto() - .setProjectUuid(projectUuid); - } - - public static WebhookDto newWebhook(OrganizationDto organizationDto) { - return getWebhookDto() - .setOrganizationUuid(organizationDto.getUuid()); - } - - @SafeVarargs - public static WebhookDto newOrganizationWebhook(String name, String organizationUuid, Consumer... consumers) { - return getWebhookDto(consumers) - .setName(name) - .setOrganizationUuid(organizationUuid); - } - - @SafeVarargs - private static WebhookDto getWebhookDto(Consumer... consumers) { - WebhookDto res = new WebhookDto() - .setUuid(randomAlphanumeric(40)) - .setName(randomAlphanumeric(64)) - .setUrl("https://www.random-site/" + randomAlphanumeric(256)) - .setSecret(randomAlphanumeric(10)) - .setCreatedAt(Calendar.getInstance().getTimeInMillis()); - Arrays.stream(consumers).forEach(consumer -> consumer.accept(res)); - return res; - } -} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/DbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/DbTester.java new file mode 100644 index 00000000000..ecccc986685 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/DbTester.java @@ -0,0 +1,406 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.apache.commons.dbcp2.BasicDataSource; +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.db.alm.AlmDbTester; +import org.sonar.db.component.ComponentDbTester; +import org.sonar.db.component.ProjectLinkDbTester; +import org.sonar.db.event.EventDbTester; +import org.sonar.db.favorite.FavoriteDbTester; +import org.sonar.db.issue.IssueDbTester; +import org.sonar.db.measure.MeasureDbTester; +import org.sonar.db.notification.NotificationDbTester; +import org.sonar.db.organization.OrganizationDbTester; +import org.sonar.db.organization.OrganizationDto; +import org.sonar.db.organization.OrganizationTesting; +import org.sonar.db.permission.template.PermissionTemplateDbTester; +import org.sonar.db.plugin.PluginDbTester; +import org.sonar.db.property.InternalComponentPropertyDbTester; +import org.sonar.db.property.PropertyDbTester; +import org.sonar.db.qualitygate.QualityGateDbTester; +import org.sonar.db.qualityprofile.QualityProfileDbTester; +import org.sonar.db.rule.RuleDbTester; +import org.sonar.db.source.FileSourceTester; +import org.sonar.db.user.RootFlagAssertions; +import org.sonar.db.user.UserDbTester; +import org.sonar.db.webhook.WebhookDbTester; +import org.sonar.db.webhook.WebhookDeliveryDbTester; + +import static com.google.common.base.Preconditions.checkState; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; + +/** + * This class should be called using @Rule. + * Data is truncated between each tests. The schema is created between each test. + */ +public class DbTester extends AbstractDbTester { + + private final System2 system2; + private DbClient client; + private DbSession session = null; + private boolean disableDefaultOrganization = false; + private boolean started = false; + private String defaultOrganizationUuid = randomAlphanumeric(40); + private OrganizationDto defaultOrganization; + + private final UserDbTester userTester; + private final ComponentDbTester componentTester; + private final ProjectLinkDbTester componentLinkTester; + private final FavoriteDbTester favoriteTester; + private final EventDbTester eventTester; + private final OrganizationDbTester organizationTester; + private final PermissionTemplateDbTester permissionTemplateTester; + private final PropertyDbTester propertyTester; + private final QualityGateDbTester qualityGateDbTester; + private final IssueDbTester issueDbTester; + private final RuleDbTester ruleDbTester; + private final NotificationDbTester notificationDbTester; + private final RootFlagAssertions rootFlagAssertions; + private final QualityProfileDbTester qualityProfileDbTester; + private final MeasureDbTester measureDbTester; + private final FileSourceTester fileSourceTester; + private final PluginDbTester pluginDbTester; + private final WebhookDbTester webhookDbTester; + private final WebhookDeliveryDbTester webhookDeliveryDbTester; + private final AlmDbTester almDbTester; + private final InternalComponentPropertyDbTester internalComponentPropertyTester; + + private DbTester(System2 system2, @Nullable String schemaPath, MyBatisConfExtension... confExtensions) { + super(TestDbImpl.create(schemaPath, confExtensions)); + this.system2 = system2; + + initDbClient(); + this.userTester = new UserDbTester(this); + this.componentTester = new ComponentDbTester(this); + this.componentLinkTester = new ProjectLinkDbTester(this); + this.favoriteTester = new FavoriteDbTester(this); + this.eventTester = new EventDbTester(this); + this.organizationTester = new OrganizationDbTester(this); + this.permissionTemplateTester = new PermissionTemplateDbTester(this); + this.propertyTester = new PropertyDbTester(this); + this.qualityGateDbTester = new QualityGateDbTester(this); + this.issueDbTester = new IssueDbTester(this); + this.ruleDbTester = new RuleDbTester(this); + this.notificationDbTester = new NotificationDbTester(this); + this.rootFlagAssertions = new RootFlagAssertions(this); + this.qualityProfileDbTester = new QualityProfileDbTester(this); + this.measureDbTester = new MeasureDbTester(this); + this.fileSourceTester = new FileSourceTester(this); + this.pluginDbTester = new PluginDbTester(this); + this.webhookDbTester = new WebhookDbTester(this); + this.webhookDeliveryDbTester = new WebhookDeliveryDbTester(this); + this.almDbTester = new AlmDbTester(this); + this.internalComponentPropertyTester = new InternalComponentPropertyDbTester(this); + } + + public static DbTester create() { + return new DbTester(System2.INSTANCE, null); + } + + public static DbTester create(System2 system2) { + return new DbTester(system2, null); + } + + public static DbTester createWithExtensionMappers(Class firstMapperClass, Class... otherMapperClasses) { + return new DbTester(System2.INSTANCE, null, new DbTesterMyBatisConfExtension(firstMapperClass, otherMapperClasses)); + } + + public static DbTester createWithExtensionMappers(System2 system2, Class firstMapperClass, Class... otherMapperClasses) { + return new DbTester(system2, null, new DbTesterMyBatisConfExtension(firstMapperClass, otherMapperClasses)); + } + + public static DbTester createForSchema(System2 system2, Class testClass, String filename) { + String path = StringUtils.replaceChars(testClass.getCanonicalName(), '.', '/'); + String schemaPath = path + "/" + filename; + return new DbTester(system2, schemaPath).setDisableDefaultOrganization(true); + } + + private void initDbClient() { + TransientPicoContainer ioc = new TransientPicoContainer(); + ioc.addComponent(db.getMyBatis()); + ioc.addComponent(system2); + ioc.addComponent(new SequenceUuidFactory()); + for (Class daoClass : DaoModule.classes()) { + ioc.addComponent(daoClass); + } + List daos = ioc.getComponents(Dao.class); + client = new DbClient(db.getDatabase(), db.getMyBatis(), new TestDBSessions(db.getMyBatis()), daos.toArray(new Dao[daos.size()])); + } + + public DbTester setDisableDefaultOrganization(boolean b) { + checkState(!started, "DbTester is already started"); + this.disableDefaultOrganization = b; + return this; + } + + public DbTester setDefaultOrganizationUuid(String uuid) { + checkState(!started, "DbTester is already started"); + this.defaultOrganizationUuid = uuid; + return this; + } + + public DbTester enableOrganizations() { + properties().insertInternal("organization.enabled", "true"); + return this; + } + + @Override + protected void before() { + db.start(); + db.truncateTables(); + initDbClient(); + if (!disableDefaultOrganization) { + insertDefaultOrganization(); + } + started = true; + } + + private void insertDefaultOrganization() { + defaultOrganization = OrganizationTesting.newOrganizationDto().setUuid(defaultOrganizationUuid); + try (DbSession dbSession = db.getMyBatis().openSession(false)) { + client.organizationDao().insert(dbSession, defaultOrganization, false); + client.internalPropertiesDao().save(dbSession, "organization.default", defaultOrganization.getUuid()); + dbSession.commit(); + } + } + + public boolean hasDefaultOrganization() { + return defaultOrganization != null; + } + + public OrganizationDto getDefaultOrganization() { + checkState(defaultOrganization != null, "Default organization has not been created"); + return defaultOrganization; + } + + public UserDbTester users() { + return userTester; + } + + public ComponentDbTester components() { + return componentTester; + } + + public ProjectLinkDbTester componentLinks() { + return componentLinkTester; + } + + public FavoriteDbTester favorites() { + return favoriteTester; + } + + public EventDbTester events() { + return eventTester; + } + + public OrganizationDbTester organizations() { + return organizationTester; + } + + public PermissionTemplateDbTester permissionTemplates() { + return permissionTemplateTester; + } + + public PropertyDbTester properties() { + return propertyTester; + } + + public QualityGateDbTester qualityGates() { + return qualityGateDbTester; + } + + public RootFlagAssertions rootFlag() { + return rootFlagAssertions; + } + + public IssueDbTester issues() { + return issueDbTester; + } + + public RuleDbTester rules() { + return ruleDbTester; + } + + public NotificationDbTester notifications() { + return notificationDbTester; + } + + public QualityProfileDbTester qualityProfiles() { + return qualityProfileDbTester; + } + + public MeasureDbTester measures() { + return measureDbTester; + } + + public FileSourceTester fileSources() { + return fileSourceTester; + } + + public PluginDbTester pluginDbTester() { + return pluginDbTester; + } + + public WebhookDbTester webhooks() { + return webhookDbTester; + } + + public WebhookDeliveryDbTester webhookDelivery() { + return webhookDeliveryDbTester; + } + + public AlmDbTester alm() { + return almDbTester; + } + + public InternalComponentPropertyDbTester internalComponentProperties() { + return internalComponentPropertyTester; + } + + @Override + protected void after() { + if (session != null) { + session.rollback(); + session.close(); + } + db.stop(); + started = false; + } + + public DbSession getSession() { + if (session == null) { + session = db.getMyBatis().openSession(false); + } + return session; + } + + public void commit() { + getSession().commit(); + } + + public DbClient getDbClient() { + return client; + } + + public int countRowsOfTable(DbSession dbSession, String tableName) { + return super.countRowsOfTable(tableName, new DbSessionConnectionSupplier(dbSession)); + } + + public int countSql(DbSession dbSession, String sql) { + return super.countSql(sql, new DbSessionConnectionSupplier(dbSession)); + } + + public List> select(DbSession dbSession, String selectSql) { + return super.select(selectSql, new DbSessionConnectionSupplier(dbSession)); + } + + public Map selectFirst(DbSession dbSession, String selectSql) { + return super.selectFirst(selectSql, new DbSessionConnectionSupplier(dbSession)); + } + + @Deprecated + public MyBatis myBatis() { + return db.getMyBatis(); + } + + @Deprecated + public Connection openConnection() throws SQLException { + return getConnection(); + } + + private Connection getConnection() throws SQLException { + return db.getDatabase().getDataSource().getConnection(); + } + + @Deprecated + public Database database() { + return db.getDatabase(); + } + + public String getUrl() { + return ((BasicDataSource) db.getDatabase().getDataSource()).getUrl(); + } + + private static class DbSessionConnectionSupplier implements ConnectionSupplier { + private final DbSession dbSession; + + public DbSessionConnectionSupplier(DbSession dbSession) { + this.dbSession = dbSession; + } + + @Override + public Connection get() { + return dbSession.getConnection(); + } + + @Override + public void close() { + // closing dbSession is not our responsability + } + } + + private static class DbTesterMyBatisConfExtension implements MyBatisConfExtension { + // do not replace with a lambda to allow cache of MyBatis instances in TestDbImpl to work + private final Class[] mapperClasses; + + public DbTesterMyBatisConfExtension(Class firstMapperClass, Class... otherMapperClasses) { + this.mapperClasses = Stream.concat( + Stream.of(firstMapperClass), + Arrays.stream(otherMapperClasses)) + .sorted(Comparator.comparing(Class::getName)) + .toArray(Class[]::new); + } + + @Override + public Stream> getMapperClasses() { + return Arrays.stream(mapperClasses); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DbTesterMyBatisConfExtension that = (DbTesterMyBatisConfExtension) o; + return Arrays.equals(mapperClasses, that.mapperClasses); + } + + @Override + public int hashCode() { + return Arrays.hashCode(mapperClasses); + } + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/OrchestratorSettingsUtils.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/OrchestratorSettingsUtils.java new file mode 100644 index 00000000000..b3f5e8f02ab --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/OrchestratorSettingsUtils.java @@ -0,0 +1,76 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db; + +import java.io.File; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URI; +import java.util.Map; +import java.util.Properties; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.text.StrSubstitutor; +import org.sonar.api.config.Settings; + +import static org.apache.commons.lang.StringUtils.isEmpty; + +public class OrchestratorSettingsUtils { + private OrchestratorSettingsUtils() { + // prevents instantiation + } + + public static void loadOrchestratorSettings(Settings settings) { + String url = settings.getString("orchestrator.configUrl"); + if (isEmpty(url)) { + return; + } + + InputStream input = null; + try { + URI uri = new URI(url); + + if (url.startsWith("file:")) { + File file = new File(uri); + input = FileUtils.openInputStream(file); + } else { + HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); + int responseCode = connection.getResponseCode(); + if (responseCode >= 400) { + throw new IllegalStateException("Fail to request: " + uri + ". Status code=" + responseCode); + } + + input = connection.getInputStream(); + } + + Properties props = new Properties(); + props.load(input); + settings.addProperties(props); + for (Map.Entry entry : settings.getProperties().entrySet()) { + String interpolatedValue = StrSubstitutor.replace(entry.getValue(), System.getenv(), "${", "}"); + settings.setProperty(entry.getKey(), interpolatedValue); + } + } catch (Exception e) { + throw new IllegalStateException("Cannot load Orchestrator properties from:" + url, e); + } finally { + IOUtils.closeQuietly(input); + } + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/SQDatabase.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/SQDatabase.java new file mode 100644 index 00000000000..4a4fd2eae79 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/SQDatabase.java @@ -0,0 +1,236 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db; + +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import javax.sql.DataSource; +import org.apache.commons.dbutils.DbUtils; +import org.apache.commons.io.output.NullWriter; +import org.apache.ibatis.io.Resources; +import org.apache.ibatis.jdbc.ScriptRunner; +import org.sonar.api.SonarEdition; +import org.sonar.api.SonarQubeSide; +import org.sonar.api.config.Settings; +import org.sonar.api.config.internal.MapSettings; +import org.sonar.api.internal.SonarRuntimeImpl; +import org.sonar.api.utils.System2; +import org.sonar.api.utils.Version; +import org.sonar.api.utils.log.Loggers; +import org.sonar.core.platform.ComponentContainer; +import org.sonar.core.util.UuidFactoryFast; +import org.sonar.core.util.logs.Profiler; +import org.sonar.db.dialect.Dialect; +import org.sonar.process.logging.LogbackHelper; +import org.sonar.server.platform.db.migration.MigrationConfigurationModule; +import org.sonar.server.platform.db.migration.engine.MigrationContainer; +import org.sonar.server.platform.db.migration.engine.MigrationContainerImpl; +import org.sonar.server.platform.db.migration.engine.MigrationContainerPopulator; +import org.sonar.server.platform.db.migration.engine.MigrationContainerPopulatorImpl; +import org.sonar.server.platform.db.migration.history.MigrationHistoryTableImpl; +import org.sonar.server.platform.db.migration.step.MigrationStep; +import org.sonar.server.platform.db.migration.step.MigrationStepExecutionException; +import org.sonar.server.platform.db.migration.step.MigrationSteps; +import org.sonar.server.platform.db.migration.step.MigrationStepsExecutor; +import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep; +import org.sonar.server.platform.db.migration.version.DbVersion; + +import static com.google.common.base.Preconditions.checkState; + +public class SQDatabase extends DefaultDatabase { + private final boolean createSchema; + + private SQDatabase(Settings settings, boolean createSchema) { + super(new LogbackHelper(), settings); + this.createSchema = createSchema; + } + + public static SQDatabase newDatabase(Settings settings, boolean createSchema) { + return new SQDatabase(settings, createSchema); + } + + public static SQDatabase newH2Database(String name, boolean createSchema) { + MapSettings settings = new MapSettings() + .setProperty("sonar.jdbc.dialect", "h2") + .setProperty("sonar.jdbc.driverClassName", "org.h2.Driver") + .setProperty("sonar.jdbc.url", "jdbc:h2:mem:" + name) + .setProperty("sonar.jdbc.username", "sonar") + .setProperty("sonar.jdbc.password", "sonar"); + return new SQDatabase(settings, createSchema); + } + + @Override + public void start() { + super.start(); + if (createSchema) { + createSchema(); + } + } + + private void createSchema() { + Connection connection = null; + try { + connection = getDataSource().getConnection(); + NoopDatabase noopDatabase = new NoopDatabase(getDialect(), getDataSource()); + // create and populate schema + createMigrationHistoryTable(noopDatabase); + executeDbMigrations(noopDatabase); + } catch (SQLException e) { + throw new IllegalStateException("Fail to create schema", e); + } finally { + DbUtils.closeQuietly(connection); + } + } + + public static final class H2MigrationContainerPopulator extends MigrationContainerPopulatorImpl { + public H2MigrationContainerPopulator(DbVersion... dbVersions) { + super(H2StepExecutor.class, dbVersions); + } + } + + public static final class H2StepExecutor implements MigrationStepsExecutor { + private static final String STEP_START_PATTERN = "{}..."; + private static final String STEP_STOP_PATTERN = "{}: {}"; + + private final ComponentContainer componentContainer; + + public H2StepExecutor(ComponentContainer componentContainer) { + this.componentContainer = componentContainer; + } + + @Override + public void execute(List steps) { + steps.forEach(step -> execute(step, componentContainer)); + } + + private void execute(RegisteredMigrationStep step, ComponentContainer componentContainer) { + MigrationStep migrationStep = componentContainer.getComponentByType(step.getStepClass()); + checkState(migrationStep != null, "Can not find instance of " + step.getStepClass()); + + execute(step, migrationStep); + } + + private void execute(RegisteredMigrationStep step, MigrationStep migrationStep) { + Profiler stepProfiler = Profiler.create(Loggers.get(SQDatabase.class)); + stepProfiler.startInfo(STEP_START_PATTERN, step); + boolean done = false; + try { + migrationStep.execute(); + done = true; + } catch (Exception e) { + throw new MigrationStepExecutionException(step, e); + } finally { + if (done) { + stepProfiler.stopInfo(STEP_STOP_PATTERN, step, "success"); + } else { + stepProfiler.stopError(STEP_STOP_PATTERN, step, "failure"); + } + } + } + } + + private void executeDbMigrations(NoopDatabase noopDatabase) { + ComponentContainer parentContainer = new ComponentContainer(); + parentContainer.add(noopDatabase); + parentContainer.add(H2MigrationContainerPopulator.class); + MigrationConfigurationModule migrationConfigurationModule = new MigrationConfigurationModule(); + migrationConfigurationModule.configure(parentContainer); + + // dependencies required by DB migrations + parentContainer.add(SonarRuntimeImpl.forSonarQube(Version.create(8, 0), SonarQubeSide.SERVER, SonarEdition.COMMUNITY)); + parentContainer.add(UuidFactoryFast.getInstance()); + parentContainer.add(System2.INSTANCE); + + parentContainer.startComponents(); + + MigrationContainer migrationContainer = new MigrationContainerImpl(parentContainer, parentContainer.getComponentByType(MigrationContainerPopulator.class)); + MigrationSteps migrationSteps = migrationContainer.getComponentByType(MigrationSteps.class); + migrationContainer.getComponentByType(MigrationStepsExecutor.class) + .execute(migrationSteps.readAll()); + } + + private void createMigrationHistoryTable(NoopDatabase noopDatabase) { + new MigrationHistoryTableImpl(noopDatabase).start(); + } + + private class NoopDatabase implements Database { + private final Dialect dialect; + private final DataSource dataSource; + + private NoopDatabase(Dialect dialect, DataSource dataSource) { + this.dialect = dialect; + this.dataSource = dataSource; + } + + @Override + public DataSource getDataSource() { + return dataSource; + } + + @Override + public Dialect getDialect() { + return dialect; + } + + @Override + public void enableSqlLogging(boolean enable) { + + } + + @Override + public void start() { + // do nothing + } + + @Override + public void stop() { + // do nothing + } + } + + public void executeScript(String classloaderPath) { + try (Connection connection = getDataSource().getConnection()) { + executeScript(connection, classloaderPath); + } catch (SQLException e) { + throw new IllegalStateException("Fail to execute script: " + classloaderPath, e); + } + } + + private static void executeScript(Connection connection, String path) { + ScriptRunner scriptRunner = newScriptRunner(connection); + try { + scriptRunner.runScript(Resources.getResourceAsReader(path)); + connection.commit(); + + } catch (Exception e) { + throw new IllegalStateException("Fail to restore: " + path, e); + } + } + + private static ScriptRunner newScriptRunner(Connection connection) { + ScriptRunner scriptRunner = new ScriptRunner(connection); + scriptRunner.setDelimiter(";"); + scriptRunner.setStopOnError(true); + scriptRunner.setLogWriter(new PrintWriter(new NullWriter())); + return scriptRunner; + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/TestDBSessions.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/TestDBSessions.java new file mode 100644 index 00000000000..34a4908bb9c --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/TestDBSessions.java @@ -0,0 +1,43 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db; + +public final class TestDBSessions implements DBSessions { + private final MyBatis myBatis; + + public TestDBSessions(MyBatis myBatis) { + this.myBatis = myBatis; + } + + @Override + public DbSession openSession(boolean batch) { + return myBatis.openSession(false); + } + + @Override + public void enableCaching() { + // ignored + } + + @Override + public void disableCaching() { + // ignored + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/TestDbImpl.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/TestDbImpl.java new file mode 100644 index 00000000000..d984564bb08 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/TestDbImpl.java @@ -0,0 +1,121 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import javax.annotation.Nullable; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang.StringUtils; +import org.junit.AssumptionViolatedException; +import org.sonar.api.config.Settings; +import org.sonar.db.dialect.H2; +import org.sonar.process.logging.LogbackHelper; + +class TestDbImpl extends CoreTestDb { + private static TestDbImpl defaultSchemaBaseTestDb; + // instantiating MyBatis objects is costly => we cache them for default schema + private static final Map defaultSchemaTestDbsWithExtensions = new HashMap<>(); + + private boolean isDefault; + private MyBatis myBatis; + + private TestDbImpl(@Nullable String schemaPath, MyBatisConfExtension... confExtensions) { + super(); + isDefault = (schemaPath == null); + init(schemaPath, confExtensions); + } + + private TestDbImpl(TestDbImpl base, MyBatis myBatis) { + super(base.getDatabase()); + this.isDefault = base.isDefault; + this.myBatis = myBatis; + } + + private void init(@Nullable String schemaPath, MyBatisConfExtension[] confExtensions) { + Consumer loadOrchestratorSettings = settings -> { + OrchestratorSettingsUtils.loadOrchestratorSettings(settings); + }; + Function databaseCreator = settings -> { + String dialect = settings.getString("sonar.jdbc.dialect"); + if (dialect != null && !"h2".equals(dialect)) { + return new DefaultDatabase(new LogbackHelper(), settings); + } + return SQDatabase.newH2Database("h2Tests" + DigestUtils.md5Hex(StringUtils.defaultString(schemaPath)), schemaPath == null); + }; + Consumer schemaPathExecutor = database -> { + if (schemaPath == null) { + return; + } + + // scripts are assumed to be using H2 specific syntax, ignore the test if not on H2 + if (!database.getDialect().getId().equals("h2")) { + database.stop(); + throw new AssumptionViolatedException("This test is intended to be run on H2 only"); + } + ((SQDatabase) database).executeScript(schemaPath); + }; + BiConsumer createMyBatis = (db, created) -> myBatis = newMyBatis(db, confExtensions); + init(loadOrchestratorSettings, databaseCreator, schemaPathExecutor, createMyBatis); + } + + private static MyBatis newMyBatis(Database db, MyBatisConfExtension[] extensions) { + MyBatis newMyBatis = new MyBatis(db, extensions); + newMyBatis.start(); + return newMyBatis; + } + + static TestDbImpl create(@Nullable String schemaPath, MyBatisConfExtension... confExtensions) { + MyBatisConfExtension[] extensionArray = confExtensions.length == 0 ? null : confExtensions; + if (schemaPath == null) { + if (defaultSchemaBaseTestDb == null) { + defaultSchemaBaseTestDb = new TestDbImpl((String) null); + } + if (extensionArray != null) { + return defaultSchemaTestDbsWithExtensions.computeIfAbsent( + extensionArray, + extensions -> new TestDbImpl(defaultSchemaBaseTestDb, newMyBatis(defaultSchemaBaseTestDb.getDatabase(), extensions))); + } + return defaultSchemaBaseTestDb; + } + return new TestDbImpl(schemaPath, confExtensions); + } + + @Override + public void start() { + if (!isDefault && !H2.ID.equals(getDatabase().getDialect().getId())) { + throw new AssumptionViolatedException("Test disabled because it supports only H2"); + } + } + + @Override + public void stop() { + if (!isDefault) { + super.stop(); + } + } + + MyBatis getMyBatis() { + return myBatis; + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/alm/AlmDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/alm/AlmDbTester.java new file mode 100644 index 00000000000..579f505a602 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/alm/AlmDbTester.java @@ -0,0 +1,69 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.alm; + +import java.util.Arrays; +import java.util.function.Consumer; +import org.apache.commons.lang.math.RandomUtils; +import org.sonar.db.DbTester; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.organization.OrganizationDto; +import org.sonar.db.user.UserDto; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.sonar.db.alm.ALM.GITHUB; + +public class AlmDbTester { + + private final DbTester db; + + public AlmDbTester(DbTester db) { + this.db = db; + } + + public OrganizationAlmBindingDto insertOrganizationAlmBinding(OrganizationDto organization, AlmAppInstallDto almAppInstall, boolean membersSync) { + UserDto user = db.users().insertUser(); + db.getDbClient().organizationAlmBindingDao().insert(db.getSession(), organization, almAppInstall, randomAlphabetic(10), user.getUuid(), membersSync); + db.commit(); + return db.getDbClient().organizationAlmBindingDao().selectByOrganization(db.getSession(), organization).get(); + } + + public ProjectAlmBindingDto insertProjectAlmBinding(ALM alm, ComponentDto componentDto, String repositoryUuid) { + db.getDbClient().projectAlmBindingsDao().insertOrUpdate(db.getSession(), alm, repositoryUuid, componentDto.uuid(), + "some_org/some_repo", "http://alm/some_org_some_repo"); + db.commit(); + return db.getDbClient().projectAlmBindingsDao().selectByProjectUuid(db.getSession(), componentDto.uuid()).get(); + } + + @SafeVarargs + public final AlmAppInstallDto insertAlmAppInstall(Consumer... dtoPopulators) { + AlmAppInstallDto dto = new AlmAppInstallDto() + .setAlm(GITHUB) + .setInstallId(randomAlphanumeric(10)) + .setOrganizationAlmId(Integer.toString(RandomUtils.nextInt())) + .setIsOwnerUser(false) + .setUserExternalId(randomAlphanumeric(10)); + Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(dto)); + db.getDbClient().almAppInstallDao().insertOrUpdate(db.getSession(), dto.getAlm(), dto.getOrganizationAlmId(), dto.isOwnerUser(), dto.getInstallId(), dto.getUserExternalId()); + db.commit(); + return db.getDbClient().almAppInstallDao().selectByOrganizationAlmId(db.getSession(), dto.getAlm(), dto.getOrganizationAlmId()).get(); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/ce/CeQueueTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/ce/CeQueueTesting.java new file mode 100644 index 00000000000..07b8074a0d9 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/ce/CeQueueTesting.java @@ -0,0 +1,71 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.ce; + +import java.util.stream.Stream; +import org.sonar.db.DbSession; + +import static com.google.common.base.Preconditions.checkArgument; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang.math.RandomUtils.nextLong; +import static org.assertj.core.api.Assertions.assertThat; +import static org.sonar.db.ce.CeQueueDto.Status.IN_PROGRESS; +import static org.sonar.db.ce.CeQueueDto.Status.PENDING; + +public class CeQueueTesting { + private CeQueueTesting() { + // static methods only + } + + public static CeQueueDto newCeQueueDto(String uuid) { + return new CeQueueDto() + .setUuid(uuid) + .setComponentUuid(randomAlphanumeric(40)) + .setMainComponentUuid(randomAlphanumeric(39)) + .setStatus(CeQueueDto.Status.PENDING) + .setTaskType(CeTaskTypes.REPORT) + .setSubmitterUuid(randomAlphanumeric(255)) + .setCreatedAt(nextLong()) + .setUpdatedAt(nextLong()); + } + + public static void makeInProgress(DbSession dbSession, String workerUuid, long now, CeQueueDto... ceQueueDtos) { + Stream.of(ceQueueDtos).forEach(ceQueueDto -> { + CeQueueMapper mapper = dbSession.getMapper(CeQueueMapper.class); + int touchedRows = mapper.updateIf(ceQueueDto.getUuid(), + new UpdateIf.NewProperties(IN_PROGRESS, workerUuid, now, now), + new UpdateIf.OldProperties(PENDING)); + assertThat(touchedRows).isEqualTo(1); + }); + } + + public static void reset(DbSession dbSession, long now, CeQueueDto... ceQueueDtos) { + Stream.of(ceQueueDtos).forEach(ceQueueDto -> { + checkArgument(ceQueueDto.getStatus() == IN_PROGRESS); + checkArgument(ceQueueDto.getWorkerUuid() != null); + + CeQueueMapper mapper = dbSession.getMapper(CeQueueMapper.class); + int touchedRows = mapper.updateIf(ceQueueDto.getUuid(), + new UpdateIf.NewProperties(PENDING, ceQueueDto.getUuid(), now, now), + new UpdateIf.OldProperties(IN_PROGRESS)); + assertThat(touchedRows).isEqualTo(1); + }); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentDbTester.java new file mode 100644 index 00000000000..472ea47c2f3 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentDbTester.java @@ -0,0 +1,325 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.component; + +import java.util.Arrays; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; +import org.sonar.db.organization.OrganizationDto; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; +import static java.util.Arrays.asList; +import static org.sonar.db.component.BranchType.LONG; + +public class ComponentDbTester { + private final DbTester db; + private final DbClient dbClient; + private final DbSession dbSession; + + public ComponentDbTester(DbTester db) { + this.db = db; + this.dbClient = db.getDbClient(); + this.dbSession = db.getSession(); + } + + public SnapshotDto insertProjectAndSnapshot(ComponentDto component) { + return insertComponentAndSnapshot(component); + } + + public SnapshotDto insertViewAndSnapshot(ComponentDto component) { + return insertComponentAndSnapshot(component); + } + + private SnapshotDto insertComponentAndSnapshot(ComponentDto component) { + dbClient.componentDao().insert(dbSession, component); + SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, SnapshotTesting.newAnalysis(component)); + db.commit(); + + return snapshot; + } + + public ComponentDto insertComponent(ComponentDto component) { + return insertComponentImpl(component, null, noExtraConfiguration()); + } + + public ComponentDto insertPrivateProject() { + return insertComponentImpl(ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()), true, noExtraConfiguration()); + } + + public ComponentDto insertPublicProject() { + return insertComponentImpl(ComponentTesting.newPublicProjectDto(db.getDefaultOrganization()), false, noExtraConfiguration()); + } + + @SafeVarargs + public final ComponentDto insertPrivateProject(Consumer... dtoPopulators) { + return insertComponentImpl(ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()), true, dtoPopulators); + } + + @SafeVarargs + public final ComponentDto insertPublicProject(Consumer... dtoPopulators) { + return insertComponentImpl(ComponentTesting.newPublicProjectDto(db.getDefaultOrganization()), false, dtoPopulators); + } + + @SafeVarargs + public final ComponentDto insertPrivateProject(OrganizationDto organizationDto, Consumer... dtoPopulators) { + return insertComponentImpl(ComponentTesting.newPrivateProjectDto(organizationDto), true, dtoPopulators); + } + + @SafeVarargs + public final ComponentDto insertPublicProject(OrganizationDto organizationDto, Consumer... dtoPopulators) { + return insertComponentImpl(ComponentTesting.newPublicProjectDto(organizationDto), false, dtoPopulators); + } + + public ComponentDto insertPrivateProject(OrganizationDto organizationDto) { + return insertComponentImpl(ComponentTesting.newPrivateProjectDto(organizationDto), true, noExtraConfiguration()); + } + + public ComponentDto insertPublicProject(OrganizationDto organizationDto) { + return insertComponentImpl(ComponentTesting.newPublicProjectDto(organizationDto), false, noExtraConfiguration()); + } + + public ComponentDto insertPrivateProject(OrganizationDto organizationDto, String uuid) { + return insertComponentImpl(ComponentTesting.newPrivateProjectDto(organizationDto, uuid), true, noExtraConfiguration()); + } + + public ComponentDto insertPublicProject(OrganizationDto organizationDto, String uuid) { + return insertComponentImpl(ComponentTesting.newPublicProjectDto(organizationDto, uuid), false, noExtraConfiguration()); + } + + @SafeVarargs + public final ComponentDto insertPrivateProject(OrganizationDto organizationDto, String uuid, Consumer... dtoPopulators) { + return insertComponentImpl(ComponentTesting.newPrivateProjectDto(organizationDto, uuid), true, dtoPopulators); + } + + /** + * @deprecated since 6.6 + * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) + */ + @Deprecated + public ComponentDto insertView() { + return insertComponentImpl(ComponentTesting.newView(db.getDefaultOrganization()), false, noExtraConfiguration()); + } + + /** + * @deprecated since 6.6 + * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) + */ + public ComponentDto insertView(Consumer dtoPopulator) { + return insertComponentImpl(ComponentTesting.newView(db.getDefaultOrganization()), false, dtoPopulator); + } + + /** + * @deprecated since 6.6 + * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) + */ + public ComponentDto insertView(OrganizationDto organizationDto) { + return insertComponentImpl(ComponentTesting.newView(organizationDto), false, noExtraConfiguration()); + } + + /** + * @deprecated since 6.6 + * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) + */ + public ComponentDto insertView(OrganizationDto organizationDto, Consumer dtoPopulator) { + return insertComponentImpl(ComponentTesting.newView(organizationDto), false, dtoPopulator); + } + + /** + * @deprecated since 6.6 + * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) + */ + public ComponentDto insertView(String uuid) { + return insertComponentImpl(ComponentTesting.newView(db.getDefaultOrganization(), uuid), false, noExtraConfiguration()); + } + + /** + * @deprecated since 6.6 + * @see #insertPublicPortfolio(OrganizationDto, Consumer[]) + */ + public ComponentDto insertView(OrganizationDto organizationDto, String uuid) { + return insertComponentImpl(ComponentTesting.newView(organizationDto, uuid), false, noExtraConfiguration()); + } + + @SafeVarargs + public final ComponentDto insertPublicPortfolio(OrganizationDto organization, Consumer... dtoPopulators) { + return insertComponentImpl(ComponentTesting.newView(organization).setPrivate(false), false, dtoPopulators); + } + + @SafeVarargs + public final ComponentDto insertPrivatePortfolio(OrganizationDto organization, Consumer... dtoPopulators) { + return insertComponentImpl(ComponentTesting.newView(organization).setPrivate(true), true, dtoPopulators); + } + + @SafeVarargs + public final ComponentDto insertPublicApplication(OrganizationDto organization, Consumer... dtoPopulators) { + return insertComponentImpl(ComponentTesting.newApplication(organization).setPrivate(false), false, dtoPopulators); + } + + @SafeVarargs + public final ComponentDto insertPrivateApplication(OrganizationDto organization, Consumer... dtoPopulators) { + return insertComponentImpl(ComponentTesting.newApplication(organization).setPrivate(true), true, dtoPopulators); + } + + /** + * @deprecated since 6.6 + * @see #insertPublicApplication(OrganizationDto, Consumer[]) + */ + @SafeVarargs + public final ComponentDto insertApplication(OrganizationDto organizationDto, Consumer... dtoPopulators) { + return insertComponentImpl(ComponentTesting.newApplication(organizationDto), false, dtoPopulators); + } + + @SafeVarargs + public final ComponentDto insertSubView(ComponentDto view, Consumer... dtoPopulators) { + return insertComponentImpl(ComponentTesting.newSubView(view), view.isPrivate(), dtoPopulators); + } + + private static Consumer noExtraConfiguration() { + return (t) -> { + }; + } + + @SafeVarargs + private final ComponentDto insertComponentImpl(ComponentDto component, @Nullable Boolean isPrivate, Consumer... dtoPopulators) { + Arrays.stream(dtoPopulators) + .forEach(dtoPopulator -> dtoPopulator.accept(component)); + checkState(isPrivate == null || component.isPrivate() == isPrivate, "Illegal modification of private flag"); + dbClient.componentDao().insert(dbSession, component); + db.commit(); + + return component; + } + + public void insertComponents(ComponentDto... components) { + dbClient.componentDao().insert(dbSession, asList(components)); + db.commit(); + } + + public SnapshotDto insertSnapshot(SnapshotDto snapshotDto) { + SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, snapshotDto); + db.commit(); + return snapshot; + } + + public SnapshotDto insertSnapshot(ComponentDto componentDto) { + return insertSnapshot(componentDto, noExtraConfiguration()); + } + + public SnapshotDto insertSnapshot(ComponentDto componentDto, Consumer consumer) { + SnapshotDto snapshotDto = SnapshotTesting.newAnalysis(componentDto); + consumer.accept(snapshotDto); + SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, snapshotDto); + db.commit(); + return snapshot; + } + + public void insertSnapshots(SnapshotDto... snapshotDtos) { + dbClient.snapshotDao().insert(dbSession, asList(snapshotDtos)); + db.commit(); + } + + @SafeVarargs + public final ComponentDto insertMainBranch(Consumer... dtoPopulators) { + return insertMainBranch(db.getDefaultOrganization(), dtoPopulators); + } + + @SafeVarargs + public final ComponentDto insertMainBranch(OrganizationDto organization, Consumer... dtoPopulators) { + ComponentDto project = ComponentTesting.newPrivateProjectDto(organization); + Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(project)); + return insertMainBranch(project); + } + + public final ComponentDto insertMainBranch(ComponentDto project) { + BranchDto branchDto = ComponentTesting.newBranchDto(project, LONG); + insertComponent(project); + dbClient.branchDao().insert(dbSession, branchDto); + db.commit(); + return project; + } + + @SafeVarargs + public final ComponentDto insertMainBranch(OrganizationDto organization, String mainBranchName, Consumer... dtoPopulators) { + ComponentDto project = ComponentTesting.newPrivateProjectDto(organization); + BranchDto branchDto = ComponentTesting.newBranchDto(project, LONG).setKey(mainBranchName); + Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(project)); + insertComponent(project); + dbClient.branchDao().insert(dbSession, branchDto); + db.commit(); + return project; + } + + @SafeVarargs + public final ComponentDto insertProjectBranch(ComponentDto project, Consumer... dtoPopulators) { + // MainBranchProjectUuid will be null if it's a main branch + BranchDto branchDto = ComponentTesting.newBranchDto(firstNonNull(project.getMainBranchProjectUuid(), project.projectUuid()), LONG); + Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(branchDto)); + ComponentDto branch = ComponentTesting.newProjectBranch(project, branchDto); + insertComponent(branch); + dbClient.branchDao().insert(dbSession, branchDto); + db.commit(); + return branch; + } + + @SafeVarargs + public final ComponentDto insertProjectBranch(OrganizationDto organization, Consumer... dtoPopulators) { + ComponentDto project = ComponentTesting.newPrivateProjectDto(organization); + return insertProjectBranch(project, dtoPopulators); + } + + public final ComponentDto insertProjectBranch(ComponentDto project, BranchDto branchDto) { + // MainBranchProjectUuid will be null if it's a main branch + checkArgument(branchDto.getProjectUuid().equals(firstNonNull(project.getMainBranchProjectUuid(), project.projectUuid()))); + ComponentDto branch = ComponentTesting.newProjectBranch(project, branchDto); + insertComponent(branch); + dbClient.branchDao().insert(dbSession, branchDto); + db.commit(); + return branch; + } + + public final void setManualBaseline(ComponentDto longOrMainBranchOfProject, SnapshotDto analysis) { + checkArgument(longOrMainBranchOfProject.isRoot()); + + BranchDto branchDto = db.getDbClient().branchDao().selectByUuid(dbSession, longOrMainBranchOfProject.uuid()) + .orElseThrow(() -> new IllegalArgumentException("BranchDto not found for component " + longOrMainBranchOfProject)); + checkArgument(branchDto.getBranchType() == LONG, "must be a main or a Long Living branch"); + db.getDbClient().branchDao().updateManualBaseline(dbSession, longOrMainBranchOfProject.uuid(), analysis.getUuid()); + db.commit(); + } + + public final void unsetManualBaseline(ComponentDto longOrMainBranchOfProject) { + checkArgument(longOrMainBranchOfProject.isRoot()); + + BranchDto branchDto = db.getDbClient().branchDao().selectByUuid(dbSession, longOrMainBranchOfProject.uuid()) + .orElseThrow(() -> new IllegalArgumentException("BranchDto not found for component " + longOrMainBranchOfProject)); + checkArgument(branchDto.getBranchType() == LONG, "must be a main or a Long Living branch"); + db.getDbClient().branchDao().updateManualBaseline(dbSession, longOrMainBranchOfProject.uuid(), null); + db.commit(); + } + + private static T firstNonNull(@Nullable T first, T second) { + return (first != null) ? first : second; + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentTesting.java new file mode 100644 index 00000000000..de911e71fe3 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentTesting.java @@ -0,0 +1,271 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.component; + +import java.util.Date; +import javax.annotation.Nullable; +import org.sonar.api.resources.Qualifiers; +import org.sonar.api.resources.Scopes; +import org.sonar.core.util.Uuids; +import org.sonar.db.organization.OrganizationDto; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.sonar.db.component.BranchType.PULL_REQUEST; +import static org.sonar.db.component.ComponentDto.BRANCH_KEY_SEPARATOR; +import static org.sonar.db.component.ComponentDto.PULL_REQUEST_SEPARATOR; +import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT; +import static org.sonar.db.component.ComponentDto.UUID_PATH_SEPARATOR; +import static org.sonar.db.component.ComponentDto.formatUuidPathFromParent; +import static org.sonar.db.component.ComponentDto.generateBranchKey; +import static org.sonar.db.component.ComponentDto.generatePullRequestKey; + +public class ComponentTesting { + + public static ComponentDto newFileDto(ComponentDto subProjectOrProject) { + return newFileDto(subProjectOrProject, null); + } + + public static ComponentDto newFileDto(ComponentDto subProjectOrProject, @Nullable ComponentDto directory) { + return newFileDto(subProjectOrProject, directory, Uuids.createFast()); + } + + public static ComponentDto newFileDto(ComponentDto module, @Nullable ComponentDto directory, String fileUuid) { + String filename = "NAME_" + fileUuid; + String path = directory != null ? directory.path() + "/" + filename : module.path() + "/" + filename; + return newChildComponent(fileUuid, module, directory == null ? module : directory) + .setDbKey(generateKey("FILE_KEY_" + fileUuid, module)) + .setName(filename) + .setLongName(path) + .setScope(Scopes.FILE) + .setQualifier(Qualifiers.FILE) + .setPath(path) + .setCreatedAt(new Date()) + .setLanguage("xoo"); + } + + public static ComponentDto newDirectory(ComponentDto module, String path) { + return newDirectory(module, Uuids.createFast(), path); + } + + public static ComponentDto newDirectory(ComponentDto module, String uuid, String path) { + String key = !path.equals("/") ? module.getKey() + ":" + path : module.getKey() + ":/"; + return newChildComponent(uuid, module, module) + .setDbKey(generateKey(key, module)) + .setName(path) + .setLongName(path) + .setPath(path) + .setScope(Scopes.DIRECTORY) + .setQualifier(Qualifiers.DIRECTORY); + } + + public static ComponentDto newSubView(ComponentDto viewOrSubView, String uuid, String key) { + return newModuleDto(uuid, viewOrSubView) + .setDbKey(key) + .setName(key) + .setLongName(key) + .setScope(Scopes.PROJECT) + .setQualifier(Qualifiers.SUBVIEW) + .setPath(null); + } + + public static ComponentDto newSubView(ComponentDto viewOrSubView) { + String uuid = Uuids.createFast(); + return newSubView(viewOrSubView, uuid, "KEY_" + uuid); + } + + public static ComponentDto newModuleDto(String uuid, ComponentDto parentModuleOrProject) { + return newChildComponent(uuid, parentModuleOrProject, parentModuleOrProject) + .setModuleUuidPath(parentModuleOrProject.moduleUuidPath() + uuid + UUID_PATH_SEPARATOR) + .setDbKey(generateKey("MODULE_KEY_" + uuid, parentModuleOrProject)) + .setName("NAME_" + uuid) + .setLongName("LONG_NAME_" + uuid) + .setPath("module") + .setScope(Scopes.PROJECT) + .setQualifier(Qualifiers.MODULE) + .setLanguage(null); + } + + private static String generateKey(String key, ComponentDto parentModuleOrProject) { + String branch = parentModuleOrProject.getBranch(); + if (branch != null) { + return generateBranchKey(key, branch); + } + String pullRequest = parentModuleOrProject.getPullRequest(); + if (pullRequest != null) { + return generatePullRequestKey(key, pullRequest); + } + + return key; + } + + public static ComponentDto newModuleDto(ComponentDto subProjectOrProject) { + return newModuleDto(Uuids.createFast(), subProjectOrProject); + } + + public static ComponentDto newPrivateProjectDto(OrganizationDto organizationDto) { + return newProjectDto(organizationDto.getUuid(), Uuids.createFast(), true); + } + + public static ComponentDto newPrivateProjectDto(OrganizationDto organizationDto, String uuid) { + return newProjectDto(organizationDto.getUuid(), uuid, true); + } + + public static ComponentDto newPublicProjectDto(OrganizationDto organizationDto) { + return newProjectDto(organizationDto.getUuid(), Uuids.createFast(), false); + } + + public static ComponentDto newPublicProjectDto(OrganizationDto organizationDto, String uuid) { + return newProjectDto(organizationDto.getUuid(), uuid, false); + } + + private static ComponentDto newProjectDto(String organizationUuid, String uuid, boolean isPrivate) { + return new ComponentDto() + .setOrganizationUuid(organizationUuid) + .setUuid(uuid) + .setUuidPath(UUID_PATH_OF_ROOT) + .setProjectUuid(uuid) + .setModuleUuidPath(UUID_PATH_SEPARATOR + uuid + UUID_PATH_SEPARATOR) + .setRootUuid(uuid) + .setDbKey("KEY_" + uuid) + .setName("NAME_" + uuid) + .setLongName("LONG_NAME_" + uuid) + .setDescription("DESCRIPTION_" + uuid) + .setScope(Scopes.PROJECT) + .setQualifier(Qualifiers.PROJECT) + .setPath(null) + .setLanguage(null) + .setEnabled(true) + .setPrivate(isPrivate); + } + + public static ComponentDto newView(OrganizationDto organizationDto) { + return newView(organizationDto.getUuid(), Uuids.createFast()); + } + + public static ComponentDto newView(OrganizationDto organizationDto, String uuid) { + return newPrivateProjectDto(organizationDto, uuid) + .setUuid(uuid) + .setScope(Scopes.PROJECT) + .setQualifier(Qualifiers.VIEW) + .setPrivate(false); + } + + private static ComponentDto newView(String organizationUuid, String uuid) { + return newProjectDto(organizationUuid, uuid, false) + .setUuid(uuid) + .setScope(Scopes.PROJECT) + .setQualifier(Qualifiers.VIEW); + } + + public static ComponentDto newApplication(OrganizationDto organizationDto) { + return newView(organizationDto.getUuid(), Uuids.createFast()) + .setQualifier(Qualifiers.APP); + } + + public static ComponentDto newProjectCopy(ComponentDto project, ComponentDto view) { + return newProjectCopy(Uuids.createFast(), project, view); + } + + public static ComponentDto newProjectCopy(String uuid, ComponentDto project, ComponentDto view) { + checkNotNull(project.getId(), "The project need to be persisted before creating this technical project."); + return newChildComponent(uuid, view, view) + .setDbKey(view.getDbKey() + project.getDbKey()) + .setName(project.name()) + .setLongName(project.longName()) + .setCopyComponentUuid(project.uuid()) + .setScope(Scopes.FILE) + .setQualifier(Qualifiers.PROJECT) + .setPath(null) + .setLanguage(null); + } + + public static ComponentDto newChildComponent(String uuid, ComponentDto moduleOrProject, ComponentDto parent) { + checkArgument(moduleOrProject.isPrivate() == parent.isPrivate(), + "private flag inconsistent between moduleOrProject (%s) and parent (%s)", + moduleOrProject.isPrivate(), parent.isPrivate()); + return new ComponentDto() + .setOrganizationUuid(parent.getOrganizationUuid()) + .setUuid(uuid) + .setUuidPath(formatUuidPathFromParent(parent)) + .setProjectUuid(moduleOrProject.projectUuid()) + .setRootUuid(moduleOrProject.uuid()) + .setModuleUuid(moduleOrProject.uuid()) + .setModuleUuidPath(moduleOrProject.moduleUuidPath()) + .setMainBranchProjectUuid(moduleOrProject.getMainBranchProjectUuid()) + .setCreatedAt(new Date()) + .setEnabled(true) + .setPrivate(moduleOrProject.isPrivate()); + } + + public static BranchDto newBranchDto(@Nullable String projectUuid, BranchType branchType) { + String key = projectUuid == null ? null : "branch_" + randomAlphanumeric(248); + return new BranchDto() + .setKey(key) + .setUuid(Uuids.createFast()) + // MainBranchProjectUuid will be null if it's a main branch + .setProjectUuid(projectUuid) + .setBranchType(branchType); + } + + public static BranchDto newBranchDto(ComponentDto project) { + return newBranchDto(project.projectUuid(), BranchType.LONG); + } + + public static BranchDto newBranchDto(ComponentDto branchComponent, BranchType branchType) { + boolean isMain = branchComponent.getMainBranchProjectUuid() == null; + String projectUuid = isMain ? branchComponent.uuid() : branchComponent.getMainBranchProjectUuid(); + String key = isMain ? "master" : "branch_" + randomAlphanumeric(248); + + return new BranchDto() + .setKey(key) + .setUuid(branchComponent.uuid()) + .setProjectUuid(projectUuid) + .setBranchType(branchType); + } + + public static ComponentDto newProjectBranch(ComponentDto project, BranchDto branchDto) { + checkArgument(project.qualifier().equals(Qualifiers.PROJECT) || project.qualifier().equals(Qualifiers.APP)); + checkArgument(project.getMainBranchProjectUuid() == null); + String branchName = branchDto.getKey(); + String branchSeparator = branchDto.getBranchType() == PULL_REQUEST ? PULL_REQUEST_SEPARATOR : BRANCH_KEY_SEPARATOR; + String uuid = branchDto.getUuid(); + return new ComponentDto() + .setUuid(uuid) + .setOrganizationUuid(project.getOrganizationUuid()) + .setUuidPath(UUID_PATH_OF_ROOT) + .setProjectUuid(uuid) + .setModuleUuidPath(UUID_PATH_SEPARATOR + uuid + UUID_PATH_SEPARATOR) + .setRootUuid(uuid) + // name of the branch is not mandatory on the main branch + .setDbKey(branchName != null ? project.getDbKey() + branchSeparator + branchName : project.getKey()) + .setMainBranchProjectUuid(project.uuid()) + .setName(project.name()) + .setLongName(project.longName()) + .setDescription(project.description()) + .setScope(project.scope()) + .setQualifier(project.qualifier()) + .setPath(null) + .setLanguage(null) + .setEnabled(true) + .setPrivate(project.isPrivate()); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkDbTester.java new file mode 100644 index 00000000000..86c9a7adfb8 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkDbTester.java @@ -0,0 +1,59 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.component; + +import java.util.Arrays; +import java.util.function.Consumer; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; + +import static org.sonar.db.component.ProjectLinkTesting.newCustomLinkDto; +import static org.sonar.db.component.ProjectLinkTesting.newProvidedLinkDto; + +public class ProjectLinkDbTester { + private final DbTester db; + private final DbClient dbClient; + private final DbSession dbSession; + + public ProjectLinkDbTester(DbTester db) { + this.db = db; + this.dbClient = db.getDbClient(); + this.dbSession = db.getSession(); + } + + @SafeVarargs + public final ProjectLinkDto insertProvidedLink(ComponentDto project, Consumer... dtoPopulators) { + return insertLink(project, newProvidedLinkDto(), dtoPopulators); + } + + @SafeVarargs + public final ProjectLinkDto insertCustomLink(ComponentDto project, Consumer... dtoPopulators) { + return insertLink(project, newCustomLinkDto(), dtoPopulators); + } + + @SafeVarargs + private final ProjectLinkDto insertLink(ComponentDto project, ProjectLinkDto componentLink, Consumer... dtoPopulators) { + Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(componentLink)); + dbClient.projectLinkDao().insert(dbSession, componentLink.setProjectUuid(project.uuid())); + db.commit(); + return componentLink; + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkTesting.java new file mode 100644 index 00000000000..08170f8855c --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkTesting.java @@ -0,0 +1,52 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.component; + +import org.apache.commons.lang.math.RandomUtils; +import org.sonar.core.util.Uuids; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; + +public class ProjectLinkTesting { + + public static ProjectLinkDto newProvidedLinkDto() { + return newCommonLinkDto() + .setName(null) + .setType(ProjectLinkDto.PROVIDED_TYPES.get(RandomUtils.nextInt(ProjectLinkDto.PROVIDED_TYPES.size() - 1))); + } + + public static ProjectLinkDto newCustomLinkDto() { + String nameAndType = randomAlphabetic(20); + return newCommonLinkDto() + .setName(nameAndType) + .setType(nameAndType); + } + + private static ProjectLinkDto newCommonLinkDto() { + return new ProjectLinkDto() + .setUuid(Uuids.createFast()) + .setProjectUuid(Uuids.createFast()) + .setHref(randomAlphanumeric(128)) + .setCreatedAt(System.currentTimeMillis()) + .setUpdatedAt(System.currentTimeMillis()); + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ResourceTypesRule.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ResourceTypesRule.java new file mode 100644 index 00000000000..25945d9848f --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ResourceTypesRule.java @@ -0,0 +1,98 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.component; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.sonar.api.resources.ResourceType; +import org.sonar.api.resources.ResourceTypeTree; +import org.sonar.api.resources.ResourceTypes; + +import static java.util.Collections.emptyList; +import static java.util.Collections.emptySet; + +public class ResourceTypesRule extends ResourceTypes { + private Set allResourceTypes = emptySet(); + private Set rootResourceTypes = emptySet(); + private List leavesQualifiers = emptyList(); + + public ResourceTypesRule() { + super(new ResourceTypeTree[0]); + } + + + @Override + public Collection getAll() { + return allResourceTypes; + } + + @Override + public Collection getRoots() { + return rootResourceTypes; + } + + public ResourceTypesRule setRootQualifiers(String... qualifiers) { + Set resourceTypes = new LinkedHashSet<>(); + for (String qualifier : qualifiers) { + resourceTypes.add(ResourceType.builder(qualifier).setProperty("deletable", true).build()); + } + rootResourceTypes = ImmutableSet.copyOf(resourceTypes); + + return this; + } + + public ResourceTypesRule setLeavesQualifiers(String... qualifiers) { + leavesQualifiers = ImmutableList.copyOf(qualifiers); + return this; + } + + public ResourceTypesRule setAllQualifiers(String... qualifiers) { + Set resourceTypes = new HashSet<>(); + for (String qualifier : qualifiers) { + resourceTypes.add(ResourceType.builder(qualifier).setProperty("deletable", true).build()); + } + allResourceTypes = ImmutableSet.copyOf(resourceTypes); + + return this; + } + + @Override + public ResourceType get(String qualifier) { + return allResourceTypes.stream() + .filter(resourceType -> qualifier.equals(resourceType.getQualifier())) + .findAny().orElse(null); + } + + @Override + public boolean isQualifierPresent(String qualifier) { + return rootResourceTypes.stream() + .anyMatch(resourceType -> qualifier.equals(resourceType.getQualifier())); + } + + @Override + public List getLeavesQualifiers(String qualifier) { + return this.leavesQualifiers; + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/SnapshotTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/SnapshotTesting.java new file mode 100644 index 00000000000..1f65b38e2b2 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/SnapshotTesting.java @@ -0,0 +1,51 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.component; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang.RandomStringUtils.randomAscii; + +public class SnapshotTesting { + + public static SnapshotDto newAnalysis(ComponentDto rootComponent) { + checkNotNull(rootComponent.uuid(), "Project UUID must be set"); + checkArgument(rootComponent.uuid().equals(rootComponent.projectUuid()), "Component is not a tree root"); + return new SnapshotDto() + .setUuid(randomAlphanumeric(40)) + .setComponentUuid(rootComponent.uuid()) + .setStatus(SnapshotDto.STATUS_PROCESSED) + .setCreatedAt(System.currentTimeMillis()) + .setBuildDate(System.currentTimeMillis()) + .setRevision(randomAlphanumeric(50)) + .setLast(true); + } + + public static SnapshotDto newSnapshot() { + return new SnapshotDto() + .setUuid(randomAlphanumeric(40)) + .setComponentUuid(randomAlphanumeric(40)) + .setStatus(randomAscii(1)) + .setCreatedAt(System.currentTimeMillis()) + .setBuildDate(System.currentTimeMillis()) + .setLast(true); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventDbTester.java new file mode 100644 index 00000000000..bc97784ed3b --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventDbTester.java @@ -0,0 +1,78 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.event; + +import java.util.Optional; +import javax.annotation.Nullable; +import org.sonar.core.util.UuidFactoryFast; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; +import org.sonar.db.component.BranchDto; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.component.SnapshotDto; +import org.sonar.db.event.EventComponentChangeDto.ChangeCategory; + +public class EventDbTester { + private final DbTester db; + private final DbClient dbClient; + private final DbSession dbSession; + + public EventDbTester(DbTester db) { + this.db = db; + this.dbClient = db.getDbClient(); + this.dbSession = db.getSession(); + } + + public EventDto insertEvent(EventDto event) { + dbClient.eventDao().insert(dbSession, event); + db.commit(); + + return event; + } + + public EventDto insertEvent(SnapshotDto analysis) { + EventDto event = EventTesting.newEvent(analysis); + dbClient.eventDao().insert(dbSession, event); + db.commit(); + + return event; + } + + public EventComponentChangeDto insertEventComponentChanges(EventDto event, SnapshotDto analysis, + ChangeCategory changeCategory, ComponentDto component, @Nullable BranchDto branch) { + + EventComponentChangeDto eventComponentChange = new EventComponentChangeDto() + .setUuid(UuidFactoryFast.getInstance().create()) + .setCategory(changeCategory) + .setEventUuid(event.getUuid()) + .setComponentUuid(component.uuid()) + .setComponentKey(component.getKey()) + .setComponentName(component.name()) + .setComponentBranchKey(Optional.ofNullable(branch).map(BranchDto::getKey).orElse(null)); + EventPurgeData eventPurgeData = new EventPurgeData(analysis.getComponentUuid(), analysis.getUuid()); + + dbClient.eventComponentChangeDao().insert(dbSession, eventComponentChange, eventPurgeData); + db.commit(); + + return eventComponentChange; + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventTesting.java new file mode 100644 index 00000000000..b3a4c135e65 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventTesting.java @@ -0,0 +1,43 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.event; + +import org.sonar.db.component.SnapshotDto; + +import static java.util.Objects.requireNonNull; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; + +public class EventTesting { + + public static EventDto newEvent(SnapshotDto analysis) { + requireNonNull(analysis.getUuid()); + requireNonNull(analysis.getComponentUuid()); + + return new EventDto() + .setAnalysisUuid(analysis.getUuid()) + .setComponentUuid(analysis.getComponentUuid()) + .setUuid(randomAlphanumeric(40)) + .setName(randomAlphanumeric(400)) + .setDescription(null) + .setCategory("Other") + .setCreatedAt(System.currentTimeMillis()) + .setDate(System.currentTimeMillis()); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/favorite/FavoriteDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/favorite/FavoriteDbTester.java new file mode 100644 index 00000000000..feb803c5f0d --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/favorite/FavoriteDbTester.java @@ -0,0 +1,66 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.favorite; + +import java.util.List; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.property.PropertyDto; +import org.sonar.db.property.PropertyQuery; + +public class FavoriteDbTester { + private static final String PROP_FAVORITE_KEY = "favourite"; + + private final DbClient dbClient; + private final DbSession dbSession; + + public FavoriteDbTester(DbTester db) { + this.dbClient = db.getDbClient(); + this.dbSession = db.getSession(); + } + + public void add(ComponentDto componentDto, int userId) { + dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto() + .setKey(PROP_FAVORITE_KEY) + .setUserId(userId) + .setResourceId(componentDto.getId())); + dbSession.commit(); + } + + public boolean hasFavorite(ComponentDto componentDto, int userId) { + List result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() + .setKey(PROP_FAVORITE_KEY) + .setComponentId(componentDto.getId()) + .setUserId(userId) + .build(), dbSession); + + return !result.isEmpty(); + } + + public boolean hasNoFavorite(ComponentDto componentDto) { + List result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() + .setKey(PROP_FAVORITE_KEY) + .setComponentId(componentDto.getId()) + .build(), dbSession); + return result.isEmpty(); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/issue/IssueDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/issue/IssueDbTester.java new file mode 100644 index 00000000000..a7c5c0c7355 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/issue/IssueDbTester.java @@ -0,0 +1,96 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.issue; + +import java.util.Arrays; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import org.sonar.core.issue.DefaultIssueComment; +import org.sonar.core.issue.FieldDiffs; +import org.sonar.db.DbTester; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.organization.OrganizationDto; +import org.sonar.db.rule.RuleDefinitionDto; +import org.sonar.db.user.UserDto; + +import static java.util.Arrays.stream; +import static org.sonar.db.component.ComponentTesting.newFileDto; +import static org.sonar.db.issue.IssueTesting.newIssue; + +public class IssueDbTester { + + private final DbTester db; + + public IssueDbTester(DbTester db) { + this.db = db; + } + + @SafeVarargs + public final IssueDto insert(RuleDefinitionDto rule, ComponentDto project, ComponentDto file, Consumer... populators) { + IssueDto issue = newIssue(rule, project, file); + stream(populators).forEach(p -> p.accept(issue)); + return insertIssue(issue); + } + + public IssueDto insertIssue(IssueDto issueDto) { + db.getDbClient().issueDao().insert(db.getSession(), issueDto); + db.commit(); + return issueDto; + } + + @SafeVarargs + public final IssueDto insertIssue(Consumer... populateIssueDto) { + return insertIssue(db.getDefaultOrganization(), populateIssueDto); + } + + @SafeVarargs + public final IssueDto insertIssue(OrganizationDto organizationDto, Consumer... populators) { + RuleDefinitionDto rule = db.rules().insert(); + ComponentDto project = db.components().insertMainBranch(organizationDto); + ComponentDto file = db.components().insertComponent(newFileDto(project)); + IssueDto issue = newIssue(rule, project, file); + stream(populators).forEach(p -> p.accept(issue)); + return insertIssue(issue); + } + + @SafeVarargs + public final IssueChangeDto insertChange(IssueDto issueDto, Consumer... populators) { + IssueChangeDto dto = IssueTesting.newIssuechangeDto(issueDto); + stream(populators).forEach(p -> p.accept(dto)); + return insertChange(dto); + } + + public IssueChangeDto insertChange(IssueChangeDto issueChangeDto) { + db.getDbClient().issueChangeDao().insert(db.getSession(), issueChangeDto); + db.commit(); + return issueChangeDto; + } + + public IssueChangeDto insertComment(IssueDto issueDto, @Nullable UserDto user, String text) { + IssueChangeDto issueChangeDto = IssueChangeDto.of(DefaultIssueComment.create(issueDto.getKey(), user == null ? null : user.getUuid(), text)); + return insertChange(issueChangeDto); + } + + public void insertFieldDiffs(IssueDto issueDto, FieldDiffs... diffs) { + Arrays.stream(diffs).forEach(diff -> db.getDbClient().issueChangeDao().insert(db.getSession(), IssueChangeDto.of(issueDto.getKey(), diff))); + db.commit(); + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/MeasureDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/MeasureDbTester.java new file mode 100644 index 00000000000..59b8c3160bd --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/MeasureDbTester.java @@ -0,0 +1,91 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.measure; + +import com.google.common.base.Preconditions; +import java.util.Arrays; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.component.SnapshotDto; +import org.sonar.db.measure.custom.CustomMeasureDto; +import org.sonar.db.metric.MetricDto; +import org.sonar.db.user.UserDto; + +import static org.sonar.db.measure.MeasureTesting.newLiveMeasure; +import static org.sonar.db.measure.MeasureTesting.newMeasureDto; +import static org.sonar.db.measure.custom.CustomMeasureTesting.newCustomMeasureDto; +import static org.sonar.db.metric.MetricTesting.newMetricDto; + +public class MeasureDbTester { + private final DbClient dbClient; + private final DbSession dbSession; + + public MeasureDbTester(DbTester db) { + this.dbClient = db.getDbClient(); + this.dbSession = db.getSession(); + } + + @SafeVarargs + public final MeasureDto insertMeasure(ComponentDto component, SnapshotDto analysis, MetricDto metricDto, Consumer... consumers) { + MeasureDto measureDto = newMeasureDto(metricDto, component, analysis); + Arrays.stream(consumers).forEach(c -> c.accept(measureDto)); + dbClient.measureDao().insert(dbSession, measureDto); + dbSession.commit(); + return measureDto; + } + + @SafeVarargs + public final LiveMeasureDto insertLiveMeasure(ComponentDto component, MetricDto metric, Consumer... consumers) { + LiveMeasureDto dto = newLiveMeasure(component, metric); + Arrays.stream(consumers).forEach(c -> c.accept(dto)); + dbClient.liveMeasureDao().insert(dbSession, dto); + dbSession.commit(); + return dto; + } + + @SafeVarargs + public final CustomMeasureDto insertCustomMeasure(@Nullable UserDto user, ComponentDto component, MetricDto metricDto, Consumer... consumers) { + Preconditions.checkArgument(metricDto.isUserManaged(),"Custom measure must be created from a custom metric"); + CustomMeasureDto dto = newCustomMeasureDto() + .setComponentUuid(component.uuid()) + .setMetricId(metricDto.getId()); + if (user != null) { + dto.setUserUuid(user.getUuid()); + } + Arrays.stream(consumers).forEach(c -> c.accept(dto)); + dbClient.customMeasureDao().insert(dbSession, dto); + dbSession.commit(); + return dto; + } + + @SafeVarargs + public final MetricDto insertMetric(Consumer... consumers) { + MetricDto metricDto = newMetricDto(); + Arrays.stream(consumers).forEach(c -> c.accept(metricDto)); + dbClient.metricDao().insert(dbSession, metricDto); + dbSession.commit(); + return metricDto; + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/MeasureTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/MeasureTesting.java new file mode 100644 index 00000000000..60b0c188757 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/MeasureTesting.java @@ -0,0 +1,78 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.measure; + +import org.apache.commons.lang.math.RandomUtils; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.component.SnapshotDto; +import org.sonar.db.metric.MetricDto; + +import static com.google.common.base.Preconditions.checkNotNull; + +public class MeasureTesting { + + private static int cursor = RandomUtils.nextInt(100); + + private MeasureTesting() { + // static methods only + } + + public static MeasureDto newMeasureDto(MetricDto metricDto, ComponentDto component, SnapshotDto analysis) { + checkNotNull(metricDto.getId()); + checkNotNull(metricDto.getKey()); + checkNotNull(component.uuid()); + checkNotNull(analysis.getUuid()); + return new MeasureDto() + .setMetricId(metricDto.getId()) + .setComponentUuid(component.uuid()) + .setAnalysisUuid(analysis.getUuid()); + } + + public static MeasureDto newMeasure() { + return new MeasureDto() + .setMetricId(cursor++) + .setComponentUuid(String.valueOf(cursor++)) + .setAnalysisUuid(String.valueOf(cursor++)) + .setData(String.valueOf(cursor++)) + .setAlertStatus(String.valueOf(cursor++)) + .setAlertText(String.valueOf(cursor++)) + .setValue((double) cursor++); + } + + public static LiveMeasureDto newLiveMeasure() { + return new LiveMeasureDto() + .setMetricId(cursor++) + .setComponentUuid(String.valueOf(cursor++)) + .setProjectUuid(String.valueOf(cursor++)) + .setData(String.valueOf(cursor++)) + .setValue((double) cursor++) + .setVariation((double) cursor++); + } + + public static LiveMeasureDto newLiveMeasure(ComponentDto component, MetricDto metric) { + return new LiveMeasureDto() + .setMetricId(metric.getId()) + .setComponentUuid(component.uuid()) + .setProjectUuid(component.projectUuid()) + .setData(String.valueOf(cursor++)) + .setValue((double) cursor++) + .setVariation((double) cursor++); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/custom/CustomMeasureTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/custom/CustomMeasureTesting.java new file mode 100644 index 00000000000..318633e316b --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/custom/CustomMeasureTesting.java @@ -0,0 +1,42 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.measure.custom; + +import org.apache.commons.lang.RandomStringUtils; +import org.apache.commons.lang.math.RandomUtils; +import org.sonar.api.utils.System2; + +public class CustomMeasureTesting { + private CustomMeasureTesting() { + // static stuff only + } + + public static CustomMeasureDto newCustomMeasureDto() { + return new CustomMeasureDto() + .setDescription(RandomStringUtils.randomAlphanumeric(255)) + .setTextValue(RandomStringUtils.randomAlphanumeric(255)) + .setUserUuid("userUuid" + RandomStringUtils.randomAlphanumeric(100)) + .setValue(RandomUtils.nextDouble()) + .setMetricId(RandomUtils.nextInt()) + .setComponentUuid(RandomStringUtils.randomAlphanumeric(50)) + .setCreatedAt(System2.INSTANCE.now()) + .setUpdatedAt(System2.INSTANCE.now()); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/metric/MetricTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/metric/MetricTesting.java new file mode 100644 index 00000000000..2158cc56dba --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/metric/MetricTesting.java @@ -0,0 +1,50 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.metric; + +import org.apache.commons.lang.RandomStringUtils; +import org.apache.commons.lang.math.RandomUtils; +import org.sonar.api.measures.Metric; + +public class MetricTesting { + private MetricTesting() { + // static stuff only + } + + public static MetricDto newMetricDto() { + Metric.ValueType[] metricTypes = Metric.ValueType.values(); + return new MetricDto() + .setId(RandomUtils.nextInt()) + .setKey(RandomStringUtils.randomAlphanumeric(64)) + .setShortName(RandomStringUtils.randomAlphanumeric(64)) + .setValueType(metricTypes[RandomUtils.nextInt(metricTypes.length - 1)].name()) + .setDomain(RandomStringUtils.randomAlphanumeric(64)) + .setDescription(RandomStringUtils.randomAlphanumeric(250)) + .setBestValue(RandomUtils.nextDouble()) + .setDeleteHistoricalData(RandomUtils.nextBoolean()) + .setDirection(RandomUtils.nextInt()) + .setHidden(RandomUtils.nextBoolean()) + .setEnabled(true) + .setOptimizedBestValue(RandomUtils.nextBoolean()) + .setQualitative(RandomUtils.nextBoolean()) + .setUserManaged(RandomUtils.nextBoolean()) + .setWorstValue(RandomUtils.nextDouble()); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/notification/NotificationDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/notification/NotificationDbTester.java new file mode 100644 index 00000000000..4449bbaafc2 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/notification/NotificationDbTester.java @@ -0,0 +1,67 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.notification; + +import java.util.List; +import javax.annotation.Nullable; +import org.sonar.core.util.stream.MoreCollectors; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.property.PropertyDto; +import org.sonar.db.property.PropertyQuery; + +import static org.assertj.core.api.Assertions.assertThat; + +public class NotificationDbTester { + private static final String PROP_NOTIFICATION_PREFIX = "notification"; + + private final DbTester db; + private final DbClient dbClient; + private final DbSession dbSession; + + public NotificationDbTester(DbTester db) { + this.db = db; + this.dbClient = db.getDbClient(); + this.dbSession = db.getSession(); + } + + public void assertExists(String channel, String dispatcher, int userId, @Nullable ComponentDto component) { + List result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() + .setKey(String.join(".", PROP_NOTIFICATION_PREFIX, dispatcher, channel)) + .setComponentId(component == null ? null : component.getId()) + .setUserId(userId) + .build(), dbSession).stream() + .filter(prop -> component == null ? prop.getResourceId() == null : prop.getResourceId() != null) + .collect(MoreCollectors.toList()); + assertThat(result).hasSize(1); + assertThat(result.get(0).getValue()).isEqualTo("true"); + } + + public void assertDoesNotExist(String channel, String dispatcher, int userId, @Nullable ComponentDto component) { + List result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() + .setKey(String.join(".", PROP_NOTIFICATION_PREFIX, dispatcher, channel)) + .setComponentId(component == null ? null : component.getId()) + .setUserId(userId) + .build(), dbSession); + assertThat(result).isEmpty(); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/organization/OrganizationDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/organization/OrganizationDbTester.java new file mode 100644 index 00000000000..5daf1ff867d --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/organization/OrganizationDbTester.java @@ -0,0 +1,138 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.organization; + +import java.util.Arrays; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; +import org.sonar.db.permission.template.PermissionTemplateDto; +import org.sonar.db.user.GroupMembershipDto; +import org.sonar.db.user.GroupMembershipQuery; +import org.sonar.db.user.UserDto; + +import static com.google.common.base.Preconditions.checkArgument; +import static org.assertj.core.api.Assertions.assertThat; +import static org.sonar.db.user.GroupMembershipQuery.IN; + +public class OrganizationDbTester { + private final DbTester db; + + public OrganizationDbTester(DbTester db) { + this.db = db; + } + + /** + * Insert an {@link OrganizationDto} and commit the session + */ + public OrganizationDto insert() { + return insert(OrganizationTesting.newOrganizationDto()); + } + + public OrganizationDto insert(Consumer populator) { + OrganizationDto dto = OrganizationTesting.newOrganizationDto(); + populator.accept(dto); + return insert(dto); + } + + public OrganizationDto insertForKey(String key) { + return insert(dto -> dto.setKey(key)); + } + + public OrganizationDto insertForUuid(String organizationUuid) { + return insert(dto -> dto.setUuid(organizationUuid)); + } + + /** + * Insert the provided {@link OrganizationDto} and commit the session + */ + public OrganizationDto insert(OrganizationDto dto) { + DbSession dbSession = db.getSession(); + db.getDbClient().organizationDao().insert(dbSession, dto, false); + dbSession.commit(); + return dto; + } + + public void setDefaultTemplates(PermissionTemplateDto projectDefaultTemplate, @Nullable PermissionTemplateDto applicationDefaultTemplate, + @Nullable PermissionTemplateDto portfolioDefaultTemplate) { + checkArgument(portfolioDefaultTemplate == null + || portfolioDefaultTemplate.getOrganizationUuid().equals(projectDefaultTemplate.getOrganizationUuid()), + "default template for project and portfolio must belong to the same organization"); + checkArgument(applicationDefaultTemplate == null + || applicationDefaultTemplate.getOrganizationUuid().equals(projectDefaultTemplate.getOrganizationUuid()), + "default template for project and application must belong to the same organization"); + + DbSession dbSession = db.getSession(); + db.getDbClient().organizationDao().setDefaultTemplates(dbSession, projectDefaultTemplate.getOrganizationUuid(), + new DefaultTemplates() + .setProjectUuid(projectDefaultTemplate.getUuid()) + .setPortfoliosUuid(portfolioDefaultTemplate == null ? null : portfolioDefaultTemplate.getUuid()) + .setApplicationsUuid(applicationDefaultTemplate == null ? null : applicationDefaultTemplate.getUuid())); + dbSession.commit(); + } + + public void setDefaultTemplates(OrganizationDto defaultOrganization, String projectDefaultTemplateUuid, + @Nullable String applicationDefaultTemplateUuid, @Nullable String portfoliosDefaultTemplateUuid) { + DbSession dbSession = db.getSession(); + db.getDbClient().organizationDao().setDefaultTemplates(dbSession, defaultOrganization.getUuid(), + new DefaultTemplates() + .setProjectUuid(projectDefaultTemplateUuid) + .setApplicationsUuid(applicationDefaultTemplateUuid) + .setPortfoliosUuid(portfoliosDefaultTemplateUuid)); + dbSession.commit(); + } + + public void addMember(OrganizationDto organization, UserDto... users) { + Arrays.stream(users) + .forEach(u -> db.getDbClient().organizationMemberDao().insert(db.getSession(), new OrganizationMemberDto().setOrganizationUuid(organization.getUuid()).setUserId(u.getId()))); + db.commit(); + } + + public void setNewProjectPrivate(OrganizationDto organization, boolean newProjectPrivate) { + db.getDbClient().organizationDao().setNewProjectPrivate(db.getSession(), organization, newProjectPrivate); + db.commit(); + } + + public boolean getNewProjectPrivate(OrganizationDto organization) { + return db.getDbClient().organizationDao().getNewProjectPrivate(db.getSession(), organization); + } + + public void assertUserIsMemberOfOrganization(OrganizationDto organization, UserDto user) { + assertThat(db.getDbClient().organizationMemberDao().select(db.getSession(), organization.getUuid(), user.getId())).as("User is not member of the organization").isPresent(); + Integer defaultGroupId = db.getDbClient().organizationDao().getDefaultGroupId(db.getSession(), organization.getUuid()).get(); + assertThat(db.getDbClient().groupMembershipDao().selectGroups( + db.getSession(), + GroupMembershipQuery.builder().membership(IN).organizationUuid(organization.getUuid()).build(), + user.getId(), 0, 10)) + .extracting(GroupMembershipDto::getId) + .as("User is not member of the default group of the organization") + .containsOnly(defaultGroupId.longValue()); + } + + public void assertUserIsNotMemberOfOrganization(OrganizationDto organization, UserDto user) { + assertThat(db.getDbClient().organizationMemberDao().select(db.getSession(), organization.getUuid(), user.getId())).as("User is still member of the organization") + .isNotPresent(); + assertThat(db.getDbClient().groupMembershipDao().countGroups(db.getSession(), + GroupMembershipQuery.builder().membership(IN).organizationUuid(organization.getUuid()).build(), + user.getId())).isZero(); + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/organization/OrganizationTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/organization/OrganizationTesting.java new file mode 100644 index 00000000000..57f1b59a289 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/organization/OrganizationTesting.java @@ -0,0 +1,46 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.organization; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.sonar.db.organization.OrganizationDto.Subscription.FREE; + +public class OrganizationTesting { + + private OrganizationTesting() { + // only statics + } + + /** + * Creates a new {@link OrganizationDto} with randomly generated field values. + */ + public static OrganizationDto newOrganizationDto() { + return new OrganizationDto() + .setKey(randomAlphanumeric(32)) + .setUuid(randomAlphanumeric(40)) + .setName(randomAlphanumeric(64)) + .setDescription(randomAlphanumeric(256)) + .setAvatarUrl(randomAlphanumeric(256)) + // Default quality gate should be set explicitly when needed in tests + .setDefaultQualityGateUuid("_NOT_SET_") + .setSubscription(FREE) + .setUrl(randomAlphanumeric(256)); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/PermissionsTestHelper.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/PermissionsTestHelper.java new file mode 100644 index 00000000000..3eb75f13258 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/PermissionsTestHelper.java @@ -0,0 +1,34 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.permission; + +import com.google.common.collect.ImmutableSet; +import java.util.Set; +import org.sonar.api.web.UserRole; +import org.sonar.core.permission.GlobalPermissions; + +public class PermissionsTestHelper { + + public static final Set ALL_PERMISSIONS = ImmutableSet.of(UserRole.ADMIN, UserRole.CODEVIEWER, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, + GlobalPermissions.SCAN_EXECUTION, UserRole.USER, OrganizationPermission.APPLICATION_CREATOR.getKey(), OrganizationPermission.PORTFOLIO_CREATOR.getKey()); + + private PermissionsTestHelper() { + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateDbTester.java new file mode 100644 index 00000000000..35e48b0d6f7 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateDbTester.java @@ -0,0 +1,92 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.permission.template; + +import javax.annotation.Nullable; +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.user.GroupDto; +import org.sonar.db.user.UserDto; + +import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateCharacteristicDto; +import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto; + +public class PermissionTemplateDbTester { + private final DbTester db; + private final DbClient dbClient; + private final DbSession dbSession; + + public PermissionTemplateDbTester(DbTester db) { + this.db = db; + this.dbClient = db.getDbClient(); + this.dbSession = db.getSession(); + } + + public PermissionTemplateDto insertTemplate() { + return insertTemplate(newPermissionTemplateDto()); + } + + public PermissionTemplateDto insertTemplate(OrganizationDto organizationDto) { + return insertTemplate(newPermissionTemplateDto().setOrganizationUuid(organizationDto.getUuid())); + } + + public PermissionTemplateDto insertTemplate(PermissionTemplateDto template) { + PermissionTemplateDto templateInDb = dbClient.permissionTemplateDao().insert(dbSession, template); + db.commit(); + + return templateInDb; + } + + public void addGroupToTemplate(PermissionTemplateDto permissionTemplate, GroupDto group, String permission) { + addGroupToTemplate(permissionTemplate.getId(), group.getId(), permission); + } + + public void addGroupToTemplate(long templateId, @Nullable Integer groupId, String permission) { + dbClient.permissionTemplateDao().insertGroupPermission(dbSession, templateId, groupId, permission); + db.commit(); + } + + public void addAnyoneToTemplate(PermissionTemplateDto permissionTemplate, String permission) { + addGroupToTemplate(permissionTemplate.getId(), null, permission); + } + + public void addUserToTemplate(PermissionTemplateDto permissionTemplate, UserDto user, String permission) { + addUserToTemplate(permissionTemplate.getId(), user.getId(), permission); + } + + public void addUserToTemplate(long templateId, int userId, String permission) { + dbClient.permissionTemplateDao().insertUserPermission(dbSession, templateId, userId, permission); + db.commit(); + } + + public void addProjectCreatorToTemplate(PermissionTemplateDto permissionTemplate, String permission) { + addProjectCreatorToTemplate(permissionTemplate.getId(), permission); + } + + public void addProjectCreatorToTemplate(long templateId, String permission) { + dbClient.permissionTemplateCharacteristicDao().insert(dbSession, newPermissionTemplateCharacteristicDto() + .setWithProjectCreator(true) + .setTemplateId(templateId) + .setPermission(permission)); + db.commit(); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateTesting.java new file mode 100644 index 00000000000..a029200457e --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateTesting.java @@ -0,0 +1,63 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.permission.template; + +import java.util.Date; +import org.apache.commons.lang.math.RandomUtils; +import org.sonar.core.util.Uuids; +import org.sonar.db.permission.PermissionsTestHelper; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang.RandomStringUtils.randomAscii; + +public class PermissionTemplateTesting { + public static PermissionTemplateDto newPermissionTemplateDto() { + return new PermissionTemplateDto() + .setName(randomAlphanumeric(60)) + .setDescription(randomAscii(500)) + .setOrganizationUuid(randomAlphanumeric(40)) + .setUuid(Uuids.create()) + .setCreatedAt(new Date()) + .setUpdatedAt(new Date()); + } + + public static PermissionTemplateUserDto newPermissionTemplateUserDto() { + return new PermissionTemplateUserDto() + .setPermission(PermissionsTestHelper.ALL_PERMISSIONS.toArray(new String[0])[RandomUtils.nextInt(PermissionsTestHelper.ALL_PERMISSIONS.size())]) + .setCreatedAt(new Date()) + .setUpdatedAt(new Date()); + } + + public static PermissionTemplateGroupDto newPermissionTemplateGroupDto() { + return new PermissionTemplateGroupDto() + .setPermission(PermissionsTestHelper.ALL_PERMISSIONS.toArray(new String[0])[RandomUtils.nextInt(PermissionsTestHelper.ALL_PERMISSIONS.size())]) + .setCreatedAt(new Date()) + .setUpdatedAt(new Date()); + } + + public static PermissionTemplateCharacteristicDto newPermissionTemplateCharacteristicDto() { + return new PermissionTemplateCharacteristicDto() + .setPermission(PermissionsTestHelper.ALL_PERMISSIONS.toArray(new String[0])[RandomUtils.nextInt(PermissionsTestHelper.ALL_PERMISSIONS.size())]) + .setWithProjectCreator(RandomUtils.nextBoolean()) + .setCreatedAt(System.currentTimeMillis()) + .setUpdatedAt(System.currentTimeMillis()); + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginDbTester.java new file mode 100644 index 00000000000..5fc1afab4e8 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginDbTester.java @@ -0,0 +1,46 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.plugin; + +import java.util.Arrays; +import java.util.function.Consumer; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; + +public class PluginDbTester { + private final DbClient dbClient; + private final DbSession dbSession; + + public PluginDbTester(DbTester db) { + this.dbClient = db.getDbClient(); + this.dbSession = db.getSession(); + } + + @SafeVarargs + public final PluginDto insertPlugin(Consumer... consumers) { + PluginDto pluginDto = PluginTesting.newPluginDto(); + Arrays.stream(consumers).forEach(c -> c.accept(pluginDto)); + dbClient.pluginDao().insert(dbSession, pluginDto); + dbSession.commit(); + return pluginDto; + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginTesting.java new file mode 100644 index 00000000000..e42b939864d --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginTesting.java @@ -0,0 +1,46 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.plugin; + +import org.sonar.core.util.Uuids; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang.math.RandomUtils.nextLong; + +public class PluginTesting { + + private PluginTesting() { + // prevent instantiation + } + + /** + * Create an instance of {@link PluginDto} with random field values. + */ + public static PluginDto newPluginDto() { + String uuid = Uuids.createFast(); + return new PluginDto() + .setUuid(uuid) + .setKee(uuid) + .setFileHash(randomAlphanumeric(32)) + .setCreatedAt(nextLong()) + .setUpdatedAt(nextLong()); + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/InternalComponentPropertyDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/InternalComponentPropertyDbTester.java new file mode 100644 index 00000000000..4588ad91853 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/InternalComponentPropertyDbTester.java @@ -0,0 +1,46 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.property; + +import java.util.Optional; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; + +public class InternalComponentPropertyDbTester { + private final DbTester db; + private final DbClient dbClient; + private final DbSession dbSession; + + public InternalComponentPropertyDbTester(DbTester db) { + this.db = db; + this.dbClient = db.getDbClient(); + this.dbSession = db.getSession(); + } + + public void insertProperty(String componentUuid, String key, String value) { + dbClient.internalComponentPropertiesDao().insertOrUpdate(dbSession, componentUuid, key, value); + db.commit(); + } + + public Optional getProperty(String componentUuid, String key) { + return dbClient.internalComponentPropertiesDao().selectByComponentUuidAndKey(dbSession, componentUuid, key); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/PropertyDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/PropertyDbTester.java new file mode 100644 index 00000000000..b00cc9f1964 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/PropertyDbTester.java @@ -0,0 +1,113 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.property; + +import com.google.common.base.Joiner; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Nullable; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; +import org.sonar.db.component.ComponentDto; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.sonar.db.property.PropertyTesting.newComponentPropertyDto; +import static org.sonar.db.property.PropertyTesting.newGlobalPropertyDto; + +public class PropertyDbTester { + private final DbTester db; + private final DbClient dbClient; + private final DbSession dbSession; + + public PropertyDbTester(DbTester db) { + this.db = db; + this.dbClient = db.getDbClient(); + this.dbSession = db.getSession(); + } + + public PropertyDto insertProperty(PropertyDto property) { + dbClient.propertiesDao().saveProperty(dbSession, property); + db.commit(); + + return property; + } + + public void insertProperties(PropertyDto... properties) { + insertProperties(asList(properties)); + } + + public void insertProperties(List properties) { + for (PropertyDto propertyDto : properties) { + dbClient.propertiesDao().saveProperty(dbSession, propertyDto); + } + dbSession.commit(); + } + + public void insertPropertySet(String settingBaseKey, @Nullable ComponentDto componentDto, Map... fieldValues) { + int index = 1; + List propertyDtos = new ArrayList<>(); + List ids = new ArrayList<>(); + for (Map fieldValue : fieldValues) { + for (Map.Entry entry : fieldValue.entrySet()) { + String key = settingBaseKey + "." + index + "." + entry.getKey(); + if (componentDto != null) { + propertyDtos.add(newComponentPropertyDto(componentDto).setKey(key).setValue(entry.getValue())); + } else { + propertyDtos.add(newGlobalPropertyDto().setKey(key).setValue(entry.getValue())); + } + } + ids.add(Integer.toString(index)); + index++; + } + String idsValue = Joiner.on(",").join(ids); + if (componentDto != null) { + propertyDtos.add(newComponentPropertyDto(componentDto).setKey(settingBaseKey).setValue(idsValue)); + } else { + propertyDtos.add(newGlobalPropertyDto().setKey(settingBaseKey).setValue(idsValue)); + } + insertProperties(propertyDtos); + } + + public PropertyDbTester verifyInternal(String key, @Nullable String expectedValue) { + Optional value = dbClient.internalPropertiesDao().selectByKey(dbSession, key); + if (expectedValue == null) { + assertThat(value).isEmpty(); + } else { + assertThat(value).hasValue(expectedValue); + } + return this; + } + + public PropertyDbTester insertInternal(String key, String value) { + dbClient.internalPropertiesDao().save(dbSession, key, value); + dbSession.commit(); + return this; + } + + public PropertyDbTester insertEmptyInternal(String key) { + dbClient.internalPropertiesDao().saveAsEmpty(dbSession, key); + dbSession.commit(); + return this; + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/PropertyTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/PropertyTesting.java new file mode 100644 index 00000000000..904f350cf9a --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/PropertyTesting.java @@ -0,0 +1,98 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.property; + +import javax.annotation.Nullable; +import org.apache.commons.lang.math.RandomUtils; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.user.UserDto; + +import static com.google.common.base.Preconditions.checkNotNull; + +public class PropertyTesting { + + private static int cursor = RandomUtils.nextInt(100); + + private PropertyTesting() { + // static methods only + } + + public static PropertyDto newGlobalPropertyDto(String key, String value) { + return newPropertyDto(key, value, (Long) null, null); + } + + public static PropertyDto newGlobalPropertyDto() { + return newPropertyDto((Long) null, null); + } + + public static PropertyDto newComponentPropertyDto(String key, String value, ComponentDto component) { + checkNotNull(component.getId()); + return newPropertyDto(key, value, component.getId(), null); + } + + public static PropertyDto newComponentPropertyDto(ComponentDto component) { + checkNotNull(component.getId()); + return newPropertyDto(component.getId(), null); + } + + public static PropertyDto newUserPropertyDto(String key, String value, UserDto user) { + checkNotNull(user.getId()); + return newPropertyDto(key, value, null, user.getId()); + } + + public static PropertyDto newUserPropertyDto(UserDto user) { + checkNotNull(user.getId()); + return newPropertyDto(null, user.getId()); + } + + public static PropertyDto newPropertyDto(String key, String value, ComponentDto component, UserDto user) { + checkNotNull(component.getId()); + checkNotNull(user.getId()); + return newPropertyDto(key, value, component.getId(), user.getId()); + } + + public static PropertyDto newPropertyDto(ComponentDto component, UserDto user) { + checkNotNull(component.getId()); + checkNotNull(user.getId()); + return newPropertyDto(component.getId(), user.getId()); + } + + private static PropertyDto newPropertyDto(@Nullable Long componentId, @Nullable Integer userId) { + String key = String.valueOf(cursor); + cursor++; + String value = String.valueOf(cursor); + cursor++; + return newPropertyDto(key, value, componentId, userId); + } + + private static PropertyDto newPropertyDto(String key, String value, @Nullable Long componentId, @Nullable Integer userId) { + PropertyDto propertyDto = new PropertyDto() + .setKey(key) + .setValue(value); + if (componentId != null) { + propertyDto.setResourceId(componentId); + } + if (userId != null) { + propertyDto.setUserId(userId); + } + return propertyDto; + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualitygate/QualityGateDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualitygate/QualityGateDbTester.java new file mode 100644 index 00000000000..6b72f94b4a2 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualitygate/QualityGateDbTester.java @@ -0,0 +1,109 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.qualitygate; + +import java.util.Arrays; +import java.util.Date; +import java.util.Optional; +import java.util.function.Consumer; +import org.sonar.core.util.Uuids; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.metric.MetricDto; +import org.sonar.db.organization.OrganizationDto; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang.RandomStringUtils.randomNumeric; + +public class QualityGateDbTester { + + private final DbTester db; + private final DbClient dbClient; + private final DbSession dbSession; + + public QualityGateDbTester(DbTester db) { + this.db = db; + this.dbClient = db.getDbClient(); + this.dbSession = db.getSession(); + } + + public QualityGateDto insertBuiltInQualityGate() { + QualityGateDto builtin = dbClient.qualityGateDao().insert(dbSession, new QualityGateDto() + .setName("Sonar way") + .setUuid(Uuids.createFast()) + .setBuiltIn(true) + .setCreatedAt(new Date())); + dbSession.commit(); + return builtin; + } + + @SafeVarargs + public final QGateWithOrgDto insertQualityGate(OrganizationDto organization, Consumer... dtoPopulators) { + QualityGateDto qualityGate = new QualityGateDto() + .setName(randomAlphanumeric(30)) + .setUuid(Uuids.createFast()) + .setBuiltIn(false); + Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(qualityGate)); + dbClient.qualityGateDao().insert(dbSession, qualityGate); + dbClient.qualityGateDao().associate(dbSession, Uuids.createFast(), organization, qualityGate); + db.commit(); + return dbClient.qualityGateDao().selectByOrganizationAndUuid(dbSession, organization, qualityGate.getUuid()); + } + + public void associateProjectToQualityGate(ComponentDto component, QualityGateDto qualityGate) { + dbClient.projectQgateAssociationDao().insertProjectQGateAssociation(dbSession, component.uuid(), qualityGate.getUuid()); + db.commit(); + } + + public void associateQualityGateToOrganization(QualityGateDto qualityGate, OrganizationDto organization) { + dbClient.qualityGateDao().associate(dbSession, Uuids.createFast(), organization, qualityGate); + db.commit(); + } + + @SafeVarargs + public final QualityGateDto createDefaultQualityGate(OrganizationDto organization, Consumer... dtoPopulators) { + QualityGateDto defaultQGate = insertQualityGate(organization, dtoPopulators); + setDefaultQualityGate(organization, defaultQGate); + return defaultQGate; + } + + public void setDefaultQualityGate(OrganizationDto organization, QualityGateDto qualityGate) { + dbClient.organizationDao().update(dbSession, organization.setDefaultQualityGateUuid(qualityGate.getUuid())); + dbSession.commit(); + } + + @SafeVarargs + public final QualityGateConditionDto addCondition(QualityGateDto qualityGate, MetricDto metric, Consumer... dtoPopulators) { + QualityGateConditionDto condition = new QualityGateConditionDto().setQualityGateId(qualityGate.getId()) + .setMetricId(metric.getId()) + .setOperator("GT") + .setErrorThreshold(randomNumeric(10)); + Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(condition)); + dbClient.gateConditionDao().insert(condition, dbSession); + db.commit(); + return condition; + } + + public Optional selectQGateUuidByComponentUuid(String componentUuid) { + return dbClient.projectQgateAssociationDao().selectQGateUuidByComponentUuid(dbSession, componentUuid); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileDbTester.java new file mode 100644 index 00000000000..d2ba860709e --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileDbTester.java @@ -0,0 +1,135 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.qualityprofile; + +import java.util.Arrays; +import java.util.Optional; +import java.util.function.Consumer; +import org.sonar.api.rule.Severity; +import org.sonar.core.util.Uuids; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.organization.OrganizationDto; +import org.sonar.db.rule.RuleDefinitionDto; +import org.sonar.db.user.GroupDto; +import org.sonar.db.user.UserDto; + +import static com.google.common.base.Preconditions.checkArgument; +import static org.apache.commons.lang.math.RandomUtils.nextInt; +import static org.apache.commons.lang.math.RandomUtils.nextLong; +import static org.sonar.db.qualityprofile.ActiveRuleDto.createFor; + +public class QualityProfileDbTester { + private final DbClient dbClient; + private final DbSession dbSession; + + public QualityProfileDbTester(DbTester dbTester) { + this.dbClient = dbTester.getDbClient(); + this.dbSession = dbTester.getSession(); + } + + public Optional selectByUuid(String uuid) { + return Optional.ofNullable(dbClient.qualityProfileDao().selectByUuid(dbSession, uuid)); + } + + /** + * Create a profile with random field values on the specified organization. + */ + public QProfileDto insert(OrganizationDto organization) { + return insert(organization, c -> { + }); + } + + /** + * Create a profile with random field values on the specified organization. + */ + public QProfileDto insert(OrganizationDto organization, Consumer consumer) { + QProfileDto profile = QualityProfileTesting.newQualityProfileDto() + .setOrganizationUuid(organization.getUuid()); + consumer.accept(profile); + + dbClient.qualityProfileDao().insert(dbSession, profile); + dbSession.commit(); + return profile; + } + + public QualityProfileDbTester insert(QProfileDto profile, QProfileDto... others) { + dbClient.qualityProfileDao().insert(dbSession, profile); + Arrays.stream(others).forEach(p -> dbClient.qualityProfileDao().insert(dbSession, p)); + dbSession.commit(); + return this; + } + + public QualityProfileDbTester associateWithProject(ComponentDto project, QProfileDto profile, QProfileDto... otherProfiles) { + dbClient.qualityProfileDao().insertProjectProfileAssociation(dbSession, project, profile); + for (QProfileDto p : otherProfiles) { + dbClient.qualityProfileDao().insertProjectProfileAssociation(dbSession, project, p); + } + dbSession.commit(); + return this; + } + + public ActiveRuleDto activateRule(QProfileDto profile, RuleDefinitionDto rule) { + return activateRule(profile, rule, ar -> { + }); + } + + public ActiveRuleDto activateRule(QProfileDto profile, RuleDefinitionDto rule, Consumer consumer) { + ActiveRuleDto activeRule = createFor(profile, rule) + .setSeverity(Severity.ALL.get(nextInt(Severity.ALL.size()))) + .setCreatedAt(nextLong()) + .setUpdatedAt(nextLong()); + consumer.accept(activeRule); + dbClient.activeRuleDao().insert(dbSession, activeRule); + dbSession.commit(); + return activeRule; + } + + public QualityProfileDbTester setAsDefault(QProfileDto profile, QProfileDto... others) { + dbClient.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(profile)); + for (QProfileDto other : others) { + dbClient.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(other)); + } + dbSession.commit(); + return this; + } + + public void addUserPermission(QProfileDto profile, UserDto user){ + checkArgument(!profile.isBuiltIn(), "Built-In profile cannot be used"); + dbClient.qProfileEditUsersDao().insert(dbSession, new QProfileEditUsersDto() + .setUuid(Uuids.createFast()) + .setUserId(user.getId()) + .setQProfileUuid(profile.getKee()) + ); + dbSession.commit(); + } + + public void addGroupPermission(QProfileDto profile, GroupDto group){ + checkArgument(!profile.isBuiltIn(), "Built-In profile cannot be used"); + dbClient.qProfileEditGroupsDao().insert(dbSession, new QProfileEditGroupsDto() + .setUuid(Uuids.createFast()) + .setGroupId(group.getId()) + .setQProfileUuid(profile.getKee()) + ); + dbSession.commit(); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileTesting.java new file mode 100644 index 00000000000..0ef23d5ad99 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileTesting.java @@ -0,0 +1,75 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.qualityprofile; + +import java.util.function.Consumer; +import org.sonar.core.util.Uuids; + +import static java.util.Arrays.stream; +import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang.math.RandomUtils.nextLong; + +public class QualityProfileTesting { + + private QualityProfileTesting() { + // prevent instantiation + } + + /** + * Create an instance of {@link QProfileDto} with random field values. + */ + public static QProfileDto newQualityProfileDto() { + String uuid = Uuids.createFast(); + return new QProfileDto() + .setKee(uuid) + .setRulesProfileUuid(Uuids.createFast()) + .setOrganizationUuid(randomAlphanumeric(40)) + .setName(uuid) + .setLanguage(randomAlphanumeric(20)) + .setLastUsed(nextLong()); + } + + /** + * Create an instance of {@link QProfileChangeDto} with random field values, + * except changeType which is always {@code "ACTIVATED"}. + */ + public static QProfileChangeDto newQProfileChangeDto() { + return new QProfileChangeDto() + .setUuid(randomAlphanumeric(40)) + .setRulesProfileUuid(randomAlphanumeric(40)) + .setCreatedAt(nextLong()) + .setChangeType("ACTIVATED") + .setUserUuid("userUuid_" + randomAlphanumeric(10)); + } + + /** + * Create an instance of {@link RulesProfileDto} with most of random field values. + */ + public static RulesProfileDto newRuleProfileDto(Consumer... populators) { + RulesProfileDto dto = new RulesProfileDto() + .setKee("uuid" + randomAlphabetic(10)) + .setName("name" + randomAlphabetic(10)) + .setLanguage("lang" + randomAlphabetic(5)) + .setIsBuiltIn(false); + stream(populators).forEach(p -> p.accept(dto)); + return dto; + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleDbTester.java new file mode 100644 index 00000000000..5e1c497f11f --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleDbTester.java @@ -0,0 +1,164 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.rule; + +import java.util.function.Consumer; +import org.sonar.api.rule.RuleKey; +import org.sonar.api.server.rule.RuleParamType; +import org.sonar.db.DbTester; +import org.sonar.db.organization.OrganizationDto; +import org.sonar.db.user.UserDto; + +import static java.util.Arrays.asList; +import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; +import static org.sonar.db.rule.RuleTesting.newDeprecatedRuleKey; +import static org.sonar.db.rule.RuleTesting.newRule; +import static org.sonar.db.rule.RuleTesting.newRuleDto; + +public class RuleDbTester { + + private final DbTester db; + + public RuleDbTester(DbTester db) { + this.db = db; + } + + public RuleDefinitionDto insert() { + return insert(newRule()); + } + + public RuleDefinitionDto insert(RuleKey key) { + return insert(newRule(key)); + } + + @SafeVarargs + public final RuleDefinitionDto insert(Consumer... populaters) { + RuleDefinitionDto rule = newRule(); + asList(populaters).forEach(populater -> populater.accept(rule)); + return insert(rule); + } + + public RuleDefinitionDto insert(RuleKey key, Consumer populater) { + RuleDefinitionDto rule = newRule(key); + populater.accept(rule); + return insert(rule); + } + + public RuleDefinitionDto insert(RuleDefinitionDto rule) { + db.getDbClient().ruleDao().insert(db.getSession(), rule); + db.commit(); + return rule; + } + + public RuleDefinitionDto update(RuleDefinitionDto rule) { + db.getDbClient().ruleDao().update(db.getSession(), rule); + db.commit(); + return rule; + } + + @SafeVarargs + public final RuleMetadataDto insertOrUpdateMetadata(RuleDefinitionDto rule, OrganizationDto organization, Consumer... populaters) { + RuleMetadataDto dto = RuleTesting.newRuleMetadata(rule, organization); + asList(populaters).forEach(populater -> populater.accept(dto)); + return insertOrUpdateMetadata(dto); + } + + @SafeVarargs + public final RuleMetadataDto insertOrUpdateMetadata(RuleDefinitionDto rule, UserDto noteUser, OrganizationDto organization, Consumer... populaters) { + RuleMetadataDto dto = RuleTesting.newRuleMetadata(rule, noteUser, organization); + asList(populaters).forEach(populater -> populater.accept(dto)); + return insertOrUpdateMetadata(dto); + } + + public RuleMetadataDto insertOrUpdateMetadata(RuleMetadataDto metadata) { + db.getDbClient().ruleDao().insertOrUpdate(db.getSession(), metadata); + db.commit(); + return metadata; + } + + public RuleParamDto insertRuleParam(RuleDefinitionDto rule) { + return insertRuleParam(rule, p -> { + }); + } + + @SafeVarargs + public final RuleParamDto insertRuleParam(RuleDefinitionDto rule, Consumer... populaters) { + RuleParamDto param = RuleTesting.newRuleParam(rule); + asList(populaters).forEach(populater -> populater.accept(param)); + db.getDbClient().ruleDao().insertRuleParam(db.getSession(), rule, param); + db.commit(); + return param; + } + + public RuleDto insertRule(RuleDto ruleDto) { + insert(ruleDto.getDefinition()); + RuleMetadataDto metadata = ruleDto.getMetadata(); + if (metadata.getOrganizationUuid() != null) { + db.getDbClient().ruleDao().insertOrUpdate(db.getSession(), metadata.setRuleId(ruleDto.getId())); + db.commit(); + } + return ruleDto; + } + + /** + * Create and persist a rule with random values. + */ + public RuleDto insertRule() { + return insertRule(rule -> { + }); + } + + @SafeVarargs + public final RuleDto insertRule(OrganizationDto organization, Consumer... populaters) { + RuleDto ruleDto = newRuleDto(organization); + asList(populaters).forEach(populater -> populater.accept(ruleDto)); + return insertRule(ruleDto); + } + + public RuleDto insertRule(Consumer populateRuleDto) { + RuleDto ruleDto = newRuleDto(); + populateRuleDto.accept(ruleDto); + return insertRule(ruleDto); + } + + @SafeVarargs + public final DeprecatedRuleKeyDto insertDeprecatedKey(Consumer... deprecatedRuleKeyDtoConsumers) { + DeprecatedRuleKeyDto deprecatedRuleKeyDto = newDeprecatedRuleKey(); + asList(deprecatedRuleKeyDtoConsumers).forEach(c -> c.accept(deprecatedRuleKeyDto)); + db.getDbClient().ruleDao().insert(db.getSession(), deprecatedRuleKeyDto); + return deprecatedRuleKeyDto; + } + + public RuleParamDto insertRuleParam(RuleDto rule) { + RuleParamDto param = new RuleParamDto(); + param.setRuleId(rule.getId()); + param.setName(randomAlphabetic(10)); + param.setType(RuleParamType.STRING.type()); + db.getDbClient().ruleDao().insertRuleParam(db.getSession(), rule.getDefinition(), param); + db.commit(); + return param; + } + + public RuleDto insertRule(RuleDefinitionDto ruleDefinition, RuleMetadataDto ruleMetadata) { + db.getDbClient().ruleDao().insertOrUpdate(db.getSession(), ruleMetadata.setRuleId(ruleDefinition.getId())); + db.commit(); + return new RuleDto(ruleDefinition, ruleMetadata); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java new file mode 100644 index 00000000000..9df18d86726 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java @@ -0,0 +1,352 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.rule; + +import com.google.common.collect.ImmutableSet; +import java.util.Date; +import java.util.Set; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import org.sonar.api.rule.RuleKey; +import org.sonar.api.rule.RuleStatus; +import org.sonar.api.rule.Severity; +import org.sonar.api.rules.RuleType; +import org.sonar.api.server.rule.RuleParamType; +import org.sonar.core.util.UuidFactory; +import org.sonar.core.util.UuidFactoryFast; +import org.sonar.db.organization.OrganizationDto; +import org.sonar.db.rule.RuleDto.Format; +import org.sonar.db.rule.RuleDto.Scope; +import org.sonar.db.user.UserDto; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.ImmutableSet.copyOf; +import static com.google.common.collect.Sets.newHashSet; +import static java.util.Objects.requireNonNull; +import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang.math.RandomUtils.nextInt; +import static org.sonar.api.rule.RuleKey.EXTERNAL_RULE_REPO_PREFIX; + +/** + * Utility class for tests involving rules + */ +public class RuleTesting { + + public static final RuleKey EXTERNAL_XOO = RuleKey.of(EXTERNAL_RULE_REPO_PREFIX + "xoo", "x1"); + public static final RuleKey XOO_X1 = RuleKey.of("xoo", "x1"); + public static final RuleKey XOO_X2 = RuleKey.of("xoo", "x2"); + public static final RuleKey XOO_X3 = RuleKey.of("xoo", "x3"); + + private static final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); + + private RuleTesting() { + // only static helpers + } + + public static RuleDefinitionDto newRule() { + return newRule(randomRuleKey()); + } + + public static RuleDefinitionDto newRule(RuleKey key) { + return new RuleDefinitionDto() + .setRepositoryKey(key.repository()) + .setRuleKey(key.rule()) + .setId(nextInt(100_000)) + .setName("name_" + randomAlphanumeric(5)) + .setDescription("description_" + randomAlphanumeric(5)) + .setDescriptionFormat(Format.HTML) + .setType(RuleType.values()[nextInt(RuleType.values().length)]) + .setStatus(RuleStatus.READY) + .setConfigKey("configKey_" + randomAlphanumeric(5)) + .setSeverity(Severity.ALL.get(nextInt(Severity.ALL.size()))) + .setIsTemplate(false) + .setIsExternal(false) + .setIsAdHoc(false) + .setSystemTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5))) + .setLanguage("lang_" + randomAlphanumeric(3)) + .setGapDescription("gapDescription_" + randomAlphanumeric(5)) + .setDefRemediationBaseEffort(nextInt(10) + "h") + .setDefRemediationGapMultiplier(nextInt(10) + "h") + .setDefRemediationFunction("LINEAR_OFFSET") + .setCreatedAt(System.currentTimeMillis()) + .setUpdatedAt(System.currentTimeMillis()) + .setScope(Scope.MAIN); + } + + public static RuleMetadataDto newRuleMetadata() { + return new RuleMetadataDto() + .setRuleId(nextInt(100_000)) + .setOrganizationUuid("org_" + randomAlphanumeric(5)) + .setRemediationBaseEffort(nextInt(10) + "h") + .setRemediationGapMultiplier(nextInt(10) + "h") + .setRemediationFunction("LINEAR_OFFSET") + .setTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5))) + .setNoteData("noteData_" + randomAlphanumeric(5)) + .setNoteUserUuid("noteUserUuid_" + randomAlphanumeric(5)) + .setNoteCreatedAt(System.currentTimeMillis() - 200) + .setNoteUpdatedAt(System.currentTimeMillis() - 150) + .setAdHocName("adHocName_" + randomAlphanumeric(5)) + .setAdHocDescription("adHocDescription_" + randomAlphanumeric(5)) + .setAdHocSeverity(Severity.ALL.get(nextInt(Severity.ALL.size()))) + .setAdHocType(RuleType.values()[nextInt(RuleType.values().length - 1)]) + .setCreatedAt(System.currentTimeMillis() - 100) + .setUpdatedAt(System.currentTimeMillis() - 50); + } + + public static RuleMetadataDto newRuleMetadata(RuleDefinitionDto rule, OrganizationDto organization) { + return newRuleMetadata() + .setRuleId(rule.getId()) + .setOrganizationUuid(organization.getUuid()); + } + + public static RuleMetadataDto newRuleMetadata(RuleDefinitionDto rule, UserDto noteUser, OrganizationDto organization) { + return newRuleMetadata(rule, organization) + .setNoteUserUuid(noteUser.getUuid()); + } + + public static RuleParamDto newRuleParam(RuleDefinitionDto rule) { + return new RuleParamDto() + .setRuleId(rule.getId()) + .setName("name_" + randomAlphabetic(5)) + .setDefaultValue("default_" + randomAlphabetic(5)) + .setDescription("description_" + randomAlphabetic(5)) + .setType(RuleParamType.STRING.type()); + } + + public static DeprecatedRuleKeyDto newDeprecatedRuleKey() { + return new DeprecatedRuleKeyDto() + .setUuid(uuidFactory.create()) + .setOldRepositoryKey(randomAlphanumeric(50)) + .setOldRuleKey(randomAlphanumeric(50)) + .setRuleId(nextInt(100_000)) + .setCreatedAt(System.currentTimeMillis()); + } + + /** + * @deprecated use newRule(...) + */ + @Deprecated + public static RuleDto newXooX1() { + return newDto(XOO_X1).setLanguage("xoo"); + } + + /** + * @deprecated use newRule(...) + */ + @Deprecated + public static RuleDto newXooX1(OrganizationDto organization) { + return newDto(XOO_X1, requireNonNull(organization, "organization can't be null")).setLanguage("xoo"); + } + + /** + * @deprecated use newRule(...) + */ + @Deprecated + public static RuleDto newXooX2() { + return newDto(XOO_X2).setLanguage("xoo"); + } + + /** + * @deprecated use newRule(...) + */ + @Deprecated + public static RuleDto newXooX2(OrganizationDto organization) { + return newDto(XOO_X2, requireNonNull(organization, "organization can't be null")).setLanguage("xoo"); + } + + /** + * @deprecated use newRule(...) + */ + @Deprecated + public static RuleDto newXooX3() { + return newDto(XOO_X3).setLanguage("xoo"); + } + + /** + * @deprecated use newRule(...) + */ + @Deprecated + public static RuleDto newXooX3(OrganizationDto organization) { + return newDto(XOO_X3, requireNonNull(organization, "organization can't be null")).setLanguage("xoo"); + } + + /** + * @deprecated use newRule(...) + */ + @Deprecated + public static RuleDto newDto(RuleKey ruleKey) { + return newDto(ruleKey, null); + } + + /** + * @deprecated use newRule(...) + */ + @Deprecated + public static RuleDto newDto(RuleKey ruleKey, @Nullable OrganizationDto organization) { + RuleDto res = new RuleDto() + .setRuleKey(ruleKey.rule()) + .setRepositoryKey(ruleKey.repository()) + .setName("Rule " + ruleKey.rule()) + .setDescription("Description " + ruleKey.rule()) + .setDescriptionFormat(Format.HTML) + .setStatus(RuleStatus.READY) + .setConfigKey("InternalKey" + ruleKey.rule()) + .setSeverity(Severity.INFO) + .setIsTemplate(false) + .setSystemTags(ImmutableSet.of("systag1", "systag2")) + .setLanguage("js") + .setDefRemediationFunction("LINEAR_OFFSET") + .setDefRemediationGapMultiplier("5d") + .setDefRemediationBaseEffort("10h") + .setGapDescription(ruleKey.repository() + "." + ruleKey.rule() + ".effortToFix") + .setType(RuleType.CODE_SMELL) + .setCreatedAt(new Date().getTime()) + .setUpdatedAt(new Date().getTime()) + .setScope(Scope.MAIN); + if (organization != null) { + res + .setOrganizationUuid(organization.getUuid()) + .setTags(ImmutableSet.of("tag1", "tag2")) + .setRemediationFunction("LINEAR") + .setRemediationGapMultiplier("1h"); + } + return res; + } + + /** + * @deprecated use newRule(...) + */ + @Deprecated + public static RuleDto newRuleDto() { + return newDto(RuleKey.of(randomAlphanumeric(30), randomAlphanumeric(30))); + } + + /** + * @deprecated use newRule(...) + */ + @Deprecated + public static RuleDto newRuleDto(OrganizationDto organization) { + return newDto(RuleKey.of(randomAlphanumeric(30), randomAlphanumeric(30)), organization); + } + + public static RuleDto newTemplateRule(RuleKey ruleKey) { + return newDto(ruleKey) + .setIsTemplate(true); + } + + public static RuleDto newTemplateRule(RuleKey ruleKey, OrganizationDto organization) { + return newDto(ruleKey, organization) + .setIsTemplate(true); + } + + /** + * @deprecated use {@link #newCustomRule(RuleDefinitionDto)} + */ + @Deprecated + public static RuleDto newCustomRule(RuleDto templateRule) { + checkNotNull(templateRule.getId(), "The template rule need to be persisted before creating this custom rule."); + return newDto(RuleKey.of(templateRule.getRepositoryKey(), templateRule.getRuleKey() + "_" + System.currentTimeMillis())) + .setLanguage(templateRule.getLanguage()) + .setTemplateId(templateRule.getId()) + .setType(templateRule.getType()); + } + + public static RuleDefinitionDto newCustomRule(RuleDefinitionDto templateRule) { + checkNotNull(templateRule.getId(), "The template rule need to be persisted before creating this custom rule."); + return newRule(RuleKey.of(templateRule.getRepositoryKey(), templateRule.getRuleKey() + "_" + System.currentTimeMillis())) + .setLanguage(templateRule.getLanguage()) + .setTemplateId(templateRule.getId()) + .setType(templateRule.getType()); + } + + public static RuleKey randomRuleKey() { + return RuleKey.of("repo_" + randomAlphanumeric(3), "rule_" + randomAlphanumeric(3)); + } + + public static RuleKey randomRuleKeyOfMaximumLength() { + return RuleKey.of(randomAlphabetic(255), randomAlphabetic(200)); + } + + public static Consumer setRepositoryKey(String repositoryKey) { + return rule -> rule.setRepositoryKey(repositoryKey); + } + + public static Consumer setCreatedAt(long createdAt) { + return rule -> rule.setCreatedAt(createdAt); + } + + public static Consumer setUpdatedAt(long updatedtAt) { + return rule -> rule.setUpdatedAt(updatedtAt); + } + + public static Consumer setRuleKey(String ruleKey) { + return rule -> rule.setRuleKey(ruleKey); + } + + public static Consumer setName(String name) { + return rule -> rule.setName(name); + } + + public static Consumer setLanguage(String language) { + return rule -> rule.setLanguage(language); + } + + public static Consumer setSeverity(String severity) { + return rule -> rule.setSeverity(severity); + } + + public static Consumer setStatus(RuleStatus status) { + return rule -> rule.setStatus(status); + } + + public static Consumer setType(RuleType type) { + return rule -> rule.setType(type); + } + + public static Consumer setIsExternal(boolean isExternal) { + return rule -> rule.setIsExternal(isExternal); + } + + public static Consumer setSecurityStandards(Set securityStandards) { + return rule -> rule.setSecurityStandards(securityStandards); + } + + public static Consumer setIsTemplate(boolean isTemplate) { + return rule -> rule.setIsTemplate(isTemplate); + } + + public static Consumer setTemplateId(@Nullable Integer templateId) { + return rule -> rule.setTemplateId(templateId); + } + + public static Consumer setSystemTags(String... tags) { + return rule -> rule.setSystemTags(copyOf(tags)); + } + + public static Consumer setOrganization(OrganizationDto organization) { + return rule -> rule.setOrganizationUuid(organization.getUuid()); + } + + public static Consumer setTags(String... tags) { + return rule -> rule.setTags(copyOf(tags)); + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/source/FileSourceTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/source/FileSourceTester.java new file mode 100644 index 00000000000..e450b0d8c63 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/source/FileSourceTester.java @@ -0,0 +1,99 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.source; + +import java.util.Arrays; +import java.util.Date; +import java.util.Random; +import java.util.function.Consumer; +import java.util.stream.IntStream; +import org.apache.commons.lang.math.RandomUtils; +import org.sonar.core.util.stream.MoreCollectors; +import org.sonar.db.DbTester; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.protobuf.DbFileSources; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; + +public class FileSourceTester { + + private final DbTester db; + + public FileSourceTester(DbTester db) { + this.db = db; + } + + @SafeVarargs + public final FileSourceDto insertFileSource(ComponentDto file, Consumer... dtoPopulators) { + FileSourceDto dto = new FileSourceDto() + .setProjectUuid(file.projectUuid()) + .setFileUuid(file.uuid()) + .setSrcHash(randomAlphanumeric(50)) + .setDataHash(randomAlphanumeric(50)) + .setLineHashes(IntStream.range(0, new Random().nextInt(21)).mapToObj(String::valueOf).collect(MoreCollectors.toList())) + .setRevision(randomAlphanumeric(100)) + .setSourceData(newRandomData(3).build()) + .setCreatedAt(new Date().getTime()) + .setUpdatedAt(new Date().getTime()); + Arrays.stream(dtoPopulators).forEach(c -> c.accept(dto)); + db.getDbClient().fileSourceDao().insert(db.getSession(), dto); + db.commit(); + dto.setId(db.getDbClient().fileSourceDao().selectByFileUuid(db.getSession(), dto.getFileUuid()).getId()); + return dto; + } + + @SafeVarargs + public final FileSourceDto insertFileSource(ComponentDto file, int numLines, Consumer... dtoPopulators) { + FileSourceDto dto = new FileSourceDto() + .setProjectUuid(file.projectUuid()) + .setFileUuid(file.uuid()) + .setSrcHash(randomAlphanumeric(50)) + .setDataHash(randomAlphanumeric(50)) + .setLineHashes(IntStream.range(0, numLines).mapToObj(String::valueOf).collect(MoreCollectors.toList())) + .setRevision(randomAlphanumeric(100)) + .setSourceData(newRandomData(numLines).build()) + .setCreatedAt(new Date().getTime()) + .setUpdatedAt(new Date().getTime()); + Arrays.stream(dtoPopulators).forEach(c -> c.accept(dto)); + db.getDbClient().fileSourceDao().insert(db.getSession(), dto); + db.commit(); + return dto; + } + + private static DbFileSources.Data.Builder newRandomData(int numberOfLines) { + DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder(); + for (int i = 1; i <= numberOfLines; i++) { + dataBuilder.addLinesBuilder() + .setLine(i) + .setScmRevision(randomAlphanumeric(15)) + .setScmAuthor(randomAlphanumeric(10)) + .setScmDate(RandomUtils.nextLong()) + .setSource(randomAlphanumeric(20)) + .setLineHits(RandomUtils.nextInt(4)) + .setConditions(RandomUtils.nextInt(4)) + .setCoveredConditions(RandomUtils.nextInt(4)) + .setHighlighting(randomAlphanumeric(40)) + .setSymbols(randomAlphanumeric(30)) + .addAllDuplication(Arrays.asList(RandomUtils.nextInt(200), RandomUtils.nextInt(200))) + .build(); + } + return dataBuilder; + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/GroupTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/GroupTesting.java new file mode 100644 index 00000000000..cfb6379e188 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/GroupTesting.java @@ -0,0 +1,44 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.user; + +import java.util.Date; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang.math.RandomUtils.nextInt; +import static org.apache.commons.lang.math.RandomUtils.nextLong; + +public class GroupTesting { + + private GroupTesting() { + // only statics + } + + public static GroupDto newGroupDto() { + GroupDto group = new GroupDto() + .setId(nextInt()) + .setOrganizationUuid(randomAlphanumeric(40)) + .setName(randomAlphanumeric(255)) + .setDescription(randomAlphanumeric(200)) + .setCreatedAt(new Date(nextLong())) + .setUpdatedAt(new Date(nextLong())); + return group; + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/RootFlagAssertions.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/RootFlagAssertions.java new file mode 100644 index 00000000000..0b84443f834 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/RootFlagAssertions.java @@ -0,0 +1,65 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.user; + +import java.util.Map; +import org.sonar.db.DbTester; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RootFlagAssertions { + private final DbTester db; + + public RootFlagAssertions(DbTester db) { + this.db = db; + } + + public void verify(UserDto userDto, boolean root, long updatedAt) { + Map row = db.selectFirst("select is_root as \"isRoot\", updated_at as \"updatedAt\" from users where login = '" + userDto.getLogin() + "'"); + Object isRoot = row.get("isRoot"); + assertThat(isRoot) + .as("Root flag of user '%s' is same as when created", userDto.getLogin()) + .isEqualTo(isRoot instanceof Long ? toLong(root) : root); + assertThat(row.get("updatedAt")) + .as("UpdatedAt of user '%s' has not changed since created") + .isEqualTo(updatedAt); + } + + public void verify(UserDto userDto, boolean root) { + Map row = db.selectFirst("select is_root as \"isRoot\", updated_at as \"updatedAt\" from users where login = '" + userDto.getLogin() + "'"); + Object isRoot = row.get("isRoot"); + assertThat(isRoot) + .as("Root flag of user '%s' is '%s'", userDto.getLogin(), root) + .isEqualTo(isRoot instanceof Long ? toLong(root) : root); + assertThat(row.get("updatedAt")) + .as("UpdatedAt of user '%s' has changed since insertion", userDto.getLogin()) + .isNotEqualTo(userDto.getUpdatedAt()); + } + + private static Long toLong(boolean root) { + return root ? 1L : 0L; + } + + public void verify(String login, boolean root) { + assertThat(db.getDbClient().userDao().selectByLogin(db.getSession(), login).isRoot()) + .as("Root flag of user '%s' is '%s'", login, root) + .isEqualTo(root); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserDbTester.java new file mode 100644 index 00000000000..bc58c94d529 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserDbTester.java @@ -0,0 +1,378 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.user; + +import com.google.common.collect.ImmutableSet; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import javax.annotation.CheckForNull; +import javax.annotation.Nullable; +import org.sonar.api.web.UserRole; +import org.sonar.core.util.stream.MoreCollectors; +import org.sonar.db.DbClient; +import org.sonar.db.DbTester; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.organization.OrganizationDto; +import org.sonar.db.permission.GroupPermissionDto; +import org.sonar.db.permission.OrganizationPermission; +import org.sonar.db.permission.UserPermissionDto; + +import static com.google.common.base.Preconditions.checkArgument; +import static java.lang.String.format; +import static java.util.Arrays.stream; +import static org.sonar.db.permission.OrganizationPermission.ADMINISTER; +import static org.sonar.db.user.GroupTesting.newGroupDto; +import static org.sonar.db.user.UserTesting.newDisabledUser; +import static org.sonar.db.user.UserTesting.newUserDto; +import static org.sonar.db.user.UserTesting.newUserSettingDto; +import static org.sonar.db.user.UserTokenTesting.newUserToken; + +public class UserDbTester { + private static final Set PUBLIC_PERMISSIONS = ImmutableSet.of(UserRole.USER, UserRole.CODEVIEWER); // FIXME to check with Simon + + private final DbTester db; + private final DbClient dbClient; + + public UserDbTester(DbTester db) { + this.db = db; + this.dbClient = db.getDbClient(); + } + + // USERS + + public UserDto insertUser() { + return insertUser(UserTesting.newUserDto()); + } + + public UserDto insertUser(String login) { + UserDto dto = UserTesting.newUserDto().setLogin(login).setActive(true); + return insertUser(dto); + } + + @SafeVarargs + public final UserDto insertUser(Consumer... populators) { + UserDto dto = UserTesting.newUserDto().setActive(true); + stream(populators).forEach(p -> p.accept(dto)); + return insertUser(dto); + } + + @SafeVarargs + public final UserDto insertDisabledUser(Consumer... populators) { + UserDto dto = UserTesting.newDisabledUser(); + stream(populators).forEach(p -> p.accept(dto)); + return insertUser(dto); + } + + public UserDto insertUser(UserDto userDto) { + UserDto updatedUser = dbClient.userDao().insert(db.getSession(), userDto); + db.commit(); + return updatedUser; + } + + public UserDto makeRoot(UserDto userDto) { + dbClient.userDao().setRoot(db.getSession(), userDto.getLogin(), true); + db.commit(); + return dbClient.userDao().selectByLogin(db.getSession(), userDto.getLogin()); + } + + public UserDto makeNotRoot(UserDto userDto) { + dbClient.userDao().setRoot(db.getSession(), userDto.getLogin(), false); + db.commit(); + return dbClient.userDao().selectByLogin(db.getSession(), userDto.getLogin()); + } + + public UserDto insertAdminByUserPermission(OrganizationDto org) { + UserDto user = insertUser(); + insertPermissionOnUser(org, user, ADMINISTER); + return user; + } + + public UserDto updateLastConnectionDate(UserDto user, long lastConnectionDate) { + db.getDbClient().userDao().update(db.getSession(), user.setLastConnectionDate(lastConnectionDate)); + db.getSession().commit(); + return user; + } + + public Optional selectUserByLogin(String login) { + return Optional.ofNullable(dbClient.userDao().selectByLogin(db.getSession(), login)); + } + + // USER SETTINGS + + @SafeVarargs + public final UserPropertyDto insertUserSetting(UserDto user, Consumer... populators) { + UserPropertyDto dto = UserTesting.newUserSettingDto(user); + stream(populators).forEach(p -> p.accept(dto)); + dbClient.userPropertiesDao().insertOrUpdate(db.getSession(), dto); + db.commit(); + return dto; + } + + // GROUPS + + public GroupDto insertGroup(OrganizationDto organization, String name) { + GroupDto group = GroupTesting.newGroupDto().setName(name).setOrganizationUuid(organization.getUuid()); + return insertGroup(group); + } + + /** + * Create group in default organization + */ + public GroupDto insertGroup() { + GroupDto group = GroupTesting.newGroupDto().setOrganizationUuid(db.getDefaultOrganization().getUuid()); + return insertGroup(group); + } + + /** + * Create group in specified organization + */ + public GroupDto insertGroup(OrganizationDto organizationDto) { + GroupDto group = GroupTesting.newGroupDto().setOrganizationUuid(organizationDto.getUuid()); + return insertGroup(group); + } + + public GroupDto insertGroup(GroupDto dto) { + db.getDbClient().groupDao().insert(db.getSession(), dto); + db.commit(); + return dto; + } + + public GroupDto insertDefaultGroup(GroupDto dto) { + String organizationUuid = dto.getOrganizationUuid(); + db.getDbClient().organizationDao().getDefaultGroupId(db.getSession(), organizationUuid) + .ifPresent(groupId -> { + throw new IllegalArgumentException(format("Organization '%s' has already a default group", organizationUuid)); + }); + db.getDbClient().groupDao().insert(db.getSession(), dto); + db.getDbClient().organizationDao().setDefaultGroupId(db.getSession(), organizationUuid, dto); + db.commit(); + return dto; + } + + public GroupDto insertDefaultGroup(OrganizationDto organization, String name) { + return insertDefaultGroup(GroupTesting.newGroupDto().setName(name).setOrganizationUuid(organization.getUuid())); + } + + public GroupDto insertDefaultGroup(OrganizationDto organization) { + return insertDefaultGroup(GroupTesting.newGroupDto().setOrganizationUuid(organization.getUuid())); + } + + @CheckForNull + public GroupDto selectGroupById(int groupId) { + return db.getDbClient().groupDao().selectById(db.getSession(), groupId); + } + + public Optional selectGroup(OrganizationDto org, String name) { + return db.getDbClient().groupDao().selectByName(db.getSession(), org.getUuid(), name); + } + + public List selectGroups(OrganizationDto org) { + return db.getDbClient().groupDao().selectByOrganizationUuid(db.getSession(), org.getUuid()); + } + + // GROUP MEMBERSHIP + + public UserGroupDto insertMember(GroupDto group, UserDto user) { + UserGroupDto dto = new UserGroupDto().setGroupId(group.getId()).setUserId(user.getId()); + db.getDbClient().userGroupDao().insert(db.getSession(), dto); + db.commit(); + return dto; + } + + public void insertMembers(GroupDto group, UserDto... users) { + Arrays.stream(users).forEach(user -> { + UserGroupDto dto = new UserGroupDto().setGroupId(group.getId()).setUserId(user.getId()); + db.getDbClient().userGroupDao().insert(db.getSession(), dto); + }); + db.commit(); + } + + public List selectGroupIdsOfUser(UserDto user) { + return db.getDbClient().groupMembershipDao().selectGroupIdsByUserId(db.getSession(), user.getId()); + } + + // GROUP PERMISSIONS + + public GroupPermissionDto insertPermissionOnAnyone(OrganizationDto org, String permission) { + GroupPermissionDto dto = new GroupPermissionDto() + .setOrganizationUuid(org.getUuid()) + .setGroupId(null) + .setRole(permission); + db.getDbClient().groupPermissionDao().insert(db.getSession(), dto); + db.commit(); + return dto; + } + + public GroupPermissionDto insertPermissionOnAnyone(OrganizationDto org, OrganizationPermission permission) { + return insertPermissionOnAnyone(org, permission.getKey()); + } + + public GroupPermissionDto insertPermissionOnGroup(GroupDto group, String permission) { + GroupPermissionDto dto = new GroupPermissionDto() + .setOrganizationUuid(group.getOrganizationUuid()) + .setGroupId(group.getId()) + .setRole(permission); + db.getDbClient().groupPermissionDao().insert(db.getSession(), dto); + db.commit(); + return dto; + } + + public GroupPermissionDto insertPermissionOnGroup(GroupDto group, OrganizationPermission permission) { + return insertPermissionOnGroup(group, permission.getKey()); + } + + public void deletePermissionFromGroup(GroupDto group, String permission) { + db.getDbClient().groupPermissionDao().delete(db.getSession(), permission, group.getOrganizationUuid(), group.getId(), null); + db.commit(); + } + + public GroupPermissionDto insertProjectPermissionOnAnyone(String permission, ComponentDto project) { + checkArgument(!project.isPrivate(), "No permission to group AnyOne can be granted on a private project"); + checkArgument(!PUBLIC_PERMISSIONS.contains(permission), + "permission %s can't be granted on a public project", permission); + checkArgument(project.getMainBranchProjectUuid() == null, "Permissions can't be granted on branches"); + GroupPermissionDto dto = new GroupPermissionDto() + .setOrganizationUuid(project.getOrganizationUuid()) + .setGroupId(null) + .setRole(permission) + .setResourceId(project.getId()); + db.getDbClient().groupPermissionDao().insert(db.getSession(), dto); + db.commit(); + return dto; + } + + public void deleteProjectPermissionFromAnyone(ComponentDto project, String permission) { + db.getDbClient().groupPermissionDao().delete(db.getSession(), permission, project.getOrganizationUuid(), null, project.getId()); + db.commit(); + } + + public GroupPermissionDto insertProjectPermissionOnGroup(GroupDto group, String permission, ComponentDto project) { + checkArgument(group.getOrganizationUuid().equals(project.getOrganizationUuid()), "Different organizations"); + checkArgument(project.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission), + "%s can't be granted on a public project", permission); + checkArgument(project.getMainBranchProjectUuid() == null, "Permissions can't be granted on branches"); + GroupPermissionDto dto = new GroupPermissionDto() + .setOrganizationUuid(group.getOrganizationUuid()) + .setGroupId(group.getId()) + .setRole(permission) + .setResourceId(project.getId()); + db.getDbClient().groupPermissionDao().insert(db.getSession(), dto); + db.commit(); + return dto; + } + + public List selectGroupPermissions(GroupDto group, @Nullable ComponentDto project) { + if (project == null) { + return db.getDbClient().groupPermissionDao().selectGlobalPermissionsOfGroup(db.getSession(), + group.getOrganizationUuid(), group.getId()); + } + return db.getDbClient().groupPermissionDao().selectProjectPermissionsOfGroup(db.getSession(), + group.getOrganizationUuid(), group.getId(), project.getId()); + } + + public List selectAnyonePermissions(OrganizationDto org, @Nullable ComponentDto project) { + if (project == null) { + return db.getDbClient().groupPermissionDao().selectGlobalPermissionsOfGroup(db.getSession(), + org.getUuid(), null); + } + checkArgument(org.getUuid().equals(project.getOrganizationUuid()), "Different organizations"); + return db.getDbClient().groupPermissionDao().selectProjectPermissionsOfGroup(db.getSession(), org.getUuid(), null, project.getId()); + } + + // USER PERMISSIONS + + /** + * Grant permission on default organization + */ + public UserPermissionDto insertPermissionOnUser(UserDto user, OrganizationPermission permission) { + return insertPermissionOnUser(db.getDefaultOrganization(), user, permission); + } + + /** + * Grant global permission + * @deprecated use {@link #insertPermissionOnUser(OrganizationDto, UserDto, OrganizationPermission)} + */ + @Deprecated + public UserPermissionDto insertPermissionOnUser(OrganizationDto org, UserDto user, String permission) { + UserPermissionDto dto = new UserPermissionDto(org.getUuid(), permission, user.getId(), null); + db.getDbClient().userPermissionDao().insert(db.getSession(), dto); + db.commit(); + return dto; + } + + /** + * Grant organization permission to user + */ + public UserPermissionDto insertPermissionOnUser(OrganizationDto org, UserDto user, OrganizationPermission permission) { + return insertPermissionOnUser(org, user, permission.getKey()); + } + + public void deletePermissionFromUser(OrganizationDto org, UserDto user, OrganizationPermission permission) { + db.getDbClient().userPermissionDao().deleteGlobalPermission(db.getSession(), user.getId(), permission.getKey(), org.getUuid()); + db.commit(); + } + + public void deletePermissionFromUser(ComponentDto project, UserDto user, String permission) { + db.getDbClient().userPermissionDao().deleteProjectPermission(db.getSession(), user.getId(), permission, project.getId()); + db.commit(); + } + + /** + * Grant permission on given project + */ + public UserPermissionDto insertProjectPermissionOnUser(UserDto user, String permission, ComponentDto project) { + checkArgument(project.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission), + "%s can't be granted on a public project", permission); + checkArgument(project.getMainBranchProjectUuid() == null, "Permissions can't be granted on branches"); + UserPermissionDto dto = new UserPermissionDto(project.getOrganizationUuid(), permission, user.getId(), project.getId()); + db.getDbClient().userPermissionDao().insert(db.getSession(), dto); + db.commit(); + return dto; + } + + public List selectPermissionsOfUser(UserDto user, OrganizationDto organization) { + return toListOfOrganizationPermissions(db.getDbClient().userPermissionDao() + .selectGlobalPermissionsOfUser(db.getSession(), user.getId(), organization.getUuid())); + } + + public List selectProjectPermissionsOfUser(UserDto user, ComponentDto project) { + return db.getDbClient().userPermissionDao().selectProjectPermissionsOfUser(db.getSession(), user.getId(), project.getId()); + } + + private static List toListOfOrganizationPermissions(List keys) { + return keys + .stream() + .map(OrganizationPermission::fromKey) + .collect(MoreCollectors.toList()); + } + + @SafeVarargs + public final UserTokenDto insertToken(UserDto user, Consumer... populators) { + UserTokenDto dto = UserTokenTesting.newUserToken().setUserUuid(user.getUuid()); + stream(populators).forEach(p -> p.accept(dto)); + db.getDbClient().userTokenDao().insert(db.getSession(), dto); + db.commit(); + return dto; + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTesting.java new file mode 100644 index 00000000000..65e76738293 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTesting.java @@ -0,0 +1,99 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.user; + +import javax.annotation.Nullable; +import org.sonar.core.util.Uuids; + +import static java.util.Collections.singletonList; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang.math.RandomUtils.nextBoolean; +import static org.apache.commons.lang.math.RandomUtils.nextInt; +import static org.apache.commons.lang.math.RandomUtils.nextLong; + +public class UserTesting { + + public static UserDto newUserDto() { + return new UserDto() + .setId(nextInt()) + .setUuid(randomAlphanumeric(40)) + .setActive(true) + .setLocal(nextBoolean()) + .setLogin(randomAlphanumeric(30)) + .setName(randomAlphanumeric(30)) + .setEmail(randomAlphanumeric(30)) + .setOnboarded(nextBoolean()) + .setScmAccounts(singletonList(randomAlphanumeric(40))) + .setExternalId(randomAlphanumeric(40)) + .setExternalLogin(randomAlphanumeric(40)) + .setExternalIdentityProvider(randomAlphanumeric(40)) + .setSalt(randomAlphanumeric(40)) + .setCryptedPassword(randomAlphanumeric(40)) + .setCreatedAt(nextLong()) + .setUpdatedAt(nextLong()); + } + + public static UserDto newUserDto(String login, String name, @Nullable String email) { + return newUserDto() + .setName(name) + .setEmail(email) + .setLogin(login); + } + + public static UserDto newLocalUser(String login, String name, @Nullable String email) { + return newUserDto() + .setLocal(true) + .setName(name) + .setEmail(email) + .setLogin(login) + .setExternalId(login) + .setExternalLogin(login) + .setExternalIdentityProvider("sonarqube"); + } + + public static UserDto newExternalUser(String login, String name, @Nullable String email) { + return newUserDto() + .setLocal(false) + .setName(name) + .setEmail(email) + .setLogin(login) + .setExternalId(randomAlphanumeric(40)) + .setExternalLogin(randomAlphanumeric(40)) + .setExternalIdentityProvider(randomAlphanumeric(40)); + } + + public static UserDto newDisabledUser() { + return newUserDto() + .setActive(false) + // All these fields are reset when disabling a user + .setScmAccounts((String) null) + .setEmail(null) + .setCryptedPassword(null) + .setSalt(null); + } + + public static UserPropertyDto newUserSettingDto(UserDto user) { + return new UserPropertyDto() + .setUuid(Uuids.createFast()) + .setUserUuid(user.getUuid()) + .setKey(randomAlphanumeric(20)) + .setValue(randomAlphanumeric(100)); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTokenTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTokenTesting.java new file mode 100644 index 00000000000..3d83071824f --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTokenTesting.java @@ -0,0 +1,33 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.user; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang.math.RandomUtils.nextLong; + +public class UserTokenTesting { + public static UserTokenDto newUserToken() { + return new UserTokenDto() + .setUserUuid("userUuid_" + randomAlphanumeric(40)) + .setName("name_" + randomAlphanumeric(20)) + .setTokenHash("hash_" + randomAlphanumeric(30)) + .setCreatedAt(nextLong()); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDbTester.java new file mode 100644 index 00000000000..24b823aa981 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDbTester.java @@ -0,0 +1,57 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.webhook; + +import java.util.Optional; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.organization.OrganizationDto; + +import static org.sonar.db.webhook.WebhookTesting.newWebhook; + +public class WebhookDbTester { + + private final DbTester dbTester; + + public WebhookDbTester(DbTester dbTester) { + this.dbTester = dbTester; + } + + public WebhookDto insertWebhook(OrganizationDto organizationDto) { + return insert(newWebhook(organizationDto)); + } + + public WebhookDto insertWebhook(ComponentDto project) { + return insert(newWebhook(project)); + } + + public WebhookDto insert(WebhookDto dto) { + DbSession dbSession = dbTester.getSession(); + dbTester.getDbClient().webhookDao().insert(dbSession, dto); + dbSession.commit(); + return dto; + } + + public Optional selectWebhook(String uuid) { + DbSession dbSession = dbTester.getSession(); + return dbTester.getDbClient().webhookDao().selectByUuid(dbSession, uuid); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryDbTester.java new file mode 100644 index 00000000000..2bd8a385975 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryDbTester.java @@ -0,0 +1,64 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.webhook; + +import java.util.Objects; +import java.util.function.Consumer; +import org.sonar.db.DbTester; + +import static java.util.Arrays.stream; +import static org.sonar.db.webhook.WebhookDeliveryTesting.newDto; + +public class WebhookDeliveryDbTester { + + private final DbTester dbTester; + + public WebhookDeliveryDbTester(DbTester dbTester) { + this.dbTester = dbTester; + } + + public WebhookDeliveryLiteDto insert(WebhookDeliveryDto dto) { + dbTester.getDbClient().webhookDeliveryDao().insert(dbTester.getSession(), dto); + dbTester.getSession().commit(); + return dto; + } + + @SafeVarargs + public final WebhookDeliveryLiteDto insert(Consumer... dtoPopulators) { + WebhookDeliveryDto dto = newDto(); + stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(dto)); + dbTester.getDbClient().webhookDeliveryDao().insert(dbTester.getSession(), dto); + dbTester.getSession().commit(); + return dto; + } + + @SafeVarargs + public final WebhookDeliveryLiteDto insert(WebhookDto webhook, Consumer... dtoPopulators) { + WebhookDeliveryDto dto = newDto(); + stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(dto)); + String projectUuid = webhook.getProjectUuid(); + dto.setComponentUuid(Objects.requireNonNull(projectUuid, "Project uuid of webhook cannot be null")); + dto.setWebhookUuid(webhook.getUuid()); + dbTester.getDbClient().webhookDeliveryDao().insert(dbTester.getSession(), dto); + dbTester.getSession().commit(); + return dto; + } + +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryTesting.java new file mode 100644 index 00000000000..edefc760292 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryTesting.java @@ -0,0 +1,73 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.webhook; + +import java.util.List; +import java.util.stream.Collectors; +import org.sonar.core.util.Uuids; +import org.sonar.db.DbSession; +import org.sonar.db.DbTester; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang.math.RandomUtils.nextBoolean; +import static org.apache.commons.lang.math.RandomUtils.nextInt; +import static org.apache.commons.lang.math.RandomUtils.nextLong; + +public class WebhookDeliveryTesting { + + private WebhookDeliveryTesting() { + // only statics + } + + /** + * Build a {@link WebhookDeliveryDto} with all mandatory fields. + * Optional fields are kept null. + */ + public static WebhookDeliveryDto newDto(String uuid, String webhookUuid, String componentUuid, String ceTaskUuid) { + return newDto() + .setUuid(uuid) + .setWebhookUuid(webhookUuid) + .setComponentUuid(componentUuid) + .setCeTaskUuid(ceTaskUuid); + } + + public static WebhookDeliveryDto newDto() { + return new WebhookDeliveryDto() + .setUuid(Uuids.createFast()) + .setWebhookUuid(randomAlphanumeric(40)) + .setComponentUuid(randomAlphanumeric(40)) + .setCeTaskUuid(randomAlphanumeric(40)) + .setAnalysisUuid(randomAlphanumeric(40)) + .setName(randomAlphanumeric(10)) + .setUrl(randomAlphanumeric(10)) + .setDurationMs(nextInt()) + .setHttpStatus(nextInt()) + .setSuccess(nextBoolean()) + .setPayload(randomAlphanumeric(10)) + .setCreatedAt(nextLong()); + } + + public static List selectAllDeliveryUuids(DbTester dbTester, DbSession dbSession) { + return dbTester.select(dbSession, "select uuid as \"uuid\" from webhook_deliveries") + .stream() + .map(columns -> (String) columns.get("uuid")) + .collect(Collectors.toList()); + } +} diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookTesting.java new file mode 100644 index 00000000000..52e532b70b0 --- /dev/null +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookTesting.java @@ -0,0 +1,70 @@ +/* + * SonarQube + * Copyright (C) 2009-2019 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.db.webhook; + +import java.util.Arrays; +import java.util.function.Consumer; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.organization.OrganizationDto; + +import java.util.Calendar; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; + +public class WebhookTesting { + + private WebhookTesting() { + // only statics + } + + public static WebhookDto newWebhook(ComponentDto project) { + return getWebhookDto() + .setProjectUuid(project.uuid()); + } + + public static WebhookDto newProjectWebhook(String projectUuid) { + return getWebhookDto() + .setProjectUuid(projectUuid); + } + + public static WebhookDto newWebhook(OrganizationDto organizationDto) { + return getWebhookDto() + .setOrganizationUuid(organizationDto.getUuid()); + } + + @SafeVarargs + public static WebhookDto newOrganizationWebhook(String name, String organizationUuid, Consumer... consumers) { + return getWebhookDto(consumers) + .setName(name) + .setOrganizationUuid(organizationUuid); + } + + @SafeVarargs + private static WebhookDto getWebhookDto(Consumer... consumers) { + WebhookDto res = new WebhookDto() + .setUuid(randomAlphanumeric(40)) + .setName(randomAlphanumeric(64)) + .setUrl("https://www.random-site/" + randomAlphanumeric(256)) + .setSecret(randomAlphanumeric(10)) + .setCreatedAt(Calendar.getInstance().getTimeInMillis()); + Arrays.stream(consumers).forEach(consumer -> consumer.accept(res)); + return res; + } +} diff --git a/server/sonar-db-testing/build.gradle b/server/sonar-db-testing/build.gradle index 0b76a66038d..73ce5f115a4 100644 --- a/server/sonar-db-testing/build.gradle +++ b/server/sonar-db-testing/build.gradle @@ -9,5 +9,5 @@ dependencies { compile 'com.h2database:h2' compile testFixtures(project(':server:sonar-db-core')) - compile project(':server:sonar-db-dao').sourceSets.test.output + compile testFixtures(project(':server:sonar-db-dao')) } diff --git a/server/sonar-webserver-api/build.gradle b/server/sonar-webserver-api/build.gradle index 62d2bd8c42f..966bc42daf6 100644 --- a/server/sonar-webserver-api/build.gradle +++ b/server/sonar-webserver-api/build.gradle @@ -21,7 +21,6 @@ dependencies { compile 'io.jsonwebtoken:jjwt-api' compile 'io.jsonwebtoken:jjwt-impl' compile project(':sonar-core') - compile project(':server:sonar-db-dao') compile project(':server:sonar-process') compile project(':server:sonar-server-common') compile project(path: ':sonar-plugin-api', configuration: 'shadow') diff --git a/server/sonar-webserver-auth/build.gradle b/server/sonar-webserver-auth/build.gradle index 44ae241588c..1a61303a9f6 100644 --- a/server/sonar-webserver-auth/build.gradle +++ b/server/sonar-webserver-auth/build.gradle @@ -18,7 +18,6 @@ dependencies { compile 'io.jsonwebtoken:jjwt-api' compile 'io.jsonwebtoken:jjwt-impl' compile project(':sonar-core') - compile project(':server:sonar-db-dao') compile project(':server:sonar-process') compile project(':server:sonar-server-common') compile project(':server:sonar-webserver-api') diff --git a/server/sonar-webserver-core/build.gradle b/server/sonar-webserver-core/build.gradle index ea21d81838d..618d5cfebc3 100644 --- a/server/sonar-webserver-core/build.gradle +++ b/server/sonar-webserver-core/build.gradle @@ -39,7 +39,6 @@ dependencies { compile project(':server:sonar-ce-common') compile project(':server:sonar-ce-task') compile project(':server:sonar-ce-task-projectanalysis') - compile project(':server:sonar-db-dao') compile project(':server:sonar-db-migration') compile project(':server:sonar-process') compile project(':server:sonar-server-common')