Browse Source

Speed-up the unit tests relying on Elasticsearch

Creation of an index is slow in Elasticsearch. It should not executed
before each test.
tags/7.5
Simon Brandhof 6 years ago
parent
commit
72be5b2eca
100 changed files with 492 additions and 1612 deletions
  1. 9
    4
      server/sonar-server/src/main/java/org/sonar/server/es/BulkIndexer.java
  2. 8
    4
      server/sonar-server/src/main/java/org/sonar/server/es/IndexCreator.java
  3. 3
    4
      server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndexDefinition.java
  4. 7
    6
      server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndexDefinition.java
  5. 0
    969
      server/sonar-server/src/test/java/org/sonar/elasticsearch/test/EsTestCluster.java
  6. 1
    2
      server/sonar-server/src/test/java/org/sonar/server/authentication/SsoAuthenticatorTest.java
  7. 1
    2
      server/sonar-server/src/test/java/org/sonar/server/authentication/UserIdentityAuthenticatorTest.java
  8. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/branch/pr/ws/ListActionTest.java
  9. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/branch/ws/ListActionTest.java
  10. 1
    2
      server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexSearchTest.java
  11. 1
    2
      server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexTest.java
  12. 1
    2
      server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexerTest.java
  13. 1
    2
      server/sonar-server/src/test/java/org/sonar/server/component/index/NewTest.java
  14. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchActionTest.java
  15. 13
    15
      server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchProjectsActionTest.java
  16. 2
    4
      server/sonar-server/src/test/java/org/sonar/server/component/ws/SuggestionsActionTest.java
  17. 7
    8
      server/sonar-server/src/test/java/org/sonar/server/computation/task/projectanalysis/issue/ScmAccountToUserLoaderTest.java
  18. 12
    12
      server/sonar-server/src/test/java/org/sonar/server/es/BulkIndexerTest.java
  19. 1
    1
      server/sonar-server/src/test/java/org/sonar/server/es/EsClientTest.java
  20. 153
    216
      server/sonar-server/src/test/java/org/sonar/server/es/EsTester.java
  21. 7
    10
      server/sonar-server/src/test/java/org/sonar/server/es/IndexCreatorTest.java
  22. 1
    1
      server/sonar-server/src/test/java/org/sonar/server/es/IndexerStartupTaskTest.java
  23. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/es/OneToManyResilientIndexingListenerTest.java
  24. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/es/OneToOneResilientIndexingListenerTest.java
  25. 1
    1
      server/sonar-server/src/test/java/org/sonar/server/es/RecoveryIndexerTest.java
  26. 1
    1
      server/sonar-server/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java
  27. 30
    0
      server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexDefinitionBridge.java
  28. 1
    1
      server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexTest.java
  29. 5
    5
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyBulkRequestBuilderTest.java
  30. 2
    3
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilderTest.java
  31. 8
    9
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilderTest.java
  32. 8
    9
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteRequestBuilderTest.java
  33. 9
    9
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyFlushRequestBuilderTest.java
  34. 7
    7
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyGetRequestBuilderTest.java
  35. 8
    8
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndexRequestBuilderTest.java
  36. 9
    9
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilderTest.java
  37. 9
    9
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilderTest.java
  38. 9
    9
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilderTest.java
  39. 9
    10
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilderTest.java
  40. 9
    9
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilderTest.java
  41. 9
    9
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyRefreshRequestBuilderTest.java
  42. 10
    10
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchRequestBuilderTest.java
  43. 9
    9
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilderTest.java
  44. 2
    3
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerHealthRequestBuilderTest.java
  45. 2
    3
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStateRequestBuilderTest.java
  46. 2
    3
      server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStatsRequestBuilderTest.java
  47. 1
    1
      server/sonar-server/src/test/java/org/sonar/server/health/EsStatusClusterCheckTest.java
  48. 1
    1
      server/sonar-server/src/test/java/org/sonar/server/health/EsStatusNodeCheckTest.java
  49. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/issue/IssueUpdaterTest.java
  50. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexDebtTest.java
  51. 4
    4
      server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexProjectStatisticsTest.java
  52. 1
    9
      server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexTest.java
  53. 4
    2
      server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexerTest.java
  54. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/issue/ws/AddCommentActionTest.java
  55. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/issue/ws/AssignActionTest.java
  56. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/issue/ws/AuthorsActionTest.java
  57. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/issue/ws/BulkChangeActionTest.java
  58. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/issue/ws/DoTransitionActionTest.java
  59. 1
    4
      server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java
  60. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java
  61. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetSeverityActionTest.java
  62. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTagsActionTest.java
  63. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTypeActionTest.java
  64. 6
    8
      server/sonar-server/src/test/java/org/sonar/server/issue/ws/TagsActionTest.java
  65. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/CreateActionTest.java
  66. 1
    2
      server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/MetricsActionTest.java
  67. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/SearchActionTest.java
  68. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/UpdateActionTest.java
  69. 12
    13
      server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java
  70. 1
    2
      server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTextSearchTest.java
  71. 1
    2
      server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexerTest.java
  72. 1
    2
      server/sonar-server/src/test/java/org/sonar/server/organization/OrganizationCreationImplTest.java
  73. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/organization/ws/AddMemberActionTest.java
  74. 7
    10
      server/sonar-server/src/test/java/org/sonar/server/organization/ws/CreateActionTest.java
  75. 4
    6
      server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java
  76. 2
    4
      server/sonar-server/src/test/java/org/sonar/server/organization/ws/EnableSupportActionTest.java
  77. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/organization/ws/RemoveMemberActionTest.java
  78. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/organization/ws/SearchMembersActionTest.java
  79. 1
    4
      server/sonar-server/src/test/java/org/sonar/server/permission/index/FooIndexer.java
  80. 2
    2
      server/sonar-server/src/test/java/org/sonar/server/permission/index/PermissionIndexerTest.java
  81. 1
    1
      server/sonar-server/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java
  82. 1
    7
      server/sonar-server/src/test/java/org/sonar/server/platform/BackendCleanupTest.java
  83. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsIndexesSectionTest.java
  84. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsStateSectionTest.java
  85. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/EsClusterStateSectionTest.java
  86. 1
    1
      server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/SearchNodesInfoLoaderImplTest.java
  87. 1
    5
      server/sonar-server/src/test/java/org/sonar/server/project/ws/BulkUpdateKeyActionTest.java
  88. 1
    1
      server/sonar-server/src/test/java/org/sonar/server/project/ws/UpdateVisibilityActionTest.java
  89. 1
    4
      server/sonar-server/src/test/java/org/sonar/server/projecttag/ws/SearchActionTest.java
  90. 3
    5
      server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileComparisonTest.java
  91. 6
    7
      server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileRuleImplTest.java
  92. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileTreeImplTest.java
  93. 2
    3
      server/sonar-server/src/test/java/org/sonar/server/qualityprofile/index/ActiveRuleIndexerTest.java
  94. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ChangeParentActionTest.java
  95. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java
  96. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/InheritanceActionTest.java
  97. 1
    3
      server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/QProfilesWsMediumTest.java
  98. 5
    7
      server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ShowActionTest.java
  99. 2
    3
      server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java
  100. 0
    0
      server/sonar-server/src/test/java/org/sonar/server/rule/RuleCreatorTest.java

