From 72be5b2eca35f07c1a11d2be34fee2648655a67f Mon Sep 17 00:00:00 2001 From: Simon Brandhof Date: Wed, 11 Apr 2018 09:41:06 +0200 Subject: [PATCH] Speed-up the unit tests relying on Elasticsearch Creation of an index is slow in Elasticsearch. It should not executed before each test. --- .../java/org/sonar/server/es/BulkIndexer.java | 13 +- .../org/sonar/server/es/IndexCreator.java | 12 +- .../issue/index/IssueIndexDefinition.java | 7 +- .../rule/index/RuleIndexDefinition.java | 13 +- .../elasticsearch/test/EsTestCluster.java | 969 ------------------ .../authentication/SsoAuthenticatorTest.java | 3 +- .../UserIdentityAuthenticatorTest.java | 3 +- .../server/branch/pr/ws/ListActionTest.java | 4 +- .../server/branch/ws/ListActionTest.java | 4 +- .../index/ComponentIndexSearchTest.java | 3 +- .../component/index/ComponentIndexTest.java | 3 +- .../component/index/ComponentIndexerTest.java | 3 +- .../sonar/server/component/index/NewTest.java | 3 +- .../server/component/ws/SearchActionTest.java | 4 +- .../ws/SearchProjectsActionTest.java | 28 +- .../component/ws/SuggestionsActionTest.java | 6 +- .../issue/ScmAccountToUserLoaderTest.java | 15 +- .../org/sonar/server/es/BulkIndexerTest.java | 24 +- .../org/sonar/server/es/EsClientTest.java | 2 +- .../java/org/sonar/server/es/EsTester.java | 369 +++---- .../org/sonar/server/es/IndexCreatorTest.java | 17 +- .../server/es/IndexerStartupTaskTest.java | 2 +- ...neToManyResilientIndexingListenerTest.java | 4 +- ...OneToOneResilientIndexingListenerTest.java | 4 +- .../sonar/server/es/RecoveryIndexerTest.java | 2 +- .../metadata/EsDbCompatibilityImplTest.java | 2 +- .../MetadataIndexDefinitionBridge.java | 30 + .../server/es/metadata/MetadataIndexTest.java | 2 +- .../request/ProxyBulkRequestBuilderTest.java | 10 +- .../ProxyClearCacheRequestBuilderTest.java | 5 +- .../ProxyCreateIndexRequestBuilderTest.java | 17 +- .../ProxyDeleteRequestBuilderTest.java | 17 +- .../request/ProxyFlushRequestBuilderTest.java | 18 +- .../request/ProxyGetRequestBuilderTest.java | 14 +- .../request/ProxyIndexRequestBuilderTest.java | 16 +- .../ProxyIndicesExistsRequestBuilderTest.java | 18 +- .../ProxyIndicesStatsRequestBuilderTest.java | 18 +- .../ProxyMultiGetRequestBuilderTest.java | 18 +- .../ProxyNodesStatsRequestBuilderTest.java | 19 +- .../ProxyPutMappingRequestBuilderTest.java | 18 +- .../ProxyRefreshRequestBuilderTest.java | 18 +- .../ProxySearchRequestBuilderTest.java | 20 +- .../ProxySearchScrollRequestBuilderTest.java | 18 +- ...roxyWebServerHealthRequestBuilderTest.java | 5 +- ...ProxyWebServerStateRequestBuilderTest.java | 5 +- ...ProxyWebServerStatsRequestBuilderTest.java | 5 +- .../health/EsStatusClusterCheckTest.java | 2 +- .../server/health/EsStatusNodeCheckTest.java | 2 +- .../sonar/server/issue/IssueUpdaterTest.java | 4 +- .../issue/index/IssueIndexDebtTest.java | 4 +- .../IssueIndexProjectStatisticsTest.java | 8 +- .../server/issue/index/IssueIndexTest.java | 10 +- .../server/issue/index/IssueIndexerTest.java | 6 +- .../server/issue/ws/AddCommentActionTest.java | 4 +- .../server/issue/ws/AssignActionTest.java | 4 +- .../server/issue/ws/AuthorsActionTest.java | 4 +- .../server/issue/ws/BulkChangeActionTest.java | 4 +- .../issue/ws/DoTransitionActionTest.java | 4 +- .../issue/ws/SearchActionComponentsTest.java | 5 +- .../server/issue/ws/SearchActionTest.java | 4 +- .../issue/ws/SetSeverityActionTest.java | 4 +- .../server/issue/ws/SetTagsActionTest.java | 4 +- .../server/issue/ws/SetTypeActionTest.java | 4 +- .../sonar/server/issue/ws/TagsActionTest.java | 14 +- .../measure/custom/ws/CreateActionTest.java | 4 +- .../measure/custom/ws/MetricsActionTest.java | 3 +- .../measure/custom/ws/SearchActionTest.java | 4 +- .../measure/custom/ws/UpdateActionTest.java | 4 +- .../index/ProjectMeasuresIndexTest.java | 25 +- .../ProjectMeasuresIndexTextSearchTest.java | 3 +- .../index/ProjectMeasuresIndexerTest.java | 3 +- .../OrganizationCreationImplTest.java | 3 +- .../organization/ws/AddMemberActionTest.java | 4 +- .../organization/ws/CreateActionTest.java | 17 +- .../organization/ws/DeleteActionTest.java | 10 +- .../ws/EnableSupportActionTest.java | 6 +- .../ws/RemoveMemberActionTest.java | 4 +- .../ws/SearchMembersActionTest.java | 4 +- .../server/permission/index/FooIndexer.java | 5 +- .../index/PermissionIndexerTest.java | 4 +- .../permission/ws/BasePermissionWsTest.java | 2 +- .../server/platform/BackendCleanupTest.java | 8 +- .../monitoring/EsIndexesSectionTest.java | 4 +- .../monitoring/EsStateSectionTest.java | 4 +- .../cluster/EsClusterStateSectionTest.java | 4 +- .../SearchNodesInfoLoaderImplTest.java | 2 +- .../project/ws/BulkUpdateKeyActionTest.java | 6 +- .../ws/UpdateVisibilityActionTest.java | 2 +- .../projecttag/ws/SearchActionTest.java | 5 +- .../QProfileComparisonTest.java | 8 +- .../qualityprofile/QProfileRuleImplTest.java | 13 +- .../qualityprofile/QProfileTreeImplTest.java | 4 +- .../index/ActiveRuleIndexerTest.java | 5 +- .../ws/ChangeParentActionTest.java | 4 +- .../qualityprofile/ws/CreateActionTest.java | 4 +- .../ws/InheritanceActionTest.java | 4 +- .../ws/QProfilesWsMediumTest.java | 4 +- .../qualityprofile/ws/ShowActionTest.java | 12 +- .../sonar/server/rule/RegisterRulesTest.java | 5 +- .../sonar/server/rule/RuleCreatorTest.java | 4 +- .../sonar/server/rule/RuleUpdaterTest.java | 4 +- .../rule/index/RuleIndexDefinitionTest.java | 2 +- .../server/rule/index/RuleIndexTest.java | 35 +- .../server/rule/index/RuleIndexerTest.java | 5 +- .../server/rule/ws/CreateActionTest.java | 4 +- .../server/rule/ws/DeleteActionTest.java | 4 +- .../server/rule/ws/SearchActionTest.java | 78 +- .../sonar/server/rule/ws/ShowActionTest.java | 11 +- .../sonar/server/rule/ws/TagsActionTest.java | 4 +- .../server/rule/ws/UpdateActionTest.java | 5 +- .../server/telemetry/TelemetryDaemonTest.java | 6 +- .../server/test/index/TestIndexTest.java | 3 +- .../server/test/index/TestIndexerTest.java | 3 +- .../test/ws/CoveredFilesActionTest.java | 4 +- .../sonar/server/test/ws/ListActionTest.java | 4 +- .../server/user/UserUpdaterCreateTest.java | 82 +- .../server/user/UserUpdaterUpdateTest.java | 36 +- .../server/user/index/UserIndexTest.java | 23 +- .../server/user/index/UserIndexerTest.java | 3 +- .../user/ws/ChangePasswordActionTest.java | 5 +- .../server/user/ws/CreateActionTest.java | 3 +- .../server/user/ws/DeactivateActionTest.java | 4 +- .../server/user/ws/SearchActionTest.java | 4 +- .../server/user/ws/UpdateActionTest.java | 3 +- .../server/view/index/ViewIndexTest.java | 3 +- .../server/view/index/ViewIndexerTest.java | 3 +- 126 files changed, 645 insertions(+), 1804 deletions(-) delete mode 100644 server/sonar-server/src/test/java/org/sonar/elasticsearch/test/EsTestCluster.java create mode 100644 server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexDefinitionBridge.java diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/BulkIndexer.java b/server/sonar-server/src/main/java/org/sonar/server/es/BulkIndexer.java index c3b58dd070e..5bfd70b3f9f 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/BulkIndexer.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/BulkIndexer.java @@ -56,8 +56,8 @@ import static java.lang.String.format; /** * Helper to bulk requests in an efficient way : * */ public class BulkIndexer { @@ -160,6 +160,9 @@ public class BulkIndexer { } String scrollId = searchResponse.getScrollId(); + if (scrollId == null) { + break; + } searchResponse = client.prepareSearchScroll(scrollId).setScroll(TimeValue.timeValueMinutes(5)).get(); if (hits.length == 0) { client.nativeClient().prepareClearScroll().addScrollId(scrollId).get(); @@ -179,7 +182,7 @@ public class BulkIndexer { /** * Delete all the documents matching the given search request. This method is blocking. * Index is refreshed, so docs are not searchable as soon as method is executed. - * + *

* Note that the parameter indexType could be removed if progress logs are not needed. */ public static IndexingResult delete(EsClient client, IndexType indexType, SearchRequestBuilder searchRequest) { @@ -216,7 +219,9 @@ public class BulkIndexer { } public enum Size { - /** Use this size for a limited number of documents. */ + /** + * Use this size for a limited number of documents. + */ REGULAR { @Override SizeHandler createHandler(Runtime2 runtime2) { diff --git a/server/sonar-server/src/main/java/org/sonar/server/es/IndexCreator.java b/server/sonar-server/src/main/java/org/sonar/server/es/IndexCreator.java index 2f6fed1b223..9cfc6b3559b 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/es/IndexCreator.java +++ b/server/sonar-server/src/main/java/org/sonar/server/es/IndexCreator.java @@ -20,8 +20,10 @@ package org.sonar.server.es; import java.util.Arrays; +import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang.StringUtils; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; @@ -74,7 +76,7 @@ public class IndexCreator implements Startable { createIndex(new Index(index), false); } - checkDbCompatibility(); + checkDbCompatibility(definitions.getIndices().values()); // create indices that do not exist or that have a new definition (different mapping, cluster enabled, ...) for (Index index : definitions.getIndices().values()) { @@ -140,13 +142,13 @@ public class IndexCreator implements Startable { }).orElse(true); } - private void checkDbCompatibility() { + private void checkDbCompatibility(Collection definitions) { boolean disabledCheck = configuration.getBoolean(PROPERY_DISABLE_CHECK).orElse(false); if (disabledCheck) { LOGGER.warn("Automatic drop of search indices in turned off (see property " + PROPERY_DISABLE_CHECK + ")"); } - List existingIndices = loadExistingIndicesExceptMetadata(); + List existingIndices = loadExistingIndicesExceptMetadata(definitions); if (!disabledCheck && !existingIndices.isEmpty()) { boolean delete = false; if (!esDbCompatibility.hasSameDbVendor()) { @@ -163,8 +165,10 @@ public class IndexCreator implements Startable { esDbCompatibility.markAsCompatible(); } - private List loadExistingIndicesExceptMetadata() { + private List loadExistingIndicesExceptMetadata(Collection definitions) { + Set definedNames = definitions.stream().map(Index::getName).collect(Collectors.toSet()); return Arrays.stream(client.nativeClient().admin().indices().prepareGetIndex().get().getIndices()) + .filter(definedNames::contains) .filter(index -> !MetadataIndexDefinition.INDEX_TYPE_METADATA.getIndex().equals(index)) .collect(Collectors.toList()); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndexDefinition.java b/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndexDefinition.java index 3521b705672..0a76b7ed736 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndexDefinition.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndexDefinition.java @@ -19,8 +19,8 @@ */ package org.sonar.server.issue.index; -import com.google.common.annotations.VisibleForTesting; import org.sonar.api.config.Configuration; +import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.IndexDefinition; import org.sonar.server.es.IndexType; import org.sonar.server.es.NewIndex; @@ -109,9 +109,8 @@ public class IssueIndexDefinition implements IndexDefinition { * Keep the document sources in index so that indexer tests can verify content * of indexed documents. */ - @VisibleForTesting - public static IssueIndexDefinition createForTest(Configuration config) { - return new IssueIndexDefinition(config, true); + public static IssueIndexDefinition createForTest() { + return new IssueIndexDefinition(new MapSettings().asConfig(), true); } @Override diff --git a/server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndexDefinition.java b/server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndexDefinition.java index a25e207e35b..38e54fcb4b0 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndexDefinition.java +++ b/server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndexDefinition.java @@ -19,11 +19,11 @@ */ package org.sonar.server.rule.index; -import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.Set; import org.sonar.api.config.Configuration; +import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.IndexDefinition; import org.sonar.server.es.IndexType; import org.sonar.server.es.NewIndex; @@ -39,7 +39,7 @@ import static org.sonar.server.es.NewIndex.SettingsConfiguration.newBuilder; */ public class RuleIndexDefinition implements IndexDefinition { - static final String INDEX = "rules"; + private static final String INDEX = "rules"; public static final IndexType INDEX_TYPE_RULE = new IndexType(INDEX, "rule"); public static final String FIELD_RULE_ID = "id"; @@ -66,7 +66,9 @@ public class RuleIndexDefinition implements IndexDefinition { // Rule extension fields public static final IndexType INDEX_TYPE_RULE_EXTENSION = new IndexType(INDEX, "ruleExtension"); - /** The uuid of a {@link RuleExtensionScope} */ + /** + * The uuid of a {@link RuleExtensionScope} + */ public static final String FIELD_RULE_EXTENSION_SCOPE = "scope"; public static final String FIELD_RULE_EXTENSION_RULE_ID = "ruleId"; public static final String FIELD_RULE_EXTENSION_TAGS = "tags"; @@ -95,9 +97,8 @@ public class RuleIndexDefinition implements IndexDefinition { * Keep the document sources in index so that indexer tests can verify content * of indexed documents. */ - @VisibleForTesting - public static RuleIndexDefinition createForTest(Configuration config) { - return new RuleIndexDefinition(config, true); + public static RuleIndexDefinition createForTest() { + return new RuleIndexDefinition(new MapSettings().asConfig(), true); } @Override diff --git a/server/sonar-server/src/test/java/org/sonar/elasticsearch/test/EsTestCluster.java b/server/sonar-server/src/test/java/org/sonar/elasticsearch/test/EsTestCluster.java deleted file mode 100644 index a3005a2d327..00000000000 --- a/server/sonar-server/src/test/java/org/sonar/elasticsearch/test/EsTestCluster.java +++ /dev/null @@ -1,969 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 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.elasticsearch.test; - -import com.carrotsearch.hppc.ObjectArrayList; -import java.io.Closeable; -import java.io.IOException; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NavigableMap; -import java.util.Random; -import java.util.Set; -import java.util.TreeMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import org.apache.logging.log4j.Logger; -import org.apache.lucene.util.IOUtils; -import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; -import org.elasticsearch.action.admin.cluster.node.stats.NodeStats; -import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; -import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequestBuilder; -import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; -import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags; -import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags.Flag; -import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse; -import org.elasticsearch.client.Client; -import org.elasticsearch.client.transport.TransportClient; -import org.elasticsearch.cluster.ClusterName; -import org.elasticsearch.cluster.metadata.IndexMetaData; -import org.elasticsearch.cluster.metadata.IndexTemplateMetaData; -import org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.breaker.CircuitBreaker; -import org.elasticsearch.common.io.FileSystemUtils; -import org.elasticsearch.common.lease.Releasables; -import org.elasticsearch.common.logging.Loggers; -import org.elasticsearch.common.network.NetworkModule; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.settings.Settings.Builder; -import org.elasticsearch.common.transport.TransportAddress; -import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.common.util.concurrent.EsExecutors; -import org.elasticsearch.common.util.concurrent.ThreadContext; -import org.elasticsearch.env.Environment; -import org.elasticsearch.env.NodeEnvironment; -import org.elasticsearch.env.ShardLockObtainFailedException; -import org.elasticsearch.index.IndexNotFoundException; -import org.elasticsearch.index.IndexService; -import org.elasticsearch.index.engine.CommitStats; -import org.elasticsearch.index.engine.Engine; -import org.elasticsearch.index.shard.IndexShard; -import org.elasticsearch.index.shard.ShardId; -import org.elasticsearch.indices.IndexTemplateMissingException; -import org.elasticsearch.indices.IndicesService; -import org.elasticsearch.indices.breaker.CircuitBreakerService; -import org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache; -import org.elasticsearch.indices.recovery.RecoverySettings; -import org.elasticsearch.node.MockNode; -import org.elasticsearch.node.Node; -import org.elasticsearch.node.NodeService; -import org.elasticsearch.node.NodeValidationException; -import org.elasticsearch.plugins.Plugin; -import org.elasticsearch.repositories.RepositoryMissingException; -import org.elasticsearch.script.ScriptService; -import org.elasticsearch.test.NodeConfigurationSource; -import org.elasticsearch.test.transport.MockTransportService; -import org.elasticsearch.transport.MockTransportClient; -import org.elasticsearch.transport.TransportService; -import org.hamcrest.CoreMatchers; -import org.hamcrest.MatcherAssert; -import org.junit.Assert; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -/** - * InternalTestCluster manages a set of JVM private nodes and allows convenient access to them. - * The cluster supports randomized configuration such that nodes started in the cluster will - * automatically load asserting services tracking resources like file handles or open searchers. - *

- * The Cluster is bound to a test lifecycle where tests must call {@link #beforeTest(java.util.Random, double)} and - * {@link #afterTest()} to initialize and reset the cluster in order to be more reproducible. The term "more" relates - * to the async nature of Elasticsearch in combination with randomized testing. Once Threads and asynchronous calls - * are involved reproducibility is very limited. - *

- */ -public final class EsTestCluster { - - protected final Logger logger = Loggers.getLogger(getClass()); - - protected Random random; - - private double transportClientRatio = 0.0; - - /* sorted map to make traverse order reproducible, concurrent since we do checks on it not within a sync block */ - private final NavigableMap nodes = new TreeMap<>(); - - private final Set dataDirToClean = new HashSet<>(); - - private final String clusterName; - - private final AtomicBoolean open = new AtomicBoolean(true); - - private final Settings defaultSettings; - - private AtomicInteger nextNodeId = new AtomicInteger(0); - - /* - * Each shared node has a node seed that is used to start up the node and get default settings - * this is important if a node is randomly shut down in a test since the next test relies on a - * fully shared cluster to be more reproducible - */ - private final long[] sharedNodesSeeds; - - private final int numSharedDataNodes; - - private final NodeConfigurationSource nodeConfigurationSource; - - private final ExecutorService executor; - - private final Collection> mockPlugins; - - /** - * All nodes started by the cluster will have their name set to nodePrefix followed by a positive number - */ - private final String nodePrefix; - private final Path baseDir; - - private Function clientWrapper; - - public EsTestCluster(long clusterSeed, Path baseDir, - int numDataNodes, String clusterName, NodeConfigurationSource nodeConfigurationSource, - String nodePrefix, Collection> mockPlugins, Function clientWrapper) { - this.clientWrapper = clientWrapper; - this.baseDir = baseDir; - this.clusterName = clusterName; - if (numDataNodes < 0) { - throw new IllegalArgumentException("number of data nodes must be >= 0"); - } - - Random random = new Random(clusterSeed); - - this.numSharedDataNodes = numDataNodes; - assert this.numSharedDataNodes >= 1; - - this.nodePrefix = nodePrefix; - - assert nodePrefix != null; - this.mockPlugins = mockPlugins; - - sharedNodesSeeds = new long[numSharedDataNodes]; - for (int i = 0; i < sharedNodesSeeds.length; i++) { - sharedNodesSeeds[i] = random.nextLong(); - } - - logger.info("Setup InternalTestCluster [{}] with seed [{}] using " + - "[{}] (data) nodes", - clusterName, clusterSeed, - numSharedDataNodes); - this.nodeConfigurationSource = nodeConfigurationSource; - Builder builder = Settings.builder(); - builder.put(NodeEnvironment.MAX_LOCAL_STORAGE_NODES_SETTING.getKey(), Integer.MAX_VALUE); - builder.put(Environment.PATH_SHARED_DATA_SETTING.getKey(), baseDir.resolve("custom")); - builder.put(Environment.PATH_HOME_SETTING.getKey(), baseDir); - builder.put(Environment.PATH_REPO_SETTING.getKey(), baseDir.resolve("repos")); - if (Strings.hasLength(System.getProperty("tests.es.logger.level"))) { - builder.put("logger.level", System.getProperty("tests.es.logger.level")); - } - if (Strings.hasLength(System.getProperty("es.logger.prefix"))) { - builder.put("logger.prefix", System.getProperty("es.logger.prefix")); - } - builder.put("action.auto_create_index", false); - // Default the watermarks to absurdly low to prevent the tests - // from failing on nodes without enough disk space - builder.put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK_SETTING.getKey(), "1b"); - builder.put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK_SETTING.getKey(), "1b"); - // Some tests make use of scripting quite a bit, so increase the limit for integration tests - builder.put(ScriptService.SCRIPT_MAX_COMPILATIONS_PER_MINUTE.getKey(), 1000); - // always reduce this - it can make tests really slow - builder.put(RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING.getKey(), TimeValue.timeValueMillis(randomIntBetween(random, 20, 50))); - defaultSettings = builder.build(); - executor = EsExecutors.newScaling("test runner", 0, Integer.MAX_VALUE, 0, TimeUnit.SECONDS, EsExecutors.daemonThreadFactory("test_" + clusterName), - new ThreadContext(Settings.EMPTY)); - } - - /** - * A random integer from min to max (inclusive). - */ - private static int randomIntBetween(Random r, int min, int max) { - assert max >= min : "max must be >= min: " + min + ", " + max; - long range = (long) max - (long) min; - if (range < Integer.MAX_VALUE) { - return min + r.nextInt(1 + (int) range); - } else { - return min + (int) Math.round(r.nextDouble() * range); - } - } - - private Settings getSettings(int nodeOrdinal, Settings others) { - Builder builder = Settings.builder().put(defaultSettings); - Settings settings = nodeConfigurationSource.nodeSettings(nodeOrdinal); - if (settings != null) { - if (settings.get(ClusterName.CLUSTER_NAME_SETTING.getKey()) != null) { - throw new IllegalStateException("Tests must not set a '" + ClusterName.CLUSTER_NAME_SETTING.getKey() + "' as a node setting set '" - + ClusterName.CLUSTER_NAME_SETTING.getKey() + "': [" + settings.get(ClusterName.CLUSTER_NAME_SETTING.getKey()) + "]"); - } - builder.put(settings); - } - if (others != null) { - builder.put(others); - } - builder.put(ClusterName.CLUSTER_NAME_SETTING.getKey(), clusterName); - return builder.build(); - } - - private Collection> getPlugins() { - Set> plugins = new HashSet<>(nodeConfigurationSource.nodePlugins()); - plugins.addAll(mockPlugins); - return plugins; - } - - private void ensureOpen() { - if (!open.get()) { - throw new RuntimeException("Cluster is already closed"); - } - } - - private synchronized NodeAndClient getOrBuildRandomNode() { - ensureOpen(); - NodeAndClient randomNodeAndClient = getRandomNodeAndClient(); - if (randomNodeAndClient != null) { - return randomNodeAndClient; - } - NodeAndClient buildNode = buildNode(); - buildNode.startNode(); - publishNode(buildNode); - return buildNode; - } - - private synchronized NodeAndClient getRandomNodeAndClient() { - return getRandomNodeAndClient(nc -> true); - } - - private synchronized NodeAndClient getRandomNodeAndClient(Predicate predicate) { - ensureOpen(); - Collection values = nodes.values().stream().filter(predicate).collect(Collectors.toCollection(ArrayList::new)); - if (!values.isEmpty()) { - int whichOne = random.nextInt(values.size()); - for (NodeAndClient nodeAndClient : values) { - if (whichOne-- == 0) { - return nodeAndClient; - } - } - } - return null; - } - - private NodeAndClient buildNode() { - int ord = nextNodeId.getAndIncrement(); - return buildNode(ord, random.nextLong(), null, false); - } - - private NodeAndClient buildNode(int nodeId, long seed, Settings settings, boolean reuseExisting) { - assert Thread.holdsLock(this); - ensureOpen(); - settings = getSettings(nodeId, settings); - Collection> plugins = getPlugins(); - String name = buildNodeName(nodeId); - if (reuseExisting && nodes.containsKey(name)) { - return nodes.get(name); - } else { - assert reuseExisting || !nodes.containsKey(name) : "node name [" + name + "] already exists but not allowed to use it"; - } - Settings finalSettings = Settings.builder() - .put(Environment.PATH_HOME_SETTING.getKey(), baseDir) // allow overriding path.home - .put(settings) - .put("node.name", name) - .put(NodeEnvironment.NODE_ID_SEED_SETTING.getKey(), seed) - .build(); - MockNode node = new MockNode(finalSettings, plugins); - return new NodeAndClient(name, node, nodeId); - } - - private String buildNodeName(int id) { - return nodePrefix + id; - } - - /** - * Returns a client connected to any node in the cluster - */ - public synchronized Client client() { - ensureOpen(); - /* Randomly return a client to one of the nodes in the cluster */ - return getOrBuildRandomNode().client(random); - } - - /** - * Returns a node client to a given node. - */ - public synchronized Client client(String nodeName) { - ensureOpen(); - NodeAndClient nodeAndClient = nodes.get(nodeName); - if (nodeAndClient != null) { - return nodeAndClient.client(random); - } - Assert.fail("No node found with name: [" + nodeName + "]"); - return null; // can't happen - } - - /** - * Returns a random node that applies to the given predicate. - * The predicate can filter nodes based on the nodes settings. - * If all nodes are filtered out this method will return null - */ - public synchronized Client client(final Predicate filterPredicate) { - ensureOpen(); - final NodeAndClient randomNodeAndClient = getRandomNodeAndClient(nodeAndClient -> filterPredicate.test(nodeAndClient.node.settings())); - if (randomNodeAndClient != null) { - return randomNodeAndClient.client(random); - } - return null; - } - - /** - * Closes the current cluster - */ - public synchronized void close() { - if (this.open.compareAndSet(true, false)) { - IOUtils.closeWhileHandlingException(nodes.values()); - nodes.clear(); - executor.shutdownNow(); - } - } - - private final class NodeAndClient implements Closeable { - private MockNode node; - private Client nodeClient; - private Client transportClient; - private final AtomicBoolean closed = new AtomicBoolean(false); - private final String name; - private final int nodeAndClientId; - - NodeAndClient(String name, MockNode node, int nodeAndClientId) { - this.node = node; - this.name = name; - this.nodeAndClientId = nodeAndClientId; - markNodeDataDirsAsNotEligableForWipe(node); - } - - Node node() { - if (closed.get()) { - throw new RuntimeException("already closed"); - } - return node; - } - - int nodeAndClientId() { - return nodeAndClientId; - } - - Client client(Random random) { - if (closed.get()) { - throw new RuntimeException("already closed"); - } - double nextDouble = random.nextDouble(); - if (nextDouble < transportClientRatio) { - if (logger.isTraceEnabled()) { - logger.trace("Using transport client for node [{}] sniff: [{}]", node.settings().get("node.name"), false); - } - return getOrBuildTransportClient(); - } else { - return getOrBuildNodeClient(); - } - } - - Client nodeClient() { - if (closed.get()) { - throw new RuntimeException("already closed"); - } - return getOrBuildNodeClient(); - } - - private Client getOrBuildNodeClient() { - if (nodeClient == null) { - nodeClient = node.client(); - } - return clientWrapper.apply(nodeClient); - } - - private Client getOrBuildTransportClient() { - if (transportClient == null) { - /* - * no sniff client for now - doesn't work will all tests since it might throw NoNodeAvailableException if nodes are shut down. - * we first need support of transportClientRatio as annotations or so - */ - Collection> plugins = new ArrayList<>(); - plugins.addAll(nodeConfigurationSource.transportClientPlugins()); - plugins.addAll(mockPlugins); - transportClient = new TransportClientFactory(false, nodeConfigurationSource.transportClientSettings(), baseDir, plugins) - .client(node, clusterName); - } - return clientWrapper.apply(transportClient); - } - - void resetClient() { - if (!closed.get()) { - Releasables.close(nodeClient, transportClient); - nodeClient = null; - transportClient = null; - } - } - - void startNode() { - try { - node.start(); - } catch (NodeValidationException e) { - throw new RuntimeException(e); - } - } - - void closeNode() throws IOException { - markNodeDataDirsAsPendingForWipe(node); - node.close(); - } - - @Override - public void close() throws IOException { - try { - resetClient(); - } finally { - closed.set(true); - closeNode(); - } - } - } - - private static final String TRANSPORT_CLIENT_PREFIX = "transport_client_"; - - static class TransportClientFactory { - private final boolean sniff; - private final Settings settings; - private final Path baseDir; - private final Collection> plugins; - - TransportClientFactory(boolean sniff, Settings settings, Path baseDir, Collection> plugins) { - this.sniff = sniff; - this.settings = settings != null ? settings : Settings.EMPTY; - this.baseDir = baseDir; - this.plugins = plugins; - } - - public Client client(Node node, String clusterName) { - TransportAddress addr = node.injector().getInstance(TransportService.class).boundAddress().publishAddress(); - Settings nodeSettings = node.settings(); - Builder builder = Settings.builder() - .put("client.transport.nodes_sampler_interval", "1s") - .put(Environment.PATH_HOME_SETTING.getKey(), baseDir) - .put("node.name", TRANSPORT_CLIENT_PREFIX + node.settings().get("node.name")) - .put(ClusterName.CLUSTER_NAME_SETTING.getKey(), clusterName) - .put("client.transport.sniff", sniff) - .put("logger.prefix", nodeSettings.get("logger.prefix", "")) - .put("logger.level", nodeSettings.get("logger.level", "INFO")) - .put(settings); - if (NetworkModule.TRANSPORT_TYPE_SETTING.exists(settings)) { - builder.put(NetworkModule.TRANSPORT_TYPE_KEY, NetworkModule.TRANSPORT_TYPE_SETTING.get(settings)); - } - TransportClient client = new MockTransportClient(builder.build(), plugins); - client.addTransportAddress(addr); - return client; - } - } - - public synchronized void beforeTest(Random random, double transportClientRatio) throws IOException { - assert transportClientRatio >= 0.0 && transportClientRatio <= 1.0; - logger.debug("Reset test cluster with transport client ratio: [{}]", transportClientRatio); - this.transportClientRatio = transportClientRatio; - this.random = new Random(random.nextLong()); - reset(true); - } - - private synchronized void reset(boolean wipeData) throws IOException { - // clear all rules for mock transport services - for (NodeAndClient nodeAndClient : nodes.values()) { - TransportService transportService = nodeAndClient.node.injector().getInstance(TransportService.class); - if (transportService instanceof MockTransportService) { - final MockTransportService mockTransportService = (MockTransportService) transportService; - mockTransportService.clearAllRules(); - mockTransportService.clearTracers(); - } - } - randomlyResetClients(); - final int newSize = sharedNodesSeeds.length; - if (nextNodeId.get() == newSize && nodes.size() == newSize) { - if (wipeData) { - wipePendingDataDirectories(); - } - logger.debug("Cluster hasn't changed - moving out - nodes: [{}] nextNodeId: [{}] numSharedNodes: [{}]", nodes.keySet(), nextNodeId.get(), newSize); - return; - } - logger.debug("Cluster is NOT consistent - restarting shared nodes - nodes: [{}] nextNodeId: [{}] numSharedNodes: [{}]", nodes.keySet(), nextNodeId.get(), newSize); - - // trash all nodes with id >= sharedNodesSeeds.length - they are non shared - - for (Iterator iterator = nodes.values().iterator(); iterator.hasNext();) { - NodeAndClient nodeAndClient = iterator.next(); - if (nodeAndClient.nodeAndClientId() >= sharedNodesSeeds.length) { - logger.debug("Close Node [{}] not shared", nodeAndClient.name); - nodeAndClient.close(); - iterator.remove(); - } - } - - // clean up what the nodes left that is unused - if (wipeData) { - wipePendingDataDirectories(); - } - - // start any missing node - assert newSize == numSharedDataNodes; - for (int i = 0; i < numSharedDataNodes; i++) { - final Settings.Builder settings = Settings.builder(); - NodeAndClient nodeAndClient = buildNode(i, sharedNodesSeeds[i], settings.build(), true); - nodeAndClient.startNode(); - publishNode(nodeAndClient); - } - - nextNodeId.set(newSize); - assert size() == newSize; - if (newSize > 0) { - ClusterHealthResponse response = client().admin().cluster().prepareHealth() - .setWaitForNodes(Integer.toString(newSize)).get(); - if (response.isTimedOut()) { - logger.warn("failed to wait for a cluster of size [{}], got [{}]", newSize, response); - throw new IllegalStateException("cluster failed to reach the expected size of [" + newSize + "]"); - } - } - logger.debug("Cluster is consistent again - nodes: [{}] nextNodeId: [{}] numSharedNodes: [{}]", nodes.keySet(), nextNodeId.get(), newSize); - } - - /** - * This method should be executed during tear down, after each test (but after assertAfterTest) - */ - public synchronized void afterTest() throws IOException { - wipePendingDataDirectories(); - randomlyResetClients(); /* reset all clients - each test gets its own client based on the Random instance created above. */ - } - - public void beforeIndexDeletion() { - // Check that the operations counter on index shard has reached 0. - // The assumption here is that after a test there are no ongoing write operations. - // test that have ongoing write operations after the test (for example because ttl is used - // and not all docs have been purged after the test) and inherit from - // ElasticsearchIntegrationTest must override beforeIndexDeletion() to avoid failures. - assertShardIndexCounter(); - // check that shards that have same sync id also contain same number of documents - assertSameSyncIdSameDocs(); - } - - private void assertSameSyncIdSameDocs() { - Map docsOnShards = new HashMap<>(); - final Collection nodesAndClients = nodes.values(); - for (NodeAndClient nodeAndClient : nodesAndClients) { - IndicesService indexServices = getInstance(IndicesService.class, nodeAndClient.name); - for (IndexService indexService : indexServices) { - for (IndexShard indexShard : indexService) { - CommitStats commitStats = indexShard.commitStats(); - if (commitStats != null) { // null if the engine is closed or if the shard is recovering - String syncId = commitStats.getUserData().get(Engine.SYNC_COMMIT_ID); - if (syncId != null) { - long liveDocsOnShard = commitStats.getNumDocs(); - if (docsOnShards.get(syncId) != null) { - assertThat( - "sync id is equal but number of docs does not match on node " + nodeAndClient.name + ". expected " + docsOnShards.get(syncId) + " but got " + liveDocsOnShard, - docsOnShards.get(syncId), equalTo(liveDocsOnShard)); - } else { - docsOnShards.put(syncId, liveDocsOnShard); - } - } - } - } - } - } - } - - private void assertShardIndexCounter() { - final Collection nodesAndClients = nodes.values(); - for (NodeAndClient nodeAndClient : nodesAndClients) { - IndicesService indexServices = getInstance(IndicesService.class, nodeAndClient.name); - for (IndexService indexService : indexServices) { - for (IndexShard indexShard : indexService) { - assertThat("index shard counter on shard " + indexShard.shardId() + " on node " + nodeAndClient.name + " not 0", indexShard.getActiveOperationsCount(), equalTo(0)); - } - } - } - } - - private void randomlyResetClients() throws IOException { - // only reset the clients on nightly tests, it causes heavy load... - // if (RandomizedTest.isNightly() && rarely(random)) { - final Collection nodesAndClients = nodes.values(); - for (NodeAndClient nodeAndClient : nodesAndClients) { - nodeAndClient.resetClient(); - } - // } - } - - private void wipePendingDataDirectories() { - assert Thread.holdsLock(this); - if (!dataDirToClean.isEmpty()) { - try { - for (Path path : dataDirToClean) { - try { - FileSystemUtils.deleteSubDirectories(path); - logger.info("Successfully wiped data directory for node location: {}", path); - } catch (IOException e) { - logger.info("Failed to wipe data directory for node location: {}", path); - } - } - } finally { - dataDirToClean.clear(); - } - } - } - - private void markNodeDataDirsAsPendingForWipe(Node node) { - assert Thread.holdsLock(this); - NodeEnvironment nodeEnv = node.getNodeEnvironment(); - if (nodeEnv.hasNodeFile()) { - dataDirToClean.addAll(Arrays.asList(nodeEnv.nodeDataPaths())); - } - } - - private void markNodeDataDirsAsNotEligableForWipe(Node node) { - assert Thread.holdsLock(this); - NodeEnvironment nodeEnv = node.getNodeEnvironment(); - if (nodeEnv.hasNodeFile()) { - dataDirToClean.removeAll(Arrays.asList(nodeEnv.nodeDataPaths())); - } - } - - /** - * Returns a reference to the given nodes instances of the given class >T< - */ - public synchronized T getInstance(Class clazz, final String node) { - return getInstance(clazz, nc -> node == null || node.equals(nc.name)); - } - - private synchronized T getInstance(Class clazz, Predicate predicate) { - NodeAndClient randomNodeAndClient = getRandomNodeAndClient(predicate); - assert randomNodeAndClient != null; - return getInstanceFromNode(clazz, randomNodeAndClient.node); - } - - private synchronized T getInstanceFromNode(Class clazz, Node node) { - return node.injector().getInstance(clazz); - } - - /** - * Returns the number of nodes in the cluster. - */ - public synchronized int size() { - return this.nodes.size(); - } - - private synchronized void publishNode(NodeAndClient nodeAndClient) { - assert !nodeAndClient.node().isClosed(); - nodes.put(nodeAndClient.name, nodeAndClient); - } - - - /** - * Returns an {@link Iterable} over all clients in this test cluster - */ - public synchronized Iterable getClients() { - ensureOpen(); - return () -> { - ensureOpen(); - final Iterator iterator = nodes.values().iterator(); - return new Iterator() { - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public Client next() { - return iterator.next().client(random); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(""); - } - - }; - }; - } - - /** - * Ensures that any breaker statistics are reset to 0. - * - * The implementation is specific to the test cluster, because the act of - * checking some breaker stats can increase them. - */ - private void ensureEstimatedStats() { - if (size() > 0) { - // Checks that the breakers have been reset without incurring a - // network request, because a network request can increment one - // of the breakers - for (NodeAndClient nodeAndClient : nodes.values()) { - final IndicesFieldDataCache fdCache = getInstanceFromNode(IndicesService.class, nodeAndClient.node).getIndicesFieldDataCache(); - // Clean up the cache, ensuring that entries' listeners have been called - fdCache.getCache().refresh(); - - final String name = nodeAndClient.name; - final CircuitBreakerService breakerService = getInstanceFromNode(CircuitBreakerService.class, nodeAndClient.node); - CircuitBreaker fdBreaker = breakerService.getBreaker(CircuitBreaker.FIELDDATA); - assertThat("Fielddata breaker not reset to 0 on node: " + name, fdBreaker.getUsed(), equalTo(0L)); - // Anything that uses transport or HTTP can increase the - // request breaker (because they use bigarrays), because of - // that the breaker can sometimes be incremented from ping - // requests from other clusters because Jenkins is running - // multiple ES testing jobs in parallel on the same machine. - // To combat this we check whether the breaker has reached 0 - // in an assertBusy loop, so it will try for 10 seconds and - // fail if it never reached 0 - try { - assertBusy(new Runnable() { - @Override - public void run() { - CircuitBreaker reqBreaker = breakerService.getBreaker(CircuitBreaker.REQUEST); - assertThat("Request breaker not reset to 0 on node: " + name, reqBreaker.getUsed(), equalTo(0L)); - } - }); - } catch (Exception e) { - fail("Exception during check for request breaker reset to 0: " + e); - } - - NodeService nodeService = getInstanceFromNode(NodeService.class, nodeAndClient.node); - CommonStatsFlags flags = new CommonStatsFlags(Flag.FieldData, Flag.QueryCache, Flag.Segments); - NodeStats stats = nodeService.stats(flags, false, false, false, false, false, false, false, false, false, false, false); - assertThat("Fielddata size must be 0 on node: " + stats.getNode(), stats.getIndices().getFieldData().getMemorySizeInBytes(), equalTo(0L)); - assertThat("Query cache size must be 0 on node: " + stats.getNode(), stats.getIndices().getQueryCache().getMemorySizeInBytes(), equalTo(0L)); - assertThat("FixedBitSet cache size must be 0 on node: " + stats.getNode(), stats.getIndices().getSegments().getBitsetMemoryInBytes(), equalTo(0L)); - } - } - } - - /** - * This method checks all the things that need to be checked after each test - */ - public void assertAfterTest() { - ensureEstimatedStats(); - assertRequestsFinished(); - for (NodeAndClient nodeAndClient : nodes.values()) { - NodeEnvironment env = nodeAndClient.node().getNodeEnvironment(); - Set shardIds = env.lockedShards(); - for (ShardId id : shardIds) { - try { - env.shardLock(id, TimeUnit.SECONDS.toMillis(5)).close(); - } catch (ShardLockObtainFailedException ex) { - fail("Shard " + id + " is still locked after 5 sec waiting"); - } - } - } - } - - private void assertRequestsFinished() { - if (size() > 0) { - for (NodeAndClient nodeAndClient : nodes.values()) { - CircuitBreaker inFlightRequestsBreaker = getInstance(CircuitBreakerService.class, nodeAndClient.name) - .getBreaker(CircuitBreaker.IN_FLIGHT_REQUESTS); - try { - // see #ensureEstimatedStats() - assertBusy(() -> { - // ensure that our size accounting on transport level is reset properly - long bytesUsed = inFlightRequestsBreaker.getUsed(); - assertThat("All incoming requests on node [" + nodeAndClient.name + "] should have finished. Expected 0 but got " + - bytesUsed, bytesUsed, equalTo(0L)); - }); - } catch (Exception e) { - logger.error("Could not assert finished requests within timeout", e); - fail("Could not assert finished requests within timeout on node [" + nodeAndClient.name + "]"); - } - } - } - } - - /** - * Simple interface that allows to wait for an async operation to finish - * - * @param the result of the async execution - */ - public interface Async { - T get() throws ExecutionException, InterruptedException; - } - - /** - * Wipes any data that a test can leave behind: indices, templates (except exclude templates) and repositories - */ - public void wipe(Set excludeTemplates) { - wipeIndices("_all"); - wipeAllTemplates(excludeTemplates); - wipeRepositories(); - } - - /** - * Deletes the given indices from the tests cluster. If no index name is passed to this method - * all indices are removed. - */ - public void wipeIndices(String... indices) { - assert indices != null && indices.length > 0; - if (size() > 0) { - try { - assertAcked(client().admin().indices().prepareDelete(indices)); - } catch (IndexNotFoundException e) { - // ignore - } catch (IllegalArgumentException e) { - // Happens if `action.destructive_requires_name` is set to true - // which is the case in the CloseIndexDisableCloseAllTests - if ("_all".equals(indices[0])) { - ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().execute().actionGet(); - ObjectArrayList concreteIndices = new ObjectArrayList<>(); - for (IndexMetaData indexMetaData : clusterStateResponse.getState().metaData()) { - concreteIndices.add(indexMetaData.getIndex().getName()); - } - if (!concreteIndices.isEmpty()) { - assertAcked(client().admin().indices().prepareDelete(concreteIndices.toArray(String.class))); - } - } - } - } - } - - public void assertAcked(DeleteIndexRequestBuilder builder) { - DeleteIndexResponse response = builder.get(); - MatcherAssert.assertThat("Delete Index failed - not acked", response.isAcknowledged(), CoreMatchers.equalTo(true)); - } - - /** - * Removes all templates, except the templates defined in the exclude - */ - public void wipeAllTemplates(Set exclude) { - if (size() > 0) { - GetIndexTemplatesResponse response = client().admin().indices().prepareGetTemplates().get(); - for (IndexTemplateMetaData indexTemplate : response.getIndexTemplates()) { - if (exclude.contains(indexTemplate.getName())) { - continue; - } - try { - client().admin().indices().prepareDeleteTemplate(indexTemplate.getName()).execute().actionGet(); - } catch (IndexTemplateMissingException e) { - // ignore - } - } - } - } - - /** - * Deletes index templates, support wildcard notation. - * If no template name is passed to this method all templates are removed. - */ - public void wipeTemplates(String... templates) { - if (size() > 0) { - // if nothing is provided, delete all - if (templates.length == 0) { - templates = new String[] {"*"}; - } - for (String template : templates) { - try { - client().admin().indices().prepareDeleteTemplate(template).execute().actionGet(); - } catch (IndexTemplateMissingException e) { - // ignore - } - } - } - } - - /** - * Deletes repositories, supports wildcard notation. - */ - public void wipeRepositories(String... repositories) { - if (size() > 0) { - // if nothing is provided, delete all - if (repositories.length == 0) { - repositories = new String[] {"*"}; - } - for (String repository : repositories) { - try { - client().admin().cluster().prepareDeleteRepository(repository).execute().actionGet(); - } catch (RepositoryMissingException ex) { - // ignore - } - } - } - } - - /** - * Runs the code block for 10 seconds waiting for no assertion to trip. - */ - public static void assertBusy(Runnable codeBlock) throws Exception { - assertBusy(codeBlock, 10, TimeUnit.SECONDS); - } - - /** - * Runs the code block for the provided interval, waiting for no assertions to trip. - */ - private static void assertBusy(Runnable codeBlock, long maxWaitTime, TimeUnit unit) throws Exception { - long maxTimeInMillis = TimeUnit.MILLISECONDS.convert(maxWaitTime, unit); - long iterations = Math.max(Math.round(Math.log10(maxTimeInMillis) / Math.log10(2)), 1); - long timeInMillis = 1; - long sum = 0; - List failures = new ArrayList<>(); - for (int i = 0; i < iterations; i++) { - try { - codeBlock.run(); - return; - } catch (AssertionError e) { - failures.add(e); - } - sum += timeInMillis; - Thread.sleep(timeInMillis); - timeInMillis *= 2; - } - timeInMillis = maxTimeInMillis - sum; - Thread.sleep(Math.max(timeInMillis, 0)); - try { - codeBlock.run(); - } catch (AssertionError e) { - for (AssertionError failure : failures) { - e.addSuppressed(failure); - } - throw e; - } - } - -} diff --git a/server/sonar-server/src/test/java/org/sonar/server/authentication/SsoAuthenticatorTest.java b/server/sonar-server/src/test/java/org/sonar/server/authentication/SsoAuthenticatorTest.java index 22549c7ac3f..431f2933e30 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/authentication/SsoAuthenticatorTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/authentication/SsoAuthenticatorTest.java @@ -47,7 +47,6 @@ import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.organization.TestOrganizationFlags; import org.sonar.server.user.NewUserNotifier; import org.sonar.server.user.UserUpdater; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.usergroups.DefaultGroupFinder; @@ -74,7 +73,7 @@ public class SsoAuthenticatorTest { @Rule public DbTester db = DbTester.create(new AlwaysIncreasingSystem2()); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(settings.asConfig())); + public EsTester es = EsTester.core(); private static final String DEFAULT_LOGIN = "john"; private static final String DEFAULT_NAME = "John"; diff --git a/server/sonar-server/src/test/java/org/sonar/server/authentication/UserIdentityAuthenticatorTest.java b/server/sonar-server/src/test/java/org/sonar/server/authentication/UserIdentityAuthenticatorTest.java index c4e774e85aa..e037b5b110b 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/authentication/UserIdentityAuthenticatorTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/authentication/UserIdentityAuthenticatorTest.java @@ -41,7 +41,6 @@ import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.organization.TestOrganizationFlags; import org.sonar.server.user.NewUserNotifier; import org.sonar.server.user.UserUpdater; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.usergroups.DefaultGroupFinder; @@ -80,7 +79,7 @@ public class UserIdentityAuthenticatorTest { @Rule public DbTester db = DbTester.create(new AlwaysIncreasingSystem2()); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(settings.asConfig())); + public EsTester es = EsTester.core(); private UserIndexer userIndexer = new UserIndexer(db.getDbClient(), es.client()); private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db); private OrganizationCreation organizationCreation = mock(OrganizationCreation.class); diff --git a/server/sonar-server/src/test/java/org/sonar/server/branch/pr/ws/ListActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/branch/pr/ws/ListActionTest.java index 434d1ca5b46..f04ac96cb9f 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/branch/pr/ws/ListActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/branch/pr/ws/ListActionTest.java @@ -23,7 +23,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.DateUtils; @@ -44,7 +43,6 @@ import org.sonar.server.es.EsTester; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.issue.index.IssueIndex; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.permission.index.AuthorizationTypeSupport; @@ -84,7 +82,7 @@ public class ListActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/branch/ws/ListActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/branch/ws/ListActionTest.java index 3fff8eb8430..a6a17902375 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/branch/ws/ListActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/branch/ws/ListActionTest.java @@ -24,7 +24,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -39,7 +38,6 @@ import org.sonar.server.component.ComponentFinder; import org.sonar.server.es.EsTester; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.issue.index.IssueIndex; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.permission.index.AuthorizationTypeSupport; @@ -80,7 +78,7 @@ public class ListActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexSearchTest.java b/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexSearchTest.java index 443f7951f36..4487d1caadc 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexSearchTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexSearchTest.java @@ -25,7 +25,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; @@ -46,7 +45,7 @@ import static org.sonar.db.component.ComponentTesting.newFileDto; public class ComponentIndexSearchTest { @Rule - public EsTester es = new EsTester(new ComponentIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexTest.java b/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexTest.java index 29ce83f1b64..b4b317b55fa 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexTest.java @@ -26,7 +26,6 @@ import java.util.stream.Collectors; import org.assertj.core.api.ListAssert; import org.junit.Before; import org.junit.Rule; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; @@ -48,7 +47,7 @@ import static org.sonar.api.resources.Qualifiers.PROJECT; public abstract class ComponentIndexTest { @Rule - public EsTester es = new EsTester(new ComponentIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); diff --git a/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexerTest.java index 6507c905579..adfc85cc645 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexerTest.java @@ -24,7 +24,6 @@ import java.util.Collection; import org.elasticsearch.search.SearchHit; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; @@ -53,7 +52,7 @@ public class ComponentIndexerTest { private System2 system2 = System2.INSTANCE; @Rule - public EsTester es = new EsTester(new ComponentIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(system2); diff --git a/server/sonar-server/src/test/java/org/sonar/server/component/index/NewTest.java b/server/sonar-server/src/test/java/org/sonar/server/component/index/NewTest.java index 4c415ba0e38..c7a77a3178b 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/component/index/NewTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/component/index/NewTest.java @@ -22,13 +22,12 @@ package org.sonar.server.component.index; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.EsTester; public class NewTest { @Rule - public EsTester es = new EsTester(new ComponentIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Test public void name() { diff --git a/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchActionTest.java index 246c8ef682e..faae1ffb102 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchActionTest.java @@ -27,7 +27,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; @@ -39,7 +38,6 @@ import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.organization.OrganizationDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.index.ComponentIndex; -import org.sonar.server.component.index.ComponentIndexDefinition; import org.sonar.server.component.index.ComponentIndexer; import org.sonar.server.component.ws.SearchAction.SearchRequest; import org.sonar.server.es.EsTester; @@ -87,7 +85,7 @@ public class SearchActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public EsTester es = new EsTester(new ComponentIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private I18nRule i18n = new I18nRule(); private TestDefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db); diff --git a/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchProjectsActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchProjectsActionTest.java index e2aaa75918e..4d73cf7681c 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchProjectsActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchProjectsActionTest.java @@ -32,7 +32,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; @@ -49,7 +48,6 @@ import org.sonar.server.component.ws.SearchProjectsAction.RequestBuilder; import org.sonar.server.component.ws.SearchProjectsAction.SearchProjectsRequest; import org.sonar.server.es.EsTester; import org.sonar.server.measure.index.ProjectMeasuresIndex; -import org.sonar.server.measure.index.ProjectMeasuresIndexDefinition; import org.sonar.server.measure.index.ProjectMeasuresIndexer; import org.sonar.server.permission.index.AuthorizationTypeSupport; import org.sonar.server.permission.index.PermissionIndexerTester; @@ -112,18 +110,18 @@ public class SearchProjectsActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule - public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @DataProvider public static Object[][] rating_metric_keys() { - return new Object[][] {{SQALE_RATING_KEY}, {RELIABILITY_RATING_KEY}, {SECURITY_RATING_KEY}}; + return new Object[][]{{SQALE_RATING_KEY}, {RELIABILITY_RATING_KEY}, {SECURITY_RATING_KEY}}; } @DataProvider public static Object[][] new_rating_metric_keys() { - return new Object[][] {{NEW_MAINTAINABILITY_RATING_KEY}, {NEW_RELIABILITY_RATING_KEY}, {NEW_SECURITY_RATING_KEY}}; + return new Object[][]{{NEW_MAINTAINABILITY_RATING_KEY}, {NEW_RELIABILITY_RATING_KEY}, {NEW_SECURITY_RATING_KEY}}; } private DbClient dbClient = db.getDbClient(); @@ -198,23 +196,23 @@ public class SearchProjectsActionTest { @Test public void json_example() { userSession.logIn(); - OrganizationDto organization1Dto = db.organizations().insert(dto-> dto.setKey("my-org-key-1").setName("Foo")); - OrganizationDto organization2Dto = db.organizations().insert(dto-> dto.setKey("my-org-key-2").setName("Bar")); + OrganizationDto organization1Dto = db.organizations().insert(dto -> dto.setKey("my-org-key-1").setName("Foo")); + OrganizationDto organization2Dto = db.organizations().insert(dto -> dto.setKey("my-org-key-2").setName("Bar")); MetricDto coverage = db.measures().insertMetric(c -> c.setKey(COVERAGE).setValueType(PERCENT.name())); ComponentDto project1 = insertProject(organization1Dto, c -> c - .setDbKey(KEY_PROJECT_EXAMPLE_001) - .setName("My Project 1") - .setTagsString("finance, java"), + .setDbKey(KEY_PROJECT_EXAMPLE_001) + .setName("My Project 1") + .setTagsString("finance, java"), new Measure(coverage, c -> c.setValue(80d))); ComponentDto project2 = insertProject(organization1Dto, c -> c - .setDbKey(KEY_PROJECT_EXAMPLE_002) - .setName("My Project 2"), + .setDbKey(KEY_PROJECT_EXAMPLE_002) + .setName("My Project 2"), new Measure(coverage, c -> c.setValue(90d))); ComponentDto project3 = insertProject(organization2Dto, c -> c - .setDbKey(KEY_PROJECT_EXAMPLE_003) - .setName("My Project 3") - .setTagsString("sales, offshore, java"), + .setDbKey(KEY_PROJECT_EXAMPLE_003) + .setName("My Project 3") + .setTagsString("sales, offshore, java"), new Measure(coverage, c -> c.setValue(20d))); addFavourite(project1); diff --git a/server/sonar-server/src/test/java/org/sonar/server/component/ws/SuggestionsActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/component/ws/SuggestionsActionTest.java index 755859ff383..b4c66136740 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/component/ws/SuggestionsActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/component/ws/SuggestionsActionTest.java @@ -27,7 +27,6 @@ import org.assertj.core.groups.Tuple; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Qualifiers; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService; @@ -39,7 +38,6 @@ import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.organization.OrganizationDto; import org.sonar.server.component.index.ComponentIndex; -import org.sonar.server.component.index.ComponentIndexDefinition; import org.sonar.server.component.index.ComponentIndexer; import org.sonar.server.es.EsTester; import org.sonar.server.favorite.FavoriteFinder; @@ -91,7 +89,7 @@ public class SuggestionsActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public EsTester es = new EsTester(new ComponentIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); public ResourceTypesRule resourceTypes = new ResourceTypesRule(); @@ -718,7 +716,7 @@ public class SuggestionsActionTest { } private void check_proposal_to_show_more_results(int numberOfProjects, int expectedNumberOfResults, long expectedNumberOfMoreResults, @Nullable SuggestionCategory more, - boolean useQuery) { + boolean useQuery) { String namePrefix = "MyProject"; List projects = range(0, numberOfProjects) diff --git a/server/sonar-server/src/test/java/org/sonar/server/computation/task/projectanalysis/issue/ScmAccountToUserLoaderTest.java b/server/sonar-server/src/test/java/org/sonar/server/computation/task/projectanalysis/issue/ScmAccountToUserLoaderTest.java index c19b136fe43..eca06309a38 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/computation/task/projectanalysis/issue/ScmAccountToUserLoaderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/computation/task/projectanalysis/issue/ScmAccountToUserLoaderTest.java @@ -22,7 +22,6 @@ package org.sonar.server.computation.task.projectanalysis.issue; import java.util.Collections; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; @@ -44,7 +43,7 @@ public class ScmAccountToUserLoaderTest { private static final String ORGANIZATION_UUID = "my-organization"; @Rule - public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public LogTester logTester = new LogTester(); @@ -62,9 +61,9 @@ public class ScmAccountToUserLoaderTest { .setActive(true) .setScmAccounts(asList("charlie", "jesuis@charlie.com")) .setOrganizationUuids(singletonList(ORGANIZATION_UUID)); - esTester.putDocuments(UserIndexDefinition.INDEX_TYPE_USER.getIndex(), UserIndexDefinition.INDEX_TYPE_USER.getType(), user); + es.putDocuments(UserIndexDefinition.INDEX_TYPE_USER.getIndex(), UserIndexDefinition.INDEX_TYPE_USER.getType(), user); - UserIndex index = new UserIndex(esTester.client(), System2.INSTANCE); + UserIndex index = new UserIndex(es.client(), System2.INSTANCE); ScmAccountToUserLoader underTest = new ScmAccountToUserLoader(index, analysisMetadataHolder); assertThat(underTest.load("missing")).isNull(); @@ -80,7 +79,7 @@ public class ScmAccountToUserLoaderTest { .setActive(true) .setScmAccounts(asList("charlie", "jesuis@charlie.com")) .setOrganizationUuids(singletonList(ORGANIZATION_UUID)); - esTester.putDocuments(UserIndexDefinition.INDEX_TYPE_USER.getIndex(), UserIndexDefinition.INDEX_TYPE_USER.getType(), user1); + es.putDocuments(UserIndexDefinition.INDEX_TYPE_USER.getIndex(), UserIndexDefinition.INDEX_TYPE_USER.getType(), user1); UserDoc user2 = new UserDoc() .setLogin("another.charlie") @@ -88,9 +87,9 @@ public class ScmAccountToUserLoaderTest { .setActive(true) .setScmAccounts(singletonList("charlie")) .setOrganizationUuids(singletonList(ORGANIZATION_UUID)); - esTester.putDocuments(UserIndexDefinition.INDEX_TYPE_USER.getIndex(), UserIndexDefinition.INDEX_TYPE_USER.getType(), user2); + es.putDocuments(UserIndexDefinition.INDEX_TYPE_USER.getIndex(), UserIndexDefinition.INDEX_TYPE_USER.getType(), user2); - UserIndex index = new UserIndex(esTester.client(), System2.INSTANCE); + UserIndex index = new UserIndex(es.client(), System2.INSTANCE); ScmAccountToUserLoader underTest = new ScmAccountToUserLoader(index, analysisMetadataHolder); assertThat(underTest.load("charlie")).isNull(); @@ -99,7 +98,7 @@ public class ScmAccountToUserLoaderTest { @Test public void load_by_multiple_scm_accounts_is_not_supported_yet() { - UserIndex index = new UserIndex(esTester.client(), System2.INSTANCE); + UserIndex index = new UserIndex(es.client(), System2.INSTANCE); ScmAccountToUserLoader underTest = new ScmAccountToUserLoader(index, analysisMetadataHolder); try { underTest.loadAll(Collections.emptyList()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/BulkIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/BulkIndexerTest.java index c7bcd8148c6..bd7b839c823 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/BulkIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/BulkIndexerTest.java @@ -43,13 +43,13 @@ public class BulkIndexerTest { private TestSystem2 testSystem2 = new TestSystem2().setNow(1_000L); @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition().setReplicas(1)); + public EsTester es = EsTester.custom(new FakeIndexDefinition().setReplicas(1)); @Rule public DbTester dbTester = DbTester.create(testSystem2); @Test public void index_nothing() { - BulkIndexer indexer = new BulkIndexer(esTester.client(), INDEX_TYPE_FAKE, Size.REGULAR); + BulkIndexer indexer = new BulkIndexer(es.client(), INDEX_TYPE_FAKE, Size.REGULAR); indexer.start(); indexer.stop(); @@ -58,7 +58,7 @@ public class BulkIndexerTest { @Test public void index_documents() { - BulkIndexer indexer = new BulkIndexer(esTester.client(), INDEX_TYPE_FAKE, Size.REGULAR); + BulkIndexer indexer = new BulkIndexer(es.client(), INDEX_TYPE_FAKE, Size.REGULAR); indexer.start(); indexer.add(newIndexRequest(42)); indexer.add(newIndexRequest(78)); @@ -76,7 +76,7 @@ public class BulkIndexerTest { // index has one replica assertThat(replicas()).isEqualTo(1); - BulkIndexer indexer = new BulkIndexer(esTester.client(), INDEX_TYPE_FAKE, Size.LARGE); + BulkIndexer indexer = new BulkIndexer(es.client(), INDEX_TYPE_FAKE, Size.LARGE); indexer.start(); // replicas are temporarily disabled @@ -104,12 +104,12 @@ public class BulkIndexerTest { for (int i = 0; i < max; i++) { docs[i] = FakeIndexDefinition.newDoc(i); } - esTester.putDocuments(INDEX_TYPE_FAKE, docs); + es.putDocuments(INDEX_TYPE_FAKE, docs); assertThat(count()).isEqualTo(max); - SearchRequestBuilder req = esTester.client().prepareSearch(INDEX_TYPE_FAKE) + SearchRequestBuilder req = es.client().prepareSearch(INDEX_TYPE_FAKE) .setQuery(QueryBuilders.rangeQuery(FakeIndexDefinition.INT_FIELD).gte(removeFrom)); - BulkIndexer.delete(esTester.client(), INDEX_TYPE_FAKE, req); + BulkIndexer.delete(es.client(), INDEX_TYPE_FAKE, req); assertThat(count()).isEqualTo(removeFrom); } @@ -117,7 +117,7 @@ public class BulkIndexerTest { @Test public void listener_is_called_on_successful_requests() { FakeListener listener = new FakeListener(); - BulkIndexer indexer = new BulkIndexer(esTester.client(), INDEX_TYPE_FAKE, Size.REGULAR, listener); + BulkIndexer indexer = new BulkIndexer(es.client(), INDEX_TYPE_FAKE, Size.REGULAR, listener); indexer.start(); indexer.addDeletion(INDEX_TYPE_FAKE, "foo"); indexer.stop(); @@ -130,7 +130,7 @@ public class BulkIndexerTest { @Test public void listener_is_called_even_if_deleting_a_doc_that_does_not_exist() { FakeListener listener = new FakeListener(); - BulkIndexer indexer = new BulkIndexer(esTester.client(), INDEX_TYPE_FAKE, Size.REGULAR, listener); + BulkIndexer indexer = new BulkIndexer(es.client(), INDEX_TYPE_FAKE, Size.REGULAR, listener); indexer.start(); indexer.add(newIndexRequestWithDocId("foo")); indexer.add(newIndexRequestWithDocId("bar")); @@ -144,7 +144,7 @@ public class BulkIndexerTest { @Test public void listener_is_not_called_with_errors() { FakeListener listener = new FakeListener(); - BulkIndexer indexer = new BulkIndexer(esTester.client(), INDEX_TYPE_FAKE, Size.REGULAR, listener); + BulkIndexer indexer = new BulkIndexer(es.client(), INDEX_TYPE_FAKE, Size.REGULAR, listener); indexer.start(); indexer.add(newIndexRequestWithDocId("foo")); indexer.add(new IndexRequest("index_does_not_exist", "index_does_not_exist", "bar").source(emptyMap())); @@ -170,11 +170,11 @@ public class BulkIndexerTest { } private long count() { - return esTester.countDocuments("fakes", "fake"); + return es.countDocuments("fakes", "fake"); } private int replicas() { - GetSettingsResponse settingsResp = esTester.client().nativeClient().admin().indices() + GetSettingsResponse settingsResp = es.client().nativeClient().admin().indices() .prepareGetSettings(INDEX).get(); return Integer.parseInt(settingsResp.getSetting(INDEX, IndexMetaData.SETTING_NUMBER_OF_REPLICAS)); } diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/EsClientTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/EsClientTest.java index a3ebb1389da..35877a165ac 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/EsClientTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/EsClientTest.java @@ -44,7 +44,7 @@ import static org.sonar.server.es.FakeIndexDefinition.INDEX_TYPE_FAKE; public class EsClientTest { @Rule - public EsTester es = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Test public void proxify_requests() { diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/EsTester.java b/server/sonar-server/src/test/java/org/sonar/server/es/EsTester.java index de37c71955f..15262da3bd3 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/EsTester.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/EsTester.java @@ -19,60 +19,59 @@ */ package org.sonar.server.es; -import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; -import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Collection; -import java.util.Collections; +import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Random; import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.commons.lang.reflect.ConstructorUtils; +import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; +import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; +import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse; import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsResponse; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.client.Client; -import org.elasticsearch.cluster.ClusterState; -import org.elasticsearch.cluster.metadata.MetaData; +import org.elasticsearch.cluster.health.ClusterHealthStatus; +import org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings; import org.elasticsearch.common.Strings; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.discovery.DiscoveryModule; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.join.ParentJoinPlugin; -import org.elasticsearch.plugins.Plugin; +import org.elasticsearch.env.Environment; +import org.elasticsearch.env.NodeEnvironment; +import org.elasticsearch.index.IndexNotFoundException; +import org.elasticsearch.indices.recovery.RecoverySettings; +import org.elasticsearch.node.MockNode; +import org.elasticsearch.node.Node; import org.elasticsearch.search.SearchHit; -import org.elasticsearch.test.NodeConfigurationSource; import org.junit.rules.ExternalResource; +import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.LoggerLevel; -import org.sonar.api.utils.log.Loggers; -import org.sonar.server.config.ConfigurationProvider; -import org.sonar.core.platform.ComponentContainer; -import org.sonar.elasticsearch.test.EsTestCluster; -import org.sonar.server.es.metadata.MetadataIndex; -import org.sonar.server.es.metadata.MetadataIndexDefinition; +import org.sonar.server.component.index.ComponentIndexDefinition; +import org.sonar.server.issue.index.IssueIndexDefinition; +import org.sonar.server.measure.index.ProjectMeasuresIndexDefinition; +import org.sonar.server.rule.index.RuleIndexDefinition; +import org.sonar.server.test.index.TestIndexDefinition; +import org.sonar.server.user.index.UserIndexDefinition; +import org.sonar.server.view.index.ViewIndexDefinition; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Lists.newArrayList; -import static java.util.Arrays.asList; -import static junit.framework.TestCase.assertNull; -import static org.elasticsearch.test.XContentTestUtils.convertToMap; -import static org.elasticsearch.test.XContentTestUtils.differenceBetweenMapsIgnoringArrayOrder; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoTimeout; -import static org.junit.Assert.assertEquals; +import static java.util.Collections.emptyList; +import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.sonar.server.es.DefaultIndexSettings.REFRESH_IMMEDIATE; public class EsTester extends ExternalResource { @@ -91,174 +90,60 @@ public class EsTester extends ExternalResource { } } - private static final Set NO_TEMPLATES_SURVIVING_WIPE = Collections.emptySet(); - private static EsTestCluster cluster; - private final List indexDefinitions; + private static final Node SHARED_NODE = createNode(); + private static final AtomicBoolean CORE_INDICES_CREATED = new AtomicBoolean(false); + private static final Set CORE_INDICES_NAMES = new HashSet<>(); - public EsTester(IndexDefinition... defs) { - this.indexDefinitions = asList(defs); - } + private final boolean isCustom; - public void init() { - Path tempDirectory; - try { - tempDirectory = Files.createTempDirectory("es-unit-test"); - tempDirectory.toFile().deleteOnExit(); - cluster = new EsTestCluster(new Random().nextLong(), tempDirectory, 1, "test cluster", getNodeConfigSource(), "node-", - Collections.singletonList(ParentJoinPlugin.class), i -> i); - Random random = new Random(); - cluster.beforeTest(random, random.nextDouble()); - cluster.wipe(NO_TEMPLATES_SURVIVING_WIPE); - } catch (IOException e) { - throw new RuntimeException(e); - } + private EsTester(boolean isCustom) { + this.isCustom = isCustom; } - private NodeConfigurationSource getNodeConfigSource() { - Settings.Builder networkSettings = Settings.builder(); - networkSettings.put(NetworkModule.TRANSPORT_TYPE_KEY, "local"); - - return new NodeConfigurationSource() { - @Override - public Settings nodeSettings(int nodeOrdinal) { - return Settings.builder() - .put(NetworkModule.HTTP_ENABLED.getKey(), false) - .put(DiscoveryModule.DISCOVERY_TYPE_SETTING.getKey(), "single-node") - .put(networkSettings.build()) - .build(); - } - - @Override - public Collection> nodePlugins() { - return Collections.emptyList(); - } - - @Override - public Settings transportClientSettings() { - return Settings.builder().put(networkSettings.build()).build(); - } - - @Override - public Collection> transportClientPlugins() { - return Collections.emptyList(); - } - }; - } - - @Override - public void before() { - if (cluster == null) { - init(); - } - - if (!indexDefinitions.isEmpty()) { - EsClient esClient = new NonClosingEsClient(cluster.client()); - ComponentContainer container = new ComponentContainer(); - container.addSingleton(new MapSettings()); - container.addSingleton(new ConfigurationProvider()); - container.addSingletons(indexDefinitions); - container.addSingleton(esClient); - container.addSingleton(IndexDefinitions.class); - container.addSingleton(IndexCreator.class); - container.addSingleton(MetadataIndex.class); - container.addSingleton(MetadataIndexDefinition.class); - container.addSingleton(TestEsDbCompatibility.class); - - Logger logger = Loggers.get(IndexCreator.class); - LoggerLevel oldLevel = logger.getLevel(); - if (oldLevel == LoggerLevel.INFO) { - logger.setLevel(LoggerLevel.WARN); - } - - try { - container.startComponents(); - } finally { - logger.setLevel(oldLevel); - } - - container.stopComponents(); - client().close(); + /** + * New instance which contains the core indices (rules, issues, ...). + */ + public static EsTester core() { + if (!CORE_INDICES_CREATED.get()) { + Configuration config = new MapSettings().asConfig(); + List createdIndices = createIndices( + new ComponentIndexDefinition(config), + IssueIndexDefinition.createForTest(), + new ProjectMeasuresIndexDefinition(config), + RuleIndexDefinition.createForTest(), + new TestIndexDefinition(config), + new UserIndexDefinition(config), + new ViewIndexDefinition(config)); + + CORE_INDICES_CREATED.set(true); + createdIndices.stream().map(IndexDefinitions.Index::getName).forEach(CORE_INDICES_NAMES::add); } + return new EsTester(false); } - public static class NonClosingEsClient extends EsClient { - NonClosingEsClient(Client nativeClient) { - super(nativeClient); - } - - @Override - public void close() { - // do nothing - } + /** + * New instance which contains the specified indices. Note that + * core indices may exist. + */ + public static EsTester custom(IndexDefinition... definitions) { + createIndices(definitions); + return new EsTester(true); } @Override - public void after() { - try { - afterTest(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void afterTest() throws Exception { - if (cluster != null) { - MetaData metaData = cluster.client().admin().cluster().prepareState().execute().actionGet().getState().getMetaData(); - assertEquals("test leaves persistent cluster metadata behind: " + metaData.persistentSettings().getAsMap(), - 0, - metaData.persistentSettings().getAsMap().size()); - assertEquals("test leaves transient cluster metadata behind: " + metaData.transientSettings().getAsMap(), 0, metaData - .transientSettings().getAsMap().size()); - ensureClusterSizeConsistency(); - ensureClusterStateConsistency(); - cluster.beforeIndexDeletion(); - cluster.wipe(NO_TEMPLATES_SURVIVING_WIPE); // wipe after to make sure we fail in the test that didn't ack the delete - cluster.assertAfterTest(); - } - } - - private void ensureClusterSizeConsistency() { - if (cluster != null) { // if static init fails the cluster can be null - // logger.trace("Check consistency for [{}] nodes", cluster().size()); - assertNoTimeout(cluster.client().admin().cluster().prepareHealth().setWaitForNodes(Integer.toString(cluster.size())).get()); + protected void after() { + if (isCustom) { + // delete non-core indices + String[] existingIndices = SHARED_NODE.client().admin().indices().prepareGetIndex().get().getIndices(); + Stream.of(existingIndices) + .filter(i -> !CORE_INDICES_NAMES.contains(i)) + .forEach(EsTester::deleteIndexIfExists); } + BulkIndexer.delete(client(), new IndexType("_all", ""), client().prepareSearch("_all").setQuery(matchAllQuery())); } - /** - * Verifies that all nodes that have the same version of the cluster state as master have same cluster state - */ - private void ensureClusterStateConsistency() throws IOException { - if (cluster != null) { - ClusterState masterClusterState = cluster.client().admin().cluster().prepareState().all().get().getState(); - Map masterStateMap = convertToMap(masterClusterState); - int masterClusterStateSize = ClusterState.Builder.toBytes(masterClusterState).length; - String masterId = masterClusterState.nodes().getMasterNodeId(); - for (Client client : cluster.getClients()) { - ClusterState localClusterState = client.admin().cluster().prepareState().all().setLocal(true).get().getState(); - final Map localStateMap = convertToMap(localClusterState); - final int localClusterStateSize = ClusterState.Builder.toBytes(localClusterState).length; - // Check that the non-master node has the same version of the cluster state as the master and - // that the master node matches the master (otherwise there is no requirement for the cluster state to match) - if (masterClusterState.version() == localClusterState.version() && masterId.equals(localClusterState.nodes().getMasterNodeId())) { - try { - assertEquals("clusterstate UUID does not match", masterClusterState.stateUUID(), localClusterState.stateUUID()); - // We cannot compare serialization bytes since serialization order of maps is not guaranteed - // but we can compare serialization sizes - they should be the same - assertEquals("clusterstate size does not match", masterClusterStateSize, localClusterStateSize); - // Compare JSON serialization - assertNull("clusterstate JSON serialization does not match", differenceBetweenMapsIgnoringArrayOrder(masterStateMap, localStateMap)); - } catch (AssertionError error) { - // logger.error("Cluster state from master:\n{}\nLocal cluster state:\n{}", masterClusterState.toString(), localClusterState.toString()); - throw error; - } - } - } - } - - } - - public void deleteIndex(String indexName) { - cluster.wipeIndices(indexName); + public EsClient client() { + return new EsClient(SHARED_NODE.client()); } public void putDocuments(String index, String type, BaseDoc... docs) { @@ -267,7 +152,7 @@ public class EsTester extends ExternalResource { public void putDocuments(IndexType indexType, BaseDoc... docs) { try { - BulkRequestBuilder bulk = cluster.client().prepareBulk() + BulkRequestBuilder bulk = SHARED_NODE.client().prepareBulk() .setRefreshPolicy(REFRESH_IMMEDIATE); for (BaseDoc doc : docs) { bulk.add(new IndexRequest(indexType.getIndex(), indexType.getType(), doc.getId()) @@ -284,11 +169,11 @@ public class EsTester extends ExternalResource { } } - public void putDocuments(IndexType indexType, Map... docs) { + public void putDocuments(IndexType indexType, Map... docs) { try { - BulkRequestBuilder bulk = cluster.client().prepareBulk() + BulkRequestBuilder bulk = SHARED_NODE.client().prepareBulk() .setRefreshPolicy(REFRESH_IMMEDIATE); - for (Map doc : docs) { + for (Map doc : docs) { bulk.add(new IndexRequest(indexType.getIndex(), indexType.getType()) .source(doc)); } @@ -328,8 +213,7 @@ public class EsTester extends ExternalResource { * Get all the indexed documents (no paginated results). Results are not sorted. */ public List getDocuments(IndexType indexType) { - Client client = cluster.client(); - SearchRequestBuilder req = client.prepareSearch(indexType.getIndex()).setTypes(indexType.getType()).setQuery(QueryBuilders.matchAllQuery()); + SearchRequestBuilder req = SHARED_NODE.client().prepareSearch(indexType.getIndex()).setTypes(indexType.getType()).setQuery(matchAllQuery()); EsUtils.optimizeScrollRequest(req); req.setScroll(new TimeValue(60000)) .setSize(100); @@ -338,7 +222,7 @@ public class EsTester extends ExternalResource { List result = newArrayList(); while (true) { Iterables.addAll(result, response.getHits()); - response = client.prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(600000)).execute().actionGet(); + response = SHARED_NODE.client().prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(600000)).execute().actionGet(); // Break condition: No hits are returned if (response.getHits().getHits().length == 0) { break; @@ -351,47 +235,100 @@ public class EsTester extends ExternalResource { * Get a list of a specific field from all indexed documents. */ public List getDocumentFieldValues(IndexType indexType, final String fieldNameToReturn) { - return newArrayList(Iterables.transform(getDocuments(indexType), new Function() { - @Override - public T apply(SearchHit input) { - return (T) input.sourceAsMap().get(fieldNameToReturn); - } - })); + return newArrayList(Iterables.transform(getDocuments(indexType), input -> (T) input.sourceAsMap().get(fieldNameToReturn))); } public List getIds(IndexType indexType) { return getDocuments(indexType).stream().map(SearchHit::id).collect(Collectors.toList()); } - public EsClient client() { - // EsClient which do not hold any reference to client returned by cluster and does not close them, to avoid leaks - return new EsClient() { - @Override - public Client nativeClient() { - return cluster.client(); - } - - @Override - public void close() { - // do nothing - } - }; - } - - public EsTester lockWrites(IndexType index) { - return setIndexSettings(index.getIndex(), ImmutableMap.of("index.blocks.write", "true")); + public void lockWrites(IndexType index) { + setIndexSettings(index.getIndex(), ImmutableMap.of("index.blocks.write", "true")); } - public EsTester unlockWrites(IndexType index) { - return setIndexSettings(index.getIndex(), ImmutableMap.of("index.blocks.write", "false")); + public void unlockWrites(IndexType index) { + setIndexSettings(index.getIndex(), ImmutableMap.of("index.blocks.write", "false")); } - private EsTester setIndexSettings(String index, Map settings) { - UpdateSettingsResponse response = client().nativeClient().admin().indices() + private void setIndexSettings(String index, Map settings) { + UpdateSettingsResponse response = SHARED_NODE.client().admin().indices() .prepareUpdateSettings(index) .setSettings(settings) .get(); checkState(response.isAcknowledged()); - return this; + } + + private static void deleteIndexIfExists(String name) { + try { + DeleteIndexResponse response = SHARED_NODE.client().admin().indices().prepareDelete(name).get(); + checkState(response.isAcknowledged(), "Fail to drop the index " + name); + } catch (IndexNotFoundException e) { + // ignore + } + } + + private static List createIndices(IndexDefinition... definitions) { + IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext(); + Stream.of(definitions).forEach(d -> d.define(context)); + + List result = new ArrayList<>(); + for (NewIndex newIndex : context.getIndices().values()) { + IndexDefinitions.Index index = new IndexDefinitions.Index(newIndex); + + deleteIndexIfExists(index.getName()); + + // create index + Settings.Builder settings = Settings.builder(); + settings.put(index.getSettings()); + CreateIndexResponse indexResponse = SHARED_NODE.client().admin().indices() + .prepareCreate(index.getName()) + .setSettings(settings) + .get(); + if (!indexResponse.isAcknowledged()) { + throw new IllegalStateException("Failed to create index " + index.getName()); + } + SHARED_NODE.client().admin().cluster().prepareHealth(index.getName()).setWaitForStatus(ClusterHealthStatus.YELLOW).get(); + + // create types + for (Map.Entry entry : index.getTypes().entrySet()) { + PutMappingResponse mappingResponse = SHARED_NODE.client().admin().indices().preparePutMapping(index.getName()) + .setType(entry.getKey()) + .setSource(entry.getValue().getAttributes()) + .get(); + if (!mappingResponse.isAcknowledged()) { + throw new IllegalStateException("Failed to create type " + entry.getKey()); + } + } + SHARED_NODE.client().admin().cluster().prepareHealth(index.getName()).setWaitForStatus(ClusterHealthStatus.YELLOW).get(); + result.add(index); + } + return result; + } + + private static Node createNode() { + try { + Path tempDir = Files.createTempDirectory("EsTester"); + tempDir.toFile().deleteOnExit(); + Settings settings = Settings.builder() + .put(Environment.PATH_HOME_SETTING.getKey(), tempDir) + .put("node.name", "EsTester") + .put(NodeEnvironment.MAX_LOCAL_STORAGE_NODES_SETTING.getKey(), Integer.MAX_VALUE) + .put("logger.level", "INFO") + .put("action.auto_create_index", false) + // Default the watermarks to absurdly low to prevent the tests + // from failing on nodes without enough disk space + .put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK_SETTING.getKey(), "1b") + .put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK_SETTING.getKey(), "1b") + // always reduce this - it can make tests really slow + .put(RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING.getKey(), TimeValue.timeValueMillis(20)) + .put(NetworkModule.TRANSPORT_TYPE_KEY, "local") + .put(NetworkModule.HTTP_ENABLED.getKey(), false) + .put(DiscoveryModule.DISCOVERY_TYPE_SETTING.getKey(), "single-node") + .build(); + MockNode node = new MockNode(settings, emptyList()); + return node.start(); + } catch (Exception e) { + throw new IllegalStateException("Fail to start embedded Elasticsearch", e); + } } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/IndexCreatorTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/IndexCreatorTest.java index 0732603b824..8e4db8cb91c 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/IndexCreatorTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/IndexCreatorTest.java @@ -20,7 +20,6 @@ package org.sonar.server.es; import com.google.common.collect.ImmutableMap; -import java.io.IOException; import java.util.Map; import java.util.function.Consumer; import javax.annotation.CheckForNull; @@ -49,7 +48,7 @@ public class IndexCreatorTest { public LogTester logTester = new LogTester(); @Rule - public EsTester es = new EsTester(); + public EsTester es = EsTester.custom(); private MetadataIndexDefinition metadataIndexDefinition = new MetadataIndexDefinition(new MapSettings().asConfig()); private MetadataIndex metadataIndex = new MetadataIndex(es.client()); @@ -57,9 +56,7 @@ public class IndexCreatorTest { private MapSettings settings = new MapSettings(); @Test - public void create_index() throws Exception { - assertThat(mappings()).isEmpty(); - + public void create_index() { IndexCreator underTest = startNewCreator(new FakeIndexDefinition()); // check that index is created with related mapping @@ -78,18 +75,18 @@ public class IndexCreatorTest { @Test public void mark_all_non_existing_index_types_as_uninitialized() { startNewCreator(context -> { - NewIndex i = context.create("i", SETTINGS_CONFIGURATION); + NewIndex i = context.create("fakes", SETTINGS_CONFIGURATION); i.createType("t1"); i.createType("t2"); }); - assertThat(metadataIndex.getHash("i")).isNotEmpty(); - assertThat(metadataIndex.getInitialized(new IndexType("i", "t1"))).isFalse(); - assertThat(metadataIndex.getInitialized(new IndexType("i", "t2"))).isFalse(); + assertThat(metadataIndex.getHash("fakes")).isNotEmpty(); + assertThat(metadataIndex.getInitialized(new IndexType("fakes", "t1"))).isFalse(); + assertThat(metadataIndex.getInitialized(new IndexType("fakes", "t2"))).isFalse(); } @Test - public void recreate_index_on_definition_changes() throws Exception { + public void recreate_index_on_definition_changes() { // v1 startNewCreator(new FakeIndexDefinition()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/IndexerStartupTaskTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/IndexerStartupTaskTest.java index 38479be76d5..c4e5e0b1e17 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/IndexerStartupTaskTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/IndexerStartupTaskTest.java @@ -37,7 +37,7 @@ import static org.sonar.server.es.FakeIndexDefinition.INDEX_TYPE_FAKE; public class IndexerStartupTaskTest { @Rule - public EsTester es = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); private final MapSettings settings = new MapSettings(); private final MetadataIndex metadataIndex = mock(MetadataIndex.class); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/OneToManyResilientIndexingListenerTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/OneToManyResilientIndexingListenerTest.java index a31fb3b1ce0..837d28a0d6c 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/OneToManyResilientIndexingListenerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/OneToManyResilientIndexingListenerTest.java @@ -25,12 +25,10 @@ import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.es.EsQueueDto; import org.sonar.server.component.index.ComponentIndexDefinition; -import org.sonar.server.issue.index.IssueIndexDefinition; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; @@ -41,7 +39,7 @@ import static org.sonar.server.issue.index.IssueIndexDefinition.INDEX_TYPE_ISSUE public class OneToManyResilientIndexingListenerTest { @Rule - public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/OneToOneResilientIndexingListenerTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/OneToOneResilientIndexingListenerTest.java index 6e189421bde..80276c731e7 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/OneToOneResilientIndexingListenerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/OneToOneResilientIndexingListenerTest.java @@ -25,11 +25,9 @@ import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.es.EsQueueDto; -import org.sonar.server.issue.index.IssueIndexDefinition; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; @@ -41,7 +39,7 @@ import static org.sonar.server.issue.index.IssueIndexDefinition.INDEX_TYPE_ISSUE public class OneToOneResilientIndexingListenerTest { @Rule - public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/RecoveryIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/RecoveryIndexerTest.java index 86a9ee5980e..434985e6f7e 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/RecoveryIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/RecoveryIndexerTest.java @@ -63,7 +63,7 @@ public class RecoveryIndexerTest { private MapSettings emptySettings = new MapSettings(); @Rule - public EsTester es = new EsTester(); + public EsTester es = EsTester.custom(); @Rule public DbTester db = DbTester.create(system2); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java index 299032bbe8b..a925871b364 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java @@ -38,7 +38,7 @@ public class EsDbCompatibilityImplTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule - public EsTester es = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new MetadataIndexDefinitionBridge(), new FakeIndexDefinition()); private DbClient dbClient = mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS); private MigrationHistory migrationHistory = mock(MigrationHistory.class); private MetadataIndex metadataIndex = new MetadataIndex(es.client()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexDefinitionBridge.java b/server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexDefinitionBridge.java new file mode 100644 index 00000000000..74ff05f8bf8 --- /dev/null +++ b/server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexDefinitionBridge.java @@ -0,0 +1,30 @@ +/* + * SonarQube + * Copyright (C) 2009-2018 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.server.es.metadata; + +import org.sonar.api.config.internal.MapSettings; +import org.sonar.server.es.IndexDefinition; + +class MetadataIndexDefinitionBridge implements IndexDefinition { + @Override + public void define(IndexDefinitionContext context) { + new MetadataIndexDefinition(new MapSettings().asConfig()).define(context); + } +} diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexTest.java index 7dfd321390f..fce57398521 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexTest.java @@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class MetadataIndexTest { @Rule - public EsTester es = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new MetadataIndexDefinitionBridge(), new FakeIndexDefinition()); private final MetadataIndex underTest = new MetadataIndex(es.client()); private final String index = randomAlphanumeric(20); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyBulkRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyBulkRequestBuilderTest.java index d4b87fdcafd..fd275f86735 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyBulkRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyBulkRequestBuilderTest.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class ProxyBulkRequestBuilderTest { @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @@ -57,7 +57,7 @@ public class ProxyBulkRequestBuilderTest { } private void testBulk() { - BulkRequestBuilder req = esTester.client().prepareBulk(); + BulkRequestBuilder req = es.client().prepareBulk(); req.add(new UpdateRequest(FakeIndexDefinition.INDEX, FakeIndexDefinition.INDEX_TYPE_FAKE.getType(), "key1") .doc(FakeIndexDefinition.newDoc(1).getFields())); req.add(new DeleteRequest(FakeIndexDefinition.INDEX, FakeIndexDefinition.INDEX_TYPE_FAKE.getType(), "key2")); @@ -73,17 +73,17 @@ public class ProxyBulkRequestBuilderTest { @Test(expected = UnsupportedOperationException.class) public void get_with_string_timeout_is_not_yet_implemented() { - esTester.client().prepareBulk().get("1"); + es.client().prepareBulk().get("1"); } @Test(expected = UnsupportedOperationException.class) public void get_with_time_value_timeout_is_not_yet_implemented() { - esTester.client().prepareBulk().get(TimeValue.timeValueMinutes(1)); + es.client().prepareBulk().get(TimeValue.timeValueMinutes(1)); } @Test(expected = UnsupportedOperationException.class) public void execute_is_not_yet_implemented() { - esTester.client().prepareBulk().execute(); + es.client().prepareBulk().execute(); } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilderTest.java index ce83f849f3c..c5240702527 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilderTest.java @@ -21,7 +21,6 @@ package org.sonar.server.es.request; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequestBuilder; import org.elasticsearch.common.unit.TimeValue; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.log.LogTester; @@ -33,8 +32,8 @@ import static org.junit.Assert.fail; public class ProxyClearCacheRequestBuilderTest { - @ClassRule - public static EsTester esTester = new EsTester(); + @Rule + public EsTester esTester = EsTester.core(); @Rule public LogTester logTester = new LogTester(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilderTest.java index c3a9208ba5c..1925ff49ef0 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilderTest.java @@ -21,7 +21,6 @@ package org.sonar.server.es.request; import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder; import org.elasticsearch.common.unit.TimeValue; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; @@ -34,29 +33,29 @@ import static org.junit.Assert.fail; public class ProxyCreateIndexRequestBuilderTest { - @ClassRule - public static EsTester esTester = new EsTester(); + @Rule + public EsTester es = EsTester.custom(); @Rule public LogTester logTester = new LogTester(); @Test public void create_index() { - CreateIndexRequestBuilder requestBuilder = esTester.client().prepareCreate(generateNewIndexName()); + CreateIndexRequestBuilder requestBuilder = es.client().prepareCreate(generateNewIndexName()); requestBuilder.get(); } @Test public void to_string() { String indexName = generateNewIndexName(); - assertThat(esTester.client().prepareCreate(indexName).toString()).contains("ES create index '" + indexName + "'"); + assertThat(es.client().prepareCreate(indexName).toString()).contains("ES create index '" + indexName + "'"); } @Test public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - CreateIndexRequestBuilder requestBuilder = esTester.client().prepareCreate(generateNewIndexName()); + CreateIndexRequestBuilder requestBuilder = es.client().prepareCreate(generateNewIndexName()); requestBuilder.get(); assertThat(logTester.logs()).hasSize(1); } @@ -64,7 +63,7 @@ public class ProxyCreateIndexRequestBuilderTest { @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().prepareCreate(generateNewIndexName()).get("1"); + es.client().prepareCreate(generateNewIndexName()).get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -74,7 +73,7 @@ public class ProxyCreateIndexRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().prepareCreate(generateNewIndexName()).get(TimeValue.timeValueMinutes(1)); + es.client().prepareCreate(generateNewIndexName()).get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -84,7 +83,7 @@ public class ProxyCreateIndexRequestBuilderTest { @Test public void execute_should_throw_an_unsupported_operation_exception() { try { - esTester.client().prepareCreate(generateNewIndexName()).execute(); + es.client().prepareCreate(generateNewIndexName()).execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteRequestBuilderTest.java index eb3dc8b6bfc..8f0fe77c871 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteRequestBuilderTest.java @@ -20,7 +20,6 @@ package org.sonar.server.es.request; import org.elasticsearch.common.unit.TimeValue; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.log.LogTester; @@ -33,26 +32,26 @@ import static org.junit.Assert.fail; public class ProxyDeleteRequestBuilderTest { - @ClassRule - public static EsTester esTester = new EsTester(new FakeIndexDefinition()); + @Rule + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @Test public void delete() { - esTester.client().prepareDelete("fakes", "fake", "the_id").get(); + es.client().prepareDelete("fakes", "fake", "the_id").get(); } @Test public void to_string() { - assertThat(esTester.client().prepareDelete("fakes", "fake", "the_id").toString()).isEqualTo("ES delete request of doc the_id in index fakes/fake"); + assertThat(es.client().prepareDelete("fakes", "fake", "the_id").toString()).isEqualTo("ES delete request of doc the_id in index fakes/fake"); } @Test public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - esTester.client().prepareDelete("fakes", "fake", "the_id").get(); + es.client().prepareDelete("fakes", "fake", "the_id").get(); assertThat(logTester.logs()).hasSize(1); } @@ -60,7 +59,7 @@ public class ProxyDeleteRequestBuilderTest { @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().prepareDelete("fakes", "fake", "the_id").get("1"); + es.client().prepareDelete("fakes", "fake", "the_id").get("1"); fail(); } catch (UnsupportedOperationException e) { assertThat(e).hasMessage("Not yet implemented"); @@ -70,7 +69,7 @@ public class ProxyDeleteRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().prepareDelete("fakes", "fake", "the_id").get(TimeValue.timeValueMinutes(1)); + es.client().prepareDelete("fakes", "fake", "the_id").get(TimeValue.timeValueMinutes(1)); fail(); } catch (UnsupportedOperationException e) { assertThat(e).hasMessage("Not yet implemented"); @@ -80,7 +79,7 @@ public class ProxyDeleteRequestBuilderTest { @Test public void execute_should_throw_an_unsupported_operation_exception() { try { - esTester.client().prepareDelete("fakes", "fake", "the_id").execute(); + es.client().prepareDelete("fakes", "fake", "the_id").execute(); fail(); } catch (UnsupportedOperationException e) { assertThat(e).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyFlushRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyFlushRequestBuilderTest.java index 61fef8fd317..9733723e213 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyFlushRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyFlushRequestBuilderTest.java @@ -33,34 +33,34 @@ import static org.junit.Assert.fail; public class ProxyFlushRequestBuilderTest { @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @Test public void flush() { - esTester.client().prepareFlush(FakeIndexDefinition.INDEX).get(); + es.client().prepareFlush(FakeIndexDefinition.INDEX).get(); } @Test public void to_string() { - assertThat(esTester.client().prepareFlush(FakeIndexDefinition.INDEX).toString()).isEqualTo("ES flush request on indices 'fakes'"); - assertThat(esTester.client().prepareFlush().toString()).isEqualTo("ES flush request"); + assertThat(es.client().prepareFlush(FakeIndexDefinition.INDEX).toString()).isEqualTo("ES flush request on indices 'fakes'"); + assertThat(es.client().prepareFlush().toString()).isEqualTo("ES flush request"); } @Test public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - esTester.client().prepareFlush(FakeIndexDefinition.INDEX).get(); + es.client().prepareFlush(FakeIndexDefinition.INDEX).get(); assertThat(logTester.logs(LoggerLevel.TRACE)).hasSize(1); } @Test public void fail_to_refresh() { try { - esTester.client().prepareFlush("unknown").get(); + es.client().prepareFlush("unknown").get(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class); @@ -71,7 +71,7 @@ public class ProxyFlushRequestBuilderTest { @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().prepareFlush(FakeIndexDefinition.INDEX).get("1"); + es.client().prepareFlush(FakeIndexDefinition.INDEX).get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -81,7 +81,7 @@ public class ProxyFlushRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().prepareFlush(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1)); + es.client().prepareFlush(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -91,7 +91,7 @@ public class ProxyFlushRequestBuilderTest { @Test public void execute_should_throw_an_unsupported_operation_exception() { try { - esTester.client().prepareFlush(FakeIndexDefinition.INDEX).execute(); + es.client().prepareFlush(FakeIndexDefinition.INDEX).execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyGetRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyGetRequestBuilderTest.java index 697f96809d2..ef44c72b179 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyGetRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyGetRequestBuilderTest.java @@ -34,14 +34,14 @@ import static org.junit.Assert.fail; public class ProxyGetRequestBuilderTest { @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @Test public void get() { - esTester.client().prepareGet() + es.client().prepareGet() .setIndex(FakeIndexDefinition.INDEX) .setType(FakeIndexDefinition.TYPE) .setId("ruleKey") @@ -52,7 +52,7 @@ public class ProxyGetRequestBuilderTest { public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - esTester.client().prepareGet() + es.client().prepareGet() .setIndex(FakeIndexDefinition.INDEX) .setType(FakeIndexDefinition.TYPE) .setId("ruleKey") @@ -62,7 +62,7 @@ public class ProxyGetRequestBuilderTest { @Test public void fail_to_get_bad_query() { - GetRequestBuilder requestBuilder = esTester.client().prepareGet() + GetRequestBuilder requestBuilder = es.client().prepareGet() .setIndex("unknown") .setType("test") .setId("rule1"); @@ -78,7 +78,7 @@ public class ProxyGetRequestBuilderTest { @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().prepareGet().get("1"); + es.client().prepareGet().get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -88,7 +88,7 @@ public class ProxyGetRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().prepareGet().get(TimeValue.timeValueMinutes(1)); + es.client().prepareGet().get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -98,7 +98,7 @@ public class ProxyGetRequestBuilderTest { @Test public void execute_should_throw_an_unsupported_operation_exception() { try { - esTester.client().prepareGet().execute(); + es.client().prepareGet().execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndexRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndexRequestBuilderTest.java index 6fe786b8db9..c3116f77ff3 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndexRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndexRequestBuilderTest.java @@ -37,14 +37,14 @@ import static org.junit.Assert.fail; public class ProxyIndexRequestBuilderTest { @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @Test public void index_with_index_type_and_id() { - IndexResponse response = esTester.client().prepareIndex(FakeIndexDefinition.INDEX_TYPE_FAKE) + IndexResponse response = es.client().prepareIndex(FakeIndexDefinition.INDEX_TYPE_FAKE) .setSource(FakeIndexDefinition.newDoc(42).getFields()) .get(); assertThat(response.getResult()).isSameAs(Result.CREATED); @@ -53,7 +53,7 @@ public class ProxyIndexRequestBuilderTest { @Test public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - IndexResponse response = esTester.client().prepareIndex(FakeIndexDefinition.INDEX_TYPE_FAKE) + IndexResponse response = es.client().prepareIndex(FakeIndexDefinition.INDEX_TYPE_FAKE) .setSource(FakeIndexDefinition.newDoc(42).getFields()) .get(); assertThat(response.getResult()).isSameAs(Result.CREATED); @@ -62,7 +62,7 @@ public class ProxyIndexRequestBuilderTest { @Test public void fail_if_bad_query() { - IndexRequestBuilder requestBuilder = esTester.client().prepareIndex(new IndexType("unknownIndex", "unknownType")); + IndexRequestBuilder requestBuilder = es.client().prepareIndex(new IndexType("unknownIndex", "unknownType")); try { requestBuilder.get(); fail(); @@ -74,7 +74,7 @@ public class ProxyIndexRequestBuilderTest { @Test public void fail_if_bad_query_with_basic_profiling() { - IndexRequestBuilder requestBuilder = esTester.client().prepareIndex(new IndexType("unknownIndex", "unknownType")); + IndexRequestBuilder requestBuilder = es.client().prepareIndex(new IndexType("unknownIndex", "unknownType")); try { requestBuilder.get(); fail(); @@ -87,7 +87,7 @@ public class ProxyIndexRequestBuilderTest { @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().prepareIndex(FakeIndexDefinition.INDEX_TYPE_FAKE).get("1"); + es.client().prepareIndex(FakeIndexDefinition.INDEX_TYPE_FAKE).get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -97,7 +97,7 @@ public class ProxyIndexRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().prepareIndex(FakeIndexDefinition.INDEX_TYPE_FAKE).get(TimeValue.timeValueMinutes(1)); + es.client().prepareIndex(FakeIndexDefinition.INDEX_TYPE_FAKE).get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -107,7 +107,7 @@ public class ProxyIndexRequestBuilderTest { @Test public void do_not_support_execute_method() { try { - esTester.client().prepareIndex(FakeIndexDefinition.INDEX_TYPE_FAKE).execute(); + es.client().prepareIndex(FakeIndexDefinition.INDEX_TYPE_FAKE).execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilderTest.java index b68d28ff3f7..b593772772d 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilderTest.java @@ -33,22 +33,22 @@ import static org.junit.Assert.fail; public class ProxyIndicesExistsRequestBuilderTest { @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @Test public void exists() { - assertThat(esTester.client().prepareIndicesExist(FakeIndexDefinition.INDEX).get().isExists()).isTrue(); - assertThat(esTester.client().prepareIndicesExist("unknown").get().isExists()).isFalse(); + assertThat(es.client().prepareIndicesExist(FakeIndexDefinition.INDEX).get().isExists()).isTrue(); + assertThat(es.client().prepareIndicesExist("unknown").get().isExists()).isFalse(); } @Test public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - esTester.client().prepareIndicesExist(FakeIndexDefinition.INDEX).get(); + es.client().prepareIndicesExist(FakeIndexDefinition.INDEX).get(); assertThat(logTester.logs(LoggerLevel.TRACE)).hasSize(1); } @@ -56,7 +56,7 @@ public class ProxyIndicesExistsRequestBuilderTest { @Test public void fail_to_exists() { try { - esTester.client().prepareIndicesExist().get(); + es.client().prepareIndicesExist().get(); // expected to fail because elasticsearch is not correctly configured, but that does not matter fail(); @@ -68,13 +68,13 @@ public class ProxyIndicesExistsRequestBuilderTest { @Test public void to_string() { - assertThat(esTester.client().prepareIndicesExist(FakeIndexDefinition.INDEX).toString()).isEqualTo("ES indices exists request on indices 'fakes'"); + assertThat(es.client().prepareIndicesExist(FakeIndexDefinition.INDEX).toString()).isEqualTo("ES indices exists request on indices 'fakes'"); } @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().prepareIndicesExist().get("1"); + es.client().prepareIndicesExist().get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -84,7 +84,7 @@ public class ProxyIndicesExistsRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().prepareIndicesExist().get(TimeValue.timeValueMinutes(1)); + es.client().prepareIndicesExist().get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -94,7 +94,7 @@ public class ProxyIndicesExistsRequestBuilderTest { @Test public void execute_should_throw_an_unsupported_operation_exception() { try { - esTester.client().prepareIndicesExist().execute(); + es.client().prepareIndicesExist().execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilderTest.java index 944a95966c8..6db4fad2b97 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilderTest.java @@ -33,27 +33,27 @@ import static org.junit.Assert.fail; public class ProxyIndicesStatsRequestBuilderTest { @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @Test public void stats() { - esTester.client().prepareStats(FakeIndexDefinition.INDEX).get(); + es.client().prepareStats(FakeIndexDefinition.INDEX).get(); } @Test public void to_string() { - assertThat(esTester.client().prepareStats(FakeIndexDefinition.INDEX).setIndices("rules").toString()).isEqualTo("ES indices stats request on indices 'rules'"); - assertThat(esTester.client().prepareStats().toString()).isEqualTo("ES indices stats request"); + assertThat(es.client().prepareStats(FakeIndexDefinition.INDEX).setIndices("rules").toString()).isEqualTo("ES indices stats request on indices 'rules'"); + assertThat(es.client().prepareStats().toString()).isEqualTo("ES indices stats request"); } @Test public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - esTester.client().prepareStats(FakeIndexDefinition.INDEX).get(); + es.client().prepareStats(FakeIndexDefinition.INDEX).get(); assertThat(logTester.logs(LoggerLevel.TRACE)).hasSize(1); } @@ -61,7 +61,7 @@ public class ProxyIndicesStatsRequestBuilderTest { @Test public void fail_to_stats() { try { - esTester.client().prepareStats("unknown").get(); + es.client().prepareStats("unknown").get(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class); @@ -72,7 +72,7 @@ public class ProxyIndicesStatsRequestBuilderTest { @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().prepareStats(FakeIndexDefinition.INDEX).get("1"); + es.client().prepareStats(FakeIndexDefinition.INDEX).get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -82,7 +82,7 @@ public class ProxyIndicesStatsRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().prepareStats(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1)); + es.client().prepareStats(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -92,7 +92,7 @@ public class ProxyIndicesStatsRequestBuilderTest { @Test public void execute_should_throw_an_unsupported_operation_exception() { try { - esTester.client().prepareStats(FakeIndexDefinition.INDEX).execute(); + es.client().prepareStats(FakeIndexDefinition.INDEX).execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilderTest.java index bfce97a5bda..59b5722a823 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilderTest.java @@ -36,14 +36,14 @@ import static org.junit.Assert.fail; public class ProxyMultiGetRequestBuilderTest { @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @Test public void multi_get() { - MultiGetRequestBuilder request = esTester.client().prepareMultiGet(); + MultiGetRequestBuilder request = es.client().prepareMultiGet(); request.add(new MultiGetRequest.Item(FakeIndexDefinition.INDEX, FakeIndexDefinition.TYPE, "ruleKey") .fetchSourceContext(FetchSourceContext.FETCH_SOURCE)); request.get(); @@ -52,10 +52,10 @@ public class ProxyMultiGetRequestBuilderTest { @Test public void to_string() { - assertThat(esTester.client().prepareMultiGet().toString()).isEqualTo("ES multi get request"); - assertThat(esTester.client().prepareMultiGet().add(new MultiGetRequest.Item(FakeIndexDefinition.INDEX, null, "fake1") + assertThat(es.client().prepareMultiGet().toString()).isEqualTo("ES multi get request"); + assertThat(es.client().prepareMultiGet().add(new MultiGetRequest.Item(FakeIndexDefinition.INDEX, null, "fake1") .fetchSourceContext(FetchSourceContext.FETCH_SOURCE)).toString()).isEqualTo("ES multi get request [key 'fake1', index 'fakes'],"); - assertThat(esTester.client().prepareMultiGet().add(new MultiGetRequest.Item(FakeIndexDefinition.INDEX, FakeIndexDefinition.TYPE, "fake1") + assertThat(es.client().prepareMultiGet().add(new MultiGetRequest.Item(FakeIndexDefinition.INDEX, FakeIndexDefinition.TYPE, "fake1") .fetchSourceContext(FetchSourceContext.FETCH_SOURCE)).toString()).isEqualTo("ES multi get request [key 'fake1', index 'fakes', type 'fake'],"); } @@ -63,7 +63,7 @@ public class ProxyMultiGetRequestBuilderTest { public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - MultiGetRequestBuilder request = esTester.client().prepareMultiGet(); + MultiGetRequestBuilder request = es.client().prepareMultiGet(); request.add(new MultiGetRequest.Item(FakeIndexDefinition.INDEX, FakeIndexDefinition.TYPE, "ruleKey") .fetchSourceContext(FetchSourceContext.FETCH_SOURCE)); request.get(); @@ -74,7 +74,7 @@ public class ProxyMultiGetRequestBuilderTest { @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().prepareMultiGet().get("1"); + es.client().prepareMultiGet().get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -84,7 +84,7 @@ public class ProxyMultiGetRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().prepareMultiGet().get(TimeValue.timeValueMinutes(1)); + es.client().prepareMultiGet().get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -94,7 +94,7 @@ public class ProxyMultiGetRequestBuilderTest { @Test public void execute_should_throw_an_unsupported_operation_exception() { try { - esTester.client().prepareMultiGet().execute(); + es.client().prepareMultiGet().execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilderTest.java index 0e142d43639..cc61d738bee 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilderTest.java @@ -20,7 +20,6 @@ package org.sonar.server.es.request; import org.elasticsearch.common.unit.TimeValue; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -33,8 +32,8 @@ import static org.assertj.core.api.Assertions.assertThat; public class ProxyNodesStatsRequestBuilderTest { - @ClassRule - public static EsTester esTester = new EsTester(); + @Rule + public EsTester es = EsTester.custom(); @Rule public LogTester logTester = new LogTester(); @@ -44,20 +43,20 @@ public class ProxyNodesStatsRequestBuilderTest { @Test public void stats() { - esTester.client().prepareNodesStats().get(); + es.client().prepareNodesStats().get(); } @Test public void to_string() { - assertThat(esTester.client().prepareNodesStats().setNodesIds("node1").toString()).isEqualTo("ES nodes stats request on nodes 'node1'"); - assertThat(esTester.client().prepareNodesStats().toString()).isEqualTo("ES nodes stats request"); + assertThat(es.client().prepareNodesStats().setNodesIds("node1").toString()).isEqualTo("ES nodes stats request on nodes 'node1'"); + assertThat(es.client().prepareNodesStats().toString()).isEqualTo("ES nodes stats request"); } @Test public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - esTester.client().prepareNodesStats().get(); + es.client().prepareNodesStats().get(); assertThat(logTester.logs()).hasSize(1); } @@ -67,7 +66,7 @@ public class ProxyNodesStatsRequestBuilderTest { thrown.expect(IllegalStateException.class); thrown.expectMessage("Not yet implemented"); - esTester.client().prepareNodesStats(FakeIndexDefinition.INDEX).get("1"); + es.client().prepareNodesStats(FakeIndexDefinition.INDEX).get("1"); } @Test @@ -75,7 +74,7 @@ public class ProxyNodesStatsRequestBuilderTest { thrown.expect(IllegalStateException.class); thrown.expectMessage("Not yet implemented"); - esTester.client().prepareNodesStats(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1)); + es.client().prepareNodesStats(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1)); } @Test @@ -83,7 +82,7 @@ public class ProxyNodesStatsRequestBuilderTest { thrown.expect(UnsupportedOperationException.class); thrown.expectMessage("execute() should not be called as it's used for asynchronous"); - esTester.client().prepareNodesStats(FakeIndexDefinition.INDEX).execute(); + es.client().prepareNodesStats(FakeIndexDefinition.INDEX).execute(); } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilderTest.java index 4b98664e5cf..23ff81ef24b 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilderTest.java @@ -37,14 +37,14 @@ import static org.junit.Assert.fail; public class ProxyPutMappingRequestBuilderTest { @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @Test public void put_mapping() { - PutMappingRequestBuilder requestBuilder = esTester.client().preparePutMapping(FakeIndexDefinition.INDEX) + PutMappingRequestBuilder requestBuilder = es.client().preparePutMapping(FakeIndexDefinition.INDEX) .setType(FakeIndexDefinition.TYPE) .setSource(mapDomain()); requestBuilder.get(); @@ -52,9 +52,9 @@ public class ProxyPutMappingRequestBuilderTest { @Test public void to_string() { - assertThat(esTester.client().preparePutMapping(FakeIndexDefinition.INDEX).setSource(mapDomain()).toString()) + assertThat(es.client().preparePutMapping(FakeIndexDefinition.INDEX).setSource(mapDomain()).toString()) .isEqualTo("ES put mapping request on indices 'fakes' with source '{\"dynamic\":false,\"_all\":{\"enabled\":false}}'"); - assertThat(esTester.client().preparePutMapping(FakeIndexDefinition.INDEX).setType(FakeIndexDefinition.TYPE).setSource(mapDomain()).toString()) + assertThat(es.client().preparePutMapping(FakeIndexDefinition.INDEX).setType(FakeIndexDefinition.TYPE).setSource(mapDomain()).toString()) .isEqualTo("ES put mapping request on indices 'fakes' on type 'fake' with source '{\"dynamic\":false,\"_all\":{\"enabled\":false}}'"); } @@ -62,7 +62,7 @@ public class ProxyPutMappingRequestBuilderTest { public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - PutMappingRequestBuilder requestBuilder = esTester.client().preparePutMapping(FakeIndexDefinition.INDEX) + PutMappingRequestBuilder requestBuilder = es.client().preparePutMapping(FakeIndexDefinition.INDEX) .setType(FakeIndexDefinition.TYPE) .setSource(mapDomain()); requestBuilder.get(); @@ -73,7 +73,7 @@ public class ProxyPutMappingRequestBuilderTest { @Test public void fail_on_bad_query() { try { - esTester.client().preparePutMapping().get(); + es.client().preparePutMapping().get(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class); @@ -84,7 +84,7 @@ public class ProxyPutMappingRequestBuilderTest { @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().preparePutMapping().get("1"); + es.client().preparePutMapping().get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -94,7 +94,7 @@ public class ProxyPutMappingRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().preparePutMapping().get(TimeValue.timeValueMinutes(1)); + es.client().preparePutMapping().get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -104,7 +104,7 @@ public class ProxyPutMappingRequestBuilderTest { @Test public void execute_should_throw_an_unsupported_operation_exception() { try { - esTester.client().preparePutMapping().execute(); + es.client().preparePutMapping().execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyRefreshRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyRefreshRequestBuilderTest.java index ae2aad75cb0..6a8c39a6954 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyRefreshRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyRefreshRequestBuilderTest.java @@ -34,28 +34,28 @@ import static org.junit.Assert.fail; public class ProxyRefreshRequestBuilderTest { @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @Test public void refresh() { - RefreshRequestBuilder requestBuilder = esTester.client().prepareRefresh(FakeIndexDefinition.INDEX); + RefreshRequestBuilder requestBuilder = es.client().prepareRefresh(FakeIndexDefinition.INDEX); requestBuilder.get(); } @Test public void to_string() { - assertThat(esTester.client().prepareRefresh(FakeIndexDefinition.INDEX).toString()).isEqualTo("ES refresh request on indices 'fakes'"); - assertThat(esTester.client().prepareRefresh().toString()).isEqualTo("ES refresh request"); + assertThat(es.client().prepareRefresh(FakeIndexDefinition.INDEX).toString()).isEqualTo("ES refresh request on indices 'fakes'"); + assertThat(es.client().prepareRefresh().toString()).isEqualTo("ES refresh request"); } @Test public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - RefreshRequestBuilder requestBuilder = esTester.client().prepareRefresh(FakeIndexDefinition.INDEX); + RefreshRequestBuilder requestBuilder = es.client().prepareRefresh(FakeIndexDefinition.INDEX); requestBuilder.get(); assertThat(logTester.logs(LoggerLevel.TRACE)).hasSize(1); } @@ -63,7 +63,7 @@ public class ProxyRefreshRequestBuilderTest { @Test public void fail_to_refresh() { try { - esTester.client().prepareRefresh("unknown").get(); + es.client().prepareRefresh("unknown").get(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class); @@ -74,7 +74,7 @@ public class ProxyRefreshRequestBuilderTest { @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().prepareRefresh(FakeIndexDefinition.INDEX).get("1"); + es.client().prepareRefresh(FakeIndexDefinition.INDEX).get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -84,7 +84,7 @@ public class ProxyRefreshRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().prepareRefresh(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1)); + es.client().prepareRefresh(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -94,7 +94,7 @@ public class ProxyRefreshRequestBuilderTest { @Test public void execute_should_throw_an_unsupported_operation_exception() { try { - esTester.client().prepareRefresh(FakeIndexDefinition.INDEX).execute(); + es.client().prepareRefresh(FakeIndexDefinition.INDEX).execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchRequestBuilderTest.java index a0a6ed6fba7..fb0e219dbbf 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchRequestBuilderTest.java @@ -34,36 +34,36 @@ import static org.junit.Assert.fail; public class ProxySearchRequestBuilderTest { @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @Test public void search() { - esTester.client().prepareSearch(FakeIndexDefinition.INDEX).get(); + es.client().prepareSearch(FakeIndexDefinition.INDEX).get(); } @Test public void to_string() { - assertThat(esTester.client().prepareSearch(FakeIndexDefinition.INDEX).setTypes(FakeIndexDefinition.TYPE).toString()).contains("ES search request '").contains( + assertThat(es.client().prepareSearch(FakeIndexDefinition.INDEX).setTypes(FakeIndexDefinition.TYPE).toString()).contains("ES search request '").contains( "' on indices '[fakes]' on types '[fake]'"); - assertThat(esTester.client().prepareSearch(FakeIndexDefinition.INDEX).toString()).contains("ES search request '").contains("' on indices '[fakes]'"); - assertThat(esTester.client().prepareSearch(new IndexType[0]).toString()).contains("ES search request"); + assertThat(es.client().prepareSearch(FakeIndexDefinition.INDEX).toString()).contains("ES search request '").contains("' on indices '[fakes]'"); + assertThat(es.client().prepareSearch(new IndexType[0]).toString()).contains("ES search request"); } @Test public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - esTester.client().prepareSearch(FakeIndexDefinition.INDEX).get(); + es.client().prepareSearch(FakeIndexDefinition.INDEX).get(); assertThat(logTester.logs(LoggerLevel.TRACE)).hasSize(1); } @Test public void fail_to_search_bad_query() { try { - esTester.client().prepareSearch("non-existing-index").get(); + es.client().prepareSearch("non-existing-index").get(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class); @@ -74,7 +74,7 @@ public class ProxySearchRequestBuilderTest { @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().prepareSearch(FakeIndexDefinition.INDEX).get("1"); + es.client().prepareSearch(FakeIndexDefinition.INDEX).get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -84,7 +84,7 @@ public class ProxySearchRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().prepareSearch(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1)); + es.client().prepareSearch(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -94,7 +94,7 @@ public class ProxySearchRequestBuilderTest { @Test public void execute_should_throw_an_unsupported_operation_exception() { try { - esTester.client().prepareSearch(FakeIndexDefinition.INDEX).execute(); + es.client().prepareSearch(FakeIndexDefinition.INDEX).execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilderTest.java index 89dd23c718d..a8244603610 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilderTest.java @@ -34,7 +34,7 @@ import static org.junit.Assert.fail; public class ProxySearchScrollRequestBuilderTest { @Rule - public EsTester esTester = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); @Rule public LogTester logTester = new LogTester(); @@ -43,11 +43,11 @@ public class ProxySearchScrollRequestBuilderTest { public void trace_logs() { logTester.setLevel(LoggerLevel.TRACE); - SearchResponse response = esTester.client().prepareSearch(FakeIndexDefinition.INDEX) + SearchResponse response = es.client().prepareSearch(FakeIndexDefinition.INDEX) .setScroll(TimeValue.timeValueMinutes(1)) .get(); logTester.clear(); - esTester.client().prepareSearchScroll(response.getScrollId()).get(); + es.client().prepareSearchScroll(response.getScrollId()).get(); assertThat(logTester.logs()).hasSize(1); } @@ -55,18 +55,18 @@ public class ProxySearchScrollRequestBuilderTest { public void no_trace_logs() { logTester.setLevel(LoggerLevel.DEBUG); - SearchResponse response = esTester.client().prepareSearch(FakeIndexDefinition.INDEX) + SearchResponse response = es.client().prepareSearch(FakeIndexDefinition.INDEX) .setScroll(TimeValue.timeValueMinutes(1)) .get(); logTester.clear(); - esTester.client().prepareSearchScroll(response.getScrollId()).get(); + es.client().prepareSearchScroll(response.getScrollId()).get(); assertThat(logTester.logs()).isEmpty(); } @Test public void fail_to_search_bad_query() { try { - esTester.client().prepareSearchScroll("unknown").get(); + es.client().prepareSearchScroll("unknown").get(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class); @@ -77,7 +77,7 @@ public class ProxySearchScrollRequestBuilderTest { @Test public void get_with_string_timeout_is_not_yet_implemented() { try { - esTester.client().prepareSearchScroll("scrollId").get("1"); + es.client().prepareSearchScroll("scrollId").get("1"); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -87,7 +87,7 @@ public class ProxySearchScrollRequestBuilderTest { @Test public void get_with_time_value_timeout_is_not_yet_implemented() { try { - esTester.client().prepareSearchScroll("scrollId").get(TimeValue.timeValueMinutes(1)); + es.client().prepareSearchScroll("scrollId").get(TimeValue.timeValueMinutes(1)); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Not yet implemented"); @@ -97,7 +97,7 @@ public class ProxySearchScrollRequestBuilderTest { @Test public void execute_should_throw_an_unsupported_operation_exception() { try { - esTester.client().prepareSearchScroll("scrollId").execute(); + es.client().prepareSearchScroll("scrollId").execute(); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(UnsupportedOperationException.class).hasMessage("execute() should not be called as it's used for asynchronous"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerHealthRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerHealthRequestBuilderTest.java index 6254fc0df31..a2fb6689b44 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerHealthRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerHealthRequestBuilderTest.java @@ -23,7 +23,6 @@ import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequestBuilder import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.unit.TimeValue; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.log.LogTester; @@ -35,8 +34,8 @@ import static org.junit.Assert.fail; public class ProxyWebServerHealthRequestBuilderTest { - @ClassRule - public static EsTester esTester = new EsTester(); + @Rule + public EsTester esTester = EsTester.custom(); @Rule public LogTester logTester = new LogTester(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStateRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStateRequestBuilderTest.java index 21b3366ab6e..9a6cd423df5 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStateRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStateRequestBuilderTest.java @@ -21,7 +21,6 @@ package org.sonar.server.es.request; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequestBuilder; import org.elasticsearch.common.unit.TimeValue; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.log.LogTester; @@ -33,8 +32,8 @@ import static org.junit.Assert.fail; public class ProxyWebServerStateRequestBuilderTest { - @ClassRule - public static EsTester esTester = new EsTester(); + @Rule + public EsTester esTester = EsTester.custom(); @Rule public LogTester logTester = new LogTester(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStatsRequestBuilderTest.java b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStatsRequestBuilderTest.java index 26dec727ec0..12ef480bad0 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStatsRequestBuilderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStatsRequestBuilderTest.java @@ -21,7 +21,6 @@ package org.sonar.server.es.request; import org.elasticsearch.action.admin.cluster.stats.ClusterStatsRequestBuilder; import org.elasticsearch.common.unit.TimeValue; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.log.LogTester; @@ -33,8 +32,8 @@ import static org.junit.Assert.fail; public class ProxyWebServerStatsRequestBuilderTest { - @ClassRule - public static EsTester esTester = new EsTester(); + @Rule + public EsTester esTester = EsTester.custom(); @Rule public LogTester logTester = new LogTester(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/health/EsStatusClusterCheckTest.java b/server/sonar-server/src/test/java/org/sonar/server/health/EsStatusClusterCheckTest.java index 7fa0e4a6e75..e8e5e75a153 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/health/EsStatusClusterCheckTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/health/EsStatusClusterCheckTest.java @@ -38,7 +38,7 @@ import static org.mockito.Mockito.when; public class EsStatusClusterCheckTest { @Rule - public EsTester esTester = new EsTester(); + public EsTester esTester = EsTester.custom(); private final Random random = new Random(); private EsStatusClusterCheck underTest = new EsStatusClusterCheck(esTester.client()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/health/EsStatusNodeCheckTest.java b/server/sonar-server/src/test/java/org/sonar/server/health/EsStatusNodeCheckTest.java index 04c0c86d112..e631fea3bb1 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/health/EsStatusNodeCheckTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/health/EsStatusNodeCheckTest.java @@ -31,7 +31,7 @@ import static org.mockito.Mockito.when; public class EsStatusNodeCheckTest { @Rule - public EsTester esTester = new EsTester(); + public EsTester esTester = EsTester.custom(); private EsStatusNodeCheck underTest = new EsStatusNodeCheck(esTester.client()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/IssueUpdaterTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/IssueUpdaterTest.java index f9f42cfc2d6..1614ccc4a01 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/IssueUpdaterTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/IssueUpdaterTest.java @@ -24,7 +24,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.RuleStatus; import org.sonar.api.utils.System2; import org.sonar.core.issue.DefaultIssue; @@ -40,7 +39,6 @@ import org.sonar.db.rule.RuleDbTester; import org.sonar.db.rule.RuleDefinitionDto; import org.sonar.db.rule.RuleDto; import org.sonar.server.es.EsTester; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.issue.notification.IssueChangeNotification; @@ -70,7 +68,7 @@ public class IssueUpdaterTest { public DbTester dbTester = DbTester.create(system2); @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); private DbClient dbClient = dbTester.getDbClient(); private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(dbTester); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexDebtTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexDebtTest.java index d518666c823..504593f7cdd 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexDebtTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexDebtTest.java @@ -24,7 +24,6 @@ import java.util.TimeZone; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.issue.Issue; import org.sonar.api.resources.Qualifiers; import org.sonar.api.rule.RuleKey; @@ -46,7 +45,6 @@ import org.sonar.server.permission.index.AuthorizationTypeSupport; import org.sonar.server.permission.index.PermissionIndexerDao; import org.sonar.server.permission.index.PermissionIndexerTester; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.view.index.ViewIndexDefinition; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; @@ -60,7 +58,7 @@ public class IssueIndexDebtTest { private System2 system2 = new TestSystem2().setNow(1_500_000_000_000L).setDefaultTimeZone(TimeZone.getTimeZone("GMT-01:00")); @Rule - public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()), new ViewIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexProjectStatisticsTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexProjectStatisticsTest.java index 4ee8ffa3876..932ead98e63 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexProjectStatisticsTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexProjectStatisticsTest.java @@ -52,14 +52,14 @@ public class IssueIndexProjectStatisticsTest { private System2 system2 = mock(System2.class); private MapSettings settings = new MapSettings(); @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(settings.asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - private IssueIndexer issueIndexer = new IssueIndexer(esTester.client(), null, new IssueIteratorFactory(null)); - private PermissionIndexerTester authorizationIndexerTester = new PermissionIndexerTester(esTester, issueIndexer); + private IssueIndexer issueIndexer = new IssueIndexer(es.client(), null, new IssueIteratorFactory(null)); + private PermissionIndexerTester authorizationIndexerTester = new PermissionIndexerTester(es, issueIndexer); - private IssueIndex underTest = new IssueIndex(esTester.client(), system2, userSessionRule, new AuthorizationTypeSupport(userSessionRule)); + private IssueIndex underTest = new IssueIndex(es.client(), system2, userSessionRule, new AuthorizationTypeSupport(userSessionRule)); @Test public void searchProjectStatistics_returns_empty_list_if_no_input() { diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexTest.java index d7c9b81ca22..82584c7f691 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexTest.java @@ -37,7 +37,6 @@ import org.elasticsearch.search.SearchHit; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.issue.Issue; import org.sonar.api.rule.Severity; import org.sonar.api.utils.System2; @@ -55,11 +54,9 @@ import org.sonar.server.issue.IssueQuery; import org.sonar.server.permission.index.AuthorizationTypeSupport; import org.sonar.server.permission.index.PermissionIndexerDao; import org.sonar.server.permission.index.PermissionIndexerTester; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.view.index.ViewDoc; -import org.sonar.server.view.index.ViewIndexDefinition; import org.sonar.server.view.index.ViewIndexer; import static com.google.common.collect.ImmutableSortedSet.of; @@ -87,13 +84,8 @@ import static org.sonar.server.issue.IssueDocTesting.newDoc; public class IssueIndexTest { - private MapSettings settings = new MapSettings(); - @Rule - public EsTester es = new EsTester( - new IssueIndexDefinition(settings.asConfig()), - new ViewIndexDefinition(settings.asConfig()), - new RuleIndexDefinition(settings.asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexerTest.java index 69b7534ca4d..6b36e2b3337 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexerTest.java @@ -30,7 +30,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; @@ -61,7 +60,7 @@ import static org.sonar.server.permission.index.AuthorizationTypeSupport.TYPE_AU public class IssueIndexerTest { @Rule - public EsTester es = new EsTester(IssueIndexDefinition.createForTest(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(); @Rule @@ -148,6 +147,7 @@ public class IssueIndexerTest { } finally { assertThatIndexHasSize(0); assertThatEsQueueTableHasSize(0); + es.unlockWrites(INDEX_TYPE_ISSUE); } } @@ -198,6 +198,7 @@ public class IssueIndexerTest { } finally { assertThatIndexHasSize(0); assertThatEsQueueTableHasSize(0); + es.unlockWrites(INDEX_TYPE_ISSUE); } } @@ -431,6 +432,7 @@ public class IssueIndexerTest { } finally { assertThatIndexHasOnly("Issue1"); assertThatEsQueueTableHasSize(0); + es.unlockWrites(INDEX_TYPE_ISSUE); } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AddCommentActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AddCommentActionTest.java index 42b134f6069..14018d6bb4b 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AddCommentActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AddCommentActionTest.java @@ -25,7 +25,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; @@ -46,7 +45,6 @@ import org.sonar.server.issue.IssueFinder; import org.sonar.server.issue.IssueUpdater; import org.sonar.server.issue.ServerIssueStorage; import org.sonar.server.issue.TestIssueChangePostProcessor; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.notification.NotificationManager; @@ -81,7 +79,7 @@ public class AddCommentActionTest { public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AssignActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AssignActionTest.java index ad6fedd889c..05abdb4fe11 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AssignActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AssignActionTest.java @@ -24,7 +24,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.utils.internal.TestSystem2; @@ -43,7 +42,6 @@ import org.sonar.server.issue.IssueFinder; import org.sonar.server.issue.IssueUpdater; import org.sonar.server.issue.ServerIssueStorage; import org.sonar.server.issue.TestIssueChangePostProcessor; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.notification.NotificationManager; @@ -76,7 +74,7 @@ public class AssignActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule - public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(system2); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AuthorsActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AuthorsActionTest.java index 89526d173c4..c7ca1c9d2f2 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AuthorsActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/AuthorsActionTest.java @@ -21,13 +21,11 @@ package org.sonar.server.issue.ws; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.server.es.EsTester; import org.sonar.server.issue.index.IssueIndex; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.permission.index.AuthorizationTypeSupport; @@ -44,7 +42,7 @@ public class AuthorsActionTest { @Rule public DbTester db = DbTester.create(); @Rule - public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/BulkChangeActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/BulkChangeActionTest.java index 764ebe56070..4864c527d2d 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/BulkChangeActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/BulkChangeActionTest.java @@ -30,7 +30,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rules.RuleType; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -50,7 +49,6 @@ import org.sonar.server.issue.IssueStorage; import org.sonar.server.issue.ServerIssueStorage; import org.sonar.server.issue.TestIssueChangePostProcessor; import org.sonar.server.issue.TransitionService; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.issue.notification.IssueChangeNotification; @@ -101,7 +99,7 @@ public class BulkChangeActionTest { @Rule public DbTester db = DbTester.create(system2); @Rule - public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/DoTransitionActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/DoTransitionActionTest.java index 1266dd4d89a..e73c30ace75 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/DoTransitionActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/DoTransitionActionTest.java @@ -25,7 +25,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.utils.System2; @@ -48,7 +47,6 @@ import org.sonar.server.issue.IssueUpdater; import org.sonar.server.issue.ServerIssueStorage; import org.sonar.server.issue.TestIssueChangePostProcessor; import org.sonar.server.issue.TransitionService; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.issue.workflow.FunctionExecutor; @@ -89,7 +87,7 @@ public class DoTransitionActionTest { public DbTester dbTester = DbTester.create(system2); @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java index 538917daf43..5b531276d1e 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java @@ -25,7 +25,6 @@ import java.util.Date; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Languages; import org.sonar.api.resources.Qualifiers; import org.sonar.api.rule.RuleKey; @@ -44,7 +43,6 @@ import org.sonar.server.issue.IssueFieldsSetter; import org.sonar.server.issue.IssueQueryFactory; import org.sonar.server.issue.TransitionService; import org.sonar.server.issue.index.IssueIndex; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.issue.workflow.FunctionExecutor; @@ -52,7 +50,6 @@ import org.sonar.server.issue.workflow.IssueWorkflow; import org.sonar.server.permission.index.AuthorizationTypeSupport; import org.sonar.server.permission.index.PermissionIndexerTester; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.view.index.ViewIndexDefinition; import org.sonar.server.view.index.ViewIndexer; import org.sonar.server.ws.WsActionTester; import org.sonar.server.ws.WsResponseCommonFormat; @@ -92,7 +89,7 @@ public class SearchActionComponentsTest { @Rule public DbTester db = DbTester.create(); @Rule - public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()), new ViewIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private DbClient dbClient = db.getDbClient(); private IssueIndex issueIndex = new IssueIndex(es.client(), System2.INSTANCE, userSession, new AuthorizationTypeSupport(userSession)); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java index ab8291ecce7..4f1e005707a 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java @@ -27,7 +27,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.issue.Issue; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleStatus; @@ -60,7 +59,6 @@ import org.sonar.server.issue.IssueQuery; import org.sonar.server.issue.IssueQueryFactory; import org.sonar.server.issue.TransitionService; import org.sonar.server.issue.index.IssueIndex; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.issue.workflow.FunctionExecutor; @@ -97,7 +95,7 @@ public class SearchActionTest { @Rule public DbTester db = DbTester.create(); @Rule - public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public ExpectedException expectedException = ExpectedException.none(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetSeverityActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetSeverityActionTest.java index 4017774cd75..fb724043a00 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetSeverityActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetSeverityActionTest.java @@ -25,7 +25,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; @@ -46,7 +45,6 @@ import org.sonar.server.issue.IssueFinder; import org.sonar.server.issue.IssueUpdater; import org.sonar.server.issue.ServerIssueStorage; import org.sonar.server.issue.TestIssueChangePostProcessor; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.notification.NotificationManager; @@ -79,7 +77,7 @@ public class SetSeverityActionTest { @Rule public DbTester dbTester = DbTester.create(); @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTagsActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTagsActionTest.java index 8dc873b6751..d3f9c6e0bb8 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTagsActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTagsActionTest.java @@ -27,7 +27,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService.Action; @@ -48,7 +47,6 @@ import org.sonar.server.issue.IssueFinder; import org.sonar.server.issue.IssueUpdater; import org.sonar.server.issue.ServerIssueStorage; import org.sonar.server.issue.TestIssueChangePostProcessor; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.notification.NotificationManager; @@ -78,7 +76,7 @@ public class SetTagsActionTest { @Rule public DbTester db = DbTester.create(); @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTypeActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTypeActionTest.java index 3c6a9c9434c..f288231be21 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTypeActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTypeActionTest.java @@ -25,7 +25,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; @@ -46,7 +45,6 @@ import org.sonar.server.issue.IssueFinder; import org.sonar.server.issue.IssueUpdater; import org.sonar.server.issue.ServerIssueStorage; import org.sonar.server.issue.TestIssueChangePostProcessor; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.notification.NotificationManager; @@ -80,7 +78,7 @@ public class SetTypeActionTest { @Rule public DbTester dbTester = DbTester.create(); @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/TagsActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/TagsActionTest.java index 1e478a28e36..011651cf23a 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ws/TagsActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ws/TagsActionTest.java @@ -34,14 +34,12 @@ import org.sonar.db.organization.OrganizationDto; import org.sonar.db.rule.RuleDefinitionDto; import org.sonar.server.es.EsTester; import org.sonar.server.issue.index.IssueIndex; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.permission.index.AuthorizationTypeSupport; import org.sonar.server.permission.index.PermissionIndexerDao; import org.sonar.server.permission.index.PermissionIndexerTester; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; @@ -61,13 +59,13 @@ public class TagsActionTest { @Rule public DbTester dbTester = DbTester.create(); @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(settings.asConfig()), new RuleIndexDefinition(settings.asConfig())); + public EsTester es = EsTester.core(); - private IssueIndexer issueIndexer = new IssueIndexer(esTester.client(), dbTester.getDbClient(), new IssueIteratorFactory(dbTester.getDbClient())); - private RuleIndexer ruleIndexer = new RuleIndexer(esTester.client(), dbTester.getDbClient()); - private PermissionIndexerTester permissionIndexerTester = new PermissionIndexerTester(esTester, issueIndexer); - private IssueIndex issueIndex = new IssueIndex(esTester.client(), System2.INSTANCE, userSession, new AuthorizationTypeSupport(userSession)); - private RuleIndex ruleIndex = new RuleIndex(esTester.client(), System2.INSTANCE); + private IssueIndexer issueIndexer = new IssueIndexer(es.client(), dbTester.getDbClient(), new IssueIteratorFactory(dbTester.getDbClient())); + private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), dbTester.getDbClient()); + private PermissionIndexerTester permissionIndexerTester = new PermissionIndexerTester(es, issueIndexer); + private IssueIndex issueIndex = new IssueIndex(es.client(), System2.INSTANCE, userSession, new AuthorizationTypeSupport(userSession)); + private RuleIndex ruleIndex = new RuleIndex(es.client(), System2.INSTANCE); private WsActionTester ws = new WsActionTester(new TagsAction(issueIndex, ruleIndex, dbTester.getDbClient())); private OrganizationDto organization; diff --git a/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/CreateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/CreateActionTest.java index 6e930b47eab..55fa8d70a65 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/CreateActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/CreateActionTest.java @@ -25,7 +25,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.Metric; import org.sonar.api.measures.Metric.ValueType; import org.sonar.api.utils.System2; @@ -49,7 +48,6 @@ import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.ServerException; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.ws.UserJsonWriter; import org.sonar.server.ws.WsTester; @@ -75,7 +73,7 @@ public class CreateActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); DbClient dbClient = db.getDbClient(); ComponentDto project; diff --git a/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/MetricsActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/MetricsActionTest.java index f14d355d5cf..2741edb75e1 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/MetricsActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/MetricsActionTest.java @@ -23,7 +23,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.Metric; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -54,7 +53,7 @@ public class MetricsActionTest { private static final String DEFAULT_PROJECT_KEY = "project-key"; @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/SearchActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/SearchActionTest.java index a4259535302..187e506c567 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/SearchActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/SearchActionTest.java @@ -25,7 +25,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.Metric.ValueType; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.DateUtils; @@ -45,7 +44,6 @@ import org.sonar.server.es.EsTester; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.ws.UserJsonWriter; import org.sonar.server.ws.WsTester; @@ -66,7 +64,7 @@ public class SearchActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); WsTester ws; DbClient dbClient = db.getDbClient(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/UpdateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/UpdateActionTest.java index 31d0759a683..3863327f45c 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/UpdateActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/UpdateActionTest.java @@ -23,7 +23,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.Metric.ValueType; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -43,7 +42,6 @@ import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.ServerException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.ws.UserJsonWriter; import org.sonar.server.ws.WsTester; @@ -65,7 +63,7 @@ public class UpdateActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java b/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java index 1236648d543..e3d09d304f1 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java @@ -33,7 +33,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.System2; import org.sonar.db.component.ComponentDto; @@ -97,7 +96,7 @@ public class ProjectMeasuresIndexTest { private static final GroupDto GROUP2 = newGroupDto(); @Rule - public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -107,7 +106,7 @@ public class ProjectMeasuresIndexTest { @DataProvider public static Object[][] rating_metric_keys() { - return new Object[][] {{MAINTAINABILITY_RATING}, {NEW_MAINTAINABILITY_RATING_KEY}, {RELIABILITY_RATING}, {NEW_RELIABILITY_RATING}, {SECURITY_RATING}, {NEW_SECURITY_RATING}}; + return new Object[][]{{MAINTAINABILITY_RATING}, {NEW_MAINTAINABILITY_RATING_KEY}, {RELIABILITY_RATING}, {NEW_RELIABILITY_RATING}, {SECURITY_RATING}, {NEW_SECURITY_RATING}}; } private ProjectMeasuresIndexer projectMeasureIndexer = new ProjectMeasuresIndexer(null, es.client()); @@ -522,8 +521,8 @@ public class ProjectMeasuresIndexTest { newDoc(NCLOC, 501_000d, COVERAGE, 81d, DUPLICATION, 20d)); Facets facets = underTest.search(new ProjectMeasuresQuery() - .addMetricCriterion(MetricCriterion.create(NCLOC, Operator.LT, 10_000d)) - .addMetricCriterion(MetricCriterion.create(DUPLICATION, Operator.LT, 10d)), + .addMetricCriterion(MetricCriterion.create(NCLOC, Operator.LT, 10_000d)) + .addMetricCriterion(MetricCriterion.create(DUPLICATION, Operator.LT, 10d)), new SearchOptions().addFacets(NCLOC, COVERAGE)).getFacets(); // Sticky facet on ncloc does not take into account ncloc filter @@ -671,8 +670,8 @@ public class ProjectMeasuresIndexTest { newDoc(NCLOC, 501_000d, COVERAGE, 810d, DUPLICATION, 20d)); Facets facets = underTest.search(new ProjectMeasuresQuery() - .addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 30d)) - .addMetricCriterion(MetricCriterion.create(DUPLICATION, Operator.LT, 10d)), + .addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 30d)) + .addMetricCriterion(MetricCriterion.create(DUPLICATION, Operator.LT, 10d)), new SearchOptions().addFacets(COVERAGE, NCLOC)).getFacets(); // Sticky facet on coverage does not take into account coverage filter @@ -825,8 +824,8 @@ public class ProjectMeasuresIndexTest { newDoc(DUPLICATION, 20d, NCLOC, 1000000d, COVERAGE, 40d)); Facets facets = underTest.search(new ProjectMeasuresQuery() - .addMetricCriterion(MetricCriterion.create(DUPLICATION, Operator.LT, 10d)) - .addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 30d)), + .addMetricCriterion(MetricCriterion.create(DUPLICATION, Operator.LT, 10d)) + .addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 30d)), new SearchOptions().addFacets(DUPLICATION, NCLOC)).getFacets(); // Sticky facet on duplication does not take into account duplication filter @@ -983,8 +982,8 @@ public class ProjectMeasuresIndexTest { newDoc(metricKey, 5d, NCLOC, 800000d, COVERAGE, 60d)); Facets facets = underTest.search(new ProjectMeasuresQuery() - .addMetricCriterion(MetricCriterion.create(metricKey, Operator.LT, 3d)) - .addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 30d)), + .addMetricCriterion(MetricCriterion.create(metricKey, Operator.LT, 3d)) + .addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 30d)), new SearchOptions().addFacets(metricKey, NCLOC)).getFacets(); // Sticky facet on maintainability rating does not take into account maintainability rating filter @@ -1077,8 +1076,8 @@ public class ProjectMeasuresIndexTest { newDoc(NCLOC, 13000d, COVERAGE, 60d).setQualityGateStatus(ERROR.name())); Facets facets = underTest.search(new ProjectMeasuresQuery() - .setQualityGateStatus(ERROR) - .addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 55d)), + .setQualityGateStatus(ERROR) + .addMetricCriterion(MetricCriterion.create(COVERAGE, Operator.LT, 55d)), new SearchOptions().addFacets(ALERT_STATUS_KEY, NCLOC)).getFacets(); // Sticky facet on quality gate does not take into account quality gate filter diff --git a/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTextSearchTest.java b/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTextSearchTest.java index b4e8f2d83a4..bf3ca24f082 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTextSearchTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTextSearchTest.java @@ -25,7 +25,6 @@ import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.System2; import org.sonar.db.component.ComponentDto; @@ -57,7 +56,7 @@ public class ProjectMeasuresIndexTextSearchTest { private static final OrganizationDto ORG = OrganizationTesting.newOrganizationDto(); @Rule - public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public ExpectedException expectedException = ExpectedException.none(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexerTest.java index ed8488e7ae1..f4e00e17851 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexerTest.java @@ -25,7 +25,6 @@ import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.search.SearchHit; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import org.sonar.db.DbTester; @@ -56,7 +55,7 @@ public class ProjectMeasuresIndexerTest { private System2 system2 = System2.INSTANCE; @Rule - public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(system2); diff --git a/server/sonar-server/src/test/java/org/sonar/server/organization/OrganizationCreationImplTest.java b/server/sonar-server/src/test/java/org/sonar/server/organization/OrganizationCreationImplTest.java index 47526f8bb12..e98b3b5b0f7 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/organization/OrganizationCreationImplTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/organization/OrganizationCreationImplTest.java @@ -56,7 +56,6 @@ import org.sonar.server.qualityprofile.BuiltInQProfile; import org.sonar.server.qualityprofile.BuiltInQProfileRepositoryRule; import org.sonar.server.qualityprofile.QProfileName; import org.sonar.server.user.index.UserIndex; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.user.index.UserQuery; import org.sonar.server.usergroups.DefaultGroupCreator; @@ -90,7 +89,7 @@ public class OrganizationCreationImplTest { @Rule public DbTester db = DbTester.create(system2); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/AddMemberActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/AddMemberActionTest.java index 7f30d03a723..6ed80caa11b 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/AddMemberActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/AddMemberActionTest.java @@ -25,7 +25,6 @@ import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -44,7 +43,6 @@ import org.sonar.server.issue.ws.AvatarResolverImpl; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.index.UserDoc; import org.sonar.server.user.index.UserIndex; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.user.index.UserQuery; import org.sonar.server.usergroups.DefaultGroupFinder; @@ -67,7 +65,7 @@ public class AddMemberActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot(); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private UserIndex userIndex = new UserIndex(es.client(), System2.INSTANCE); @Rule public DbTester db = DbTester.create(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/CreateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/CreateActionTest.java index 4dc84d03add..b9467885086 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/CreateActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/CreateActionTest.java @@ -19,8 +19,6 @@ */ package org.sonar.server.organization.ws; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -58,7 +56,6 @@ import org.sonar.server.organization.TestOrganizationFlags; import org.sonar.server.qualityprofile.BuiltInQProfileRepository; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.index.UserIndex; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.usergroups.DefaultGroupCreatorImpl; import org.sonar.server.ws.TestRequest; @@ -87,7 +84,7 @@ public class CreateActionTest { @Rule public DbTester dbTester = DbTester.create(system2).setDisableDefaultOrganization(true); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -614,7 +611,7 @@ public class CreateActionTest { } private static void populateRequest(@Nullable String name, @Nullable String key, @Nullable String description, @Nullable String url, @Nullable String avatar, - TestRequest request) { + TestRequest request) { OrganizationsWsTestSupport.setParam(request, "name", name); OrganizationsWsTestSupport.setParam(request, "key", key); OrganizationsWsTestSupport.setParam(request, "description", description); @@ -623,15 +620,15 @@ public class CreateActionTest { } private void verifyResponseAndDb(CreateWsResponse response, - String uuid, String name, String key, - long createdAt) { + String uuid, String name, String key, + long createdAt) { verifyResponseAndDb(response, uuid, name, key, null, null, null, createdAt); } private void verifyResponseAndDb(CreateWsResponse response, - String id, String name, String key, - @Nullable String description, @Nullable String url, @Nullable String avatar, - long createdAt) { + String id, String name, String key, + @Nullable String description, @Nullable String url, @Nullable String avatar, + long createdAt) { Organization organization = response.getOrganization(); assertThat(organization.getName()).isEqualTo(name); assertThat(organization.getKey()).isEqualTo(key); diff --git a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java index c0c635ff151..447c7018b99 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java @@ -32,7 +32,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; @@ -69,7 +68,6 @@ import org.sonar.server.qualityprofile.QProfileFactoryImpl; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.index.UserIndex; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.user.index.UserQuery; import org.sonar.server.ws.WsActionTester; @@ -102,7 +100,7 @@ public class DeleteActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -381,7 +379,7 @@ public class DeleteActionTest { @DataProvider public static Object[][] OneOrMoreIterations() { - return new Object[][] { + return new Object[][]{ {1}, {1 + new Random().nextInt(10)}, }; @@ -525,7 +523,7 @@ public class DeleteActionTest { @UseDataProvider("indexOfFailingProjectDeletion") public void projectLifeCycleListener_are_notified_even_if_deletion_of_a_project_throws_an_Exception(int failingProjectIndex) { OrganizationDto organization = db.organizations().insert(); - ComponentDto[] projects = new ComponentDto[] { + ComponentDto[] projects = new ComponentDto[]{ db.components().insertPrivateProject(organization), db.components().insertPrivateProject(organization), db.components().insertPrivateProject(organization) @@ -546,7 +544,7 @@ public class DeleteActionTest { @DataProvider public static Object[][] indexOfFailingProjectDeletion() { - return new Object[][] { + return new Object[][]{ {0}, {1}, {2} diff --git a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/EnableSupportActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/EnableSupportActionTest.java index e2a0b7dd206..af549b17547 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/EnableSupportActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/EnableSupportActionTest.java @@ -27,7 +27,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.RuleStatus; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -46,7 +45,6 @@ import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.organization.OrganizationFlags; import org.sonar.server.organization.OrganizationFlagsImpl; import org.sonar.server.organization.TestDefaultOrganizationProvider; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.usergroups.DefaultGroupCreatorImpl; @@ -70,11 +68,11 @@ public class EnableSupportActionTest { @Rule public DbTester dbTester = DbTester.create(); @Rule - public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(dbTester); private OrganizationFlags organizationFlags = new OrganizationFlagsImpl(dbTester.getDbClient()); - private RuleIndexer ruleIndexer = spy(new RuleIndexer(esTester.client(), dbTester.getDbClient())); + private RuleIndexer ruleIndexer = spy(new RuleIndexer(es.client(), dbTester.getDbClient())); private EnableSupportAction underTest = new EnableSupportAction(userSession, dbTester.getDbClient(), defaultOrganizationProvider, organizationFlags, new DefaultGroupCreatorImpl(dbTester.getDbClient()), new DefaultGroupFinder(dbTester.getDbClient()), ruleIndexer); private WsActionTester tester = new WsActionTester(underTest); diff --git a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/RemoveMemberActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/RemoveMemberActionTest.java index ee930985834..7e3b8872d1e 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/RemoveMemberActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/RemoveMemberActionTest.java @@ -25,7 +25,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -48,7 +47,6 @@ import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.index.UserIndex; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.user.index.UserQuery; import org.sonar.server.ws.TestRequest; @@ -74,7 +72,7 @@ public class RemoveMemberActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot(); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(); private DbClient dbClient = db.getDbClient(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/SearchMembersActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/SearchMembersActionTest.java index f527e4e1c0b..6aeeeaae0bb 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/organization/ws/SearchMembersActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/organization/ws/SearchMembersActionTest.java @@ -25,7 +25,6 @@ import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; @@ -42,7 +41,6 @@ import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.index.UserIndex; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; @@ -62,7 +60,7 @@ public class SearchMembersActionTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/permission/index/FooIndexer.java b/server/sonar-server/src/test/java/org/sonar/server/permission/index/FooIndexer.java index e26430ee5ba..f5122681075 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/permission/index/FooIndexer.java +++ b/server/sonar-server/src/test/java/org/sonar/server/permission/index/FooIndexer.java @@ -23,7 +23,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.Set; -import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.es.EsQueueDto; import org.sonar.server.es.EsClient; @@ -37,11 +36,9 @@ public class FooIndexer implements ProjectIndexer, NeedAuthorizationIndexer { private static final AuthorizationScope AUTHORIZATION_SCOPE = new AuthorizationScope(INDEX_TYPE_FOO, p -> true); - private final DbClient dbClient; private final EsClient esClient; - public FooIndexer(DbClient dbClient, EsClient esClient) { - this.dbClient = dbClient; + public FooIndexer(EsClient esClient) { this.esClient = esClient; } diff --git a/server/sonar-server/src/test/java/org/sonar/server/permission/index/PermissionIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/permission/index/PermissionIndexerTest.java index 859179a7672..5514f7f9d13 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/permission/index/PermissionIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/permission/index/PermissionIndexerTest.java @@ -53,12 +53,12 @@ public class PermissionIndexerTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public EsTester es = new EsTester(new FooIndexDefinition()); + public EsTester es = EsTester.custom(new FooIndexDefinition()); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private FooIndex fooIndex = new FooIndex(es.client(), new AuthorizationTypeSupport(userSession)); - private FooIndexer fooIndexer = new FooIndexer(db.getDbClient(), es.client()); + private FooIndexer fooIndexer = new FooIndexer(es.client()); private PermissionIndexer underTest = new PermissionIndexer(db.getDbClient(), es.client(), fooIndexer); @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java b/server/sonar-server/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java index 251fc0d0060..082cea4a7c4 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java @@ -53,7 +53,7 @@ public abstract class BasePermissionWsTest { public DbTester db = DbTester.create(new AlwaysIncreasingSystem2()); @Rule - public EsTester esTester = new EsTester(new FooIndexDefinition()); + public EsTester esTester = EsTester.custom(new FooIndexDefinition()); @Rule public ExpectedException expectedException = ExpectedException.none(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/platform/BackendCleanupTest.java b/server/sonar-server/src/test/java/org/sonar/server/platform/BackendCleanupTest.java index 6e62504d530..a5a4524139d 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/platform/BackendCleanupTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/platform/BackendCleanupTest.java @@ -23,7 +23,6 @@ import java.util.Random; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentTesting; @@ -49,12 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class BackendCleanupTest { @Rule - public EsTester esTester = new EsTester( - new RuleIndexDefinition(new MapSettings().asConfig()), - new IssueIndexDefinition(new MapSettings().asConfig()), - new ViewIndexDefinition(new MapSettings().asConfig()), - new ProjectMeasuresIndexDefinition(new MapSettings().asConfig()), - new ComponentIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); diff --git a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsIndexesSectionTest.java b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsIndexesSectionTest.java index 33d0163e8ea..ae1a8a04d1b 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsIndexesSectionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsIndexesSectionTest.java @@ -22,11 +22,9 @@ package org.sonar.server.platform.monitoring; import org.elasticsearch.ElasticsearchException; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.es.EsClient; import org.sonar.server.es.EsTester; -import org.sonar.server.issue.index.IssueIndexDefinition; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -37,7 +35,7 @@ import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatA public class EsIndexesSectionTest { @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); private EsIndexesSection underTest = new EsIndexesSection(esTester.client()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsStateSectionTest.java b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsStateSectionTest.java index 61a2612461a..166b0793e25 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsStateSectionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsStateSectionTest.java @@ -23,11 +23,9 @@ import org.elasticsearch.ElasticsearchException; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.es.EsClient; import org.sonar.server.es.EsTester; -import org.sonar.server.issue.index.IssueIndexDefinition; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -38,7 +36,7 @@ import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatA public class EsStateSectionTest { @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); private EsStateSection underTest = new EsStateSection(esTester.client()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/EsClusterStateSectionTest.java b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/EsClusterStateSectionTest.java index eb2118a28f2..c273f8b0659 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/EsClusterStateSectionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/EsClusterStateSectionTest.java @@ -21,10 +21,8 @@ package org.sonar.server.platform.monitoring.cluster; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.es.EsTester; -import org.sonar.server.issue.index.IssueIndexDefinition; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; @@ -32,7 +30,7 @@ import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; public class EsClusterStateSectionTest { @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); private EsClusterStateSection underTest = new EsClusterStateSection(esTester.client()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/SearchNodesInfoLoaderImplTest.java b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/SearchNodesInfoLoaderImplTest.java index 0983fba047f..51e7b08b308 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/SearchNodesInfoLoaderImplTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/SearchNodesInfoLoaderImplTest.java @@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class SearchNodesInfoLoaderImplTest { @Rule - public EsTester es = new EsTester(new FakeIndexDefinition()); + public EsTester es = EsTester.custom(new FakeIndexDefinition()); private SearchNodesInfoLoaderImpl underTest = new SearchNodesInfoLoaderImpl(es.client()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/project/ws/BulkUpdateKeyActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/project/ws/BulkUpdateKeyActionTest.java index 871980caf4a..8e7d6244b86 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/project/ws/BulkUpdateKeyActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/project/ws/BulkUpdateKeyActionTest.java @@ -23,7 +23,6 @@ import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -37,12 +36,10 @@ import org.sonar.db.organization.OrganizationDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.component.ComponentService; import org.sonar.server.component.TestComponentFinder; -import org.sonar.server.component.index.ComponentIndexDefinition; import org.sonar.server.es.EsTester; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; -import org.sonar.server.measure.index.ProjectMeasuresIndexDefinition; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; @@ -76,8 +73,7 @@ public class BulkUpdateKeyActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot(); @Rule - public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig()), - new ComponentIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(system2); diff --git a/server/sonar-server/src/test/java/org/sonar/server/project/ws/UpdateVisibilityActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/project/ws/UpdateVisibilityActionTest.java index 946ba9b80a9..a146b13c0b6 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/project/ws/UpdateVisibilityActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/project/ws/UpdateVisibilityActionTest.java @@ -85,7 +85,7 @@ public class UpdateVisibilityActionTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule - public EsTester esTester = new EsTester(new FooIndexDefinition()); + public EsTester esTester = EsTester.custom(new FooIndexDefinition()); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone() .logIn(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/projecttag/ws/SearchActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/projecttag/ws/SearchActionTest.java index f2f2d1c68d8..5631bc2ff57 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/projecttag/ws/SearchActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/projecttag/ws/SearchActionTest.java @@ -19,12 +19,10 @@ */ package org.sonar.server.projecttag.ws; -import java.io.IOException; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Qualifiers; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -35,7 +33,6 @@ import org.sonar.db.organization.OrganizationTesting; import org.sonar.server.es.EsTester; import org.sonar.server.measure.index.ProjectMeasuresDoc; import org.sonar.server.measure.index.ProjectMeasuresIndex; -import org.sonar.server.measure.index.ProjectMeasuresIndexDefinition; import org.sonar.server.measure.index.ProjectMeasuresIndexer; import org.sonar.server.permission.index.AuthorizationTypeSupport; import org.sonar.server.permission.index.PermissionIndexerDao; @@ -55,7 +52,7 @@ public class SearchActionTest { private static final OrganizationDto ORG = OrganizationTesting.newOrganizationDto(); @Rule - public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public ExpectedException expectedException = ExpectedException.none(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileComparisonTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileComparisonTest.java index fadb2a400a9..5aa2d33a0f4 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileComparisonTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileComparisonTest.java @@ -26,7 +26,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.Severity; import org.sonar.api.server.rule.RuleParamType; import org.sonar.api.utils.System2; @@ -42,7 +41,6 @@ import org.sonar.server.qualityprofile.QProfileComparison.ActiveRuleDiff; import org.sonar.server.qualityprofile.QProfileComparison.QProfileComparisonResult; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.util.IntegerTypeValidation; import org.sonar.server.util.TypeValidations; @@ -58,7 +56,7 @@ public class QProfileComparisonTest { @Rule public DbTester dbTester = DbTester.create(); @Rule - public EsTester esTester = new EsTester(RuleIndexDefinition.createForTest(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private DbClient db; private DbSession dbSession; @@ -74,8 +72,8 @@ public class QProfileComparisonTest { public void before() { db = dbTester.getDbClient(); dbSession = db.openSession(false); - RuleIndex ruleIndex = new RuleIndex(esTester.client(), System2.INSTANCE); - ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db, esTester.client()); + RuleIndex ruleIndex = new RuleIndex(es.client(), System2.INSTANCE); + ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db, es.client()); RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, db, new TypeValidations(singletonList(new IntegerTypeValidation())), userSession); qProfileRules = new QProfileRulesImpl(db, ruleActivator, ruleIndex, activeRuleIndexer); comparison = new QProfileComparison(db); diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileRuleImplTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileRuleImplTest.java index d858d86a4e1..6c35c6d720a 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileRuleImplTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileRuleImplTest.java @@ -30,7 +30,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.sonar.api.PropertyType; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.utils.System2; @@ -47,7 +46,6 @@ import org.sonar.server.es.SearchOptions; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.rule.index.RuleQuery; import org.sonar.server.tester.UserSessionRule; @@ -79,7 +77,7 @@ public class QProfileRuleImplTest { @Rule public DbTester db = DbTester.create(system2); @Rule - public EsTester es = new EsTester(RuleIndexDefinition.createForTest(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private RuleIndex ruleIndex = new RuleIndex(es.client(), system2); @@ -152,8 +150,8 @@ public class QProfileRuleImplTest { } /** - * SONAR-5841 - */ + * SONAR-5841 + */ @Test public void activate_rule_with_empty_parameter_having_no_default_value() { RuleDefinitionDto rule = createRule(); @@ -168,8 +166,9 @@ public class QProfileRuleImplTest { } /** - // * SONAR-5840 - // */ + * // * SONAR-5840 + * // + */ @Test public void activate_rule_with_negative_integer_value_on_parameter_having_no_default_value() { RuleDefinitionDto rule = createRule(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileTreeImplTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileTreeImplTest.java index 31b3857b905..8ffd2bf6b73 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileTreeImplTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileTreeImplTest.java @@ -26,7 +26,6 @@ import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.utils.System2; @@ -39,7 +38,6 @@ import org.sonar.db.rule.RuleDefinitionDto; import org.sonar.server.es.EsTester; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.util.IntegerTypeValidation; import org.sonar.server.util.StringTypeValidation; @@ -61,7 +59,7 @@ public class QProfileTreeImplTest { @Rule public DbTester db = DbTester.create(system2); @Rule - public EsTester es = new EsTester(RuleIndexDefinition.createForTest(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/index/ActiveRuleIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/index/ActiveRuleIndexerTest.java index fff22e50be2..e5fa5e7c761 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/index/ActiveRuleIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/index/ActiveRuleIndexerTest.java @@ -27,7 +27,6 @@ import org.assertj.core.groups.Tuple; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.es.EsQueueDto; @@ -37,7 +36,6 @@ import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.RuleDefinitionDto; import org.sonar.server.es.EsTester; import org.sonar.server.qualityprofile.ActiveRuleChange; -import org.sonar.server.rule.index.RuleIndexDefinition; import static java.lang.String.valueOf; import static java.util.Arrays.asList; @@ -55,7 +53,7 @@ public class ActiveRuleIndexerTest { public DbTester db = DbTester.create(system2); @Rule - public EsTester es = new EsTester(RuleIndexDefinition.createForTest(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private ActiveRuleIndexer underTest = new ActiveRuleIndexer(db.getDbClient(), es.client()); private RuleDefinitionDto rule1; @@ -127,6 +125,7 @@ public class ActiveRuleIndexerTest { EsQueueDto expectedItem = EsQueueDto.create(INDEX_TYPE_ACTIVE_RULE.format(), "" + ar.getId(), "activeRuleId", valueOf(ar.getRuleId())); assertThatEsQueueContainsExactly(expectedItem); + es.unlockWrites(INDEX_TYPE_ACTIVE_RULE); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ChangeParentActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ChangeParentActionTest.java index 0d690645cf4..fa2a1becbb8 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ChangeParentActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ChangeParentActionTest.java @@ -25,7 +25,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; @@ -56,7 +55,6 @@ import org.sonar.server.qualityprofile.QProfileTreeImpl; import org.sonar.server.qualityprofile.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.rule.index.RuleQuery; import org.sonar.server.tester.UserSessionRule; @@ -82,7 +80,7 @@ public class ChangeParentActionTest { @Rule public DbTester db = new DbTester(System2.INSTANCE, null); @Rule - public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java index 70b43938eb0..7a2496f1a57 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java @@ -27,7 +27,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.profiles.ProfileImporter; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.rules.RulePriority; @@ -55,7 +54,6 @@ import org.sonar.server.qualityprofile.QProfileRulesImpl; import org.sonar.server.qualityprofile.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.rule.index.RuleQuery; import org.sonar.server.tester.UserSessionRule; @@ -84,7 +82,7 @@ public class CreateActionTest { @Rule public DbTester db = DbTester.create(); @Rule - public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/InheritanceActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/InheritanceActionTest.java index bf57686f58b..81fe585c9f9 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/InheritanceActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/InheritanceActionTest.java @@ -25,7 +25,6 @@ import java.util.Date; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -54,7 +53,6 @@ import org.sonar.server.qualityprofile.RuleActivation; import org.sonar.server.qualityprofile.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.util.TypeValidations; @@ -74,7 +72,7 @@ public class InheritanceActionTest { @Rule public DbTester dbTester = DbTester.create(); @Rule - public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/QProfilesWsMediumTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/QProfilesWsMediumTest.java index e673d15d2f3..e0024353ccc 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/QProfilesWsMediumTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/QProfilesWsMediumTest.java @@ -25,7 +25,6 @@ import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; @@ -52,7 +51,6 @@ import org.sonar.server.qualityprofile.QProfileTesting; import org.sonar.server.qualityprofile.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.rule.index.RuleQuery; import org.sonar.server.rule.ws.RuleQueryFactory; @@ -79,7 +77,7 @@ public class QProfilesWsMediumTest { public UserSessionRule userSessionRule = UserSessionRule.standalone() .logIn().setRoot(); @Rule - public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public DbTester dbTester = DbTester.create(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ShowActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ShowActionTest.java index 06dbddd09b9..c4b5bf360db 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ShowActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ShowActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; @@ -36,7 +35,6 @@ import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; @@ -63,7 +61,7 @@ public class ShowActionTest { private static Languages LANGUAGES = new Languages(XOO1, XOO2); @Rule - public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(); @Rule @@ -194,7 +192,7 @@ public class ShowActionTest { CompareToSonarWay result = call(ws.newRequest() .setParam(PARAM_KEY, profile.getKee()) .setParam(PARAM_COMPARE_TO_SONAR_WAY, "true")) - .getCompareToSonarWay(); + .getCompareToSonarWay(); assertThat(result) .extracting(CompareToSonarWay::getProfile, CompareToSonarWay::getProfileName, CompareToSonarWay::getMissingRuleCount) @@ -214,7 +212,7 @@ public class ShowActionTest { CompareToSonarWay result = call(ws.newRequest() .setParam(PARAM_KEY, profile.getKee()) .setParam(PARAM_COMPARE_TO_SONAR_WAY, "true")) - .getCompareToSonarWay(); + .getCompareToSonarWay(); assertThat(result) .extracting(CompareToSonarWay::getProfile, CompareToSonarWay::getProfileName, CompareToSonarWay::getMissingRuleCount) @@ -278,7 +276,7 @@ public class ShowActionTest { CompareToSonarWay result = call(ws.newRequest() .setParam(PARAM_KEY, profile.getKee()) .setParam(PARAM_COMPARE_TO_SONAR_WAY, "true")) - .getCompareToSonarWay(); + .getCompareToSonarWay(); assertThat(result) .extracting(CompareToSonarWay::getProfile, CompareToSonarWay::getProfileName) @@ -294,7 +292,7 @@ public class ShowActionTest { CompareToSonarWay result = call(ws.newRequest() .setParam(PARAM_KEY, profile.getKee()) .setParam(PARAM_COMPARE_TO_SONAR_WAY, "true")) - .getCompareToSonarWay(); + .getCompareToSonarWay(); assertThat(result) .extracting(CompareToSonarWay::getProfile, CompareToSonarWay::getProfileName) diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java index 5ad35663a30..1842e691133 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java @@ -32,7 +32,6 @@ import org.junit.Before; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; @@ -104,7 +103,7 @@ public class RegisterRulesTest { @org.junit.Rule public DbTester dbTester = DbTester.create(system); @org.junit.Rule - public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @org.junit.Rule public LogTester logTester = new LogTester(); @@ -497,7 +496,7 @@ public class RegisterRulesTest { @DataProvider public static Object[][] allRenamingCases() { - return new Object[][] { + return new Object[][]{ {"repo1", "rule1", "repo1", "rule2"}, {"repo1", "rule1", "repo2", "rule1"}, {"repo1", "rule1", "repo2", "rule2"}, diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/RuleCreatorTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/RuleCreatorTest.java index b66702330ec..515a4eba16b 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/RuleCreatorTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/RuleCreatorTest.java @@ -27,7 +27,6 @@ import org.assertj.core.api.Fail; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; @@ -45,7 +44,6 @@ import org.sonar.server.es.SearchOptions; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.rule.index.RuleQuery; @@ -66,7 +64,7 @@ public class RuleCreatorTest { public DbTester dbTester = DbTester.create(system2); @Rule - public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private RuleIndex ruleIndex = new RuleIndex(es.client(), system2); private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), dbTester.getDbClient()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java index 7e5256c34f2..e78dc45b318 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java @@ -30,7 +30,6 @@ import javax.annotation.Nonnull; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; @@ -51,7 +50,6 @@ import org.sonar.server.es.EsTester; import org.sonar.server.es.SearchOptions; import org.sonar.server.qualityprofile.QProfileTesting; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.rule.index.RuleQuery; import org.sonar.server.tester.UserSessionRule; @@ -79,7 +77,7 @@ public class RuleUpdaterTest { public DbTester db = DbTester.create(system2); @Rule - public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private RuleIndex ruleIndex = new RuleIndex(es.client(), system2); private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexDefinitionTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexDefinitionTest.java index 3bac138aff5..2dca70212a4 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexDefinitionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexDefinitionTest.java @@ -46,7 +46,7 @@ public class RuleIndexDefinitionTest { private RuleIndexDefinition underTest = new RuleIndexDefinition(settings.asConfig()); @Rule - public EsTester tester = new EsTester(underTest); + public EsTester tester = EsTester.core(); @Test public void test_definition_of_index() { diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java index 602c3f54ca8..4610a09ff95 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java @@ -30,7 +30,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.utils.System2; @@ -91,7 +90,7 @@ public class RuleIndexTest { private System2 system2 = new AlwaysIncreasingSystem2(); @Rule - public EsTester es = new EsTester(RuleIndexDefinition.createForTest(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(system2); @Rule @@ -780,8 +779,8 @@ public class RuleIndexTest { } /** - * Facet with no filters at all - */ + * Facet with no filters at all + */ @Test public void sticky_facets_no_filters() { setupStickyFacets(); @@ -800,9 +799,9 @@ public class RuleIndexTest { } /** - * Facet with a language filter - * -- lang facet should still have all language - */ + * Facet with a language filter + * -- lang facet should still have all language + */ @Test public void sticky_facets_with_1_filter() { setupStickyFacets(); @@ -908,11 +907,11 @@ public class RuleIndexTest { } /** - * Facet with 2 filters - * -- lang facet for tag T2 - * -- tag facet for lang cpp - * -- repository for cpp & T2 - */ + * Facet with 2 filters + * -- lang facet for tag T2 + * -- tag facet for lang cpp + * -- repository for cpp & T2 + */ @Test public void sticky_facets_with_2_filters() { setupStickyFacets(); @@ -933,12 +932,12 @@ public class RuleIndexTest { } /** - * Facet with 3 filters - * -- lang facet for tag T2 - * -- tag facet for lang cpp & java - * -- repository for (cpp || java) & T2 - * -- type - */ + * Facet with 3 filters + * -- lang facet for tag T2 + * -- tag facet for lang cpp & java + * -- repository for (cpp || java) & T2 + * -- type + */ @Test public void sticky_facets_with_3_filters() { setupStickyFacets(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexerTest.java index 476ce55125f..e05272d092c 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/index/RuleIndexerTest.java @@ -25,7 +25,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; @@ -35,8 +34,8 @@ import org.sonar.db.DbTester; import org.sonar.db.organization.OrganizationDto; import org.sonar.db.rule.RuleDefinitionDto; import org.sonar.db.rule.RuleDto; -import org.sonar.db.rule.RuleTesting; import org.sonar.db.rule.RuleDto.Scope; +import org.sonar.db.rule.RuleTesting; import org.sonar.server.es.EsTester; import static com.google.common.collect.Sets.newHashSet; @@ -46,7 +45,7 @@ import static org.elasticsearch.index.query.QueryBuilders.termQuery; public class RuleIndexerTest { @Rule - public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public DbTester dbTester = DbTester.create(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java index 79aecea7868..39152fd2133 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.rule.ws; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -37,7 +36,6 @@ import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.rule.RuleCreator; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.text.MacroInterpreter; @@ -72,7 +70,7 @@ public class CreateActionTest { public DbTester db = DbTester.create(system2); @Rule - public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db); diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/DeleteActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/DeleteActionTest.java index 19ed708fe55..58b5995a2c3 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/DeleteActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/DeleteActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.rule.ws; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.RuleStatus; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -35,7 +34,6 @@ import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.qualityprofile.QProfileRules; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; @@ -56,7 +54,7 @@ public class DeleteActionTest { @Rule public DbTester dbTester = DbTester.create(); @Rule - public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java index a981bea606c..beec0a59ad0 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java @@ -27,7 +27,6 @@ import org.assertj.core.api.iterable.Extractor; import org.junit.Before; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -56,7 +55,6 @@ import org.sonar.server.qualityprofile.RuleActivation; import org.sonar.server.qualityprofile.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.text.MacroInterpreter; @@ -103,10 +101,10 @@ public class SearchActionTest { @org.junit.Rule public DbTester db = DbTester.create(system2); @org.junit.Rule - public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db); - private RuleIndex ruleIndex = new RuleIndex(es.client() ,system2); + private RuleIndex ruleIndex = new RuleIndex(es.client(), system2); private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient()); private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client()); private Languages languages = LanguageTesting.newLanguages(JAVA, "js"); @@ -331,7 +329,7 @@ public class SearchActionTest { .executeProtobuf(SearchResponse.class); assertThat(result.getFacets().getFacets(0).getValuesList()).extracting(v -> v.getVal(), v -> v.getCount()) .containsExactly(tuple("tag1", 1L), tuple("tag2", 1L), tuple("tag3", 1L), tuple("tag4", 1L), tuple("tag5", 1L), tuple("tag6", 1L), tuple("tag7", 1L), tuple("tag8", 1L), - tuple("tag9", 1L), tuple("tagA", 1L)); + tuple("tag9", 1L), tuple("tagA", 1L)); } @Test @@ -348,7 +346,7 @@ public class SearchActionTest { .executeProtobuf(SearchResponse.class); assertThat(result.getFacets().getFacets(0).getValuesList()).extracting(v -> v.getVal(), v -> v.getCount()) .containsExactly(tuple("tag2", 2L), tuple("tag1", 1L), tuple("tag3", 1L), tuple("tag4", 1L), tuple("tag5", 1L), tuple("tag6", 1L), tuple("tag7", 1L), tuple("tag8", 1L), - tuple("tag9", 1L), tuple("tagA", 1L)); + tuple("tag9", 1L), tuple("tagA", 1L)); } @Test @@ -824,40 +822,40 @@ public class SearchActionTest { ); assertThat(result.getFacets().getFacetsList().stream().filter(f -> "repositories".equals(f.getProperty())).findAny().get().getValuesList()) - .extracting(Common.FacetValue::getVal, Common.FacetValue::getCount) - .as("Facet repositories") - .containsExactlyInAnyOrder( - tuple(rule1.getRepositoryKey(), 1L) - ); - - assertThat(result.getFacets().getFacetsList().stream().filter(f -> "severities".equals(f.getProperty())).findAny().get().getValuesList()) - .extracting(Common.FacetValue::getVal, Common.FacetValue::getCount) - .as("Facet severities") - .containsExactlyInAnyOrder( - tuple("BLOCKER" /*rule2*/, 0L), - tuple("CRITICAL"/*rule1*/, 1L), - tuple("MAJOR", 0L), - tuple("MINOR", 0L), - tuple("INFO", 0L) - ); - - assertThat(result.getFacets().getFacetsList().stream().filter(f -> "statuses".equals(f.getProperty())).findAny().get().getValuesList()) - .extracting(Common.FacetValue::getVal, Common.FacetValue::getCount) - .as("Facet statuses") - .containsExactlyInAnyOrder( - tuple("READY"/*rule2*/, 0L), - tuple("BETA" /*rule1*/, 1L), - tuple("DEPRECATED", 0L) - ); - - assertThat(result.getFacets().getFacetsList().stream().filter(f -> "types".equals(f.getProperty())).findAny().get().getValuesList()) - .extracting(Common.FacetValue::getVal, Common.FacetValue::getCount) - .as("Facet types") - .containsExactlyInAnyOrder( - tuple("BUG" /*rule2*/, 0L), - tuple("CODE_SMELL"/*rule1*/, 1L), - tuple("VULNERABILITY", 0L) - ); + .extracting(Common.FacetValue::getVal, Common.FacetValue::getCount) + .as("Facet repositories") + .containsExactlyInAnyOrder( + tuple(rule1.getRepositoryKey(), 1L) + ); + + assertThat(result.getFacets().getFacetsList().stream().filter(f -> "severities".equals(f.getProperty())).findAny().get().getValuesList()) + .extracting(Common.FacetValue::getVal, Common.FacetValue::getCount) + .as("Facet severities") + .containsExactlyInAnyOrder( + tuple("BLOCKER" /*rule2*/, 0L), + tuple("CRITICAL"/*rule1*/, 1L), + tuple("MAJOR", 0L), + tuple("MINOR", 0L), + tuple("INFO", 0L) + ); + + assertThat(result.getFacets().getFacetsList().stream().filter(f -> "statuses".equals(f.getProperty())).findAny().get().getValuesList()) + .extracting(Common.FacetValue::getVal, Common.FacetValue::getCount) + .as("Facet statuses") + .containsExactlyInAnyOrder( + tuple("READY"/*rule2*/, 0L), + tuple("BETA" /*rule1*/, 1L), + tuple("DEPRECATED", 0L) + ); + + assertThat(result.getFacets().getFacetsList().stream().filter(f -> "types".equals(f.getProperty())).findAny().get().getValuesList()) + .extracting(Common.FacetValue::getVal, Common.FacetValue::getCount) + .as("Facet types") + .containsExactlyInAnyOrder( + tuple("BUG" /*rule2*/, 0L), + tuple("CODE_SMELL"/*rule1*/, 1L), + tuple("VULNERABILITY", 0L) + ); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/ShowActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/ShowActionTest.java index cded9decf2a..e9f3951cc21 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/ShowActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/ShowActionTest.java @@ -27,7 +27,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -59,7 +58,6 @@ import org.sonar.server.qualityprofile.QProfileTesting; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.NewCustomRule; import org.sonar.server.rule.RuleCreator; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.text.MacroInterpreter; import org.sonar.server.util.TypeValidations; @@ -91,8 +89,7 @@ public class ShowActionTest { @org.junit.Rule public DbTester dbTester = DbTester.create(); @org.junit.Rule - public EsTester esTester = new EsTester( - new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @org.junit.Rule public ExpectedException thrown = ExpectedException.none(); @@ -143,9 +140,9 @@ public class ShowActionTest { RuleMetadataDto metadata = insertMetadata(organization, rule, setTags("tag1", "tag2")); Rules.ShowResponse result = actionTester.newRequest() - .setParam(PARAM_KEY, rule.getKey().toString()) - .setParam(PARAM_ORGANIZATION, organization.getKey()) - .executeProtobuf(Rules.ShowResponse.class); + .setParam(PARAM_KEY, rule.getKey().toString()) + .setParam(PARAM_ORGANIZATION, organization.getKey()) + .executeProtobuf(Rules.ShowResponse.class); assertThat(result.getRule().getTags().getTagsList()) .containsExactly(metadata.getTags().toArray(new String[0])); } diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/TagsActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/TagsActionTest.java index 667cfbcadcb..b6256560f05 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/TagsActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/TagsActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.rule.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -33,7 +32,6 @@ import org.sonar.server.es.EsClient; import org.sonar.server.es.EsTester; import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; @@ -50,7 +48,7 @@ public class TagsActionTest { @Rule public DbTester db = DbTester.create(); @Rule - public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private DbClient dbClient = db.getDbClient(); private EsClient esClient = es.client(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java index 6178d9c3eeb..4a2605f4fd6 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java @@ -19,11 +19,9 @@ */ package org.sonar.server.rule.ws; -import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -43,7 +41,6 @@ import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.rule.RuleUpdater; -import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.text.MacroInterpreter; @@ -84,7 +81,7 @@ public class UpdateActionTest { public DbTester db = DbTester.create(); @Rule - public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/telemetry/TelemetryDaemonTest.java b/server/sonar-server/src/test/java/org/sonar/server/telemetry/TelemetryDaemonTest.java index 3bdd92eaed0..9ab4d9167c2 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/telemetry/TelemetryDaemonTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/telemetry/TelemetryDaemonTest.java @@ -41,13 +41,11 @@ import org.sonar.db.component.ComponentDto; import org.sonar.db.metric.MetricDto; import org.sonar.server.es.EsTester; import org.sonar.server.measure.index.ProjectMeasuresIndex; -import org.sonar.server.measure.index.ProjectMeasuresIndexDefinition; import org.sonar.server.measure.index.ProjectMeasuresIndexer; import org.sonar.server.property.InternalProperties; import org.sonar.server.property.MapInternalProperties; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.index.UserIndex; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.updatecenter.common.Version; @@ -86,7 +84,7 @@ public class TelemetryDaemonTest { @Rule public DbTester db = DbTester.create(); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(emptyConfig), new ProjectMeasuresIndexDefinition(emptyConfig)); + public EsTester es = EsTester.core(); @Rule public LogTester logger = new LogTester().setLevel(LoggerLevel.DEBUG); @@ -273,7 +271,7 @@ public class TelemetryDaemonTest { .setVersion(Version.create(version)); } - private void initTelemetrySettingsToDefaultValues(){ + private void initTelemetrySettingsToDefaultValues() { settings.setProperty(SONAR_TELEMETRY_ENABLE.getKey(), SONAR_TELEMETRY_ENABLE.getDefaultValue()); settings.setProperty(SONAR_TELEMETRY_URL.getKey(), SONAR_TELEMETRY_URL.getDefaultValue()); settings.setProperty(SONAR_TELEMETRY_FREQUENCY_IN_SECONDS.getKey(), SONAR_TELEMETRY_FREQUENCY_IN_SECONDS.getDefaultValue()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexTest.java b/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexTest.java index 08799797f3d..e5f915c1961 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexTest.java @@ -23,7 +23,6 @@ import com.google.common.base.Optional; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.server.es.EsTester; import org.sonar.server.es.SearchOptions; @@ -35,7 +34,7 @@ import static org.sonar.server.test.index.TestIndexDefinition.INDEX_TYPE_TEST; public class TestIndexTest { @Rule - public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private TestIndex underTest = new TestIndex(es.client(), System2.INSTANCE); diff --git a/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexerTest.java index aabff4e89d6..1b39b9a9d9a 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexerTest.java @@ -27,7 +27,6 @@ import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.search.SearchHit; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.server.es.EsTester; @@ -50,7 +49,7 @@ public class TestIndexerTest { private System2 system2 = System2.INSTANCE; @Rule - public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(system2); diff --git a/server/sonar-server/src/test/java/org/sonar/server/test/ws/CoveredFilesActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/test/ws/CoveredFilesActionTest.java index e0b5103e8cf..6a25a2e52ec 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/test/ws/CoveredFilesActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/test/ws/CoveredFilesActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.test.ws; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.core.util.Uuids; @@ -34,7 +33,6 @@ import org.sonar.db.source.FileSourceDto; import org.sonar.server.es.EsTester; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.test.index.TestIndex; -import org.sonar.server.test.index.TestIndexDefinition; import org.sonar.server.test.index.TestIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; @@ -55,7 +53,7 @@ public class CoveredFilesActionTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule - public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/test/ws/ListActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/test/ws/ListActionTest.java index d99241c41a9..5e5d3eff1a6 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/test/ws/ListActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/test/ws/ListActionTest.java @@ -23,7 +23,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -37,7 +36,6 @@ import org.sonar.server.es.EsTester; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.test.index.TestIndex; -import org.sonar.server.test.index.TestIndexDefinition; import org.sonar.server.test.index.TestIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; @@ -69,7 +67,7 @@ public class ListActionTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule - public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/UserUpdaterCreateTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/UserUpdaterCreateTest.java index 928ba19bb21..8d7452a5d22 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/user/UserUpdaterCreateTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/user/UserUpdaterCreateTest.java @@ -72,7 +72,7 @@ public class UserUpdaterCreateTest { public ExpectedException expectedException = ExpectedException.none(); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(system2); @@ -100,7 +100,7 @@ public class UserUpdaterCreateTest { .setPassword("PASSWORD") .setScmAccounts(ImmutableList.of("u1", "u_1", "User 1")) .build(), u -> { - }); + }); assertThat(dto.getId()).isNotNull(); assertThat(dto.getLogin()).isEqualTo("user"); @@ -134,7 +134,7 @@ public class UserUpdaterCreateTest { .setLogin("us") .setName("User") .build(), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, "us"); assertThat(dto.getId()).isNotNull(); @@ -154,7 +154,7 @@ public class UserUpdaterCreateTest { .setName("User") .setPassword("password") .build(), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, "user"); assertThat(dto.getExternalIdentity()).isEqualTo("user"); @@ -171,7 +171,7 @@ public class UserUpdaterCreateTest { .setName("User") .setExternalIdentity(new ExternalIdentity("github", "github-user")) .build(), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, "user"); assertThat(dto.isLocal()).isFalse(); @@ -190,7 +190,7 @@ public class UserUpdaterCreateTest { .setName("User") .setExternalIdentity(new ExternalIdentity(SQ_AUTHORITY, "user")) .build(), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, "user"); assertThat(dto.isLocal()).isFalse(); @@ -210,7 +210,7 @@ public class UserUpdaterCreateTest { .setPassword("password") .setScmAccounts(asList("u1", "", null)) .build(), u -> { - }); + }); assertThat(dbClient.userDao().selectByLogin(session, "user").getScmAccountsAsList()).containsOnly("u1"); } @@ -225,7 +225,7 @@ public class UserUpdaterCreateTest { .setPassword("password") .setScmAccounts(asList("")) .build(), u -> { - }); + }); assertThat(dbClient.userDao().selectByLogin(session, "user").getScmAccounts()).isNull(); } @@ -240,7 +240,7 @@ public class UserUpdaterCreateTest { .setPassword("password") .setScmAccounts(asList("u1", "u1")) .build(), u -> { - }); + }); assertThat(dbClient.userDao().selectByLogin(session, "user").getScmAccountsAsList()).containsOnly("u1"); } @@ -254,7 +254,7 @@ public class UserUpdaterCreateTest { .setLogin("user") .setName("User") .build(), u -> { - }); + }); assertThat(dbClient.userDao().selectByLogin(session, "user").isOnboarded()).isTrue(); } @@ -268,7 +268,7 @@ public class UserUpdaterCreateTest { .setLogin("user") .setName("User") .build(), u -> { - }); + }); assertThat(dbClient.userDao().selectByLogin(session, "user").isOnboarded()).isFalse(); } @@ -284,7 +284,7 @@ public class UserUpdaterCreateTest { .setEmail("user@mail.com") .setPassword("PASSWORD") .build(), u -> { - }, otherUser); + }, otherUser); assertThat(es.getIds(UserIndexDefinition.INDEX_TYPE_USER)).containsExactlyInAnyOrder(created.getLogin(), otherUser.getLogin()); } @@ -300,7 +300,7 @@ public class UserUpdaterCreateTest { .setEmail("marius@mail.com") .setPassword("password") .build(), u -> { - }); + }); } @Test @@ -314,7 +314,7 @@ public class UserUpdaterCreateTest { .setEmail("marius@mail.com") .setPassword("password") .build(), u -> { - }); + }); } @Test @@ -328,7 +328,7 @@ public class UserUpdaterCreateTest { .setEmail("marius@mail.com") .setPassword("password") .build(), u -> { - }); + }); } @Test @@ -342,7 +342,7 @@ public class UserUpdaterCreateTest { .setEmail("marius@mail.com") .setPassword("password") .build(), u -> { - }); + }); } @Test @@ -356,7 +356,7 @@ public class UserUpdaterCreateTest { .setEmail("marius@mail.com") .setPassword("password") .build(), u -> { - }); + }); } @Test @@ -370,7 +370,7 @@ public class UserUpdaterCreateTest { .setEmail("marius@mail.com") .setPassword("password") .build(), u -> { - }); + }); } @Test @@ -384,7 +384,7 @@ public class UserUpdaterCreateTest { .setEmail("marius@mail.com") .setPassword("password") .build(), u -> { - }); + }); } @Test @@ -398,7 +398,7 @@ public class UserUpdaterCreateTest { .setEmail(Strings.repeat("m", 101)) .setPassword("password") .build(), u -> { - }); + }); } @Test @@ -410,7 +410,7 @@ public class UserUpdaterCreateTest { .setEmail("marius@mail.com") .setPassword("") .build(), u -> { - }); + }); fail(); } catch (BadRequestException e) { assertThat(e.errors()).hasSize(3); @@ -431,7 +431,7 @@ public class UserUpdaterCreateTest { .setPassword("password") .setScmAccounts(asList("jo")) .build(), u -> { - }); + }); } @Test @@ -449,7 +449,7 @@ public class UserUpdaterCreateTest { .setPassword("password") .setScmAccounts(asList("john@email.com")) .build(), u -> { - }); + }); } @Test @@ -464,7 +464,7 @@ public class UserUpdaterCreateTest { .setPassword("password2") .setScmAccounts(asList(DEFAULT_LOGIN)) .build(), u -> { - }); + }); } @Test @@ -479,7 +479,7 @@ public class UserUpdaterCreateTest { .setPassword("password2") .setScmAccounts(asList("marius2@mail.com")) .build(), u -> { - }); + }); } @Test @@ -493,7 +493,7 @@ public class UserUpdaterCreateTest { .setPassword("password") .setScmAccounts(asList("u1", "u_1")) .build(), u -> { - }); + }); verify(newUserNotifier).onNewUser(newUserHandler.capture()); assertThat(newUserHandler.getValue().getLogin()).isEqualTo("user"); @@ -512,7 +512,7 @@ public class UserUpdaterCreateTest { .setEmail("user@mail.com") .setPassword("password") .build(), u -> { - }); + }); Multimap groups = dbClient.groupMembershipDao().selectGroupsByLogins(session, asList("user")); assertThat(groups.get("user")).containsOnly(defaultGroup.getName()); @@ -529,7 +529,7 @@ public class UserUpdaterCreateTest { .setEmail("user@mail.com") .setPassword("password") .build(), u -> { - }); + }); Multimap groups = dbClient.groupMembershipDao().selectGroupsByLogins(session, asList("user")); assertThat(groups.get("user")).isEmpty(); @@ -547,7 +547,7 @@ public class UserUpdaterCreateTest { .setPassword("password") .setScmAccounts(asList("u1", "u_1")) .build(), u -> { - }); + }); } @Test @@ -560,7 +560,7 @@ public class UserUpdaterCreateTest { .setEmail("user@mail.com") .setPassword("PASSWORD") .build(), u -> { - }); + }); verify(organizationCreation).createForUser(any(DbSession.class), eq(dto)); } @@ -576,7 +576,7 @@ public class UserUpdaterCreateTest { .setEmail("user@mail.com") .setPassword("PASSWORD") .build(), u -> { - }); + }); assertThat(dbClient.organizationMemberDao().select(db.getSession(), defaultOrganizationProvider.get().getUuid(), dto.getId())).isPresent(); } @@ -592,7 +592,7 @@ public class UserUpdaterCreateTest { .setEmail("user@mail.com") .setPassword("PASSWORD") .build(), u -> { - }); + }); assertThat(dbClient.organizationMemberDao().select(db.getSession(), defaultOrganizationProvider.get().getUuid(), dto.getId())).isNotPresent(); } @@ -609,7 +609,7 @@ public class UserUpdaterCreateTest { .setEmail("marius2@mail.com") .setPassword("password2") .build(), u -> { - }); + }); session.commit(); assertThat(dto.isActive()).isTrue(); @@ -638,7 +638,7 @@ public class UserUpdaterCreateTest { .setName("Marius2") .setEmail("marius2@mail.com") .build(), u -> { - }); + }); session.commit(); assertThat(dto.isActive()).isTrue(); @@ -663,7 +663,7 @@ public class UserUpdaterCreateTest { .setName("Marius2") .setExternalIdentity(new ExternalIdentity("github", "john")) .build(), u -> { - }); + }); session.commit(); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); @@ -683,7 +683,7 @@ public class UserUpdaterCreateTest { .setName("Marius2") .setPassword("password") .build(), u -> { - }); + }); session.commit(); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); @@ -706,7 +706,7 @@ public class UserUpdaterCreateTest { .setEmail("marius2@mail.com") .setPassword("password2") .build(), u -> { - }); + }); } @Test @@ -725,7 +725,7 @@ public class UserUpdaterCreateTest { .setEmail("marius2@mail.com") .setPassword("password2") .build(), u -> { - }); + }); session.commit(); Multimap groups = dbClient.groupMembershipDao().selectGroupsByLogins(session, asList(DEFAULT_LOGIN)); @@ -748,7 +748,7 @@ public class UserUpdaterCreateTest { .setEmail("marius2@mail.com") .setPassword("password2") .build(), u -> { - }); + }); session.commit(); Multimap groups = dbClient.groupMembershipDao().selectGroupsByLogins(session, asList(DEFAULT_LOGIN)); @@ -793,7 +793,7 @@ public class UserUpdaterCreateTest { .setLogin(user.getLogin()) .setName("name") .build(), u -> { - }); + }); assertThat(dbClient.userDao().selectByLogin(session, user.getLogin()).isOnboarded()).isTrue(); } @@ -810,7 +810,7 @@ public class UserUpdaterCreateTest { .setLogin(user.getLogin()) .setName("name") .build(), u -> { - }); + }); assertThat(dbClient.userDao().selectByLogin(session, user.getLogin()).isOnboarded()).isFalse(); } diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/UserUpdaterUpdateTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/UserUpdaterUpdateTest.java index f6fbc223f9f..81bc9bc79a2 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/user/UserUpdaterUpdateTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/user/UserUpdaterUpdateTest.java @@ -64,7 +64,7 @@ public class UserUpdaterUpdateTest { public ExpectedException expectedException = ExpectedException.none(); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); @Rule public DbTester db = DbTester.create(system2); @@ -94,7 +94,7 @@ public class UserUpdaterUpdateTest { .setEmail("marius2@mail.com") .setPassword("password2") .setScmAccounts(asList("ma2")), u -> { - }); + }); UserDto updatedUser = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); assertThat(updatedUser.isActive()).isTrue(); @@ -125,7 +125,7 @@ public class UserUpdaterUpdateTest { .setName("Marius2") .setEmail("marius2@email.com") .setExternalIdentity(new ExternalIdentity("github", "john")), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); assertThat(dto.getExternalIdentity()).isEqualTo("john"); @@ -142,7 +142,7 @@ public class UserUpdaterUpdateTest { .setName("Marius2") .setEmail("marius2@email.com") .setExternalIdentity(new ExternalIdentity("github", "john")), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); assertThat(dto.getExternalIdentity()).isEqualTo("john"); @@ -166,7 +166,7 @@ public class UserUpdaterUpdateTest { .setEmail("marius2@mail.com") .setPassword("password2") .setScmAccounts(asList("ma2")), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); assertThat(dto.isActive()).isTrue(); @@ -199,7 +199,7 @@ public class UserUpdaterUpdateTest { .setEmail("marius2@mail.com") .setPassword("password2") .setScmAccounts(asList("ma2", "", null)), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); assertThat(dto.getScmAccountsAsList()).containsOnly("ma2"); @@ -215,7 +215,7 @@ public class UserUpdaterUpdateTest { underTest.updateAndCommit(session, UpdateUser.create(DEFAULT_LOGIN) .setName("Marius2"), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); assertThat(dto.getName()).isEqualTo("Marius2"); @@ -237,7 +237,7 @@ public class UserUpdaterUpdateTest { underTest.updateAndCommit(session, UpdateUser.create(DEFAULT_LOGIN) .setEmail("marius2@mail.com"), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); assertThat(dto.getEmail()).isEqualTo("marius2@mail.com"); @@ -259,7 +259,7 @@ public class UserUpdaterUpdateTest { underTest.updateAndCommit(session, UpdateUser.create(DEFAULT_LOGIN) .setScmAccounts(asList("ma2")), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); assertThat(dto.getScmAccountsAsList()).containsOnly("ma2"); @@ -279,7 +279,7 @@ public class UserUpdaterUpdateTest { underTest.updateAndCommit(session, UpdateUser.create(DEFAULT_LOGIN) .setScmAccounts(asList("ma", "marius33")), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); assertThat(dto.getScmAccountsAsList()).containsOnly("ma", "marius33"); @@ -293,7 +293,7 @@ public class UserUpdaterUpdateTest { underTest.updateAndCommit(session, UpdateUser.create(DEFAULT_LOGIN) .setScmAccounts(null), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); assertThat(dto.getScmAccounts()).isNull(); @@ -309,7 +309,7 @@ public class UserUpdaterUpdateTest { underTest.updateAndCommit(session, UpdateUser.create(DEFAULT_LOGIN) .setPassword("password2"), u -> { - }); + }); UserDto dto = dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN); assertThat(dto.getSalt()).isNotEqualTo("salt"); @@ -365,7 +365,7 @@ public class UserUpdaterUpdateTest { .setEmail(user.getEmail()) .setScmAccounts(user.getScmAccountsAsList()) .setExternalIdentity(new ExternalIdentity(user.getExternalIdentityProvider(), user.getExternalIdentity())), u -> { - }); + }); assertThat(dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN).getUpdatedAt()).isEqualTo(user.getUpdatedAt()); } @@ -384,7 +384,7 @@ public class UserUpdaterUpdateTest { .setEmail(user.getEmail()) .setScmAccounts(asList("ma2", "ma1")) .setExternalIdentity(new ExternalIdentity(user.getExternalIdentityProvider(), user.getExternalIdentity())), u -> { - }); + }); assertThat(dbClient.userDao().selectByLogin(session, DEFAULT_LOGIN).getUpdatedAt()).isEqualTo(user.getUpdatedAt()); } @@ -441,7 +441,7 @@ public class UserUpdaterUpdateTest { .setEmail("marius2@mail.com") .setPassword("password2") .setScmAccounts(asList("ma2")), u -> { - }); + }); Multimap groups = dbClient.groupMembershipDao().selectGroupsByLogins(session, asList(DEFAULT_LOGIN)); assertThat(groups.get(DEFAULT_LOGIN).stream().anyMatch(g -> g.equals(defaultGroup.getName()))).isFalse(); @@ -462,7 +462,7 @@ public class UserUpdaterUpdateTest { .setEmail("marius2@mail.com") .setPassword("password2") .setScmAccounts(asList("ma2")), u -> { - }); + }); // Nothing as changed groups = dbClient.groupMembershipDao().selectGroupsByLogins(session, asList(DEFAULT_LOGIN)); @@ -483,7 +483,7 @@ public class UserUpdaterUpdateTest { .setEmail("marius2@mail.com") .setPassword("password2") .setScmAccounts(asList("jo")), u -> { - }); + }); } @Test @@ -518,7 +518,7 @@ public class UserUpdaterUpdateTest { underTest.updateAndCommit(session, UpdateUser.create(DEFAULT_LOGIN) .setEmail("marius@newmail.com") .setScmAccounts(asList("marius@newmail.com")), u -> { - }); + }); } private GroupDto createDefaultGroup() { diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/index/UserIndexTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/index/UserIndexTest.java index 45af16daf7b..1b73cad0dc8 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/user/index/UserIndexTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/user/index/UserIndexTest.java @@ -25,7 +25,6 @@ import java.util.Locale; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.server.es.EsTester; import org.sonar.server.es.SearchOptions; @@ -46,7 +45,7 @@ public class UserIndexTest { private static final long DATE_2 = 1_500_000_000_001L; @Rule - public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); private UserIndex underTest; @@ -58,7 +57,7 @@ public class UserIndexTest { } @Test - public void get_nullable_by_login() { + public void get_nullable_by_login() { UserDoc user1 = newUser(USER1_LOGIN, asList("scmA", "scmB")); esTester.putDocuments(INDEX_TYPE_USER, user1); esTester.putDocuments(INDEX_TYPE_USER, newUser(USER2_LOGIN, Collections.emptyList())); @@ -76,7 +75,7 @@ public class UserIndexTest { } @Test - public void getNullableByLogin_is_case_sensitive() { + public void getNullableByLogin_is_case_sensitive() { UserDoc user1 = newUser(USER1_LOGIN, asList("scmA", "scmB")); esTester.putDocuments(INDEX_TYPE_USER, user1); @@ -85,7 +84,7 @@ public class UserIndexTest { } @Test - public void getAtMostThreeActiveUsersForScmAccount_returns_the_users_with_specified_scm_account() { + public void getAtMostThreeActiveUsersForScmAccount_returns_the_users_with_specified_scm_account() { UserDoc user1 = newUser("user1", asList("user_1", "u1")); UserDoc user2 = newUser("user_with_same_email_as_user1", asList("user_2")).setEmail(user1.email()); UserDoc user3 = newUser("inactive_user_with_same_scm_as_user1", user1.scmAccounts()).setActive(false); @@ -104,7 +103,7 @@ public class UserIndexTest { } @Test - public void getAtMostThreeActiveUsersForScmAccount_ignores_inactive_user() { + public void getAtMostThreeActiveUsersForScmAccount_ignores_inactive_user() { String scmAccount = "scmA"; UserDoc user = newUser(USER1_LOGIN, singletonList(scmAccount)).setActive(false); esTester.putDocuments(INDEX_TYPE_USER, user); @@ -114,7 +113,7 @@ public class UserIndexTest { } @Test - public void getAtMostThreeActiveUsersForScmAccount_returns_maximum_three_users() { + public void getAtMostThreeActiveUsersForScmAccount_returns_maximum_three_users() { String email = "user@mail.com"; UserDoc user1 = newUser("user1", Collections.emptyList()).setEmail(email); UserDoc user2 = newUser("user2", Collections.emptyList()).setEmail(email); @@ -130,7 +129,7 @@ public class UserIndexTest { } @Test - public void getAtMostThreeActiveUsersForScmAccount_is_case_sensitive_for_login() { + public void getAtMostThreeActiveUsersForScmAccount_is_case_sensitive_for_login() { UserDoc user = newUser("the_login", singletonList("John.Smith")); esTester.putDocuments(INDEX_TYPE_USER, user); @@ -139,7 +138,7 @@ public class UserIndexTest { } @Test - public void getAtMostThreeActiveUsersForScmAccount_is_case_insensitive_for_email() { + public void getAtMostThreeActiveUsersForScmAccount_is_case_insensitive_for_email() { UserDoc user = newUser("the_login", "the_EMAIL@corp.com", singletonList("John.Smith")); esTester.putDocuments(INDEX_TYPE_USER, user); @@ -149,7 +148,7 @@ public class UserIndexTest { } @Test - public void getAtMostThreeActiveUsersForScmAccount_is_case_insensitive_for_scm_account() { + public void getAtMostThreeActiveUsersForScmAccount_is_case_insensitive_for_scm_account() { UserDoc user = newUser("the_login", singletonList("John.Smith")); esTester.putDocuments(INDEX_TYPE_USER, user); @@ -160,7 +159,7 @@ public class UserIndexTest { } @Test - public void getAtMostThreeActiveUsersForScmAccount_search_only_user_within_given_organization() { + public void getAtMostThreeActiveUsersForScmAccount_search_only_user_within_given_organization() { UserDoc user1 = newUser("user1", singletonList("same_scm")).setOrganizationUuids(singletonList(ORGANIZATION_UUID)); UserDoc user2 = newUser("user2", singletonList("same_scm")).setOrganizationUuids(singletonList("another_organization")); esTester.putDocuments(INDEX_TYPE_USER, user1); @@ -170,7 +169,7 @@ public class UserIndexTest { } @Test - public void searchUsers() { + public void searchUsers() { esTester.putDocuments(INDEX_TYPE_USER, newUser(USER1_LOGIN, asList("user_1", "u1")).setEmail("email1")); esTester.putDocuments(INDEX_TYPE_USER, newUser(USER2_LOGIN, Collections.emptyList()).setEmail("email2")); diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/index/UserIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/index/UserIndexerTest.java index 4445bc4133c..dd4b86caa43 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/user/index/UserIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/user/index/UserIndexerTest.java @@ -23,7 +23,6 @@ import java.util.HashSet; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.user.UserDto; @@ -41,7 +40,7 @@ public class UserIndexerTest { public DbTester db = DbTester.create(system2); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester es = EsTester.core(); private UserIndexer underTest = new UserIndexer(db.getDbClient(), es.client()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/ws/ChangePasswordActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/ws/ChangePasswordActionTest.java index b35639e33cc..9f653698af9 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/user/ws/ChangePasswordActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/user/ws/ChangePasswordActionTest.java @@ -37,7 +37,6 @@ import org.sonar.server.user.ExternalIdentity; import org.sonar.server.user.NewUser; import org.sonar.server.user.NewUserNotifier; import org.sonar.server.user.UserUpdater; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.usergroups.DefaultGroupFinder; import org.sonar.server.ws.WsTester; @@ -52,7 +51,7 @@ public class ChangePasswordActionTest { @Rule public DbTester db = DbTester.create(); @Rule - public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone().logIn(); @@ -182,6 +181,6 @@ public class ChangePasswordActionTest { .setScmAccounts(newArrayList("jn")) .setPassword("Valar Dohaeris") .build(), u -> { - }); + }); } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/ws/CreateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/ws/CreateActionTest.java index 2d9c134f9db..229b9cf6492 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/user/ws/CreateActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/user/ws/CreateActionTest.java @@ -45,7 +45,6 @@ import org.sonar.server.user.NewUserNotifier; import org.sonar.server.user.UserUpdater; import org.sonar.server.user.index.UserDoc; import org.sonar.server.user.index.UserIndex; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.user.ws.CreateAction.CreateRequest; import org.sonar.server.usergroups.DefaultGroupFinder; @@ -71,7 +70,7 @@ public class CreateActionTest { @Rule public DbTester db = DbTester.create(system2); @Rule - public EsTester esTester = new EsTester(new UserIndexDefinition(settings.asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/ws/DeactivateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/ws/DeactivateActionTest.java index e238420e118..249611b9f85 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/user/ws/DeactivateActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/user/ws/DeactivateActionTest.java @@ -23,7 +23,6 @@ import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.api.utils.internal.AlwaysIncreasingSystem2; import org.sonar.db.DbClient; @@ -47,7 +46,6 @@ import org.sonar.server.organization.DefaultOrganizationProvider; import org.sonar.server.organization.TestDefaultOrganizationProvider; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.index.UserIndex; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; @@ -77,7 +75,7 @@ public class DeactivateActionTest { public DbTester db = DbTester.create(system2); @Rule - public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/ws/SearchActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/ws/SearchActionTest.java index 14a6031986e..20d96c8bba2 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/user/ws/SearchActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/user/ws/SearchActionTest.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.function.Consumer; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -38,7 +37,6 @@ import org.sonar.server.es.EsTester; import org.sonar.server.issue.ws.AvatarResolverImpl; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.index.UserIndex; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.ws.WsTester; @@ -56,7 +54,7 @@ public class SearchActionTest { private System2 system2 = System2.INSTANCE; @Rule - public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/ws/UpdateActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/ws/UpdateActionTest.java index 2c8b07f0099..d6fe89abd96 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/user/ws/UpdateActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/user/ws/UpdateActionTest.java @@ -40,7 +40,6 @@ import org.sonar.server.organization.TestOrganizationFlags; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.NewUserNotifier; import org.sonar.server.user.UserUpdater; -import org.sonar.server.user.index.UserIndexDefinition; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.usergroups.DefaultGroupFinder; import org.sonar.server.ws.WsActionTester; @@ -60,7 +59,7 @@ public class UpdateActionTest { @Rule public DbTester db = DbTester.create(system2); @Rule - public EsTester es = new EsTester(new UserIndexDefinition(settings.asConfig())); + public EsTester es = EsTester.core(); @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator(); @Rule diff --git a/server/sonar-server/src/test/java/org/sonar/server/view/index/ViewIndexTest.java b/server/sonar-server/src/test/java/org/sonar/server/view/index/ViewIndexTest.java index 2f6224d7414..ffba3c29212 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/view/index/ViewIndexTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/view/index/ViewIndexTest.java @@ -22,7 +22,6 @@ package org.sonar.server.view.index; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.EsTester; import static com.google.common.collect.Lists.newArrayList; @@ -33,7 +32,7 @@ import static org.sonar.server.view.index.ViewIndexDefinition.INDEX_TYPE_VIEW; public class ViewIndexTest { @Rule - public EsTester esTester = new EsTester(new ViewIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); ViewIndex index = new ViewIndex(esTester.client()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/view/index/ViewIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/view/index/ViewIndexerTest.java index c45db75114d..9f975ab24f9 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/view/index/ViewIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/view/index/ViewIndexerTest.java @@ -46,7 +46,6 @@ import org.sonar.server.es.RecoveryIndexer; import org.sonar.server.es.SearchOptions; import org.sonar.server.issue.IssueQuery; import org.sonar.server.issue.index.IssueIndex; -import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.permission.index.AuthorizationTypeSupport; @@ -71,7 +70,7 @@ public class ViewIndexerTest { public DbTester dbTester = DbTester.create(system2); @Rule - public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()), new ViewIndexDefinition(new MapSettings().asConfig())); + public EsTester esTester = EsTester.core(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); -- 2.39.5