move version related stuff to dedicated test utility

This commit is contained in:
Ryan Ernst 2015-04-18 03:00:45 -07:00
parent d8a92947d1
commit ce6b3774ec
29 changed files with 201 additions and 259 deletions

View File

@ -23,6 +23,7 @@ import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.test.ElasticsearchTestCase; import org.elasticsearch.test.ElasticsearchTestCase;
import org.elasticsearch.test.VersionTestUtil;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Test; 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_20_0;
import static org.elasticsearch.Version.V_0_90_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.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance; 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)); assertThat(Version.CURRENT.luceneVersion, equalTo(org.apache.lucene.util.Version.LATEST));
final int iters = scaledRandomIntBetween(20, 100); final int iters = scaledRandomIntBetween(20, 100);
for (int i = 0; i < iters; i++) { for (int i = 0; i < iters; i++) {
Version version = randomVersion(); Version version = randomVersion(random());
assertThat(version, sameInstance(Version.fromId(version.id))); assertThat(version, sameInstance(Version.fromId(version.id)));
assertThat(version.luceneVersion, sameInstance(Version.fromId(version.id).luceneVersion)); assertThat(version.luceneVersion, sameInstance(Version.fromId(version.id).luceneVersion));
} }
@ -80,7 +82,7 @@ public class VersionTests extends ElasticsearchTestCase {
public void testCURRENTIsLatest() { public void testCURRENTIsLatest() {
final int iters = scaledRandomIntBetween(100, 1000); final int iters = scaledRandomIntBetween(100, 1000);
for (int i = 0; i < iters; i++) { for (int i = 0; i < iters; i++) {
Version version = randomVersion(); Version version = randomVersion(random());
if (version != Version.CURRENT) { if (version != Version.CURRENT) {
assertThat("Version: " + version + " should be before: " + Version.CURRENT + " but wasn't", version.before(Version.CURRENT), is(true)); 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() { public void testVersionFromString() {
final int iters = scaledRandomIntBetween(100, 1000); final int iters = scaledRandomIntBetween(100, 1000);
for (int i = 0; i < iters; i++) { 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 if (version.snapshot()) { // number doesn't include SNAPSHOT but the parser checks for that
assertEquals(Version.fromString(version.number()), version); assertEquals(Version.fromString(version.number()), version);
} else { } else {
@ -137,7 +139,7 @@ public class VersionTests extends ElasticsearchTestCase {
public void testParseVersion() { public void testParseVersion() {
final int iters = scaledRandomIntBetween(100, 1000); final int iters = scaledRandomIntBetween(100, 1000);
for (int i = 0; i < iters; i++) { for (int i = 0; i < iters; i++) {
Version version = randomVersion(); Version version = randomVersion(random());
String stringVersion = version.toString(); String stringVersion = version.toString();
if (version.snapshot() == false && random().nextBoolean()) { if (version.snapshot() == false && random().nextBoolean()) {
version = new Version(version.id, true, version.luceneVersion); version = new Version(version.id, true, version.luceneVersion);
@ -150,7 +152,7 @@ public class VersionTests extends ElasticsearchTestCase {
public void testParseLenient() { public void testParseLenient() {
// note this is just a silly sanity check, we test it in lucene // 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; org.apache.lucene.util.Version luceneVersion = version.luceneVersion;
String string = luceneVersion.toString().toUpperCase(Locale.ROOT) String string = luceneVersion.toString().toUpperCase(Locale.ROOT)
.replaceFirst("^LUCENE_(\\d+)_(\\d+)$", "$1.$2"); .replaceFirst("^LUCENE_(\\d+)_(\\d+)$", "$1.$2");

View File

@ -27,6 +27,7 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
public class OriginalIndicesTests extends ElasticsearchTestCase { public class OriginalIndicesTests extends ElasticsearchTestCase {
@ -42,7 +43,7 @@ public class OriginalIndicesTests extends ElasticsearchTestCase {
OriginalIndices originalIndices = randomOriginalIndices(); OriginalIndices originalIndices = randomOriginalIndices();
BytesStreamOutput out = new BytesStreamOutput(); BytesStreamOutput out = new BytesStreamOutput();
out.setVersion(randomVersion()); out.setVersion(randomVersion(random()));
OriginalIndices.writeOriginalIndices(originalIndices, out); OriginalIndices.writeOriginalIndices(originalIndices, out);
BytesStreamInput in = new BytesStreamInput(out.bytes()); BytesStreamInput in = new BytesStreamInput(out.bytes());

View File

@ -24,6 +24,7 @@ import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.test.ElasticsearchTestCase; import org.elasticsearch.test.ElasticsearchTestCase;
import org.elasticsearch.test.VersionTestUtil;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
@ -42,7 +43,7 @@ public class ClusterStateRequestTest extends ElasticsearchTestCase {
ClusterStateRequest clusterStateRequest = new ClusterStateRequest().routingTable(randomBoolean()).metaData(randomBoolean()) ClusterStateRequest clusterStateRequest = new ClusterStateRequest().routingTable(randomBoolean()).metaData(randomBoolean())
.nodes(randomBoolean()).blocks(randomBoolean()).indices("testindex", "testindex2").indicesOptions(indicesOptions); .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(); BytesStreamOutput output = new BytesStreamOutput();
output.setVersion(testVersion); output.setVersion(testVersion);
clusterStateRequest.writeTo(output); clusterStateRequest.writeTo(output);

View File

@ -19,7 +19,6 @@
package org.elasticsearch.action.get; package org.elasticsearch.action.get;
import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.index.VersionType; import org.elasticsearch.index.VersionType;
@ -29,6 +28,7 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
public class MultiGetShardRequestTests extends ElasticsearchTestCase { public class MultiGetShardRequestTests extends ElasticsearchTestCase {
@ -70,7 +70,7 @@ public class MultiGetShardRequestTests extends ElasticsearchTestCase {
} }
BytesStreamOutput out = new BytesStreamOutput(); BytesStreamOutput out = new BytesStreamOutput();
out.setVersion(randomVersion()); out.setVersion(randomVersion(random()));
multiGetShardRequest.writeTo(out); multiGetShardRequest.writeTo(out);
BytesStreamInput in = new BytesStreamInput(out.bytes()); BytesStreamInput in = new BytesStreamInput(out.bytes());

View File

@ -27,6 +27,7 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
public class GetIndexedScriptRequestTests extends ElasticsearchTestCase { public class GetIndexedScriptRequestTests extends ElasticsearchTestCase {
@ -40,7 +41,7 @@ public class GetIndexedScriptRequestTests extends ElasticsearchTestCase {
} }
BytesStreamOutput out = new BytesStreamOutput(); BytesStreamOutput out = new BytesStreamOutput();
out.setVersion(randomVersion()); out.setVersion(randomVersion(random()));
request.writeTo(out); request.writeTo(out);
BytesStreamInput in = new BytesStreamInput(out.bytes()); BytesStreamInput in = new BytesStreamInput(out.bytes());

View File

@ -19,7 +19,6 @@
package org.elasticsearch.action.mlt; package org.elasticsearch.action.mlt;
import org.elasticsearch.Version;
import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamInput;
@ -33,6 +32,7 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
public class MoreLikeThisRequestTests extends ElasticsearchTestCase { public class MoreLikeThisRequestTests extends ElasticsearchTestCase {
@ -99,7 +99,7 @@ public class MoreLikeThisRequestTests extends ElasticsearchTestCase {
} }
BytesStreamOutput out = new BytesStreamOutput(); BytesStreamOutput out = new BytesStreamOutput();
out.setVersion(randomVersion()); out.setVersion(randomVersion(random()));
mltRequest.writeTo(out); mltRequest.writeTo(out);
BytesStreamInput in = new BytesStreamInput(out.bytes()); BytesStreamInput in = new BytesStreamInput(out.bytes());

View File

@ -25,6 +25,7 @@ import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.test.ElasticsearchTestCase; import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Test; import org.junit.Test;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
public class IndicesOptionsTests extends ElasticsearchTestCase { public class IndicesOptionsTests extends ElasticsearchTestCase {
@ -36,12 +37,12 @@ public class IndicesOptionsTests extends ElasticsearchTestCase {
IndicesOptions indicesOptions = IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean()); IndicesOptions indicesOptions = IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean());
BytesStreamOutput output = new BytesStreamOutput(); BytesStreamOutput output = new BytesStreamOutput();
Version outputVersion = randomVersion(); Version outputVersion = randomVersion(random());
output.setVersion(outputVersion); output.setVersion(outputVersion);
indicesOptions.writeIndicesOptions(output); indicesOptions.writeIndicesOptions(output);
BytesStreamInput bytesStreamInput = new BytesStreamInput(output.bytes()); BytesStreamInput bytesStreamInput = new BytesStreamInput(output.bytes());
bytesStreamInput.setVersion(randomVersion()); bytesStreamInput.setVersion(randomVersion(random()));
IndicesOptions indicesOptions2 = IndicesOptions.readIndicesOptions(bytesStreamInput); IndicesOptions indicesOptions2 = IndicesOptions.readIndicesOptions(bytesStreamInput);
assertThat(indicesOptions2.ignoreUnavailable(), equalTo(indicesOptions.ignoreUnavailable())); assertThat(indicesOptions2.ignoreUnavailable(), equalTo(indicesOptions.ignoreUnavailable()));

View File

@ -48,6 +48,7 @@ import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.elasticsearch.test.VersionTestUtil;
import org.elasticsearch.test.hamcrest.ElasticsearchAssertions; import org.elasticsearch.test.hamcrest.ElasticsearchAssertions;
import org.elasticsearch.test.index.merge.NoMergePolicyProvider; import org.elasticsearch.test.index.merge.NoMergePolicyProvider;
import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpRequestBuilder;
@ -226,21 +227,11 @@ public class OldIndexBackwardsCompatibilityTests extends ElasticsearchIntegratio
public void testAllVersionsTested() throws Exception { public void testAllVersionsTested() throws Exception {
SortedSet<String> expectedVersions = new TreeSet<>(); SortedSet<String> expectedVersions = new TreeSet<>();
for (java.lang.reflect.Field field : Version.class.getDeclaredFields()) { for (Version v : VersionTestUtil.allVersions()) {
if (Modifier.isStatic(field.getModifiers()) && field.getType() == Version.class) { if (v.snapshot()) continue; // snapshots are unreleased, so there is no backcompat yet
Version v = (Version) field.get(Version.class); if (v.onOrBefore(Version.V_0_20_6)) continue; // we can only test back one major lucene version
if (v.snapshot()) { if (v.equals(Version.CURRENT)) continue; // the current version is always compatible with itself
continue; // snapshots are unreleased, so there is no backcompat yet expectedVersions.add("index-" + v.toString() + ".zip");
}
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) { for (String index : indexes) {

View File

@ -33,6 +33,8 @@ import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
public class DiscoveryNodeTests extends ElasticsearchTestCase { public class DiscoveryNodeTests extends ElasticsearchTestCase {
@ -49,7 +51,7 @@ public class DiscoveryNodeTests extends ElasticsearchTestCase {
for (int a = randomInt(10); a > 0; a--) { for (int a = randomInt(10); a > 0; a--) {
attributes.put(randomUnicodeOfLengthBetween(3, 20), randomUnicodeOfLengthBetween(3, 20)); 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); DiscoveryNode discoveryNode = new DiscoveryNode(nodeName, id, hostName, hostAddress, transportAddress, attributes, version);
BytesStreamOutput bytesOutput = new BytesStreamOutput(); BytesStreamOutput bytesOutput = new BytesStreamOutput();
ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(bytesOutput); ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(bytesOutput);

View File

@ -29,6 +29,7 @@ import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.Node; import org.elasticsearch.node.Node;
import org.elasticsearch.test.ElasticsearchTestCase; import org.elasticsearch.test.ElasticsearchTestCase;
import org.elasticsearch.test.VersionTestUtil;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -57,7 +58,7 @@ public class RoutingBackwardCompatibilityTests extends ElasticsearchTestCase {
final int currentExpectedShard = Integer.parseInt(parts[6]); final int currentExpectedShard = Integer.parseInt(parts[6]);
OperationRouting operationRouting = node.injector().getInstance(OperationRouting.class); OperationRouting operationRouting = node.injector().getInstance(OperationRouting.class);
for (Version version : allVersions()) { for (Version version : VersionTestUtil.allVersions()) {
final Settings settings = settings(version).build(); final Settings settings = settings(version).build();
IndexMetaData indexMetaData = IndexMetaData.builder(index).settings(settings).numberOfShards(numberOfShards).numberOfReplicas(randomInt(3)).build(); IndexMetaData indexMetaData = IndexMetaData.builder(index).settings(settings).numberOfShards(numberOfShards).numberOfReplicas(randomInt(3)).build();
MetaData.Builder metaData = MetaData.builder().put(indexMetaData, false); MetaData.Builder metaData = MetaData.builder().put(indexMetaData, false);

View File

@ -33,6 +33,7 @@ import org.elasticsearch.cluster.routing.allocation.decider.ClusterRebalanceAllo
import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.test.ElasticsearchAllocationTestCase; import org.elasticsearch.test.ElasticsearchAllocationTestCase;
import org.elasticsearch.test.VersionTestUtil;
import org.junit.Test; import org.junit.Test;
import java.util.ArrayList; import java.util.ArrayList;
@ -41,6 +42,7 @@ import java.util.List;
import static org.elasticsearch.cluster.routing.ShardRoutingState.*; import static org.elasticsearch.cluster.routing.ShardRoutingState.*;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
/** /**
@ -122,7 +124,7 @@ public class NodeVersionAllocationDeciderTests extends ElasticsearchAllocationTe
} }
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()) clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())
.put(newNode("node3", getPreviousVersion()))) .put(newNode("node3", VersionTestUtil.getPreviousVersion())))
.build(); .build();
prevRoutingTable = routingTable; prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable(); routingTable = strategy.reroute(clusterState).routingTable();
@ -202,9 +204,9 @@ public class NodeVersionAllocationDeciderTests extends ElasticsearchAllocationTe
} else { } else {
for (int j = nodes.size(); j < numNodes; j++) { for (int j = nodes.size(); j < numNodes; j++) {
if (frequently()) { if (frequently()) {
nodes.add(newNode("node" + (nodeIdx++), randomBoolean() ? getPreviousVersion() : Version.CURRENT)); nodes.add(newNode("node" + (nodeIdx++), randomBoolean() ? VersionTestUtil.getPreviousVersion() : Version.CURRENT));
} else { } 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()); assertThat(routingTable.index("test").shard(i).shards().get(2).currentNodeId(), nullValue());
} }
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("old0", getPreviousVersion())) .put(newNode("old0", VersionTestUtil.getPreviousVersion()))
.put(newNode("old1", getPreviousVersion())) .put(newNode("old1", VersionTestUtil.getPreviousVersion()))
.put(newNode("old2", getPreviousVersion()))).build(); .put(newNode("old2", VersionTestUtil.getPreviousVersion()))).build();
clusterState = stabilize(clusterState, service); clusterState = stabilize(clusterState, service);
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("old0", getPreviousVersion())) .put(newNode("old0", VersionTestUtil.getPreviousVersion()))
.put(newNode("old1", getPreviousVersion())) .put(newNode("old1", VersionTestUtil.getPreviousVersion()))
.put(newNode("new0"))).build(); .put(newNode("new0"))).build();
clusterState = stabilize(clusterState, service); clusterState = stabilize(clusterState, service);
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("node0", getPreviousVersion())) .put(newNode("node0", VersionTestUtil.getPreviousVersion()))
.put(newNode("new1")) .put(newNode("new1"))
.put(newNode("new0"))).build(); .put(newNode("new0"))).build();

View File

@ -29,6 +29,7 @@ import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.mapper.DocumentMapperParser; import org.elasticsearch.index.mapper.DocumentMapperParser;
import org.elasticsearch.index.mapper.MapperParsingException; import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.test.ElasticsearchSingleNodeTest; import org.elasticsearch.test.ElasticsearchSingleNodeTest;
import org.elasticsearch.test.VersionTestUtil;
import org.junit.Assert; import org.junit.Assert;
import java.io.IOException; 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() .startObject("properties").startObject("field").field("type", "string").field("postings_format", Codec.getDefault().postingsFormat().getName()).endObject().endObject()
.endObject().endObject().string(); .endObject().endObject().string();
int i = 0; 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()); IndexService indexService = createIndex("test-" + i++, ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, v).build());
DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); DocumentMapperParser parser = indexService.mapperService().documentMapperParser();
try { 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() .startObject("properties").startObject("field").field("type", "string").field("doc_values_format", Codec.getDefault().docValuesFormat().getName()).endObject().endObject()
.endObject().endObject().string(); .endObject().endObject().string();
int i = 0; 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()); IndexService indexService = createIndex("test-" + i++, ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, v).build());
DocumentMapperParser parser = indexService.mapperService().documentMapperParser(); DocumentMapperParser parser = indexService.mapperService().documentMapperParser();
try { try {

View File

@ -37,6 +37,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
/** /**
@ -86,7 +87,7 @@ public class PreBuiltAnalyzerTests extends ElasticsearchSingleNodeTest {
assertThat(list, contains("dude")); assertThat(list, contains("dude"));
} }
ts.close(); ts.close();
version = randomVersion(); version = randomVersion(random());
} }
} }
@ -121,7 +122,7 @@ public class PreBuiltAnalyzerTests extends ElasticsearchSingleNodeTest {
assertThat(list, contains("dude")); assertThat(list, contains("dude"));
} }
ts.close(); ts.close();
version = randomVersion(); version = randomVersion(random());
} }
} }
@ -152,7 +153,7 @@ public class PreBuiltAnalyzerTests extends ElasticsearchSingleNodeTest {
PreBuiltAnalyzers randomPreBuiltAnalyzer = PreBuiltAnalyzers.values()[randomInt]; PreBuiltAnalyzers randomPreBuiltAnalyzer = PreBuiltAnalyzers.values()[randomInt];
String analyzerName = randomPreBuiltAnalyzer.name().toLowerCase(Locale.ROOT); 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(); Settings indexSettings = ImmutableSettings.settingsBuilder().put(IndexMetaData.SETTING_VERSION_CREATED, randomVersion).build();
NamedAnalyzer namedAnalyzer = new PreBuiltAnalyzerProvider(analyzerName, AnalyzerScope.INDEX, randomPreBuiltAnalyzer.getAnalyzer(randomVersion)).get(); NamedAnalyzer namedAnalyzer = new PreBuiltAnalyzerProvider(analyzerName, AnalyzerScope.INDEX, randomPreBuiltAnalyzer.getAnalyzer(randomVersion)).get();

View File

@ -26,8 +26,8 @@ import org.apache.lucene.analysis.snowball.SnowballFilter;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.elasticsearch.test.ElasticsearchTokenStreamTestCase; import org.elasticsearch.test.ElasticsearchTokenStreamTestCase;
import org.elasticsearch.test.VersionTestUtil;
import org.junit.Test; import org.junit.Test;
import java.io.IOException; import java.io.IOException;
@ -47,7 +47,7 @@ public class StemmerTokenFilterFactoryTests extends ElasticsearchTokenStreamTest
int iters = scaledRandomIntBetween(20, 100); int iters = scaledRandomIntBetween(20, 100);
for (int i = 0; i < iters; i++) { for (int i = 0; i < iters; i++) {
Version v = ElasticsearchTestCase.randomVersion(random()); Version v = VersionTestUtil.randomVersion(random());
Settings settings = ImmutableSettings.settingsBuilder() Settings settings = ImmutableSettings.settingsBuilder()
.put("index.analysis.filter.my_english.type", "stemmer") .put("index.analysis.filter.my_english.type", "stemmer")
.put("index.analysis.filter.my_english.language", "english") .put("index.analysis.filter.my_english.language", "english")
@ -80,7 +80,7 @@ public class StemmerTokenFilterFactoryTests extends ElasticsearchTokenStreamTest
int iters = scaledRandomIntBetween(20, 100); int iters = scaledRandomIntBetween(20, 100);
for (int i = 0; i < iters; i++) { for (int i = 0; i < iters; i++) {
Version v = ElasticsearchTestCase.randomVersion(random()); Version v = VersionTestUtil.randomVersion(random());
Settings settings = ImmutableSettings.settingsBuilder() Settings settings = ImmutableSettings.settingsBuilder()
.put("index.analysis.filter.my_porter2.type", "stemmer") .put("index.analysis.filter.my_porter2.type", "stemmer")
.put("index.analysis.filter.my_porter2.language", "porter2") .put("index.analysis.filter.my_porter2.language", "porter2")

View File

@ -31,7 +31,6 @@ import org.elasticsearch.common.compress.CompressedString;
import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.joda.Joda; import org.elasticsearch.common.joda.Joda;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent; 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.*;
import org.elasticsearch.index.mapper.internal.TimestampFieldMapper; import org.elasticsearch.index.mapper.internal.TimestampFieldMapper;
import org.elasticsearch.test.ElasticsearchSingleNodeTest; import org.elasticsearch.test.ElasticsearchSingleNodeTest;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Test; import org.junit.Test;
import java.io.IOException; import java.io.IOException;
@ -51,6 +49,9 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; 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.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
@ -92,7 +93,7 @@ public class TimestampMappingTests extends ElasticsearchSingleNodeTest {
@Test @Test
public void testDefaultValues() throws Exception { 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( for (String mapping : Arrays.asList(
XContentFactory.jsonBuilder().startObject().startObject("type").endObject().string(), XContentFactory.jsonBuilder().startObject().startObject("type").endObject().string(),
XContentFactory.jsonBuilder().startObject().startObject("type").startObject("_timestamp").endObject().endObject().string())) { XContentFactory.jsonBuilder().startObject().startObject("type").startObject("_timestamp").endObject().endObject().string())) {

View File

@ -36,6 +36,7 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; 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.is;
import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.notNullValue;
@ -64,7 +65,7 @@ public class PreBuiltAnalyzerIntegrationTests extends ElasticsearchIntegrationTe
PreBuiltAnalyzers preBuiltAnalyzer = PreBuiltAnalyzers.values()[randomInt]; PreBuiltAnalyzers preBuiltAnalyzer = PreBuiltAnalyzers.values()[randomInt];
String name = preBuiltAnalyzer.name().toLowerCase(Locale.ROOT); String name = preBuiltAnalyzer.name().toLowerCase(Locale.ROOT);
Version randomVersion = randomVersion(); Version randomVersion = randomVersion(random());
if (!loadedAnalyzers.containsKey(preBuiltAnalyzer)) { if (!loadedAnalyzers.containsKey(preBuiltAnalyzer)) {
loadedAnalyzers.put(preBuiltAnalyzer, Lists.<Version>newArrayList()); loadedAnalyzers.put(preBuiltAnalyzer, Lists.<Version>newArrayList());
} }
@ -138,7 +139,7 @@ public class PreBuiltAnalyzerIntegrationTests extends ElasticsearchIntegrationTe
.endObject() .endObject()
.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.type", "custom")
.put("index.analysis.analyzer.my_dummy.filter", "my_dummy_token_filter") .put("index.analysis.analyzer.my_dummy.filter", "my_dummy_token_filter")
.put("index.analysis.analyzer.my_dummy.char_filter", "my_dummy_char_filter") .put("index.analysis.analyzer.my_dummy.char_filter", "my_dummy_char_filter")

View File

@ -39,6 +39,7 @@ import java.util.Collections;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
public class RecoveryStateTest extends ElasticsearchTestCase { public class RecoveryStateTest extends ElasticsearchTestCase {
@ -52,7 +53,7 @@ public class RecoveryStateTest extends ElasticsearchTestCase {
final Version streamVersion; final Version streamVersion;
Streamer(AtomicBoolean shouldStop, T source) { Streamer(AtomicBoolean shouldStop, T source) {
this(shouldStop, source, randomVersion()); this(shouldStop, source, randomVersion(random()));
} }
Streamer(AtomicBoolean shouldStop, T source, Version streamVersion) { Streamer(AtomicBoolean shouldStop, T source, Version streamVersion) {

View File

@ -33,6 +33,7 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.util.Collections; import java.util.Collections;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.nullValue;
@ -42,7 +43,7 @@ public class StartRecoveryRequestTest extends ElasticsearchTestCase {
@Test @Test
public void testSerialization() throws Exception { public void testSerialization() throws Exception {
Version targetNodeVersion = randomVersion(); Version targetNodeVersion = randomVersion(random());
StartRecoveryRequest outRequest = new StartRecoveryRequest( StartRecoveryRequest outRequest = new StartRecoveryRequest(
new ShardId("test", 0), new ShardId("test", 0),
new DiscoveryNode("a", new LocalTransportAddress("1"), targetNodeVersion), new DiscoveryNode("a", new LocalTransportAddress("1"), targetNodeVersion),

View File

@ -39,6 +39,8 @@ import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import static org.elasticsearch.Version.CURRENT;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
/** /**
@ -149,7 +151,7 @@ public class IndicesStoreTests extends ElasticsearchTestCase {
int numReplicas = randomInt(2); int numReplicas = randomInt(2);
// Most of the times don't test bwc and use current version // 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.Builder clusterState = ClusterState.builder(new ClusterName("test"));
clusterState.metaData(MetaData.builder().put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(numShards).numberOfReplicas(numReplicas))); 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))); 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.Builder clusterState = ClusterState.builder(new ClusterName("test"));
clusterState.metaData(MetaData.builder().put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(numShards).numberOfReplicas(numReplicas))); 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()) clusterState.nodes(DiscoveryNodes.builder().localNodeId(localNode.id())
.put(localNode) .put(localNode)

View File

@ -581,7 +581,7 @@ public class MoreLikeThisActionTests extends ElasticsearchIntegrationTest {
logger.info("Indexing a single document ..."); logger.info("Indexing a single document ...");
XContentBuilder doc = jsonBuilder().startObject(); XContentBuilder doc = jsonBuilder().startObject();
for (int i = 0; i < numFields; i++) { for (int i = 0; i < numFields; i++) {
doc.field("field"+i, generateRandomStringArray(5, 10)); doc.field("field"+i, generateRandomStringArray(5, 10, false));
} }
doc.endObject(); doc.endObject();
indexRandom(true, client().prepareIndex("test", "type1", "0").setSource(doc)); indexRandom(true, client().prepareIndex("test", "type1", "0").setSource(doc));

View File

@ -32,7 +32,6 @@ import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.aggregations.InternalAggregations; import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.*; import org.elasticsearch.search.aggregations.bucket.significant.heuristics.*;
import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.elasticsearch.test.ElasticsearchTestCase; import org.elasticsearch.test.ElasticsearchTestCase;
import org.elasticsearch.test.TestSearchContext; import org.elasticsearch.test.TestSearchContext;
import org.junit.Test; import org.junit.Test;
@ -45,6 +44,7 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo;
@ -76,7 +76,7 @@ public class SignificanceHeuristicTests extends ElasticsearchTestCase {
SignificanceHeuristicStreams.registerStream(GND.STREAM, GND.STREAM.getName()); SignificanceHeuristicStreams.registerStream(GND.STREAM, GND.STREAM.getName());
SignificanceHeuristicStreams.registerStream(ChiSquare.STREAM, ChiSquare.STREAM.getName()); SignificanceHeuristicStreams.registerStream(ChiSquare.STREAM, ChiSquare.STREAM.getName());
SignificanceHeuristicStreams.registerStream(ScriptHeuristic.STREAM, ScriptHeuristic.STREAM.getName()); SignificanceHeuristicStreams.registerStream(ScriptHeuristic.STREAM, ScriptHeuristic.STREAM.getName());
Version version = ElasticsearchIntegrationTest.randomVersion(); Version version = randomVersion(random());
InternalSignificantTerms[] sigTerms = getRandomSignificantTerms(getRandomSignificanceheuristic()); InternalSignificantTerms[] sigTerms = getRandomSignificantTerms(getRandomSignificanceheuristic());
// write // write

View File

@ -53,13 +53,13 @@ import java.util.Random;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutionException; 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.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.FilterBuilders.*; import static org.elasticsearch.index.query.FilterBuilders.*;
import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.scriptFunction; 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.elasticsearch.test.hamcrest.ElasticsearchAssertions.*;
import static org.hamcrest.Matchers.*; 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(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")); assertThat(ex.getCause().getMessage(), equalTo("'omit_term_freq_and_positions' is not supported anymore - use ['index_options' : 'docs'] instead"));
} }
version = randomVersion(); version = randomVersion(random());
} }
} }

View File

@ -158,7 +158,7 @@ public class DuelScrollTests extends ElasticsearchIntegrationTest {
int scrollRequestSize = randomIntBetween(1, rarely() ? numDocs : numDocs / 2); int scrollRequestSize = randomIntBetween(1, rarely() ? numDocs : numDocs / 2);
boolean unevenRouting = randomBoolean(); boolean unevenRouting = randomBoolean();
int numMissingDocs = atMost(numDocs / 100); int numMissingDocs = scaledRandomIntBetween(0, numDocs / 100);
IntOpenHashSet missingDocs = new IntOpenHashSet(numMissingDocs); IntOpenHashSet missingDocs = new IntOpenHashSet(numMissingDocs);
for (int i = 0; i < numMissingDocs; i++) { for (int i = 0; i < numMissingDocs; i++) {
while (!missingDocs.add(randomInt(numDocs))) {} while (!missingDocs.add(randomInt(numDocs))) {}

View File

@ -21,7 +21,6 @@ package org.elasticsearch.test;
import com.carrotsearch.randomizedtesting.RandomizedContext; import com.carrotsearch.randomizedtesting.RandomizedContext;
import com.carrotsearch.randomizedtesting.RandomizedTest; import com.carrotsearch.randomizedtesting.RandomizedTest;
import com.carrotsearch.randomizedtesting.annotations.Listeners; import com.carrotsearch.randomizedtesting.annotations.Listeners;
import com.carrotsearch.randomizedtesting.annotations.TestGroup;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope; 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.RandomPicks;
import com.carrotsearch.randomizedtesting.generators.RandomStrings; import com.carrotsearch.randomizedtesting.generators.RandomStrings;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.uninverting.UninvertingReader; import org.apache.lucene.uninverting.UninvertingReader;
import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.LuceneTestCase;
@ -62,28 +60,18 @@ import org.junit.After;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Ignore;
import java.io.Closeable; import java.io.Closeable;
import java.io.IOException; 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.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.Formatter; import java.util.Formatter;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; 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 // old helper stuff, a lot of it is bad news and we should see if its all used
/** /** Shortcut for {@link RandomizedContext#getRandom()}. Use {@link #random()} instead. */
* Shortcut for {@link RandomizedContext#getRandom()}. Even though this method
* is static, it returns per-thread {@link Random} instance, so no race conditions
* can occur.
*
* <p>It is recommended that specific methods are used to pick random values.
*/
public static Random getRandom() { public static Random getRandom() {
// TODO: replace uses of this function with random()
return random(); return random();
} }
/** /** Shortcut for {@link RandomizedContext#current()}. */
* Shortcut for {@link RandomizedContext#current()}.
*/
public static RandomizedContext getContext() { public static RandomizedContext getContext() {
return RandomizedTest.getContext(); return RandomizedTest.getContext();
} }
@ -309,92 +290,69 @@ public abstract class ElasticsearchTestCase extends LuceneTestCase {
public static boolean randomBoolean() { public static boolean randomBoolean() {
return random().nextBoolean(); 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(); }
/** public static byte randomByte() { return (byte) random().nextInt(); }
* Pick a random object from the given array. The array must not be empty. 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> T randomFrom(T... array) { public static <T> T randomFrom(T... array) {
return RandomPicks.randomFrom(random(), 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> T randomFrom(List<T> list) { public static <T> T randomFrom(List<T> list) {
return RandomPicks.randomFrom(random(), 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) { 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) { public static String randomAsciiOfLengthBetween(int minCodeUnits, int maxCodeUnits) {
return RandomizedTest.randomAsciiOfLengthBetween(minCodeUnits, maxCodeUnits); return RandomizedTest.randomAsciiOfLengthBetween(minCodeUnits, maxCodeUnits);
} }
/** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */
public static String randomAsciiOfLength(int codeUnits) { public static String randomAsciiOfLength(int codeUnits) {
return RandomizedTest.randomAsciiOfLength(codeUnits); return RandomizedTest.randomAsciiOfLength(codeUnits);
} }
/** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */
public static String randomUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) { public static String randomUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) {
return RandomizedTest.randomUnicodeOfLengthBetween(minCodeUnits, maxCodeUnits); return RandomizedTest.randomUnicodeOfLengthBetween(minCodeUnits, maxCodeUnits);
} }
/** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */
public static String randomUnicodeOfLength(int codeUnits) { public static String randomUnicodeOfLength(int codeUnits) {
return RandomizedTest.randomUnicodeOfLength(codeUnits); return RandomizedTest.randomUnicodeOfLength(codeUnits);
} }
/** @see StringGenerator#ofCodePointsLength(Random, int, int) */
public static String randomUnicodeOfCodepointLengthBetween(int minCodePoints, int maxCodePoints) { public static String randomUnicodeOfCodepointLengthBetween(int minCodePoints, int maxCodePoints) {
return RandomizedTest.randomUnicodeOfCodepointLengthBetween(minCodePoints, maxCodePoints); return RandomizedTest.randomUnicodeOfCodepointLengthBetween(minCodePoints, maxCodePoints);
} }
/** @see StringGenerator#ofCodePointsLength(Random, int, int) */
public static String randomUnicodeOfCodepointLength(int codePoints) { public static String randomUnicodeOfCodepointLength(int codePoints) {
return RandomizedTest.randomUnicodeOfCodepointLength(codePoints); return RandomizedTest.randomUnicodeOfCodepointLength(codePoints);
} }
/** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */
public static String randomRealisticUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) { public static String randomRealisticUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) {
return RandomizedTest.randomRealisticUnicodeOfLengthBetween(minCodeUnits, maxCodeUnits); return RandomizedTest.randomRealisticUnicodeOfLengthBetween(minCodeUnits, maxCodeUnits);
} }
/** @see StringGenerator#ofCodeUnitsLength(Random, int, int) */
public static String randomRealisticUnicodeOfLength(int codeUnits) { public static String randomRealisticUnicodeOfLength(int codeUnits) {
return RandomizedTest.randomRealisticUnicodeOfLength(codeUnits); return RandomizedTest.randomRealisticUnicodeOfLength(codeUnits);
} }
/** @see StringGenerator#ofCodePointsLength(Random, int, int) */
public static String randomRealisticUnicodeOfCodepointLengthBetween(int minCodePoints, int maxCodePoints) { public static String randomRealisticUnicodeOfCodepointLengthBetween(int minCodePoints, int maxCodePoints) {
return RandomizedTest.randomRealisticUnicodeOfCodepointLengthBetween(minCodePoints, maxCodePoints); return RandomizedTest.randomRealisticUnicodeOfCodepointLengthBetween(minCodePoints, maxCodePoints);
} }
/** @see StringGenerator#ofCodePointsLength(Random, int, int) */
public static String randomRealisticUnicodeOfCodepointLength(int codePoints) { public static String randomRealisticUnicodeOfCodepointLength(int codePoints) {
return RandomizedTest.randomRealisticUnicodeOfCodepointLength(codePoints); return RandomizedTest.randomRealisticUnicodeOfCodepointLength(codePoints);
} }
/**
* Returns a non-negative random value smaller or equal <code>max</code>.
* @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. * 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<Version> SORTED_VERSIONS;
static {
Field[] declaredFields = Version.class.getDeclaredFields();
Set<Integer> 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<Integer> idList = new ArrayList<>(ids);
Collections.sort(idList);
Collections.reverse(idList);
ImmutableList.Builder<Version> 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<Version> allVersions() {
return Collections.unmodifiableList(SORTED_VERSIONS);
}
/**
* A random {@link Version} from <code>minVersion</code> to
* <code>maxVersion</code> (inclusive).
*
* @param minVersion
* the minimum version (inclusive)
* @param maxVersion
* the maximum version (inclusive)
* @return a random {@link Version} from <code>minVersion</code> to
* <code>maxVersion</code> (inclusive)
*/
public static Version randomVersionBetween(Version minVersion, Version maxVersion) {
return randomVersionBetween(random(), minVersion, maxVersion);
}
/**
* A random {@link Version} from <code>minVersion</code> to
* <code>maxVersion</code> (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 <code>minVersion</code> to
* <code>maxVersion</code> (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. * Return consistent index settings for the provided index version.
*/ */
@ -618,7 +463,6 @@ public abstract class ElasticsearchTestCase extends LuceneTestCase {
this.parent = parent; this.parent = parent;
} }
@Override @Override
public void uncaughtException(Thread t, Throwable e) { public void uncaughtException(Thread t, Throwable e) {
if (e instanceof EsRejectedExecutionException) { if (e instanceof EsRejectedExecutionException) {
@ -632,7 +476,6 @@ public abstract class ElasticsearchTestCase extends LuceneTestCase {
} }
parent.uncaughtException(t, e); parent.uncaughtException(t, e);
} }
} }
protected static final void printStackDump(ESLogger logger) { protected static final void printStackDump(ESLogger logger) {
@ -690,11 +533,6 @@ public abstract class ElasticsearchTestCase extends LuceneTestCase {
return array; return array;
} }
public static String[] generateRandomStringArray(int maxArraySize, int maxStringSize) {
return generateRandomStringArray(maxArraySize, maxStringSize, false);
}
public static boolean terminate(ExecutorService... services) throws InterruptedException { public static boolean terminate(ExecutorService... services) throws InterruptedException {
boolean terminated = true; boolean terminated = true;
for (ExecutorService service : services) { for (ExecutorService service : services) {

View File

@ -20,9 +20,6 @@
package org.elasticsearch.test; package org.elasticsearch.test;
import com.carrotsearch.randomizedtesting.annotations.Listeners; 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 com.carrotsearch.randomizedtesting.annotations.TimeoutSuite;
import org.apache.lucene.analysis.BaseTokenStreamTestCase; import org.apache.lucene.analysis.BaseTokenStreamTestCase;
@ -50,7 +47,7 @@ public abstract class ElasticsearchTokenStreamTestCase extends BaseTokenStreamTe
} }
public static Version randomVersion() { public static Version randomVersion() {
return ElasticsearchTestCase.randomVersion(random()); return VersionTestUtil.randomVersion(random());
} }
public ImmutableSettings.Builder newAnalysisSettingsBuilder() { public ImmutableSettings.Builder newAnalysisSettingsBuilder() {

View File

@ -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<Version> SORTED_VERSIONS;
static {
Field[] declaredFields = Version.class.getDeclaredFields();
Set<Integer> 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<Integer> idList = new ArrayList<>(ids);
Collections.sort(idList);
Collections.reverse(idList);
ImmutableList.Builder<Version> 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<Version> 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 <code>minVersion</code> and <code>maxVersion</code> (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));
}
}
}

View File

@ -23,11 +23,9 @@ import com.google.common.primitives.Ints;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.elasticsearch.test.InternalTestCluster; import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.test.SettingsSource; import org.elasticsearch.test.SettingsSource;
import org.elasticsearch.transport.local.LocalTransport; import org.elasticsearch.transport.local.LocalTransport;
import org.omg.CORBA.INTERNAL;
import java.io.IOException; import java.io.IOException;
import java.net.ServerSocket; import java.net.ServerSocket;
@ -42,10 +40,6 @@ public class ClusterDiscoveryConfiguration extends SettingsSource {
final Settings nodeSettings; final Settings nodeSettings;
final Settings transportClientSettings; final Settings transportClientSettings;
public ClusterDiscoveryConfiguration(int numOfNodes) {
this(numOfNodes, ImmutableSettings.EMPTY);
}
public ClusterDiscoveryConfiguration(int numOfNodes, Settings extraSettings) { public ClusterDiscoveryConfiguration(int numOfNodes, Settings extraSettings) {
this.numOfNodes = numOfNodes; this.numOfNodes = numOfNodes;
this.nodeSettings = ImmutableSettings.builder().put(DEFAULT_NODE_SETTINGS).put(extraSettings).build(); this.nodeSettings = ImmutableSettings.builder().put(DEFAULT_NODE_SETTINGS).put(extraSettings).build();

View File

@ -64,6 +64,7 @@ import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.rest.RestStatus; import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.suggest.Suggest; import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.test.VersionTestUtil;
import org.elasticsearch.test.engine.AssertingSearcher; import org.elasticsearch.test.engine.AssertingSearcher;
import org.elasticsearch.test.engine.MockInternalEngine; import org.elasticsearch.test.engine.MockInternalEngine;
import org.elasticsearch.test.engine.MockShadowEngine; 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 com.google.common.base.Predicates.isNull;
import static org.elasticsearch.test.ElasticsearchTestCase.*; import static org.elasticsearch.test.ElasticsearchTestCase.*;
import static org.elasticsearch.test.VersionTestUtil.randomVersion;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
@ -585,8 +587,8 @@ public class ElasticsearchAssertions {
} }
public static void assertVersionSerializable(Streamable streamable) { public static void assertVersionSerializable(Streamable streamable) {
assertTrue(Version.CURRENT.after(getPreviousVersion())); assertTrue(Version.CURRENT.after(VersionTestUtil.getPreviousVersion()));
assertVersionSerializable(randomVersion(), streamable); assertVersionSerializable(randomVersion(random()), streamable);
} }
public static void assertVersionSerializable(Version version, Streamable streamable) { public static void assertVersionSerializable(Version version, Streamable streamable) {

View File

@ -24,7 +24,7 @@ import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.elasticsearch.test.ElasticsearchTestCase; import org.elasticsearch.test.VersionTestUtil;
import org.elasticsearch.test.hamcrest.ElasticsearchAssertions; import org.elasticsearch.test.hamcrest.ElasticsearchAssertions;
import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*; import org.elasticsearch.transport.*;
@ -55,13 +55,13 @@ public class AssertingLocalTransport extends LocalTransport {
@Override @Override
protected void handleParsedResponse(final TransportResponse response, final TransportResponseHandler handler) { 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); super.handleParsedResponse(response, handler);
} }
@Override @Override
public void sendRequest(final DiscoveryNode node, final long requestId, final String action, final TransportRequest request, TransportRequestOptions options) throws IOException, TransportException { 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); super.sendRequest(node, requestId, action, request, options);
} }
} }