+ 9
- 4
server/sonar-server/src/main/java/org/sonar/server/es/BulkIndexer.java View File

@@ -56,8 +56,8 @@ import static java.lang.String.format;
/**
* Helper to bulk requests in an efficient way :
* <ul>
* <li>bulk request is sent on the wire when its size is higher than 5Mb</li>
* <li>on large table indexing, replicas and automatic refresh can be temporarily disabled</li>
* <li>bulk request is sent on the wire when its size is higher than 5Mb</li>
* <li>on large table indexing, replicas and automatic refresh can be temporarily disabled</li>
* </ul>
*/
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.
*
* <p>
* 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) {

+ 8
- 4
server/sonar-server/src/main/java/org/sonar/server/es/IndexCreator.java View File

@@ -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<Index> 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<String> existingIndices = loadExistingIndicesExceptMetadata();
List<String> 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<String> loadExistingIndicesExceptMetadata() {
private List<String> loadExistingIndicesExceptMetadata(Collection<Index> definitions) {
Set<String> 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());
}

+ 3
- 4
server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndexDefinition.java View File

@@ -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

+ 7
- 6
server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndexDefinition.java View File

@@ -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

+ 0
- 969
server/sonar-server/src/test/java/org/sonar/elasticsearch/test/EsTestCluster.java View File

@@ -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.
* <p>
* 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.
* </p>
*/
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<String, NodeAndClient> nodes = new TreeMap<>();

private final Set<Path> 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<Class<? extends Plugin>> 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<Client, Client> clientWrapper;

public EsTestCluster(long clusterSeed, Path baseDir,
int numDataNodes, String clusterName, NodeConfigurationSource nodeConfigurationSource,
String nodePrefix, Collection<Class<? extends Plugin>> mockPlugins, Function<Client, Client> 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 <code>min</code> to <code>max</code> (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<Class<? extends Plugin>> getPlugins() {
Set<Class<? extends Plugin>> 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<NodeAndClient> predicate) {
ensureOpen();
Collection<NodeAndClient> 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<Class<? extends Plugin>> 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 <code>null</code>
*/
public synchronized Client client(final Predicate<Settings> 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<Class<? extends Plugin>> 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<Class<? extends Plugin>> plugins;

TransportClientFactory(boolean sniff, Settings settings, Path baseDir, Collection<Class<? extends Plugin>> 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<NodeAndClient> 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<String, Long> docsOnShards = new HashMap<>();
final Collection<NodeAndClient> 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<NodeAndClient> 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<NodeAndClient> 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 &gt;T&lt;
*/
public synchronized <T> T getInstance(Class<T> clazz, final String node) {
return getInstance(clazz, nc -> node == null || node.equals(nc.name));
}

private synchronized <T> T getInstance(Class<T> clazz, Predicate<NodeAndClient> predicate) {
NodeAndClient randomNodeAndClient = getRandomNodeAndClient(predicate);
assert randomNodeAndClient != null;
return getInstanceFromNode(clazz, randomNodeAndClient.node);
}

private synchronized <T> T getInstanceFromNode(Class<T> 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<Client> getClients() {
ensureOpen();
return () -> {
ensureOpen();
final Iterator<NodeAndClient> iterator = nodes.values().iterator();
return new Iterator<Client>() {

@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<ShardId> 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 <T> the result of the async execution
*/
public interface Async<T> {
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<String> 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<String> 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<String> 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<AssertionError> 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;
}
}

}

+ 1
- 2
server/sonar-server/src/test/java/org/sonar/server/authentication/SsoAuthenticatorTest.java View File

@@ -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";

+ 1
- 2
server/sonar-server/src/test/java/org/sonar/server/authentication/UserIdentityAuthenticatorTest.java View File

@@ -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);

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/branch/pr/ws/ListActionTest.java View File

@@ -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();


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/branch/ws/ListActionTest.java View File

@@ -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();


+ 1
- 2
server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexSearchTest.java View File

@@ -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

+ 1
- 2
server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexTest.java View File

@@ -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);

+ 1
- 2
server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexerTest.java View File

@@ -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);


+ 1
- 2
server/sonar-server/src/test/java/org/sonar/server/component/index/NewTest.java View File

@@ -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() {

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchActionTest.java View File

@@ -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);

+ 13
- 15
server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchProjectsActionTest.java View File

@@ -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);


+ 2
- 4
server/sonar-server/src/test/java/org/sonar/server/component/ws/SuggestionsActionTest.java View File

@@ -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<ComponentDto> projects = range(0, numberOfProjects)

+ 7
- 8
server/sonar-server/src/test/java/org/sonar/server/computation/task/projectanalysis/issue/ScmAccountToUserLoaderTest.java View File

@@ -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());

+ 12
- 12
server/sonar-server/src/test/java/org/sonar/server/es/BulkIndexerTest.java View File

@@ -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));
}

