Package org.elasticsearch.test
Class ESTestCase
java.lang.Object
org.junit.Assert
org.apache.lucene.util.LuceneTestCase
org.elasticsearch.test.ESTestCase
- Direct Known Subclasses:
AbstractAsyncBulkByScrollActionTestCase
,AbstractBlobContainerRetriesTestCase
,AbstractBootstrapCheckTestCase
,AbstractBuilderTestCase
,AbstractBytesReferenceTestCase
,AbstractCoordinatorTestCase
,AbstractFilteringTestCase
,AbstractHttpServerTransportTestCase
,AbstractMultiClustersTestCase
,AbstractSchemaValidationTestCase
,AbstractSignificanceHeuristicTestCase
,AbstractSimpleTransportTestCase
,AbstractWireTestCase
,AbstractXContentTestCase
,AggregatorTestCase
,AnalysisFactoryTestCase
,BasePipelineAggregationTestCase
,CommandTestCase
,EngineTestCase
,ESAllocationTestCase
,ESIndexInputTestCase
,ESIntegTestCase
,ESRestTestCase
,ESSingleNodeTestCase
,FieldTypeTestCase
,IndexShardTestCase
,MapperServiceTestCase
,ModuleTestCase
,RestActionTestCase
,RestClientBuilderTestCase
@Listeners({ReproduceInfoPrinter.class,LoggingListener.class})
@SuppressSysoutChecks(bugUrl="we log a lot on purpose")
@SuppressCodecs({"SimpleText","Memory","CheapBastard","Direct","Compressing","FST50","FSTOrd50","TestBloomFilteredLucenePostings","MockRandom","BlockTreeOrds","LuceneFixedGap","LuceneVarGapFixedInterval","LuceneVarGapDocFreqInterval","Lucene50"})
@SuppressReproduceLine
public abstract class ESTestCase
extends LuceneTestCase
Base testcase for randomized unit testing with Elasticsearch
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic final class
static class
static final class
This cute helper class just holds all analysis building blocks that are used to build IndexAnalyzers.Nested classes/interfaces inherited from class org.apache.lucene.util.LuceneTestCase
LuceneTestCase.AwaitsFix, LuceneTestCase.BadApple, LuceneTestCase.Monster, LuceneTestCase.Nightly, LuceneTestCase.Slow, LuceneTestCase.SuppressCodecs, LuceneTestCase.SuppressFileSystems, LuceneTestCase.SuppressFsync, LuceneTestCase.SuppressReproduceLine, LuceneTestCase.SuppressSysoutChecks, LuceneTestCase.SuppressTempFileChecks, LuceneTestCase.ThrowingRunnable, LuceneTestCase.Weekly
-
Field Summary
Modifier and TypeFieldDescriptionMockFSDirectoryService sets this:protected static final NamedWriteableRegistry
static final String
org.junit.rules.RuleChain
static final String
protected final org.apache.logging.log4j.Logger
protected static final int
Defines the minimum port that test workers should use.static final String
static final String
Fields inherited from class org.apache.lucene.util.LuceneTestCase
assertsAreEnabled, classRules, DEFAULT_LINE_DOCS_FILE, INFOSTREAM, JENKINS_LARGE_LINE_DOCS_FILE, LEAVE_TEMPORARY, MAYBE_CACHE_POLICY, RANDOM_MULTIPLIER, ruleChain, suiteFailureMarker, SYSPROP_AWAITSFIX, SYSPROP_BADAPPLES, SYSPROP_FAILFAST, SYSPROP_MAXFAILURES, SYSPROP_MONSTER, SYSPROP_NIGHTLY, SYSPROP_SLOW, SYSPROP_WEEKLY, TEST_ASSERTS_ENABLED, TEST_AWAITSFIX, TEST_BADAPPLES, TEST_CODEC, TEST_DIRECTORY, TEST_DOCVALUESFORMAT, TEST_LINE_DOCS_FILE, TEST_MONSTER, TEST_NIGHTLY, TEST_POSTINGSFORMAT, TEST_SLOW, TEST_THROTTLING, TEST_WEEKLY, VERBOSE
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionfinal void
after()
protected void
afterIfFailed
(List<Throwable> errors) Called when a test fails, supplying the errors it generated.protected void
called after a test is finished, but only if successfulprotected final void
allowedWarnings
(String... allowedWarnings) Allow the given warnings, but don't require their presence.static void
assertArrayEquals
(StackTraceElement[] expected, StackTraceElement[] actual) Compares two stack traces, ignoring module (which is not yet serialized)static void
assertBusy
(org.elasticsearch.core.CheckedRunnable<Exception> codeBlock) Runs the code block for 10 seconds waiting for no assertion to trip.static void
assertBusy
(org.elasticsearch.core.CheckedRunnable<Exception> codeBlock, long maxWaitTime, TimeUnit unit) Runs the code block for the provided interval, waiting for no assertions to trip.static void
assertEquals
(StackTraceElement expected, StackTraceElement actual) Compares two stack trace elements, ignoring module (which is not yet serialized)protected final void
assertSettingDeprecationsAndWarnings
(Setting<?>[] settings, ESTestCase.DeprecationWarning... warnings) Convenience method to assert warnings for settings deprecations and general deprecation warnings.protected final void
assertWarnings
(boolean stripXContentPosition, ESTestCase.DeprecationWarning... expectedWarnings) protected final void
assertWarnings
(String... expectedWarnings) Convenience method to assert warnings for settings deprecations and general deprecation warnings.protected final void
assertWarnings
(org.apache.logging.log4j.Level level, String... expectedWarnings) Convenience method to assert warnings at a specific level for settings deprecations and general deprecation warnings.final void
before()
static int
between
(int min, int max) An alias forrandomIntBetween(int, int)
.buildEnvSettings
(Settings settings) static TransportAddress
Generates a new transport address usingTransportAddress.META_ADDRESS
with an incrementing port number.protected static void
static void
protected static <T> T
copyInstance
(T original, NamedWriteableRegistry namedWriteableRegistry, Writeable.Writer<T> writer, Writeable.Reader<T> reader, Version version) static <T extends NamedWriteable>
TcopyNamedWriteable
(T original, NamedWriteableRegistry namedWriteableRegistry, Class<T> categoryClass) Create a copy of an originalNamedWriteable
object by running it through aBytesStreamOutput
and reading it in again using a providedWriteable.Reader
.static <T extends NamedWriteable>
TcopyNamedWriteable
(T original, NamedWriteableRegistry namedWriteableRegistry, Class<T> categoryClass, Version version) Same ascopyNamedWriteable(NamedWriteable, NamedWriteableRegistry, Class)
but also allows to provide aVersion
argument which will be used to write and read back the object.static <T extends Writeable>
TcopyWriteable
(T original, NamedWriteableRegistry namedWriteableRegistry, Writeable.Reader<T> reader) Create a copy of an originalWriteable
object by running it through aBytesStreamOutput
and reading it in again using a providedWriteable.Reader
.static <T extends Writeable>
TcopyWriteable
(T original, NamedWriteableRegistry namedWriteableRegistry, Writeable.Reader<T> reader, Version version) Same ascopyWriteable(Writeable, NamedWriteableRegistry, Writeable.Reader)
but also allows to provide aVersion
argument which will be used to write and read back the object.protected IndexAnalyzers
Creates an IndexAnalyzers with a single default analyzerprotected final org.elasticsearch.xcontent.XContentParser
createParser
(org.elasticsearch.xcontent.NamedXContentRegistry namedXContentRegistry, org.elasticsearch.xcontent.XContent xContent, BytesReference data) Create a newXContentParser
.protected final org.elasticsearch.xcontent.XContentParser
createParser
(org.elasticsearch.xcontent.XContentBuilder builder) Create a newXContentParser
.protected final org.elasticsearch.xcontent.XContentParser
createParser
(org.elasticsearch.xcontent.XContent xContent, byte[] data) Create a newXContentParser
.protected final org.elasticsearch.xcontent.XContentParser
createParser
(org.elasticsearch.xcontent.XContent xContent, InputStream data) Create a newXContentParser
.protected final org.elasticsearch.xcontent.XContentParser
createParser
(org.elasticsearch.xcontent.XContent xContent, String data) Create a newXContentParser
.protected final org.elasticsearch.xcontent.XContentParser
createParser
(org.elasticsearch.xcontent.XContent xContent, BytesReference data) Create a newXContentParser
.static ESTestCase.TestAnalysis
createTestAnalysis
(Index index, Settings nodeSettings, Settings settings, AnalysisPlugin... analysisPlugins) Creates an TestAnalysis with all the default analyzers configured.static ESTestCase.TestAnalysis
createTestAnalysis
(Index index, Settings settings, AnalysisPlugin... analysisPlugins) Creates an TestAnalysis with all the default analyzers configured.static ESTestCase.TestAnalysis
createTestAnalysis
(IndexSettings indexSettings, Settings nodeSettings, AnalysisPlugin... analysisPlugins) Creates an TestAnalysis with all the default analyzers configured.protected boolean
protected boolean
Whether or not we check after each test whether it has left warnings behind.final void
final void
void
static void
static boolean
The exact opposite ofLuceneTestCase.rarely()
.static String[]
generateRandomStringArray
(int maxArraySize, int stringSize, boolean allowNull) static String[]
generateRandomStringArray
(int maxArraySize, int stringSize, boolean allowNull, boolean allowEmpty) getDataPath
(String relativePath) Returns aPath
pointing to the class path relative resource given as the first argument.static String
Returns a port range for this JVM according to its Gradle worker ID.static TestRuleMarkFailure
Returns the suite failure marker: internal use only!static String
protected static int
Returns the start of the port range for this JVM according to its Gradle worker ID.static boolean
protected static boolean
static int
iterations
(int min, int max) Returns a "scaled" number of iterations for loops which can have a variable iteration count.static <T> void
helper to randomly perform onconsumer
withvalue
static Script
mockScript
(String id) Create a "mock" script for use either withMockScriptEngine
or anywhere where you need a script but don't really care about its contents.newEnvironment
(Settings settings) newNodeEnvironment
(Settings settings) static String
randomAlphaOfLength
(int codeUnits) static String
randomAlphaOfLengthBetween
(int minCodeUnits, int maxCodeUnits) static <T> T[]
randomArray
(int minArraySize, int maxArraySize, IntFunction<T[]> arrayConstructor, Supplier<T> valueConstructor) static <T> T[]
randomArray
(int maxArraySize, IntFunction<T[]> arrayConstructor, Supplier<T> valueConstructor) static BigInteger
Returns a random BigInteger uniformly distributed over the range 0 to (2^64 - 1) inclusive Currently BigIntegers are only used for unsigned_long field type, where the max value is 2^64 - 1.static boolean
static byte
static byte[]
randomByteArrayOfLength
(int size) Helper method to create a byte array of a given length populated with random byte valuesstatic String
Generate a random valid date formatter pattern.static org.joda.time.DateTimeZone
generate a random DateTimeZone from the ones available in joda librarystatic double
static double
randomDoubleBetween
(double start, double end, boolean lowerInclusive) Returns a double value in the interval [start, end) if lowerInclusive is set to true, (start, end) otherwise.static float
static <T> T
randomFrom
(Collection<T> collection) Pick a random object from the given collection.static <T> T
randomFrom
(List<T> list) Pick a random object from the given list.static <T> T
randomFrom
(Random random, Collection<T> collection) Pick a random object from the given collection.static <T> T
randomFrom
(Random random, Supplier<T>... array) Pick a random object from the given array of suppliers.static <T> T
randomFrom
(Random random, T... array) Pick a random object from the given array.static <T> T
randomFrom
(T... array) Pick a random object from the given array.static String
randomGeohash
(int minPrecision, int maxPrecision) static int
static int
randomInt
(int max) A random integer from 0..max (inclusive).static int
randomIntBetween
(int min, int max) A random integer frommin
tomax
(inclusive).protected static InetAddress
randomIp
(boolean v4) static <T> List<T>
randomList
(int minListSize, int maxListSize, Supplier<T> valueConstructor) static <T> List<T>
randomList
(int maxListSize, Supplier<T> valueConstructor) static long
static long
randomLongBetween
(long min, long max) A random long number between min (inclusive) and max (inclusive).static <K,
V> Map<K, V> randomMap
(int minMapSize, int maxMapSize, Supplier<org.elasticsearch.core.Tuple<K, V>> entryConstructor) long
generate a random epoch millis in a range 1 to 9999-12-31T23:59:59.999static <T> List<T>
randomNonEmptySubsetOf
(Collection<T> collection) static byte
static long
static String
static String
randomRealisticUnicodeOfCodepointLength
(int codePoints) static String
randomRealisticUnicodeOfCodepointLengthBetween
(int minCodePoints, int maxCodePoints) static String
randomRealisticUnicodeOfLength
(int codeUnits) static String
randomRealisticUnicodeOfLengthBetween
(int minCodeUnits, int maxCodeUnits) static short
static <T> List<T>
randomSubsetOf
(int size, Collection<T> collection) Returns size random valuesstatic <T> List<T>
randomSubsetOf
(int size, T... values) Returns size random valuesstatic <T> List<T>
randomSubsetOf
(Collection<T> collection) Returns a random subset of values (including a potential empty list, or the full original list)static String
static String
randomTimeValue
(int lower, int upper) static String
randomTimeValue
(int lower, int upper, String... suffixes) static TimeZone
generate a random TimeZone from the ones available in java.utilstatic String
randomUnicodeOfCodepointLength
(int codePoints) static String
randomUnicodeOfCodepointLengthBetween
(int minCodePoints, int maxCodePoints) static String
randomUnicodeOfLength
(int codeUnits) static String
randomUnicodeOfLengthBetween
(int minCodeUnits, int maxCodeUnits) static <T> Set<T>
randomUnique
(Supplier<T> supplier, int targetCount) Builds a set of unique items.static <T> T
randomValueOtherThan
(T input, Supplier<T> randomSupplier) helper to get a random value in a certain range that's different from the inputstatic <T> T
randomValueOtherThanMany
(Predicate<T> input, Supplier<T> randomSupplier) helper to get a random value in a certain range that's different from the inputstatic ZoneId
generate a random TimeZone from the ones available in java.timevoid
final void
static void
static void
static void
static void
safeAwait
(CountDownLatch countDownLatch) static void
safeAwait
(CyclicBarrier barrier) static int
scaledRandomIntBetween
(int min, int max) Returns a "scaled" random number between min and max (inclusive).static void
static void
void
static Settings.Builder
Return consistent index settings for the provided index version.static LinkedHashMap<String,
Object> shuffleMap
(LinkedHashMap<String, Object> map, Set<String> exceptFields) protected final org.elasticsearch.xcontent.XContentBuilder
shuffleXContent
(org.elasticsearch.xcontent.XContentBuilder builder, String... exceptFieldNames) Randomly shuffles the fields inside objects in theXContentBuilder
passed in.static org.elasticsearch.xcontent.XContentBuilder
shuffleXContent
(org.elasticsearch.xcontent.XContentParser parser, boolean prettyPrint, String... exceptFieldNames) Randomly shuffles the fields inside objects parsed using theXContentParser
passed in.protected static long
spinForAtLeastNMilliseconds
(long ms) protected static long
static boolean
terminate
(ExecutorService... services) static boolean
terminate
(ThreadPool threadPool) String[]
tmpPaths()
Returns a random number of temporary paths.protected final BytesReference
toShuffledXContent
(org.elasticsearch.xcontent.ToXContent toXContent, org.elasticsearch.xcontent.XContentType xContentType, org.elasticsearch.xcontent.ToXContent.Params params, boolean humanReadable, String... exceptFieldNames) Returns the bytes that represent the XContent output of the providedToXContent
object, using the providedXContentType
.static boolean
waitUntil
(BooleanSupplier breakSupplier) Periodically execute the supplied function until it returns true, or a timeout is reached.static boolean
waitUntil
(BooleanSupplier breakSupplier, long maxWaitTime, TimeUnit unit) Periodically execute the supplied function until it returns true, or until the specified maximum wait time has elapsed.protected NamedWriteableRegistry
TheNamedWriteableRegistry
to use for this test.protected org.elasticsearch.xcontent.NamedXContentRegistry
TheNamedXContentRegistry
to use for this test.Methods inherited from class org.apache.lucene.util.LuceneTestCase
addVirusChecker, assertDeletedDocsEquals, assertDocsAndPositionsEnumEquals, assertDocsEnumEquals, assertDocsSkippingEquals, assertDocValuesEquals, assertDocValuesEquals, assertFieldInfosEquals, assertNormsEquals, assertPointsEquals, assertPositionsSkippingEquals, assertReaderEquals, assertReaderStatisticsEquals, assertStoredFieldEquals, assertStoredFieldsEquals, assertTermsEnumEquals, assertTermsEquals, assertTermsEquals, assertTermsStatisticsEquals, assertTermStatsEquals, assertTermVectorsEquals, asSet, assumeFalse, assumeNoException, assumeTrue, assumeWorkingMMapOnWindows, atLeast, atLeast, callStackContains, callStackContains, callStackContainsAnyOf, closeAfterSuite, closeAfterTest, collate, createTempDir, createTempDir, createTempFile, createTempFile, dumpArray, dumpIterator, ensureSaneIWCOnNightly, expectThrows, expectThrows, expectThrows, expectThrowsAnyOf, expectThrowsAnyOf, getBaseTempDirForTestClass, getDataInputStream, getOnlyLeafReader, getTestClass, getTestName, hasWorkingMMapOnWindows, isTestThread, localeForLanguageTag, maybeChangeLiveIndexWriterConfig, maybeWrapReader, newAlcoholicMergePolicy, newAlcoholicMergePolicy, newBytesRef, newBytesRef, newBytesRef, newBytesRef, newBytesRef, newBytesRef, newDirectory, newDirectory, newDirectory, newDirectory, newDirectory, newField, newField, newFSDirectory, newFSDirectory, newIndexWriterConfig, newIndexWriterConfig, newIndexWriterConfig, newIOContext, newIOContext, newLogMergePolicy, newLogMergePolicy, newLogMergePolicy, newLogMergePolicy, newLogMergePolicy, newMaybeVirusCheckingDirectory, newMaybeVirusCheckingFSDirectory, newMergePolicy, newMergePolicy, newMergePolicy, newMockDirectory, newMockDirectory, newMockDirectory, newMockFSDirectory, newMockFSDirectory, newSearcher, newSearcher, newSearcher, newSearcher, newStringField, newStringField, newStringField, newStringField, newTextField, newTextField, newTieredMergePolicy, newTieredMergePolicy, overrideDefaultQueryCache, overrideTestDefaultQueryCache, random, randomLocale, randomTimeZone, rarely, rarely, replaceMaxFailureRule, resetDefaultQueryCache, restoreCPUCoreCount, restoreIndexWriterMaxDocs, restoreSpins, runWithRestrictedPermissions, setIndexWriterMaxDocs, setUp, setupCPUCoreCount, setupSpins, slowFileExists, tearDown, usually, usually, wrapReader
Methods inherited from class org.junit.Assert
assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotEquals, assertNotEquals, assertNotEquals, assertNotEquals, assertNotEquals, assertNotEquals, assertNotEquals, assertNotEquals, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertThat, assertThat, assertTrue, assertTrue, fail, fail
-
Field Details
-
JODA_TIMEZONE_IDS
-
JAVA_TIMEZONE_IDS
-
JAVA_ZONE_IDS
-
TEST_WORKER_VM_ID
-
TEST_WORKER_SYS_PROPERTY
- See Also:
-
DEFAULT_TEST_WORKER_ID
- See Also:
-
FIPS_SYSPROP
- See Also:
-
logger
protected final org.apache.logging.log4j.Logger logger -
failureAndSuccessEvents
public org.junit.rules.RuleChain failureAndSuccessEvents -
checkIndexFailures
MockFSDirectoryService sets this: -
DEFAULT_NAMED_WRITABLE_REGISTRY
-
MIN_PRIVATE_PORT
protected static final int MIN_PRIVATE_PORTDefines the minimum port that test workers should use. See also [NOTE: Port ranges for tests].- See Also:
-
-
Constructor Details
-
ESTestCase
public ESTestCase()
-
-
Method Details
-
resetPortCounter
public static void resetPortCounter() -
buildNewFakeTransportAddress
Generates a new transport address usingTransportAddress.META_ADDRESS
with an incrementing port number. The port number starts at 0 and is reset after each test suite run. -
afterIfFailed
Called when a test fails, supplying the errors it generated. Not called when the test fails because assumptions are violated. -
afterIfSuccessful
called after a test is finished, but only if successful- Throws:
Exception
-
setFileSystem
- Throws:
Exception
-
restoreFileSystem
- Throws:
Exception
-
setContentType
- Throws:
Exception
-
restoreContentType
public static void restoreContentType() -
ensureSupportedLocale
public static void ensureSupportedLocale() -
setHeaderWarningAppender
public void setHeaderWarningAppender() -
removeHeaderWarningAppender
public void removeHeaderWarningAppender() -
before
public final void before() -
clearAdditionalRoles
public static void clearAdditionalRoles() -
enableWarningsCheck
protected boolean enableWarningsCheck()Whether or not we check after each test whether it has left warnings behind. That happens if any deprecated feature or syntax was used by the test and the test didn't assert on it usingassertWarnings(String...)
. -
enableJodaDeprecationWarningsCheck
protected boolean enableJodaDeprecationWarningsCheck() -
after
- Throws:
Exception
-
ensureNoWarnings
public void ensureNoWarnings() -
filteredWarnings
-
assertSettingDeprecationsAndWarnings
protected final void assertSettingDeprecationsAndWarnings(Setting<?>[] settings, ESTestCase.DeprecationWarning... warnings) Convenience method to assert warnings for settings deprecations and general deprecation warnings.- Parameters:
settings
- the settings that are expected to be deprecatedwarnings
- other expected general deprecation warnings
-
assertWarnings
protected final void assertWarnings(org.apache.logging.log4j.Level level, String... expectedWarnings) Convenience method to assert warnings at a specific level for settings deprecations and general deprecation warnings.- Parameters:
expectedWarnings
- expected general deprecation warnings.
-
assertWarnings
Convenience method to assert warnings for settings deprecations and general deprecation warnings. All warnings passed to this method are assumed to be at DeprecationLogger.CRITICAL level.- Parameters:
expectedWarnings
- expected general deprecation warnings.
-
allowedWarnings
Allow the given warnings, but don't require their presence. -
assertWarnings
protected final void assertWarnings(boolean stripXContentPosition, ESTestCase.DeprecationWarning... expectedWarnings) -
checkStaticState
- Throws:
Exception
-
ensureAllSearchContextsReleased
- Throws:
Exception
-
resetCheckIndexStatus
- Throws:
Exception
-
ensureCheckIndexPassed
public final void ensureCheckIndexPassed() -
scaledRandomIntBetween
public static int scaledRandomIntBetween(int min, int max) Returns a "scaled" random number between min and max (inclusive).- See Also:
-
RandomizedTest.scaledRandomIntBetween(int, int)
-
randomIntBetween
public static int randomIntBetween(int min, int max) A random integer frommin
tomax
(inclusive).- See Also:
-
randomLongBetween
public static long randomLongBetween(long min, long max) A random long number between min (inclusive) and max (inclusive). -
iterations
public static int iterations(int min, int max) Returns a "scaled" number of iterations for loops which can have a variable iteration count. This method is effectively an alias toscaledRandomIntBetween(int, int)
. -
between
public static int between(int min, int max) An alias forrandomIntBetween(int, int)
.- See Also:
-
frequently
public static boolean frequently()The exact opposite ofLuceneTestCase.rarely()
. -
randomBoolean
public static boolean randomBoolean() -
randomByte
public static byte randomByte() -
randomNonNegativeByte
public static byte randomNonNegativeByte() -
randomByteArrayOfLength
public static byte[] randomByteArrayOfLength(int size) Helper method to create a byte array of a given length populated with random byte values- See Also:
-
randomShort
public static short randomShort() -
randomInt
public static int randomInt() -
randomNonNegativeLong
public static long randomNonNegativeLong()- Returns:
- a
long
between0
andLong.MAX_VALUE
(inclusive) chosen uniformly at random.
-
randomFloat
public static float randomFloat() -
randomDouble
public static double randomDouble() -
randomDoubleBetween
public static double randomDoubleBetween(double start, double end, boolean lowerInclusive) Returns a double value in the interval [start, end) if lowerInclusive is set to true, (start, end) otherwise.- Parameters:
start
- lower bound of interval to draw uniformly distributed random numbers fromend
- upper boundlowerInclusive
- whether or not to include lower end of the interval
-
randomLong
public static long randomLong() -
randomBigInteger
Returns a random BigInteger uniformly distributed over the range 0 to (2^64 - 1) inclusive Currently BigIntegers are only used for unsigned_long field type, where the max value is 2^64 - 1. Modify this random generator if a wider range for BigIntegers is necessary.- Returns:
- a random bigInteger in the range [0 ; 2^64 - 1]
-
randomInt
public static int randomInt(int max) A random integer from 0..max (inclusive). -
randomFrom
Pick a random object from the given array. The array must not be empty. -
randomFrom
Pick a random object from the given array. The array must not be empty. -
randomFrom
Pick a random object from the given array of suppliers. The array must not be empty. -
randomFrom
Pick a random object from the given list. -
randomFrom
Pick a random object from the given collection. -
randomFrom
Pick a random object from the given collection. -
randomAlphaOfLengthBetween
-
randomAlphaOfLength
-
randomUnicodeOfLengthBetween
-
randomUnicodeOfLength
-
randomUnicodeOfCodepointLengthBetween
-
randomUnicodeOfCodepointLength
-
randomRealisticUnicodeOfLengthBetween
-
randomRealisticUnicodeOfLength
-
randomRealisticUnicodeOfCodepointLengthBetween
public static String randomRealisticUnicodeOfCodepointLengthBetween(int minCodePoints, int maxCodePoints) -
randomRealisticUnicodeOfCodepointLength
-
generateRandomStringArray
public static String[] generateRandomStringArray(int maxArraySize, int stringSize, boolean allowNull, boolean allowEmpty) - Parameters:
maxArraySize
- The maximum number of elements in the random arraystringSize
- The length of each String in the arrayallowNull
- Whether the returned array may be nullallowEmpty
- Whether the returned array may be empty (have zero elements)
-
generateRandomStringArray
public static String[] generateRandomStringArray(int maxArraySize, int stringSize, boolean allowNull) -
randomArray
public static <T> T[] randomArray(int maxArraySize, IntFunction<T[]> arrayConstructor, Supplier<T> valueConstructor) -
randomArray
public static <T> T[] randomArray(int minArraySize, int maxArraySize, IntFunction<T[]> arrayConstructor, Supplier<T> valueConstructor) -
randomList
-
randomList
-
randomMap
-
randomTimeValue
-
randomTimeValue
-
randomTimeValue
-
randomPositiveTimeValue
-
randomDateTimeZone
public static org.joda.time.DateTimeZone randomDateTimeZone()generate a random DateTimeZone from the ones available in joda library -
randomMillisUpToYear9999
public long randomMillisUpToYear9999()generate a random epoch millis in a range 1 to 9999-12-31T23:59:59.999 -
randomTimeZone
generate a random TimeZone from the ones available in java.util -
randomZone
generate a random TimeZone from the ones available in java.time -
randomDateFormatterPattern
Generate a random valid date formatter pattern. -
maybeSet
helper to randomly perform onconsumer
withvalue
-
randomValueOtherThan
helper to get a random value in a certain range that's different from the input -
randomValueOtherThanMany
helper to get a random value in a certain range that's different from the input -
assertBusy
public static void assertBusy(org.elasticsearch.core.CheckedRunnable<Exception> codeBlock) throws Exception Runs the code block for 10 seconds waiting for no assertion to trip.- Throws:
Exception
-
assertBusy
public static void assertBusy(org.elasticsearch.core.CheckedRunnable<Exception> codeBlock, long maxWaitTime, TimeUnit unit) throws Exception Runs the code block for the provided interval, waiting for no assertions to trip.- Throws:
Exception
-
waitUntil
Periodically execute the supplied function until it returns true, or a timeout is reached. This version uses a timeout of 10 seconds. If at all possible, useassertBusy(CheckedRunnable)
instead.- Parameters:
breakSupplier
- determines whether to return immediately or continue waiting.- Returns:
- the last value returned by
breakSupplier
- Throws:
InterruptedException
- if any sleep calls were interrupted.
-
waitUntil
public static boolean waitUntil(BooleanSupplier breakSupplier, long maxWaitTime, TimeUnit unit) throws InterruptedException Periodically execute the supplied function until it returns true, or until the specified maximum wait time has elapsed. If at all possible, useassertBusy(CheckedRunnable)
instead.- Parameters:
breakSupplier
- determines whether to return immediately or continue waiting.maxWaitTime
- the maximum amount of time to waitunit
- the unit of tie formaxWaitTime
- Returns:
- the last value returned by
breakSupplier
- Throws:
InterruptedException
- if any sleep calls were interrupted.
-
terminate
-
terminate
-
getDataPath
Returns aPath
pointing to the class path relative resource given as the first argument. In contrast togetClass().getResource(...).getFile()
this method will not return URL encoded paths if the parent path contains spaces or other non-standard characters.- Overrides:
getDataPath
in classLuceneTestCase
-
tmpPaths
Returns a random number of temporary paths. -
newNodeEnvironment
- Throws:
IOException
-
buildEnvSettings
-
newNodeEnvironment
- Throws:
IOException
-
newEnvironment
-
newEnvironment
-
settings
Return consistent index settings for the provided index version. -
randomSubsetOf
Returns size random values -
randomSubsetOf
Returns a random subset of values (including a potential empty list, or the full original list) -
randomNonEmptySubsetOf
-
randomSubsetOf
Returns size random values -
randomUnique
Builds a set of unique items. Usually you'll get the requested count but you might get less than that number if the supplier returns lots of repeats. Make sure that the items properly implement equals and hashcode. -
randomGeohash
-
getTestTransportType
-
getTestTransportPlugin
-
toShuffledXContent
protected final BytesReference toShuffledXContent(org.elasticsearch.xcontent.ToXContent toXContent, org.elasticsearch.xcontent.XContentType xContentType, org.elasticsearch.xcontent.ToXContent.Params params, boolean humanReadable, String... exceptFieldNames) throws IOException Returns the bytes that represent the XContent output of the providedToXContent
object, using the providedXContentType
. Wraps the output into a new anonymous object according to the value returned by theToXContent.isFragment()
method returns. Shuffles the keys to make sure that parsing never relies on keys ordering.- Throws:
IOException
-
shuffleXContent
protected final org.elasticsearch.xcontent.XContentBuilder shuffleXContent(org.elasticsearch.xcontent.XContentBuilder builder, String... exceptFieldNames) throws IOException Randomly shuffles the fields inside objects in theXContentBuilder
passed in. Recursively goes through inner objects and also shuffles them. Exceptions for this recursive shuffling behavior can be made by passing in the names of fields which internally should stay untouched.- Throws:
IOException
-
shuffleXContent
public static org.elasticsearch.xcontent.XContentBuilder shuffleXContent(org.elasticsearch.xcontent.XContentParser parser, boolean prettyPrint, String... exceptFieldNames) throws IOException Randomly shuffles the fields inside objects parsed using theXContentParser
passed in. Recursively goes through inner objects and also shuffles them. Exceptions for this recursive shuffling behavior can be made by passing in the names of fields which internally should stay untouched.- Throws:
IOException
-
shuffleMap
public static LinkedHashMap<String,Object> shuffleMap(LinkedHashMap<String, Object> map, Set<String> exceptFields) -
copyWriteable
public static <T extends Writeable> T copyWriteable(T original, NamedWriteableRegistry namedWriteableRegistry, Writeable.Reader<T> reader) throws IOException Create a copy of an originalWriteable
object by running it through aBytesStreamOutput
and reading it in again using a providedWriteable.Reader
. The stream that is wrapped around theStreamInput
potentially need to use aNamedWriteableRegistry
, so this needs to be provided too (although it can be empty if the object that is streamed doesn't contain anyNamedWriteable
objects itself.- Throws:
IOException
-
copyWriteable
public static <T extends Writeable> T copyWriteable(T original, NamedWriteableRegistry namedWriteableRegistry, Writeable.Reader<T> reader, Version version) throws IOException Same ascopyWriteable(Writeable, NamedWriteableRegistry, Writeable.Reader)
but also allows to provide aVersion
argument which will be used to write and read back the object.- Throws:
IOException
-
copyNamedWriteable
public static <T extends NamedWriteable> T copyNamedWriteable(T original, NamedWriteableRegistry namedWriteableRegistry, Class<T> categoryClass) throws IOException Create a copy of an originalNamedWriteable
object by running it through aBytesStreamOutput
and reading it in again using a providedWriteable.Reader
.- Throws:
IOException
-
copyNamedWriteable
public static <T extends NamedWriteable> T copyNamedWriteable(T original, NamedWriteableRegistry namedWriteableRegistry, Class<T> categoryClass, Version version) throws IOException Same ascopyNamedWriteable(NamedWriteable, NamedWriteableRegistry, Class)
but also allows to provide aVersion
argument which will be used to write and read back the object.- Throws:
IOException
-
copyInstance
protected static <T> T copyInstance(T original, NamedWriteableRegistry namedWriteableRegistry, Writeable.Writer<T> writer, Writeable.Reader<T> reader, Version version) throws IOException - Throws:
IOException
-
createParser
protected final org.elasticsearch.xcontent.XContentParser createParser(org.elasticsearch.xcontent.XContentBuilder builder) throws IOException Create a newXContentParser
.- Throws:
IOException
-
createParser
protected final org.elasticsearch.xcontent.XContentParser createParser(org.elasticsearch.xcontent.XContent xContent, String data) throws IOException Create a newXContentParser
.- Throws:
IOException
-
createParser
protected final org.elasticsearch.xcontent.XContentParser createParser(org.elasticsearch.xcontent.XContent xContent, InputStream data) throws IOException Create a newXContentParser
.- Throws:
IOException
-
createParser
protected final org.elasticsearch.xcontent.XContentParser createParser(org.elasticsearch.xcontent.XContent xContent, byte[] data) throws IOException Create a newXContentParser
.- Throws:
IOException
-
createParser
protected final org.elasticsearch.xcontent.XContentParser createParser(org.elasticsearch.xcontent.XContent xContent, BytesReference data) throws IOException Create a newXContentParser
.- Throws:
IOException
-
createParser
protected final org.elasticsearch.xcontent.XContentParser createParser(org.elasticsearch.xcontent.NamedXContentRegistry namedXContentRegistry, org.elasticsearch.xcontent.XContent xContent, BytesReference data) throws IOException Create a newXContentParser
.- Throws:
IOException
-
xContentRegistry
protected org.elasticsearch.xcontent.NamedXContentRegistry xContentRegistry()TheNamedXContentRegistry
to use for this test. Subclasses should override and use liberally. -
writableRegistry
TheNamedWriteableRegistry
to use for this test. Subclasses should override and use liberally. -
mockScript
Create a "mock" script for use either withMockScriptEngine
or anywhere where you need a script but don't really care about its contents. -
getSuiteFailureMarker
Returns the suite failure marker: internal use only! -
assertArrayEquals
Compares two stack traces, ignoring module (which is not yet serialized) -
assertEquals
Compares two stack trace elements, ignoring module (which is not yet serialized) -
spinForAtLeastOneMillisecond
protected static long spinForAtLeastOneMillisecond() -
spinForAtLeastNMilliseconds
protected static long spinForAtLeastNMilliseconds(long ms) -
createDefaultIndexAnalyzers
Creates an IndexAnalyzers with a single default analyzer -
createTestAnalysis
public static ESTestCase.TestAnalysis createTestAnalysis(Index index, Settings settings, AnalysisPlugin... analysisPlugins) throws IOException Creates an TestAnalysis with all the default analyzers configured.- Throws:
IOException
-
createTestAnalysis
public static ESTestCase.TestAnalysis createTestAnalysis(Index index, Settings nodeSettings, Settings settings, AnalysisPlugin... analysisPlugins) throws IOException Creates an TestAnalysis with all the default analyzers configured.- Throws:
IOException
-
createTestAnalysis
public static ESTestCase.TestAnalysis createTestAnalysis(IndexSettings indexSettings, Settings nodeSettings, AnalysisPlugin... analysisPlugins) throws IOException Creates an TestAnalysis with all the default analyzers configured.- Throws:
IOException
-
inFipsJvm
public static boolean inFipsJvm() -
getPortRange
Returns a port range for this JVM according to its Gradle worker ID. See also [NOTE: Port ranges for tests]. -
getWorkerBasePort
protected static int getWorkerBasePort()Returns the start of the port range for this JVM according to its Gradle worker ID. See also [NOTE: Port ranges for tests]. -
randomIp
-
isTurkishLocale
protected static boolean isTurkishLocale() -
safeAwait
-
safeAwait
-