diff --git a/src/test/java/org/elasticsearch/VersionTests.java b/src/test/java/org/elasticsearch/VersionTests.java index 4b5986f3937..c63d06fff89 100644 --- a/src/test/java/org/elasticsearch/VersionTests.java +++ b/src/test/java/org/elasticsearch/VersionTests.java @@ -23,6 +23,7 @@ import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.test.ElasticsearchTestCase; +import org.elasticsearch.test.VersionTestUtil; import org.hamcrest.Matchers; import org.junit.Test; @@ -33,6 +34,7 @@ import java.util.Map; import static org.elasticsearch.Version.V_0_20_0; import static org.elasticsearch.Version.V_0_90_0; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.sameInstance; @@ -71,7 +73,7 @@ public class VersionTests extends ElasticsearchTestCase { assertThat(Version.CURRENT.luceneVersion, equalTo(org.apache.lucene.util.Version.LATEST)); final int iters = scaledRandomIntBetween(20, 100); for (int i = 0; i < iters; i++) { - Version version = randomVersion(); + Version version = randomVersion(random()); assertThat(version, sameInstance(Version.fromId(version.id))); assertThat(version.luceneVersion, sameInstance(Version.fromId(version.id).luceneVersion)); } @@ -80,7 +82,7 @@ public class VersionTests extends ElasticsearchTestCase { public void testCURRENTIsLatest() { final int iters = scaledRandomIntBetween(100, 1000); for (int i = 0; i < iters; i++) { - Version version = randomVersion(); + Version version = randomVersion(random()); if (version != Version.CURRENT) { assertThat("Version: " + version + " should be before: " + Version.CURRENT + " but wasn't", version.before(Version.CURRENT), is(true)); } @@ -90,7 +92,7 @@ public class VersionTests extends ElasticsearchTestCase { public void testVersionFromString() { final int iters = scaledRandomIntBetween(100, 1000); for (int i = 0; i < iters; i++) { - Version version = randomVersion(); + Version version = randomVersion(random()); if (version.snapshot()) { // number doesn't include SNAPSHOT but the parser checks for that assertEquals(Version.fromString(version.number()), version); } else { @@ -137,7 +139,7 @@ public class VersionTests extends ElasticsearchTestCase { public void testParseVersion() { final int iters = scaledRandomIntBetween(100, 1000); for (int i = 0; i < iters; i++) { - Version version = randomVersion(); + Version version = randomVersion(random()); String stringVersion = version.toString(); if (version.snapshot() == false && random().nextBoolean()) { version = new Version(version.id, true, version.luceneVersion); @@ -150,7 +152,7 @@ public class VersionTests extends ElasticsearchTestCase { public void testParseLenient() { // note this is just a silly sanity check, we test it in lucene - for (Version version : allVersions()) { + for (Version version : VersionTestUtil.allVersions()) { org.apache.lucene.util.Version luceneVersion = version.luceneVersion; String string = luceneVersion.toString().toUpperCase(Locale.ROOT) .replaceFirst("^LUCENE_(\\d+)_(\\d+)$", "$1.$2"); diff --git a/src/test/java/org/elasticsearch/action/OriginalIndicesTests.java b/src/test/java/org/elasticsearch/action/OriginalIndicesTests.java index 0253a0a691c..1637aea25b1 100644 --- a/src/test/java/org/elasticsearch/action/OriginalIndicesTests.java +++ b/src/test/java/org/elasticsearch/action/OriginalIndicesTests.java @@ -27,6 +27,7 @@ import org.junit.Test; import java.io.IOException; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.CoreMatchers.equalTo; public class OriginalIndicesTests extends ElasticsearchTestCase { @@ -42,7 +43,7 @@ public class OriginalIndicesTests extends ElasticsearchTestCase { OriginalIndices originalIndices = randomOriginalIndices(); BytesStreamOutput out = new BytesStreamOutput(); - out.setVersion(randomVersion()); + out.setVersion(randomVersion(random())); OriginalIndices.writeOriginalIndices(originalIndices, out); BytesStreamInput in = new BytesStreamInput(out.bytes()); diff --git a/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTest.java b/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTest.java index d0d1e2e2452..c4633db43b4 100644 --- a/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTest.java +++ b/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTest.java @@ -24,6 +24,7 @@ import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.test.ElasticsearchTestCase; +import org.elasticsearch.test.VersionTestUtil; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; @@ -42,7 +43,7 @@ public class ClusterStateRequestTest extends ElasticsearchTestCase { ClusterStateRequest clusterStateRequest = new ClusterStateRequest().routingTable(randomBoolean()).metaData(randomBoolean()) .nodes(randomBoolean()).blocks(randomBoolean()).indices("testindex", "testindex2").indicesOptions(indicesOptions); - Version testVersion = randomVersionBetween(Version.CURRENT.minimumCompatibilityVersion(), Version.CURRENT); + Version testVersion = VersionTestUtil.randomVersionBetween(random(), Version.CURRENT.minimumCompatibilityVersion(), Version.CURRENT); BytesStreamOutput output = new BytesStreamOutput(); output.setVersion(testVersion); clusterStateRequest.writeTo(output); diff --git a/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java b/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java index aafa5e076ca..aca40ee21be 100644 --- a/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java +++ b/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.action.get; -import org.elasticsearch.Version; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.index.VersionType; @@ -29,6 +28,7 @@ import org.junit.Test; import java.io.IOException; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.CoreMatchers.equalTo; public class MultiGetShardRequestTests extends ElasticsearchTestCase { @@ -70,7 +70,7 @@ public class MultiGetShardRequestTests extends ElasticsearchTestCase { } BytesStreamOutput out = new BytesStreamOutput(); - out.setVersion(randomVersion()); + out.setVersion(randomVersion(random())); multiGetShardRequest.writeTo(out); BytesStreamInput in = new BytesStreamInput(out.bytes()); diff --git a/src/test/java/org/elasticsearch/action/indexedscripts/get/GetIndexedScriptRequestTests.java b/src/test/java/org/elasticsearch/action/indexedscripts/get/GetIndexedScriptRequestTests.java index 153d14298a0..3a578cec4b6 100644 --- a/src/test/java/org/elasticsearch/action/indexedscripts/get/GetIndexedScriptRequestTests.java +++ b/src/test/java/org/elasticsearch/action/indexedscripts/get/GetIndexedScriptRequestTests.java @@ -27,6 +27,7 @@ import org.junit.Test; import java.io.IOException; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.CoreMatchers.equalTo; public class GetIndexedScriptRequestTests extends ElasticsearchTestCase { @@ -40,7 +41,7 @@ public class GetIndexedScriptRequestTests extends ElasticsearchTestCase { } BytesStreamOutput out = new BytesStreamOutput(); - out.setVersion(randomVersion()); + out.setVersion(randomVersion(random())); request.writeTo(out); BytesStreamInput in = new BytesStreamInput(out.bytes()); diff --git a/src/test/java/org/elasticsearch/action/mlt/MoreLikeThisRequestTests.java b/src/test/java/org/elasticsearch/action/mlt/MoreLikeThisRequestTests.java index 99a01de5047..4793c2dc64e 100644 --- a/src/test/java/org/elasticsearch/action/mlt/MoreLikeThisRequestTests.java +++ b/src/test/java/org/elasticsearch/action/mlt/MoreLikeThisRequestTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.action.mlt; -import org.elasticsearch.Version; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.BytesStreamInput; @@ -33,6 +32,7 @@ import org.junit.Test; import java.io.IOException; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.CoreMatchers.*; public class MoreLikeThisRequestTests extends ElasticsearchTestCase { @@ -99,7 +99,7 @@ public class MoreLikeThisRequestTests extends ElasticsearchTestCase { } BytesStreamOutput out = new BytesStreamOutput(); - out.setVersion(randomVersion()); + out.setVersion(randomVersion(random())); mltRequest.writeTo(out); BytesStreamInput in = new BytesStreamInput(out.bytes()); diff --git a/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java b/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java index 96d56848fe5..c732d2bb726 100644 --- a/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java +++ b/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java @@ -25,6 +25,7 @@ import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.test.ElasticsearchTestCase; import org.junit.Test; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.CoreMatchers.equalTo; public class IndicesOptionsTests extends ElasticsearchTestCase { @@ -36,12 +37,12 @@ public class IndicesOptionsTests extends ElasticsearchTestCase { IndicesOptions indicesOptions = IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean()); BytesStreamOutput output = new BytesStreamOutput(); - Version outputVersion = randomVersion(); + Version outputVersion = randomVersion(random()); output.setVersion(outputVersion); indicesOptions.writeIndicesOptions(output); BytesStreamInput bytesStreamInput = new BytesStreamInput(output.bytes()); - bytesStreamInput.setVersion(randomVersion()); + bytesStreamInput.setVersion(randomVersion(random())); IndicesOptions indicesOptions2 = IndicesOptions.readIndicesOptions(bytesStreamInput); assertThat(indicesOptions2.ignoreUnavailable(), equalTo(indicesOptions.ignoreUnavailable())); diff --git a/src/test/java/org/elasticsearch/bwcompat/OldIndexBackwardsCompatibilityTests.java b/src/test/java/org/elasticsearch/bwcompat/OldIndexBackwardsCompatibilityTests.java index 5993aa0a27b..7e4a4f6d180 100644 --- a/src/test/java/org/elasticsearch/bwcompat/OldIndexBackwardsCompatibilityTests.java +++ b/src/test/java/org/elasticsearch/bwcompat/OldIndexBackwardsCompatibilityTests.java @@ -48,6 +48,7 @@ import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.test.ElasticsearchIntegrationTest; +import org.elasticsearch.test.VersionTestUtil; import org.elasticsearch.test.hamcrest.ElasticsearchAssertions; import org.elasticsearch.test.index.merge.NoMergePolicyProvider; import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; @@ -226,21 +227,11 @@ public class OldIndexBackwardsCompatibilityTests extends ElasticsearchIntegratio public void testAllVersionsTested() throws Exception { SortedSet expectedVersions = new TreeSet<>(); - for (java.lang.reflect.Field field : Version.class.getDeclaredFields()) { - if (Modifier.isStatic(field.getModifiers()) && field.getType() == Version.class) { - Version v = (Version) field.get(Version.class); - if (v.snapshot()) { - continue; // snapshots are unreleased, so there is no backcompat yet - } - if (v.onOrBefore(Version.V_0_20_6)) { - continue; // we can only test back one major lucene version - } - if (v.equals(Version.CURRENT)) { - continue; // the current version is always compatible with itself - } - - expectedVersions.add("index-" + v.toString() + ".zip"); - } + for (Version v : VersionTestUtil.allVersions()) { + if (v.snapshot()) continue; // snapshots are unreleased, so there is no backcompat yet + if (v.onOrBefore(Version.V_0_20_6)) continue; // we can only test back one major lucene version + if (v.equals(Version.CURRENT)) continue; // the current version is always compatible with itself + expectedVersions.add("index-" + v.toString() + ".zip"); } for (String index : indexes) { diff --git a/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeTests.java b/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeTests.java index ace51a3587e..0e64056b517 100644 --- a/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeTests.java +++ b/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeTests.java @@ -33,6 +33,8 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; + public class DiscoveryNodeTests extends ElasticsearchTestCase { @@ -49,7 +51,7 @@ public class DiscoveryNodeTests extends ElasticsearchTestCase { for (int a = randomInt(10); a > 0; a--) { attributes.put(randomUnicodeOfLengthBetween(3, 20), randomUnicodeOfLengthBetween(3, 20)); } - final Version version = randomVersion(); + final Version version = randomVersion(random()); DiscoveryNode discoveryNode = new DiscoveryNode(nodeName, id, hostName, hostAddress, transportAddress, attributes, version); BytesStreamOutput bytesOutput = new BytesStreamOutput(); ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(bytesOutput); diff --git a/src/test/java/org/elasticsearch/cluster/routing/RoutingBackwardCompatibilityTests.java b/src/test/java/org/elasticsearch/cluster/routing/RoutingBackwardCompatibilityTests.java index 247ef928d19..a7d91fc8a3f 100644 --- a/src/test/java/org/elasticsearch/cluster/routing/RoutingBackwardCompatibilityTests.java +++ b/src/test/java/org/elasticsearch/cluster/routing/RoutingBackwardCompatibilityTests.java @@ -29,6 +29,7 @@ import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.node.Node; import org.elasticsearch.test.ElasticsearchTestCase; +import org.elasticsearch.test.VersionTestUtil; import java.io.BufferedReader; import java.io.InputStreamReader; @@ -57,7 +58,7 @@ public class RoutingBackwardCompatibilityTests extends ElasticsearchTestCase { final int currentExpectedShard = Integer.parseInt(parts[6]); OperationRouting operationRouting = node.injector().getInstance(OperationRouting.class); - for (Version version : allVersions()) { + for (Version version : VersionTestUtil.allVersions()) { final Settings settings = settings(version).build(); IndexMetaData indexMetaData = IndexMetaData.builder(index).settings(settings).numberOfShards(numberOfShards).numberOfReplicas(randomInt(3)).build(); MetaData.Builder metaData = MetaData.builder().put(indexMetaData, false); diff --git a/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java b/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java index c78bd1a3075..64d49a16f22 100644 --- a/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java +++ b/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java @@ -33,6 +33,7 @@ import org.elasticsearch.cluster.routing.allocation.decider.ClusterRebalanceAllo import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.test.ElasticsearchAllocationTestCase; +import org.elasticsearch.test.VersionTestUtil; import org.junit.Test; import java.util.ArrayList; @@ -41,6 +42,7 @@ import java.util.List; import static org.elasticsearch.cluster.routing.ShardRoutingState.*; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.Matchers.*; /** @@ -122,7 +124,7 @@ public class NodeVersionAllocationDeciderTests extends ElasticsearchAllocationTe } clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()) - .put(newNode("node3", getPreviousVersion()))) + .put(newNode("node3", VersionTestUtil.getPreviousVersion()))) .build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); @@ -202,9 +204,9 @@ public class NodeVersionAllocationDeciderTests extends ElasticsearchAllocationTe } else { for (int j = nodes.size(); j < numNodes; j++) { if (frequently()) { - nodes.add(newNode("node" + (nodeIdx++), randomBoolean() ? getPreviousVersion() : Version.CURRENT)); + nodes.add(newNode("node" + (nodeIdx++), randomBoolean() ? VersionTestUtil.getPreviousVersion() : Version.CURRENT)); } else { - nodes.add(newNode("node" + (nodeIdx++), randomVersion())); + nodes.add(newNode("node" + (nodeIdx++), randomVersion(random()))); } } } @@ -247,20 +249,20 @@ public class NodeVersionAllocationDeciderTests extends ElasticsearchAllocationTe assertThat(routingTable.index("test").shard(i).shards().get(2).currentNodeId(), nullValue()); } clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() - .put(newNode("old0", getPreviousVersion())) - .put(newNode("old1", getPreviousVersion())) - .put(newNode("old2", getPreviousVersion()))).build(); + .put(newNode("old0", VersionTestUtil.getPreviousVersion())) + .put(newNode("old1", VersionTestUtil.getPreviousVersion())) + .put(newNode("old2", VersionTestUtil.getPreviousVersion()))).build(); clusterState = stabilize(clusterState, service); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() - .put(newNode("old0", getPreviousVersion())) - .put(newNode("old1", getPreviousVersion())) + .put(newNode("old0", VersionTestUtil.getPreviousVersion())) + .put(newNode("old1", VersionTestUtil.getPreviousVersion())) .put(newNode("new0"))).build(); clusterState = stabilize(clusterState, service); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() - .put(newNode("node0", getPreviousVersion())) + .put(newNode("node0", VersionTestUtil.getPreviousVersion())) .put(newNode("new1")) .put(newNode("new0"))).build(); diff --git a/src/test/java/org/elasticsearch/codecs/CodecTests.java b/src/test/java/org/elasticsearch/codecs/CodecTests.java index 79c72b851b2..ccfb9bd593f 100644 --- a/src/test/java/org/elasticsearch/codecs/CodecTests.java +++ b/src/test/java/org/elasticsearch/codecs/CodecTests.java @@ -29,6 +29,7 @@ import org.elasticsearch.index.IndexService; import org.elasticsearch.index.mapper.DocumentMapperParser; import org.elasticsearch.index.mapper.MapperParsingException; import org.elasticsearch.test.ElasticsearchSingleNodeTest; +import org.elasticsearch.test.VersionTestUtil; import org.junit.Assert; import java.io.IOException; @@ -45,7 +46,7 @@ public class CodecTests extends ElasticsearchSingleNodeTest { .startObject("properties").startObject("field").field("type", "string").field("postings_format", Codec.getDefault().postingsFormat().getName()).endObject().endObject() .endObject().endObject().string(); int i = 0; - for (Version v : allVersions()) { + for (Version v : VersionTestUtil.allVersions()) { IndexService indexService = createIndex("test-" + i++, ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, v).build()); DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); try { @@ -68,7 +69,7 @@ public class CodecTests extends ElasticsearchSingleNodeTest { .startObject("properties").startObject("field").field("type", "string").field("doc_values_format", Codec.getDefault().docValuesFormat().getName()).endObject().endObject() .endObject().endObject().string(); int i = 0; - for (Version v : allVersions()) { + for (Version v : VersionTestUtil.allVersions()) { IndexService indexService = createIndex("test-" + i++, ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, v).build()); DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); try { diff --git a/src/test/java/org/elasticsearch/index/analysis/PreBuiltAnalyzerTests.java b/src/test/java/org/elasticsearch/index/analysis/PreBuiltAnalyzerTests.java index 241ac52d4cc..831f17658c3 100644 --- a/src/test/java/org/elasticsearch/index/analysis/PreBuiltAnalyzerTests.java +++ b/src/test/java/org/elasticsearch/index/analysis/PreBuiltAnalyzerTests.java @@ -37,6 +37,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.Matchers.*; /** @@ -86,7 +87,7 @@ public class PreBuiltAnalyzerTests extends ElasticsearchSingleNodeTest { assertThat(list, contains("dude")); } ts.close(); - version = randomVersion(); + version = randomVersion(random()); } } @@ -121,7 +122,7 @@ public class PreBuiltAnalyzerTests extends ElasticsearchSingleNodeTest { assertThat(list, contains("dude")); } ts.close(); - version = randomVersion(); + version = randomVersion(random()); } } @@ -152,7 +153,7 @@ public class PreBuiltAnalyzerTests extends ElasticsearchSingleNodeTest { PreBuiltAnalyzers randomPreBuiltAnalyzer = PreBuiltAnalyzers.values()[randomInt]; String analyzerName = randomPreBuiltAnalyzer.name().toLowerCase(Locale.ROOT); - Version randomVersion = randomVersion(); + Version randomVersion = randomVersion(random()); Settings indexSettings = ImmutableSettings.settingsBuilder().put(IndexMetaData.SETTING_VERSION_CREATED, randomVersion).build(); NamedAnalyzer namedAnalyzer = new PreBuiltAnalyzerProvider(analyzerName, AnalyzerScope.INDEX, randomPreBuiltAnalyzer.getAnalyzer(randomVersion)).get(); diff --git a/src/test/java/org/elasticsearch/index/analysis/StemmerTokenFilterFactoryTests.java b/src/test/java/org/elasticsearch/index/analysis/StemmerTokenFilterFactoryTests.java index 15f18f016ec..14e40804c15 100644 --- a/src/test/java/org/elasticsearch/index/analysis/StemmerTokenFilterFactoryTests.java +++ b/src/test/java/org/elasticsearch/index/analysis/StemmerTokenFilterFactoryTests.java @@ -26,8 +26,8 @@ import org.apache.lucene.analysis.snowball.SnowballFilter; import org.elasticsearch.Version; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.test.ElasticsearchTestCase; import org.elasticsearch.test.ElasticsearchTokenStreamTestCase; +import org.elasticsearch.test.VersionTestUtil; import org.junit.Test; import java.io.IOException; @@ -47,7 +47,7 @@ public class StemmerTokenFilterFactoryTests extends ElasticsearchTokenStreamTest int iters = scaledRandomIntBetween(20, 100); for (int i = 0; i < iters; i++) { - Version v = ElasticsearchTestCase.randomVersion(random()); + Version v = VersionTestUtil.randomVersion(random()); Settings settings = ImmutableSettings.settingsBuilder() .put("index.analysis.filter.my_english.type", "stemmer") .put("index.analysis.filter.my_english.language", "english") @@ -80,7 +80,7 @@ public class StemmerTokenFilterFactoryTests extends ElasticsearchTokenStreamTest int iters = scaledRandomIntBetween(20, 100); for (int i = 0; i < iters; i++) { - Version v = ElasticsearchTestCase.randomVersion(random()); + Version v = VersionTestUtil.randomVersion(random()); Settings settings = ImmutableSettings.settingsBuilder() .put("index.analysis.filter.my_porter2.type", "stemmer") .put("index.analysis.filter.my_porter2.language", "porter2") diff --git a/src/test/java/org/elasticsearch/index/mapper/timestamp/TimestampMappingTests.java b/src/test/java/org/elasticsearch/index/mapper/timestamp/TimestampMappingTests.java index 8aa725607c7..e235e9e25b4 100644 --- a/src/test/java/org/elasticsearch/index/mapper/timestamp/TimestampMappingTests.java +++ b/src/test/java/org/elasticsearch/index/mapper/timestamp/TimestampMappingTests.java @@ -31,7 +31,6 @@ import org.elasticsearch.common.compress.CompressedString; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.joda.Joda; -import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.ToXContent; @@ -41,7 +40,6 @@ import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.index.mapper.*; import org.elasticsearch.index.mapper.internal.TimestampFieldMapper; import org.elasticsearch.test.ElasticsearchSingleNodeTest; -import org.elasticsearch.test.ElasticsearchTestCase; import org.junit.Test; import java.io.IOException; @@ -51,6 +49,9 @@ import java.util.Arrays; import java.util.List; import java.util.Map; +import static org.elasticsearch.Version.V_1_5_0; +import static org.elasticsearch.Version.V_2_0_0; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.hamcrest.Matchers.*; @@ -92,7 +93,7 @@ public class TimestampMappingTests extends ElasticsearchSingleNodeTest { @Test public void testDefaultValues() throws Exception { - for (Version version : Arrays.asList(Version.V_1_5_0, Version.V_2_0_0, ElasticsearchTestCase.randomVersion())) { + for (Version version : Arrays.asList(V_1_5_0, V_2_0_0, randomVersion(random()))) { for (String mapping : Arrays.asList( XContentFactory.jsonBuilder().startObject().startObject("type").endObject().string(), XContentFactory.jsonBuilder().startObject().startObject("type").startObject("_timestamp").endObject().endObject().string())) { diff --git a/src/test/java/org/elasticsearch/indices/analysis/PreBuiltAnalyzerIntegrationTests.java b/src/test/java/org/elasticsearch/indices/analysis/PreBuiltAnalyzerIntegrationTests.java index 4a346f4bb82..d0df326cc52 100644 --- a/src/test/java/org/elasticsearch/indices/analysis/PreBuiltAnalyzerIntegrationTests.java +++ b/src/test/java/org/elasticsearch/indices/analysis/PreBuiltAnalyzerIntegrationTests.java @@ -36,6 +36,7 @@ import java.util.Locale; import java.util.Map; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -64,7 +65,7 @@ public class PreBuiltAnalyzerIntegrationTests extends ElasticsearchIntegrationTe PreBuiltAnalyzers preBuiltAnalyzer = PreBuiltAnalyzers.values()[randomInt]; String name = preBuiltAnalyzer.name().toLowerCase(Locale.ROOT); - Version randomVersion = randomVersion(); + Version randomVersion = randomVersion(random()); if (!loadedAnalyzers.containsKey(preBuiltAnalyzer)) { loadedAnalyzers.put(preBuiltAnalyzer, Lists.newArrayList()); } @@ -138,7 +139,7 @@ public class PreBuiltAnalyzerIntegrationTests extends ElasticsearchIntegrationTe .endObject() .endObject(); - Settings versionSettings = settings(randomVersion()) + Settings versionSettings = settings(randomVersion(random())) .put("index.analysis.analyzer.my_dummy.type", "custom") .put("index.analysis.analyzer.my_dummy.filter", "my_dummy_token_filter") .put("index.analysis.analyzer.my_dummy.char_filter", "my_dummy_char_filter") diff --git a/src/test/java/org/elasticsearch/indices/recovery/RecoveryStateTest.java b/src/test/java/org/elasticsearch/indices/recovery/RecoveryStateTest.java index bd8b51b276d..240cdec329f 100644 --- a/src/test/java/org/elasticsearch/indices/recovery/RecoveryStateTest.java +++ b/src/test/java/org/elasticsearch/indices/recovery/RecoveryStateTest.java @@ -39,6 +39,7 @@ import java.util.Collections; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.Matchers.*; public class RecoveryStateTest extends ElasticsearchTestCase { @@ -52,7 +53,7 @@ public class RecoveryStateTest extends ElasticsearchTestCase { final Version streamVersion; Streamer(AtomicBoolean shouldStop, T source) { - this(shouldStop, source, randomVersion()); + this(shouldStop, source, randomVersion(random())); } Streamer(AtomicBoolean shouldStop, T source, Version streamVersion) { diff --git a/src/test/java/org/elasticsearch/indices/recovery/StartRecoveryRequestTest.java b/src/test/java/org/elasticsearch/indices/recovery/StartRecoveryRequestTest.java index 9b5ec3d863f..cb011cee6ee 100644 --- a/src/test/java/org/elasticsearch/indices/recovery/StartRecoveryRequestTest.java +++ b/src/test/java/org/elasticsearch/indices/recovery/StartRecoveryRequestTest.java @@ -33,6 +33,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Collections; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; @@ -42,7 +43,7 @@ public class StartRecoveryRequestTest extends ElasticsearchTestCase { @Test public void testSerialization() throws Exception { - Version targetNodeVersion = randomVersion(); + Version targetNodeVersion = randomVersion(random()); StartRecoveryRequest outRequest = new StartRecoveryRequest( new ShardId("test", 0), new DiscoveryNode("a", new LocalTransportAddress("1"), targetNodeVersion), diff --git a/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java b/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java index 0949033df1a..11f9e3c0502 100644 --- a/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java +++ b/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java @@ -39,6 +39,8 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Set; +import static org.elasticsearch.Version.CURRENT; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.Matchers.is; /** @@ -149,7 +151,7 @@ public class IndicesStoreTests extends ElasticsearchTestCase { int numReplicas = randomInt(2); // Most of the times don't test bwc and use current version - final Version nodeVersion = randomBoolean() ? Version.CURRENT : randomVersion(); + final Version nodeVersion = randomBoolean() ? CURRENT : randomVersion(random()); ClusterState.Builder clusterState = ClusterState.builder(new ClusterName("test")); clusterState.metaData(MetaData.builder().put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(numShards).numberOfReplicas(numReplicas))); clusterState.nodes(DiscoveryNodes.builder().localNodeId(localNode.id()).put(localNode).put(new DiscoveryNode("xyz", new LocalTransportAddress("xyz"), nodeVersion))); @@ -172,7 +174,7 @@ public class IndicesStoreTests extends ElasticsearchTestCase { ClusterState.Builder clusterState = ClusterState.builder(new ClusterName("test")); clusterState.metaData(MetaData.builder().put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(numShards).numberOfReplicas(numReplicas))); - final Version nodeVersion = randomBoolean() ? Version.CURRENT : randomVersion(); + final Version nodeVersion = randomBoolean() ? CURRENT : randomVersion(random()); clusterState.nodes(DiscoveryNodes.builder().localNodeId(localNode.id()) .put(localNode) diff --git a/src/test/java/org/elasticsearch/mlt/MoreLikeThisActionTests.java b/src/test/java/org/elasticsearch/mlt/MoreLikeThisActionTests.java index 63c4cc238e4..97b41cfcd5f 100644 --- a/src/test/java/org/elasticsearch/mlt/MoreLikeThisActionTests.java +++ b/src/test/java/org/elasticsearch/mlt/MoreLikeThisActionTests.java @@ -581,7 +581,7 @@ public class MoreLikeThisActionTests extends ElasticsearchIntegrationTest { logger.info("Indexing a single document ..."); XContentBuilder doc = jsonBuilder().startObject(); for (int i = 0; i < numFields; i++) { - doc.field("field"+i, generateRandomStringArray(5, 10)); + doc.field("field"+i, generateRandomStringArray(5, 10, false)); } doc.endObject(); indexRandom(true, client().prepareIndex("test", "type1", "0").setSource(doc)); diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/significant/SignificanceHeuristicTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/significant/SignificanceHeuristicTests.java index e84a785f5ad..e19259628cd 100644 --- a/src/test/java/org/elasticsearch/search/aggregations/bucket/significant/SignificanceHeuristicTests.java +++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/significant/SignificanceHeuristicTests.java @@ -32,7 +32,6 @@ import org.elasticsearch.search.SearchShardTarget; import org.elasticsearch.search.aggregations.InternalAggregations; import org.elasticsearch.search.aggregations.bucket.significant.heuristics.*; import org.elasticsearch.search.internal.SearchContext; -import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.ElasticsearchTestCase; import org.elasticsearch.test.TestSearchContext; import org.junit.Test; @@ -45,6 +44,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThanOrEqualTo; @@ -76,7 +76,7 @@ public class SignificanceHeuristicTests extends ElasticsearchTestCase { SignificanceHeuristicStreams.registerStream(GND.STREAM, GND.STREAM.getName()); SignificanceHeuristicStreams.registerStream(ChiSquare.STREAM, ChiSquare.STREAM.getName()); SignificanceHeuristicStreams.registerStream(ScriptHeuristic.STREAM, ScriptHeuristic.STREAM.getName()); - Version version = ElasticsearchIntegrationTest.randomVersion(); + Version version = randomVersion(random()); InternalSignificantTerms[] sigTerms = getRandomSignificantTerms(getRandomSignificanceheuristic()); // write diff --git a/src/test/java/org/elasticsearch/search/query/SearchQueryTests.java b/src/test/java/org/elasticsearch/search/query/SearchQueryTests.java index e4dda3f34a0..3404338e769 100644 --- a/src/test/java/org/elasticsearch/search/query/SearchQueryTests.java +++ b/src/test/java/org/elasticsearch/search/query/SearchQueryTests.java @@ -53,13 +53,13 @@ import java.util.Random; import java.util.Set; import java.util.concurrent.ExecutionException; -import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.FilterBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.scriptFunction; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; import static org.hamcrest.Matchers.*; @@ -490,7 +490,7 @@ public class SearchQueryTests extends ElasticsearchIntegrationTest { assertThat(version.toString(), version.onOrAfter(Version.V_1_0_0_RC2), equalTo(true)); assertThat(ex.getCause().getMessage(), equalTo("'omit_term_freq_and_positions' is not supported anymore - use ['index_options' : 'docs'] instead")); } - version = randomVersion(); + version = randomVersion(random()); } } diff --git a/src/test/java/org/elasticsearch/search/scroll/DuelScrollTests.java b/src/test/java/org/elasticsearch/search/scroll/DuelScrollTests.java index 116a03bfe02..3e77aa4b4f1 100644 --- a/src/test/java/org/elasticsearch/search/scroll/DuelScrollTests.java +++ b/src/test/java/org/elasticsearch/search/scroll/DuelScrollTests.java @@ -158,7 +158,7 @@ public class DuelScrollTests extends ElasticsearchIntegrationTest { int scrollRequestSize = randomIntBetween(1, rarely() ? numDocs : numDocs / 2); boolean unevenRouting = randomBoolean(); - int numMissingDocs = atMost(numDocs / 100); + int numMissingDocs = scaledRandomIntBetween(0, numDocs / 100); IntOpenHashSet missingDocs = new IntOpenHashSet(numMissingDocs); for (int i = 0; i < numMissingDocs; i++) { while (!missingDocs.add(randomInt(numDocs))) {} diff --git a/src/test/java/org/elasticsearch/test/ElasticsearchTestCase.java b/src/test/java/org/elasticsearch/test/ElasticsearchTestCase.java index f392b2ae928..dc2c828839a 100644 --- a/src/test/java/org/elasticsearch/test/ElasticsearchTestCase.java +++ b/src/test/java/org/elasticsearch/test/ElasticsearchTestCase.java @@ -21,7 +21,6 @@ package org.elasticsearch.test; import com.carrotsearch.randomizedtesting.RandomizedContext; import com.carrotsearch.randomizedtesting.RandomizedTest; import com.carrotsearch.randomizedtesting.annotations.Listeners; -import com.carrotsearch.randomizedtesting.annotations.TestGroup; import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; @@ -30,7 +29,6 @@ import com.carrotsearch.randomizedtesting.generators.RandomInts; import com.carrotsearch.randomizedtesting.generators.RandomPicks; import com.carrotsearch.randomizedtesting.generators.RandomStrings; import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableList; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.uninverting.UninvertingReader; import org.apache.lucene.util.LuceneTestCase; @@ -62,28 +60,18 @@ import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Ignore; import java.io.Closeable; import java.io.IOException; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; import java.lang.reflect.Field; -import java.lang.reflect.Modifier; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.Formatter; -import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; -import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -247,20 +235,13 @@ public abstract class ElasticsearchTestCase extends LuceneTestCase { // old helper stuff, a lot of it is bad news and we should see if its all used - /** - * Shortcut for {@link RandomizedContext#getRandom()}. Even though this method - * is static, it returns per-thread {@link Random} instance, so no race conditions - * can occur. - * - *

It is recommended that specific methods are used to pick random values. - */ + /** Shortcut for {@link RandomizedContext#getRandom()}. Use {@link #random()} instead. */ public static Random getRandom() { + // TODO: replace uses of this function with random() return random(); } - /** - * Shortcut for {@link RandomizedContext#current()}. - */ + /** Shortcut for {@link RandomizedContext#current()}. */ public static RandomizedContext getContext() { return RandomizedTest.getContext(); } @@ -309,91 +290,68 @@ public abstract class ElasticsearchTestCase extends LuceneTestCase { public static boolean randomBoolean() { return random().nextBoolean(); } - public static byte randomByte() { return (byte) getRandom().nextInt(); } - public static short randomShort() { return (short) getRandom().nextInt(); } - public static int randomInt() { return getRandom().nextInt(); } - public static float randomFloat() { return getRandom().nextFloat(); } - public static double randomDouble() { return getRandom().nextDouble(); } - public static long randomLong() { return getRandom().nextLong(); } - /** - * Pick a random object from the given array. The array must not be empty. - */ + public static byte randomByte() { return (byte) random().nextInt(); } + public static short randomShort() { return (short) random().nextInt(); } + public static int randomInt() { return random().nextInt(); } + public static float randomFloat() { return random().nextFloat(); } + public static double randomDouble() { return random().nextDouble(); } + public static long randomLong() { return random().nextLong(); } + + /** Pick a random object from the given array. The array must not be empty. */ public static T randomFrom(T... array) { return RandomPicks.randomFrom(random(), array); } - /** - * Pick a random object from the given list. - */ + /** Pick a random object from the given list. */ public static T randomFrom(List list) { return RandomPicks.randomFrom(random(), list); } - /** - * A random integer from 0..max (inclusive). - */ + /** A random integer from 0..max (inclusive). */ public static int randomInt(int max) { - return RandomizedTest.randomInt(max); + return RandomizedTest.randomInt(max); } - - /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ + public static String randomAsciiOfLengthBetween(int minCodeUnits, int maxCodeUnits) { return RandomizedTest.randomAsciiOfLengthBetween(minCodeUnits, maxCodeUnits); } - /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ public static String randomAsciiOfLength(int codeUnits) { return RandomizedTest.randomAsciiOfLength(codeUnits); } - /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ public static String randomUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) { return RandomizedTest.randomUnicodeOfLengthBetween(minCodeUnits, maxCodeUnits); } - /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ public static String randomUnicodeOfLength(int codeUnits) { return RandomizedTest.randomUnicodeOfLength(codeUnits); } - - /** @see StringGenerator#ofCodePointsLength(Random, int, int) */ + public static String randomUnicodeOfCodepointLengthBetween(int minCodePoints, int maxCodePoints) { return RandomizedTest.randomUnicodeOfCodepointLengthBetween(minCodePoints, maxCodePoints); } - /** @see StringGenerator#ofCodePointsLength(Random, int, int) */ public static String randomUnicodeOfCodepointLength(int codePoints) { return RandomizedTest.randomUnicodeOfCodepointLength(codePoints); } - - /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ + public static String randomRealisticUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) { return RandomizedTest.randomRealisticUnicodeOfLengthBetween(minCodeUnits, maxCodeUnits); } - /** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */ public static String randomRealisticUnicodeOfLength(int codeUnits) { return RandomizedTest.randomRealisticUnicodeOfLength(codeUnits); } - - /** @see StringGenerator#ofCodePointsLength(Random, int, int) */ + public static String randomRealisticUnicodeOfCodepointLengthBetween(int minCodePoints, int maxCodePoints) { return RandomizedTest.randomRealisticUnicodeOfCodepointLengthBetween(minCodePoints, maxCodePoints); } - /** @see StringGenerator#ofCodePointsLength(Random, int, int) */ public static String randomRealisticUnicodeOfCodepointLength(int codePoints) { return RandomizedTest.randomRealisticUnicodeOfCodepointLength(codePoints); } - - /** - * Returns a non-negative random value smaller or equal max. - * @see RandomizedTest#atMost(int); - */ - public static int atMost(int max) { - return RandomizedTest.atMost(max); - } /** * Runs the code block for 10 seconds waiting for no assertion to trip. @@ -485,119 +443,6 @@ public abstract class ElasticsearchTestCase extends LuceneTestCase { } } - private static final List SORTED_VERSIONS; - - static { - Field[] declaredFields = Version.class.getDeclaredFields(); - Set ids = new HashSet<>(); - for (Field field : declaredFields) { - final int mod = field.getModifiers(); - if (Modifier.isStatic(mod) && Modifier.isFinal(mod) && Modifier.isPublic(mod)) { - if (field.getType() == Version.class) { - try { - Version object = (Version) field.get(null); - ids.add(object.id); - } catch (Throwable e) { - throw new RuntimeException(e); - } - } - } - } - List idList = new ArrayList<>(ids); - Collections.sort(idList); - Collections.reverse(idList); - ImmutableList.Builder version = ImmutableList.builder(); - for (Integer integer : idList) { - version.add(Version.fromId(integer)); - } - SORTED_VERSIONS = version.build(); - } - - /** - * @return the {@link Version} before the {@link Version#CURRENT} - */ - public static Version getPreviousVersion() { - Version version = SORTED_VERSIONS.get(1); - assert version.before(Version.CURRENT); - return version; - } - - /** - * A random {@link Version}. - * - * @return a random {@link Version} from all available versions - */ - public static Version randomVersion() { - return randomVersion(random()); - } - - /** - * A random {@link Version}. - * - * @param random - * the {@link Random} to use to generate the random version - * - * @return a random {@link Version} from all available versions - */ - public static Version randomVersion(Random random) { - return SORTED_VERSIONS.get(random.nextInt(SORTED_VERSIONS.size())); - } - - /** - * Returns immutable list of all known versions. - */ - public static List allVersions() { - return Collections.unmodifiableList(SORTED_VERSIONS); - } - - /** - * A random {@link Version} from minVersion to - * maxVersion (inclusive). - * - * @param minVersion - * the minimum version (inclusive) - * @param maxVersion - * the maximum version (inclusive) - * @return a random {@link Version} from minVersion to - * maxVersion (inclusive) - */ - public static Version randomVersionBetween(Version minVersion, Version maxVersion) { - return randomVersionBetween(random(), minVersion, maxVersion); - } - - /** - * A random {@link Version} from minVersion to - * maxVersion (inclusive). - * - * @param random - * the {@link Random} to use to generate the random version - * @param minVersion - * the minimum version (inclusive) - * @param maxVersion - * the maximum version (inclusive) - * @return a random {@link Version} from minVersion to - * maxVersion (inclusive) - */ - public static Version randomVersionBetween(Random random, Version minVersion, Version maxVersion) { - int minVersionIndex = SORTED_VERSIONS.size(); - if (minVersion != null) { - minVersionIndex = SORTED_VERSIONS.indexOf(minVersion); - } - int maxVersionIndex = 0; - if (maxVersion != null) { - maxVersionIndex = SORTED_VERSIONS.indexOf(maxVersion); - } - if (minVersionIndex == -1) { - throw new IllegalArgumentException("minVersion [" + minVersion + "] does not exist."); - } else if (maxVersionIndex == -1) { - throw new IllegalArgumentException("maxVersion [" + maxVersion + "] does not exist."); - } else { - // minVersionIndex is inclusive so need to add 1 to this index - int range = minVersionIndex + 1 - maxVersionIndex; - return SORTED_VERSIONS.get(maxVersionIndex + random.nextInt(range)); - } - } - /** * Return consistent index settings for the provided index version. */ @@ -617,8 +462,7 @@ public abstract class ElasticsearchTestCase extends LuceneTestCase { private ElasticsearchUncaughtExceptionHandler(Thread.UncaughtExceptionHandler parent) { this.parent = parent; } - - + @Override public void uncaughtException(Thread t, Throwable e) { if (e instanceof EsRejectedExecutionException) { @@ -632,7 +476,6 @@ public abstract class ElasticsearchTestCase extends LuceneTestCase { } parent.uncaughtException(t, e); } - } protected static final void printStackDump(ESLogger logger) { @@ -690,11 +533,6 @@ public abstract class ElasticsearchTestCase extends LuceneTestCase { return array; } - public static String[] generateRandomStringArray(int maxArraySize, int maxStringSize) { - return generateRandomStringArray(maxArraySize, maxStringSize, false); - } - - public static boolean terminate(ExecutorService... services) throws InterruptedException { boolean terminated = true; for (ExecutorService service : services) { diff --git a/src/test/java/org/elasticsearch/test/ElasticsearchTokenStreamTestCase.java b/src/test/java/org/elasticsearch/test/ElasticsearchTokenStreamTestCase.java index 6334588d30e..eeba7129cbd 100644 --- a/src/test/java/org/elasticsearch/test/ElasticsearchTokenStreamTestCase.java +++ b/src/test/java/org/elasticsearch/test/ElasticsearchTokenStreamTestCase.java @@ -20,9 +20,6 @@ package org.elasticsearch.test; import com.carrotsearch.randomizedtesting.annotations.Listeners; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite; import org.apache.lucene.analysis.BaseTokenStreamTestCase; @@ -50,7 +47,7 @@ public abstract class ElasticsearchTokenStreamTestCase extends BaseTokenStreamTe } public static Version randomVersion() { - return ElasticsearchTestCase.randomVersion(random()); + return VersionTestUtil.randomVersion(random()); } public ImmutableSettings.Builder newAnalysisSettingsBuilder() { diff --git a/src/test/java/org/elasticsearch/test/VersionTestUtil.java b/src/test/java/org/elasticsearch/test/VersionTestUtil.java new file mode 100644 index 00000000000..5927292acb8 --- /dev/null +++ b/src/test/java/org/elasticsearch/test/VersionTestUtil.java @@ -0,0 +1,101 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.elasticsearch.test; + +import com.google.common.collect.ImmutableList; +import org.elasticsearch.Version; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; + +/** Utilities for selection versions in tests */ +public class VersionTestUtil { + + private static final List SORTED_VERSIONS; + static { + Field[] declaredFields = Version.class.getDeclaredFields(); + Set ids = new HashSet<>(); + for (Field field : declaredFields) { + final int mod = field.getModifiers(); + if (Modifier.isStatic(mod) && Modifier.isFinal(mod) && Modifier.isPublic(mod)) { + if (field.getType() == Version.class) { + try { + Version object = (Version) field.get(null); + ids.add(object.id); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + } + } + List idList = new ArrayList<>(ids); + Collections.sort(idList); + Collections.reverse(idList); + ImmutableList.Builder version = ImmutableList.builder(); + for (Integer integer : idList) { + version.add(Version.fromId(integer)); + } + SORTED_VERSIONS = version.build(); + } + + /** Returns immutable list of all known versions. */ + public static List allVersions() { + return Collections.unmodifiableList(SORTED_VERSIONS); + } + + /** Returns the {@link Version} before the {@link Version#CURRENT} */ + public static Version getPreviousVersion() { + Version version = SORTED_VERSIONS.get(1); + assert version.before(Version.CURRENT); + return version; + } + + /** Returns a random {@link Version} from all available versions. */ + public static Version randomVersion(Random random) { + return SORTED_VERSIONS.get(random.nextInt(SORTED_VERSIONS.size())); + } + + /** Returns a random {@link Version} between minVersion and maxVersion (inclusive). */ + public static Version randomVersionBetween(Random random, Version minVersion, Version maxVersion) { + int minVersionIndex = SORTED_VERSIONS.size(); + if (minVersion != null) { + minVersionIndex = SORTED_VERSIONS.indexOf(minVersion); + } + int maxVersionIndex = 0; + if (maxVersion != null) { + maxVersionIndex = SORTED_VERSIONS.indexOf(maxVersion); + } + if (minVersionIndex == -1) { + throw new IllegalArgumentException("minVersion [" + minVersion + "] does not exist."); + } else if (maxVersionIndex == -1) { + throw new IllegalArgumentException("maxVersion [" + maxVersion + "] does not exist."); + } else { + // minVersionIndex is inclusive so need to add 1 to this index + int range = minVersionIndex + 1 - maxVersionIndex; + return SORTED_VERSIONS.get(maxVersionIndex + random.nextInt(range)); + } + } +} diff --git a/src/test/java/org/elasticsearch/test/discovery/ClusterDiscoveryConfiguration.java b/src/test/java/org/elasticsearch/test/discovery/ClusterDiscoveryConfiguration.java index 57c512224b5..1be28a9a8a1 100644 --- a/src/test/java/org/elasticsearch/test/discovery/ClusterDiscoveryConfiguration.java +++ b/src/test/java/org/elasticsearch/test/discovery/ClusterDiscoveryConfiguration.java @@ -23,11 +23,9 @@ import com.google.common.primitives.Ints; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.InternalTestCluster; import org.elasticsearch.test.SettingsSource; import org.elasticsearch.transport.local.LocalTransport; -import org.omg.CORBA.INTERNAL; import java.io.IOException; import java.net.ServerSocket; @@ -42,10 +40,6 @@ public class ClusterDiscoveryConfiguration extends SettingsSource { final Settings nodeSettings; final Settings transportClientSettings; - public ClusterDiscoveryConfiguration(int numOfNodes) { - this(numOfNodes, ImmutableSettings.EMPTY); - } - public ClusterDiscoveryConfiguration(int numOfNodes, Settings extraSettings) { this.numOfNodes = numOfNodes; this.nodeSettings = ImmutableSettings.builder().put(DEFAULT_NODE_SETTINGS).put(extraSettings).build(); diff --git a/src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java b/src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java index cc0d0c59ff4..008e8cf2cc1 100644 --- a/src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java +++ b/src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java @@ -64,6 +64,7 @@ import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.suggest.Suggest; +import org.elasticsearch.test.VersionTestUtil; import org.elasticsearch.test.engine.AssertingSearcher; import org.elasticsearch.test.engine.MockInternalEngine; import org.elasticsearch.test.engine.MockShadowEngine; @@ -82,6 +83,7 @@ import java.util.concurrent.TimeUnit; import static com.google.common.base.Predicates.isNull; import static org.elasticsearch.test.ElasticsearchTestCase.*; +import static org.elasticsearch.test.VersionTestUtil.randomVersion; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -585,8 +587,8 @@ public class ElasticsearchAssertions { } public static void assertVersionSerializable(Streamable streamable) { - assertTrue(Version.CURRENT.after(getPreviousVersion())); - assertVersionSerializable(randomVersion(), streamable); + assertTrue(Version.CURRENT.after(VersionTestUtil.getPreviousVersion())); + assertVersionSerializable(randomVersion(random()), streamable); } public static void assertVersionSerializable(Version version, Streamable streamable) { diff --git a/src/test/java/org/elasticsearch/test/transport/AssertingLocalTransport.java b/src/test/java/org/elasticsearch/test/transport/AssertingLocalTransport.java index 5a2f4f560fb..0568e869506 100644 --- a/src/test/java/org/elasticsearch/test/transport/AssertingLocalTransport.java +++ b/src/test/java/org/elasticsearch/test/transport/AssertingLocalTransport.java @@ -24,7 +24,7 @@ import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ElasticsearchIntegrationTest; -import org.elasticsearch.test.ElasticsearchTestCase; +import org.elasticsearch.test.VersionTestUtil; import org.elasticsearch.test.hamcrest.ElasticsearchAssertions; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.*; @@ -55,13 +55,13 @@ public class AssertingLocalTransport extends LocalTransport { @Override protected void handleParsedResponse(final TransportResponse response, final TransportResponseHandler handler) { - ElasticsearchAssertions.assertVersionSerializable(ElasticsearchTestCase.randomVersionBetween(random, minVersion, maxVersion), response); + ElasticsearchAssertions.assertVersionSerializable(VersionTestUtil.randomVersionBetween(random, minVersion, maxVersion), response); super.handleParsedResponse(response, handler); } @Override public void sendRequest(final DiscoveryNode node, final long requestId, final String action, final TransportRequest request, TransportRequestOptions options) throws IOException, TransportException { - ElasticsearchAssertions.assertVersionSerializable(ElasticsearchTestCase.randomVersionBetween(random, minVersion, maxVersion), request); + ElasticsearchAssertions.assertVersionSerializable(VersionTestUtil.randomVersionBetween(random, minVersion, maxVersion), request); super.sendRequest(node, requestId, action, request, options); } }