+ 1
- 1
server/sonar-server/src/test/java/org/sonar/server/es/EsClientTest.java View File

@@ -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() {

+ 153
- 216
server/sonar-server/src/test/java/org/sonar/server/es/EsTester.java View File

@@ -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<String> NO_TEMPLATES_SURVIVING_WIPE = Collections.emptySet();
private static EsTestCluster cluster;
private final List<IndexDefinition> indexDefinitions;
private static final Node SHARED_NODE = createNode();
private static final AtomicBoolean CORE_INDICES_CREATED = new AtomicBoolean(false);
private static final Set<String> 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<Class<? extends Plugin>> nodePlugins() {
return Collections.emptyList();
}

@Override
public Settings transportClientSettings() {
return Settings.builder().put(networkSettings.build()).build();
}

@Override
public Collection<Class<? extends Plugin>> 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<IndexDefinitions.Index> 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<String, Object> 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<String, Object> 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<String,Object>... docs) {
public void putDocuments(IndexType indexType, Map<String, Object>... docs) {
try {
BulkRequestBuilder bulk = cluster.client().prepareBulk()
BulkRequestBuilder bulk = SHARED_NODE.client().prepareBulk()
.setRefreshPolicy(REFRESH_IMMEDIATE);
for (Map<String,Object> doc : docs) {
for (Map<String, Object> 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<SearchHit> 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<SearchHit> 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 <T> List<T> getDocumentFieldValues(IndexType indexType, final String fieldNameToReturn) {
return newArrayList(Iterables.transform(getDocuments(indexType), new Function<SearchHit, T>() {
@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<String> 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<String, Object> settings) {
UpdateSettingsResponse response = client().nativeClient().admin().indices()
private void setIndexSettings(String index, Map<String, Object> 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<IndexDefinitions.Index> createIndices(IndexDefinition... definitions) {
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
Stream.of(definitions).forEach(d -> d.define(context));

List<IndexDefinitions.Index> 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<String, IndexDefinitions.IndexType> 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);
}
}
}

+ 7
- 10
server/sonar-server/src/test/java/org/sonar/server/es/IndexCreatorTest.java View File

@@ -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());


+ 1
- 1
server/sonar-server/src/test/java/org/sonar/server/es/IndexerStartupTaskTest.java View File

@@ -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);

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/es/OneToManyResilientIndexingListenerTest.java View File

@@ -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

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/es/OneToOneResilientIndexingListenerTest.java View File

@@ -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

+ 1
- 1
server/sonar-server/src/test/java/org/sonar/server/es/RecoveryIndexerTest.java View File

@@ -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

+ 1
- 1
server/sonar-server/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java View File

@@ -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());

+ 30
- 0
server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexDefinitionBridge.java View File

@@ -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);
}
}

+ 1
- 1
server/sonar-server/src/test/java/org/sonar/server/es/metadata/MetadataIndexTest.java View File

@@ -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);


+ 5
- 5
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyBulkRequestBuilderTest.java View File

@@ -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();
}

}

+ 2
- 3
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyClearCacheRequestBuilderTest.java View File

@@ -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();

+ 8
- 9
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyCreateIndexRequestBuilderTest.java View File

@@ -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");

+ 8
- 9
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyDeleteRequestBuilderTest.java View File

@@ -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");

+ 9
- 9
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyFlushRequestBuilderTest.java View File

@@ -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");

+ 7
- 7
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyGetRequestBuilderTest.java View File

@@ -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");

+ 8
- 8
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndexRequestBuilderTest.java View File

@@ -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");

+ 9
- 9
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesExistsRequestBuilderTest.java View File

@@ -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");

+ 9
- 9
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyIndicesStatsRequestBuilderTest.java View File

@@ -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");

+ 9
- 9
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyMultiGetRequestBuilderTest.java View File

@@ -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");

+ 9
- 10
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyNodesStatsRequestBuilderTest.java View File

@@ -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();
}

}

+ 9
- 9
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyPutMappingRequestBuilderTest.java View File

@@ -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");

+ 9
- 9
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyRefreshRequestBuilderTest.java View File

@@ -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");

+ 10
- 10
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchRequestBuilderTest.java View File

@@ -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");

+ 9
- 9
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxySearchScrollRequestBuilderTest.java View File

@@ -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");

+ 2
- 3
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerHealthRequestBuilderTest.java View File

@@ -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();

+ 2
- 3
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStateRequestBuilderTest.java View File

@@ -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();

+ 2
- 3
server/sonar-server/src/test/java/org/sonar/server/es/request/ProxyWebServerStatsRequestBuilderTest.java View File

@@ -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();

+ 1
- 1
server/sonar-server/src/test/java/org/sonar/server/health/EsStatusClusterCheckTest.java View File

@@ -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());

+ 1
- 1
server/sonar-server/src/test/java/org/sonar/server/health/EsStatusNodeCheckTest.java View File

@@ -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());


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/issue/IssueUpdaterTest.java View File

@@ -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);

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexDebtTest.java View File

@@ -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

+ 4
- 4
server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexProjectStatisticsTest.java View File

@@ -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() {

+ 1
- 9
server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexTest.java View File

@@ -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

+ 4
- 2
server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueIndexerTest.java View File

@@ -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);
}
}


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/issue/ws/AddCommentActionTest.java View File

@@ -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();

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/issue/ws/AssignActionTest.java View File

@@ -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);


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/issue/ws/AuthorsActionTest.java View File

@@ -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();


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/issue/ws/BulkChangeActionTest.java View File

@@ -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();


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/issue/ws/DoTransitionActionTest.java View File

@@ -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();

+ 1
- 4
server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java View File

@@ -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));

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java View File

@@ -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();


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetSeverityActionTest.java View File

@@ -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();


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTagsActionTest.java View File

@@ -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();


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/issue/ws/SetTypeActionTest.java View File

@@ -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();


+ 6
- 8
server/sonar-server/src/test/java/org/sonar/server/issue/ws/TagsActionTest.java View File

@@ -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;

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/CreateActionTest.java View File

@@ -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;

+ 1
- 2
server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/MetricsActionTest.java View File

@@ -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

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/SearchActionTest.java View File

@@ -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();

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/measure/custom/ws/UpdateActionTest.java View File

@@ -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();

+ 12
- 13
server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java View File

@@ -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

+ 1
- 2
server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTextSearchTest.java View File

@@ -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();

+ 1
- 2
server/sonar-server/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexerTest.java View File

@@ -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);


+ 1
- 2
server/sonar-server/src/test/java/org/sonar/server/organization/OrganizationCreationImplTest.java View File

@@ -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

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/organization/ws/AddMemberActionTest.java View File

@@ -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();

+ 7
- 10
server/sonar-server/src/test/java/org/sonar/server/organization/ws/CreateActionTest.java View File

@@ -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);

+ 4
- 6
server/sonar-server/src/test/java/org/sonar/server/organization/ws/DeleteActionTest.java View File

@@ -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}

+ 2
- 4
server/sonar-server/src/test/java/org/sonar/server/organization/ws/EnableSupportActionTest.java View File

@@ -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);

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/organization/ws/RemoveMemberActionTest.java View File

@@ -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();

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/organization/ws/SearchMembersActionTest.java View File

@@ -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();

+ 1
- 4
server/sonar-server/src/test/java/org/sonar/server/permission/index/FooIndexer.java View File

@@ -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;
}


+ 2
- 2
server/sonar-server/src/test/java/org/sonar/server/permission/index/PermissionIndexerTest.java View File

@@ -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

+ 1
- 1
server/sonar-server/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java View File

@@ -53,7 +53,7 @@ public abstract class BasePermissionWsTest<A extends PermissionsWsAction> {
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();

+ 1
- 7
server/sonar-server/src/test/java/org/sonar/server/platform/BackendCleanupTest.java View File

@@ -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);

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsIndexesSectionTest.java View File

@@ -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());


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/EsStateSectionTest.java View File

@@ -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());


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/EsClusterStateSectionTest.java View File

@@ -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());


+ 1
- 1
server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/SearchNodesInfoLoaderImplTest.java View File

@@ -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());


+ 1
- 5
server/sonar-server/src/test/java/org/sonar/server/project/ws/BulkUpdateKeyActionTest.java View File

@@ -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);


+ 1
- 1
server/sonar-server/src/test/java/org/sonar/server/project/ws/UpdateVisibilityActionTest.java View File

@@ -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();

+ 1
- 4
server/sonar-server/src/test/java/org/sonar/server/projecttag/ws/SearchActionTest.java View File

@@ -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();

+ 3
- 5
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileComparisonTest.java View File

@@ -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);

+ 6
- 7
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileRuleImplTest.java View File

@@ -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();

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileTreeImplTest.java View File

@@ -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());

+ 2
- 3
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/index/ActiveRuleIndexerTest.java View File

@@ -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

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ChangeParentActionTest.java View File

@@ -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

+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java View File

@@ -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();


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/InheritanceActionTest.java View File

@@ -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();


+ 1
- 3
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/QProfilesWsMediumTest.java View File

@@ -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();


+ 5
- 7
server/sonar-server/src/test/java/org/sonar/server/qualityprofile/ws/ShowActionTest.java View File

@@ -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)

+ 2
- 3
server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java View File

@@ -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"},

+ 0
- 0
server/sonar-server/src/test/java/org/sonar/server/rule/RuleCreatorTest.java View File


Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save