Class ESTestCase
- Direct Known Subclasses:
AbstractAsyncBulkByScrollActionTestCase,AbstractBlobContainerRetriesTestCase,AbstractBootstrapCheckTestCase,AbstractBuilderTestCase,AbstractBytesReferenceTestCase,AbstractCoordinatorTestCase,AbstractFilteringTestCase,AbstractHttpServerTransportTestCase,AbstractIndicesClusterStateServiceTestCase,AbstractMultiClustersTestCase,AbstractScriptFieldQueryTestCase,AbstractScriptFieldQueryTests,AbstractSignificanceHeuristicTestCase,AbstractSimpleTransportTestCase,AbstractWireTestCase,AbstractXContentTestCase,AggregatorTestCase,AnalysisFactoryTestCase,BasePipelineAggregationTestCase,CommandTestCase,EngineTestCase,ESAllocationTestCase,ESIndexInputTestCase,ESIntegTestCase,ESRestTestCase,ESSingleNodeTestCase,ESTokenStreamTestCase,FieldScriptTestCase,FieldTypeTestCase,IndexShardTestCase,ModuleTestCase,RestActionTestCase,RestClientBuilderTestCase
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classstatic @interfacestatic classstatic final classThis cute helper class just holds all analysis building blocks that are used to build IndexAnalyzers.static @interfaceMarks a test suite or a test method that enforce entitlements on the test code itself.static @interfaceMarks a test suite or a test method that should run without checking for entitlements.Nested classes/interfaces inherited from class org.apache.lucene.tests.util.LuceneTestCase
org.apache.lucene.tests.util.LuceneTestCase.AwaitsFix, org.apache.lucene.tests.util.LuceneTestCase.Concurrency, org.apache.lucene.tests.util.LuceneTestCase.Monster, org.apache.lucene.tests.util.LuceneTestCase.Nightly, org.apache.lucene.tests.util.LuceneTestCase.SuppressCodecs, org.apache.lucene.tests.util.LuceneTestCase.SuppressFileSystems, org.apache.lucene.tests.util.LuceneTestCase.SuppressFsync, org.apache.lucene.tests.util.LuceneTestCase.SuppressReproduceLine, org.apache.lucene.tests.util.LuceneTestCase.SuppressSysoutChecks, org.apache.lucene.tests.util.LuceneTestCase.SuppressTempFileChecks, org.apache.lucene.tests.util.LuceneTestCase.ThrowingConsumer<T>, org.apache.lucene.tests.util.LuceneTestCase.ThrowingRunnable, org.apache.lucene.tests.util.LuceneTestCase.Weekly -
Field Summary
FieldsModifier and TypeFieldDescriptionMockFSDirectoryService sets this:static final Stringorg.junit.rules.RuleChainstatic final Stringprotected final org.apache.logging.log4j.Loggerprotected static final intDefines the minimum port that test workers should use.static final org.elasticsearch.core.TimeValueThe timeout used for the various "safe" wait methods such assafeAwait(java.util.concurrent.CyclicBarrier)andsafeAcquire(java.util.concurrent.Semaphore).static final TestEntitlementsRulestatic final org.elasticsearch.core.TimeValueVarious timeouts in various REST APIs default to 30s, and many tests do not care about such timeouts, but must specify some value anyway when constructing the corresponding transport/action request instance since we would prefer to avoid having implicit defaults in these requests.static final Stringstatic final Stringstatic final BigIntegerThe maximum value that can be represented as an unsigned long.Fields inherited from class org.apache.lucene.tests.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_FAILFAST, SYSPROP_MAXFAILURES, SYSPROP_MONSTER, SYSPROP_NIGHTLY, SYSPROP_WEEKLY, TEST_ASSERTS_ENABLED, TEST_AWAITSFIX, TEST_CODEC, TEST_DIRECTORY, TEST_DOCVALUESFORMAT, TEST_LINE_DOCS_FILE, TEST_MONSTER, TEST_NIGHTLY, TEST_POSTINGSFORMAT, TEST_THROTTLING, TEST_WEEKLY, VERBOSE -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionfinal voidafter()protected voidafterIfFailed(List<Throwable> errors) Called when a test fails, supplying the errors it generated.protected voidcalled after a test is finished, but only if successfulfinal voidstatic <T> TasInstanceOf(Class<T> clazz, Object o) static voidassertArrayEquals(StackTraceElement[] expected, StackTraceElement[] actual) Compares two stack traces, ignoring module (which is not yet serialized)static voidassertBusy(org.elasticsearch.core.CheckedRunnable<Exception> codeBlock) Runs the code block for 10 seconds waiting for no assertion to trip.static voidassertBusy(org.elasticsearch.core.CheckedRunnable<Exception> codeBlock, long maxWaitTime, TimeUnit unit) Runs the code block for the provided interval, waiting for no assertions to trip.protected final voidassertCriticalWarnings(String... expectedWarnings) Convenience method to assert warnings for settings deprecations and general deprecation warnings.static voidassertEquals(StackTraceElement expected, StackTraceElement actual) Compares two stack trace elements, ignoring module (which is not yet serialized)protected static voidAssert that at least one leak was detected, also clear the list of detected leaks so the test won't fail for leaks detected up until this point.protected final voidassertSettingDeprecationsAndWarnings(Setting<?>[] settings, ESTestCase.DeprecationWarning... warnings) Convenience method to assert warnings for settings deprecations and general deprecation warnings.static <T> voidassertThat(String reason, T actual, org.hamcrest.Matcher<? super T> matcher) static <T> voidassertThat(T actual, org.hamcrest.Matcher<? super T> matcher) protected final voidassertWarnings(boolean stripXContentPosition, ESTestCase.DeprecationWarning... expectedWarnings) protected final voidassertWarnings(String... expectedWarnings) Convenience method to assert warnings for settings deprecations and general deprecation warnings.final voidbefore()static intbetween(int min, int max) An alias forrandomIntBetween(int, int).buildEnvSettings(Settings settings) static TransportAddressGenerates a new transport address usingTransportAddress.META_ADDRESSwith an incrementing port number.static voidprotected static voidcompatibleMediaType(org.elasticsearch.xcontent.XContentType type, org.elasticsearch.core.RestApiVersion version) protected static <T extends Writeable>
TcopyInstance(T original, NamedWriteableRegistry namedWriteableRegistry, Writeable.Writer<T> writer, Writeable.Reader<T> reader, TransportVersion version) static <C extends NamedWriteable,T extends C>
CcopyNamedWriteable(T original, NamedWriteableRegistry namedWriteableRegistry, Class<C> categoryClass) Create a copy of an originalNamedWriteableobject by running it through aBytesStreamOutputand reading it in again using a providedWriteable.Reader.static <C extends NamedWriteable,T extends C>
CcopyNamedWriteable(T original, NamedWriteableRegistry namedWriteableRegistry, Class<C> categoryClass, TransportVersion version) Same ascopyNamedWriteable(NamedWriteable, NamedWriteableRegistry, Class)but also allows to provide aTransportVersionargument 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 originalWriteableobject by running it through aBytesStreamOutputand reading it in again using a providedWriteable.Reader.static <T extends Writeable>
TcopyWriteable(T original, NamedWriteableRegistry namedWriteableRegistry, Writeable.Reader<T> reader, TransportVersion version) Same ascopyWriteable(Writeable, NamedWriteableRegistry, Writeable.Reader)but also allows to provide aTransportVersionargument which will be used to write and read back the object.protected IndexAnalyzersCreates an IndexAnalyzers with a single default analyzerprotected final org.elasticsearch.xcontent.XContentParsercreateParser(org.elasticsearch.xcontent.XContentBuilder builder) Create a newXContentParser.protected final org.elasticsearch.xcontent.XContentParsercreateParser(org.elasticsearch.xcontent.XContentParserConfiguration config, org.elasticsearch.xcontent.XContent xContent, BytesReference data) Create a newXContentParser.protected final org.elasticsearch.xcontent.XContentParsercreateParser(org.elasticsearch.xcontent.XContent xContent, byte[] data) Create a newXContentParser.protected final org.elasticsearch.xcontent.XContentParsercreateParser(org.elasticsearch.xcontent.XContent xContent, InputStream data) Create a newXContentParser.protected final org.elasticsearch.xcontent.XContentParsercreateParser(org.elasticsearch.xcontent.XContent xContent, String data) Create a newXContentParser.protected final org.elasticsearch.xcontent.XContentParsercreateParser(org.elasticsearch.xcontent.XContent xContent, BytesReference data) Create a newXContentParser.protected final org.elasticsearch.xcontent.XContentParsercreateParserWithCompatibilityFor(org.elasticsearch.xcontent.XContent xContent, String data, org.elasticsearch.core.RestApiVersion restApiVersion) static ESTestCase.TestAnalysiscreateTestAnalysis(Index index, Settings nodeSettings, Settings settings, AnalysisPlugin... analysisPlugins) Creates an TestAnalysis with all the default analyzers configured.static ESTestCase.TestAnalysiscreateTestAnalysis(Index index, Settings settings, AnalysisPlugin... analysisPlugins) Creates an TestAnalysis with all the default analyzers configured.static ESTestCase.TestAnalysiscreateTestAnalysis(IndexSettings indexSettings, Settings nodeSettings, AnalysisPlugin... analysisPlugins) Creates an TestAnalysis with all the default analyzers configured.protected TestThreadPoolcreateThreadPool(ExecutorBuilder<?>... executorBuilders) static ProjectMetadataConstructs an emptyProjectMetadatawith a random ID.protected booleanprotected booleanWhether or not we check after each test whether it has left warnings behind.static voidensureAllContextsReleased(SearchService searchService) final voidfinal voidvoidstatic voidstatic <T extends Throwable>
TexpectThrows(Class<T> expectedType, ActionFuture<? extends org.elasticsearch.core.RefCounted> future) static <T extends Throwable>
TexpectThrows(Class<T> expectedType, RequestBuilder<?, ?> builder) static <T extends Throwable>
TexpectThrows(Class<T> expectedType, org.hamcrest.Matcher<String> messageMatcher, org.apache.lucene.tests.util.LuceneTestCase.ThrowingRunnable runnable) Checks a specific exception class with matched message is thrown by the given runnable, and returns it.static <T extends Throwable>
TexpectThrows(String reason, Class<T> expectedType, org.hamcrest.Matcher<String> messageMatcher, org.apache.lucene.tests.util.LuceneTestCase.ThrowingRunnable runnable) Checks a specific exception class with matched message is thrown by the given runnable, and returns it.static <T> Tstatic <T> Tstatic voidflushThreadPoolExecutor(ThreadPool threadPool, String executorName) Wait for all tasks currently running or enqueued on the given executor to complete.static booleanThe 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 aPathpointing to the class path relative resource given as the first argument.static StringReturns a port range for this JVM according to its Gradle worker ID.static PathgetResourceDataPath(Class<?> clazz, String relativePath) static org.apache.lucene.tests.util.TestRuleMarkFailureReturns the suite failure marker: internal use only!static Stringprotected static intReturns the start of the port range for this JVM according to its Gradle worker ID.static Settings.BuilderindexSettings(int shards, int replicas) Return consistent index settings for the provided shard- and replica-count.static Settings.BuilderindexSettings(IndexVersion indexVersionCreated, int shards, int replicas) Return consistent index settings for the provided index version, shard- and replica-count.static Settings.BuilderindexSettings(IndexVersion indexVersionCreated, String uuid, int shards, int replicas) Return consistent index settings for the provided index version, uuid, shard- and replica-count,static booleanprotected static Randomprotected static booleanstatic intiterations(int min, int max) Returns a "scaled" number of iterations for loops which can have a variable iteration count.static <T> voidhelper to randomly perform onconsumerwithvaluestatic ScriptmockScript(String id) Create a "mock" script for use either withMockScriptEngineor anywhere where you need a script but don't really care about its contents.newEnvironment(Settings settings) protected static CircuitBreakernewNodeEnvironment(Settings settings) static org.apache.lucene.search.IndexSearchernewSearcher(org.apache.lucene.index.IndexReader r) Create a new searcher over the reader.static org.apache.lucene.search.IndexSearchernewSearcher(org.apache.lucene.index.IndexReader r, boolean maybeWrap) Create a new searcher over the reader.static org.apache.lucene.search.IndexSearchernewSearcher(org.apache.lucene.index.IndexReader r, boolean maybeWrap, boolean wrapWithAssertions) Create a new searcher over the reader.static org.apache.lucene.search.IndexSearchernewSearcher(org.apache.lucene.index.IndexReader r, boolean maybeWrap, boolean wrapWithAssertions, boolean useThreads) Create a new searcher over the reader.protected final org.elasticsearch.xcontent.XContentParserConfigurationstatic ProjectStateprojectStateFromProject(ProjectMetadata project) Constructs aProjectStatefor the givenProjectMetadata.static ProjectStateConstructs aProjectStatefor the givenProjectMetadata.Builder.static ProjectStateConstructs an emptyProjectStatewith one (empty) project.static StringrandomAlphanumericOfLength(int length) Generate a random string containing only alphanumeric characters.static StringrandomAlphaOfLength(int codeUnits) static StringrandomAlphaOfLengthBetween(int minCodeUnits, int maxCodeUnits) static StringrandomAlphaOfLengthOrNull(int codeUnits) 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 BigIntegerReturns 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 booleanstatic bytestatic byte[]randomByteArrayOfLength(int size) Helper method to create a byte array of a given length populated with random byte valuesstatic byterandomByteBetween(byte minInclusive, byte maxInclusive) static voidrandomBytesBetween(byte[] bytes, byte minInclusive, byte maxInclusive) static ByteSizeValueA random byte size value.static BytesReferencerandomBytesReference(int length) randomCompatibleMediaType(org.elasticsearch.core.RestApiVersion version) static StringGenerate a random valid date formatter pattern.static doublestatic doublerandomDoubleBetween(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 DoubleStreamstatic DoubleStreamrandomDoubles(long streamSize) static ExecutorrandomExecutor(ThreadPool threadPool, String... otherExecutorNames) Randomly choose betweenEsExecutors.DIRECT_EXECUTOR_SERVICE(which does not fork),ThreadPool.generic(), and one of the other named threadpool executors.static floatstatic floatrandomFloatBetween(float start, float end, boolean lowerInclusive) Returns a float value in the interval [start, end) if lowerInclusive is set to true, (start, end) otherwise.static Floatstatic <T> TrandomFrom(Collection<T> collection) Pick a random object from the given collection.static <T> TrandomFrom(List<T> list) Pick a random object from the given list.static <T> TrandomFrom(Random random, Collection<T> collection) Pick a random object from the given collection.static <T> TrandomFrom(Random random, Supplier<T>... array) Pick a random object from the given array of suppliers.static <T> TrandomFrom(Random random, T... array) Pick a random object from the given array.static <T> TrandomFrom(T... array) Pick a random object from the given array.static StringrandomGeohash(int minPrecision, int maxPrecision) static StringCreates a valid random identifier such as node id or index namestatic InstantrandomInstantBetween(Instant minInstant, Instant maxInstant) static intstatic intrandomInt(int max) A random integer from 0..max (inclusive).static intrandomIntBetween(int min, int max) A random integer frommintomax(inclusive).static Integerstatic IntStreamstatic IntStreamrandomInts(long streamSize) static InetAddressrandomIp(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 longstatic longrandomLongBetween(long min, long max) A random long number between min (inclusive) and max (inclusive).static Longstatic LongStreamstatic LongStreamrandomLongs(long streamSize) static <K,V> Map <K, V> randomMap(int minMapSize, int maxMapSize, Supplier<org.elasticsearch.core.Tuple<K, V>> entryConstructor) static longgenerate a random epoch millis in a range 1 to 9999-12-31T23:59:59.999static intstatic longstatic <T> List<T> randomNonEmptySubsetOf(Collection<T> collection) static bytestatic intstatic Integerstatic longstatic Longstatic Booleanstatic Doublestatic org.elasticsearch.core.TimeValuestatic ProjectIdReturns a project id.static StringrandomRealisticUnicodeOfCodepointLength(int codePoints) static StringrandomRealisticUnicodeOfCodepointLengthBetween(int minCodePoints, int maxCodePoints) static StringrandomRealisticUnicodeOfLength(int codeUnits) static StringrandomRealisticUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) randomReleasableBytesReference(int length) static StringGenerate a random string of at least 112 bits to satisfy minimum entropy requirement when running in FIPS mode.static SecureStringrandomSecureStringOfLength(int codeUnits) static <T> Set<T> static shortstatic <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 org.elasticsearch.core.TimeValuestatic org.elasticsearch.core.TimeValuerandomTimeValue(int lower, int upper) static org.elasticsearch.core.TimeValuerandomTimeValue(int lower, int upper, TimeUnit... units) static TimeZonegenerate a random TimeZone from the ones available in java.utilstatic StringrandomUnicodeOfCodepointLength(int codePoints) static StringrandomUnicodeOfCodepointLengthBetween(int minCodePoints, int maxCodePoints) static StringrandomUnicodeOfLength(int codeUnits) static StringrandomUnicodeOfLengthBetween(int minCodeUnits, int maxCodeUnits) static <T> Set<T> randomUnique(Supplier<T> supplier, int targetCount) Builds a set of unique items.static ProjectIdReturns a new randomly-generated project idstatic BigIntegerrandomUnsignedLongBetween(BigInteger min, BigInteger max) A unsigned long in aBigIntegerbetween min (inclusive) and max (inclusive).static Stringstatic <T> TrandomValueOtherThan(T input, Supplier<T> randomSupplier) helper to get a random value in a certain range that's different from the inputstatic <T> TrandomValueOtherThanMany(Predicate<T> input, Supplier<T> randomSupplier) helper to get a random value in a certain range that's different from the inputorg.elasticsearch.xcontent.XContentTypestatic ZoneIdgenerate a random TimeZone from the ones available in java.timevoidfinal voidstatic voidstatic voidstatic voidstatic voidstatic voidrunInParallel(int numberOfTasks, IntConsumer taskFactory) RunnumberOfTasksparallel tasks that were created by the giventaskFactory.static voidsafeAcquire(int permits, Semaphore semaphore) Acquire the specified number of permits from the givenSemaphore, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and asserting that the permits were all successfully acquired.static voidsafeAcquire(Semaphore semaphore) Acquire a single permit from the givenSemaphore, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and asserting that the permit was successfully acquired.static voidsafeAwait(CountDownLatch countDownLatch) Await on the givenCountDownLatchwith a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and asserting that the latch is indeed completed before the timeout.static voidsafeAwait(CountDownLatch countDownLatch, org.elasticsearch.core.TimeValue timeout) Await on the givenCountDownLatchwith a supplied timeout, preserving the thread's interrupt status flag and asserting that the latch is indeed completed before the timeout.static voidsafeAwait(CyclicBarrier barrier) Await on the givenCyclicBarrierwith a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting all exceptions into anAssertionErrorto trigger a test failure.static <T> TsafeAwait(SubscribableListener<T> listener) Wait for the successful completion of the givenSubscribableListener, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting all exceptions into anAssertionErrorto trigger a test failure.static <T> TsafeAwait(SubscribableListener<T> listener, org.elasticsearch.core.TimeValue timeout) Wait for the successful completion of the givenSubscribableListener, respecting the provided timeout, preserving the thread's interrupt status flag and converting all exceptions into anAssertionErrorto trigger a test failure.static <T> TsafeAwait(org.elasticsearch.core.CheckedConsumer<ActionListener<T>, ?> consumer) Call an async action (aConsumerof anActionListener), wait for it to complete the listener, and then return the result.static <Response,ExpectedException extends Exception>
ExpectedExceptionsafeAwaitAndUnwrapFailure(Class<ExpectedException> exceptionType, Class<Response> responseType, Consumer<ActionListener<Response>> consumer) Wait for the exceptional completion of the given async action, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into anAssertionErrorto trigger a test failure.static <Response,ExpectedException extends Exception>
ExpectedExceptionsafeAwaitFailure(Class<ExpectedException> exceptionType, Class<Response> responseType, Consumer<ActionListener<Response>> consumer) Wait for the exceptional completion of the given async action, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into anAssertionErrorto trigger a test failure.static <T> ExceptionsafeAwaitFailure(Class<T> responseType, Consumer<ActionListener<T>> consumer) Wait for the exceptional completion of the given async action, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into anAssertionErrorto trigger a test failure.static <T> ExceptionsafeAwaitFailure(Consumer<ActionListener<T>> consumer) Wait for the exceptional completion of the given async action, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into anAssertionErrorto trigger a test failure.static ExceptionsafeAwaitFailure(SubscribableListener<?> listener) Wait for the exceptional completion of the givenSubscribableListener, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into anAssertionErrorto trigger a test failure.static <T extends ActionResponse>
TsafeExecute(ElasticsearchClient client, ActionType<T> action, ActionRequest request) Execute the givenActionRequestusing the givenActionTypeand the givenElasticsearchClient, wait for it to complete with a timeout ofSAFE_AWAIT_TIMEOUT, and then return the result.static <T> TWait for the successful completion of the givenFuture, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting all exceptions into anAssertionErrorto trigger a test failure.static <T> TsafeGet(CheckedSupplier<T, ?> supplier) Call aCheckedSupplier, converting all exceptions into anAssertionError.static voidsafeSleep(long millis) Send the current thread to sleep for the given number of milliseconds, asserting that the sleep is not interrupted but preserving the thread's interrupt status flag in any case.static voidsafeSleep(org.elasticsearch.core.TimeValue timeValue) Send the current thread to sleep for the given duration, asserting that the sleep is not interrupted but preserving the thread's interrupt status flag in any case.static intscaledRandomIntBetween(int min, int max) Returns a "scaled" random number between min and max (inclusive).static SecureRandomIn non-FIPS mode, get a deterministic SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().static SecureRandomsecureRandom(byte[] seed) In non-FIPS mode, get a deterministic SecureRandom SHA1PRNG/SUN instance seeded by the input value.protected static SecureRandomReturns non-deterministic FIPS SecureRandom DEFAULT/BCFIPS instance.protected static SecureRandomsecureRandomFips(byte[] seed) Returns non-deterministic FIPS SecureRandom DEFAULT/BCFIPS instance.protected static SecureRandomReturns deterministic non-FIPS SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().protected static SecureRandomsecureRandomNonFips(byte[] seed) Returns deterministic non-FIPS SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().static voidstatic voidvoidstatic Settings.Buildersettings(IndexVersion version) Return consistent index settings for the provided index version.static <T> List<T> shuffledList(List<T> list) static LinkedHashMap<String, Object> shuffleMap(LinkedHashMap<String, Object> map, Set<String> exceptFields) protected final org.elasticsearch.xcontent.XContentBuildershuffleXContent(org.elasticsearch.xcontent.XContentBuilder builder, String... exceptFieldNames) Randomly shuffles the fields inside objects in theXContentBuilderpassed in.static org.elasticsearch.xcontent.XContentBuildershuffleXContent(org.elasticsearch.xcontent.XContentParser parser, boolean prettyPrint, String... exceptFieldNames) Randomly shuffles the fields inside objects parsed using theXContentParserpassed in.protected voidskipTestWaitingForLuceneFix(org.apache.lucene.util.Version luceneVersionWithFix, String message) Call method at the beginning of a test to disable its execution until a given Lucene version is released and integrated into Elasticsearchprotected static longspinForAtLeastNMilliseconds(long ms) protected static longstatic voidstartInParallel(int numberOfTasks, IntConsumer taskFactory) Same asrunInParallel(int, IntConsumer)but also attempts to start all tasks at the same time by blocking execution on a barrier until all threads are started and ready to execute their task.static booleanterminate(ExecutorService... services) static booleanterminate(ThreadPool threadPool) String[]tmpPaths()Returns a random number of temporary paths.protected final BytesReferencetoShuffledXContent(org.elasticsearch.xcontent.ToXContent toXContent, org.elasticsearch.xcontent.XContentType xContentType, org.elasticsearch.core.RestApiVersion restApiVersion, org.elasticsearch.xcontent.ToXContent.Params params, boolean humanReadable, String... exceptFieldNames) Returns the bytes that represent the XContent output of the providedToXContentobject, using the providedXContentType.protected final BytesReferencetoShuffledXContent(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 providedToXContentobject, using the providedXContentType.static booleanwaitUntil(BooleanSupplier breakSupplier) Periodically execute the supplied function until it returns true, or a timeout is reached.static booleanwaitUntil(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 NamedWriteableRegistryTheNamedWriteableRegistryto use for this test.protected org.elasticsearch.xcontent.NamedXContentRegistryTheNamedXContentRegistryto use for this test.Methods inherited from class org.apache.lucene.tests.util.LuceneTestCase
addVirusChecker, assertDeletedDocsEquals, assertDocsAndPositionsEnumEquals, assertDocsEnumEquals, assertDocsSkippingEquals, assertDocValuesEquals, assertDocValuesEquals, assertDoubleUlpEquals, assertFieldInfosEquals, assertFloatUlpEquals, assertNormsEquals, assertPointsEquals, assertPositionsSkippingEquals, assertReaderEquals, assertReaderStatisticsEquals, assertStoredFieldEquals, assertStoredFieldsEquals, assertTermsEnumEquals, assertTermsEquals, assertTermsEquals, assertTermsStatisticsEquals, assertTermStatsEquals, assertTermVectorsEquals, asSet, assumeFalse, assumeNoException, assumeTrue, atLeast, atLeast, callStackContains, callStackContains, callStackContainsAnyOf, closeAfterSuite, closeAfterTest, collate, createTempDir, createTempDir, createTempFile, createTempFile, dumpArray, dumpIterator, ensureSaneIWCOnNightly, expectThrows, expectThrows, expectThrows, expectThrowsAnyOf, expectThrowsAnyOf, getDataInputStream, getJvmForkArguments, getOnlyLeafReader, getTestClass, getTestName, 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, newSnapshotIndexWriterConfig, newStringField, newStringField, newStringField, newStringField, newTextField, newTextField, newTieredMergePolicy, newTieredMergePolicy, overrideDefaultQueryCache, overrideTestDefaultQueryCache, random, randomLocale, randomTimeZone, randomVectorFormat, rarely, rarely, replaceMaxFailureRule, resetDefaultQueryCache, restoreCPUCoreCount, restoreIndexWriterMaxDocs, runWithRestrictedPermissions, setIndexWriterMaxDocs, setUp, setupCPUCoreCount, setUpExecutorService, shutdownExecutorService, slowFileExists, tearDown, usually, usually, wrapReaderMethods 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, assertThrows, assertThrows, assertTrue, assertTrue, fail, fail
-
Field Details
-
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 -
TEST_ENTITLEMENTS
-
checkIndexFailures
MockFSDirectoryService sets this: -
UNSIGNED_LONG_MAX
The maximum value that can be represented as an unsigned long. -
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:
-
TEST_REQUEST_TIMEOUT
public static final org.elasticsearch.core.TimeValue TEST_REQUEST_TIMEOUTVarious timeouts in various REST APIs default to 30s, and many tests do not care about such timeouts, but must specify some value anyway when constructing the corresponding transport/action request instance since we would prefer to avoid having implicit defaults in these requests. This constant can be used as a slightly more meaningful way to refer to the 30s default value in tests. -
SAFE_AWAIT_TIMEOUT
public static final org.elasticsearch.core.TimeValue SAFE_AWAIT_TIMEOUTThe timeout used for the various "safe" wait methods such assafeAwait(java.util.concurrent.CyclicBarrier)andsafeAcquire(java.util.concurrent.Semaphore). In tests we generally want these things to complete almost immediately, but sometimes the CI runner executes things rather slowly so we use10sas a fairly relaxed definition of "immediately".A well-designed test should not need to wait for anything close to this duration when run in isolation. If you think you need to do so, instead seek a better way to write the test such that it does not need to wait for so long. Tests that take multiple seconds to complete are a big drag on CI times which slows everyone down.
For instance, tests which verify things that require the passage of time ought to simulate this (e.g. using a
DeterministicTaskQueue). Excessive busy-waits ought to be replaced by blocking waits. For instance, use aCountDownLatchorCyclicBarrieror similar to continue execution as soon as a condition is satisfied. To wait for a particular cluster state, useClusterServiceUtils.addTemporaryStateListener(org.elasticsearch.cluster.service.ClusterService, java.util.function.Predicate<org.elasticsearch.cluster.ClusterState>)rather than busy-waiting on an API.
-
-
Constructor Details
-
ESTestCase
public ESTestCase()
-
-
Method Details
-
resetPortCounter
public static void resetPortCounter() -
initTestSeed
-
buildNewFakeTransportAddress
Generates a new transport address usingTransportAddress.META_ADDRESSwith 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() -
captureLoggingLevel
public static void captureLoggingLevel() -
restoreLoggingLevel
public static void restoreLoggingLevel() -
before
public final void before() -
newLimitedBreaker
-
allBreakersMemoryReleased
public final void allBreakersMemoryReleased() -
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...). -
enableBigArraysReleasedCheck
protected boolean enableBigArraysReleasedCheck() -
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
Convenience method to assert warnings for settings deprecations and general deprecation warnings. All warnings passed to this method are assumed to be at WARNING level.- Parameters:
expectedWarnings- expected general deprecation warning messages.
-
assertCriticalWarnings
Convenience method to assert warnings for settings deprecations and general deprecation warnings. All warnings passed to this method are assumed to be at CRITICAL level.- Parameters:
expectedWarnings- expected general deprecation warning messages.
-
assertWarnings
protected final void assertWarnings(boolean stripXContentPosition, ESTestCase.DeprecationWarning... expectedWarnings) -
checkStaticState
- Throws:
Exception
-
assertLeakDetected
protected static void assertLeakDetected()Assert that at least one leak was detected, also clear the list of detected leaks so the test won't fail for leaks detected up until this point. -
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:
-
randomIntBetween
public static int randomIntBetween(int min, int max) A random integer frommintomax(inclusive).- See Also:
-
randomLongBetween
public static long randomLongBetween(long min, long max) A random long number between min (inclusive) and max (inclusive). -
randomInstantBetween
- Returns:
- a random instant between a min and a max value with a random nanosecond precision
-
randomUnsignedLongBetween
A unsigned long in aBigIntegerbetween 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() -
randomOptionalBoolean
-
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:
-
randomByteBetween
public static byte randomByteBetween(byte minInclusive, byte maxInclusive) -
randomBytesBetween
public static void randomBytesBetween(byte[] bytes, byte minInclusive, byte maxInclusive) -
randomBytesReference
-
randomReleasableBytesReference
-
randomShort
public static short randomShort() -
randomInt
public static int randomInt() -
randomInts
-
randomInts
-
randomNonNegativeLong
public static long randomNonNegativeLong()- Returns:
- a
longbetween0andLong.MAX_VALUE(inclusive) chosen uniformly at random.
-
randomNegativeLong
public static long randomNegativeLong()- Returns:
- a
longbetweenLong.MIN_VALUEand-1(inclusive) chosen uniformly at random.
-
randomNonNegativeInt
public static int randomNonNegativeInt()- Returns:
- an
intbetween0andInteger.MAX_VALUE(inclusive) chosen uniformly at random.
-
randomNegativeInt
public static int randomNegativeInt()- Returns:
- an
intbetweenInteger.MIN_VALUEand-1(inclusive) chosen uniformly at random.
-
randomFloat
public static float randomFloat() -
randomFloatBetween
public static float randomFloatBetween(float start, float end, boolean lowerInclusive) Returns a float 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
-
randomDouble
public static double randomDouble() -
randomDoubles
-
randomDoubles
-
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
-
randomOptionalDouble
-
randomLong
public static long randomLong() -
randomLongs
-
randomLongs
-
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). -
randomByteSizeValue
A random byte size value. -
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
-
randomAlphanumericOfLength
Generate a random string containing only alphanumeric characters. The locale for the string isLocale.ROOT.- Parameters:
length- the length of the string to generate- Returns:
- the generated string
-
randomSecureStringOfLength
-
randomAlphaOfLengthOrNull
-
randomLongOrNull
-
randomNonNegativeLongOrNull
-
randomIntOrNull
-
randomNonNegativeIntOrNull
-
randomFloatOrNull
-
randomIdentifier
Creates a valid random identifier such as node id or index name -
randomProjectIdOrDefault
Returns a project id. This may beMetadata.DEFAULT_PROJECT_ID, or it may be a randomly-generated id. -
randomUniqueProjectId
Returns a new randomly-generated project id -
randomUUID
-
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
-
randomSet
-
randomTimeValue
public static org.elasticsearch.core.TimeValue randomTimeValue(int lower, int upper, TimeUnit... units) -
randomTimeValue
public static org.elasticsearch.core.TimeValue randomTimeValue(int lower, int upper) -
randomTimeValue
public static org.elasticsearch.core.TimeValue randomTimeValue() -
randomPositiveTimeValue
public static org.elasticsearch.core.TimeValue randomPositiveTimeValue() -
randomMillisUpToYear9999
public static 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. -
randomSecretKey
Generate a random string of at least 112 bits to satisfy minimum entropy requirement when running in FIPS mode. -
randomExecutor
Randomly choose betweenEsExecutors.DIRECT_EXECUTOR_SERVICE(which does not fork),ThreadPool.generic(), and one of the other named threadpool executors. -
maybeSet
helper to randomly perform onconsumerwithvalue -
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. Retries on AssertionError with exponential backoff until provided time runs out- 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
-
waitUntil
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
-
createThreadPool
-
terminate
-
terminate
-
getDataPath
Returns aPathpointing 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:
getDataPathin classorg.apache.lucene.tests.util.LuceneTestCase
-
getResourceDataPath
-
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. -
indexSettings
public static Settings.Builder indexSettings(IndexVersion indexVersionCreated, int shards, int replicas) Return consistent index settings for the provided index version, shard- and replica-count. -
indexSettings
public static Settings.Builder indexSettings(IndexVersion indexVersionCreated, String uuid, int shards, int replicas) Return consistent index settings for the provided index version, uuid, shard- and replica-count, -
indexSettings
Return consistent index settings for the provided shard- and replica-count. -
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 -
shuffledList
-
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
-
randomCompatibleMediaType
-
compatibleMediaType
public String compatibleMediaType(org.elasticsearch.xcontent.XContentType type, org.elasticsearch.core.RestApiVersion version) -
randomVendorType
public org.elasticsearch.xcontent.XContentType randomVendorType() -
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 providedToXContentobject, 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
-
toShuffledXContent
protected final BytesReference toShuffledXContent(org.elasticsearch.xcontent.ToXContent toXContent, org.elasticsearch.xcontent.XContentType xContentType, org.elasticsearch.core.RestApiVersion restApiVersion, org.elasticsearch.xcontent.ToXContent.Params params, boolean humanReadable, String... exceptFieldNames) throws IOException Returns the bytes that represent the XContent output of the providedToXContentobject, 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 theXContentBuilderpassed 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 theXContentParserpassed 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 originalWriteableobject by running it through aBytesStreamOutputand reading it in again using a providedWriteable.Reader. The stream that is wrapped around theStreamInputpotentially 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 anyNamedWriteableobjects itself.- Throws:
IOException
-
copyWriteable
public static <T extends Writeable> T copyWriteable(T original, NamedWriteableRegistry namedWriteableRegistry, Writeable.Reader<T> reader, TransportVersion version) throws IOException Same ascopyWriteable(Writeable, NamedWriteableRegistry, Writeable.Reader)but also allows to provide aTransportVersionargument which will be used to write and read back the object.- Throws:
IOException
-
copyNamedWriteable
public static <C extends NamedWriteable,T extends C> C copyNamedWriteable(T original, NamedWriteableRegistry namedWriteableRegistry, Class<C> categoryClass) throws IOException Create a copy of an originalNamedWriteableobject by running it through aBytesStreamOutputand reading it in again using a providedWriteable.Reader.- Throws:
IOException
-
copyNamedWriteable
public static <C extends NamedWriteable,T extends C> C copyNamedWriteable(T original, NamedWriteableRegistry namedWriteableRegistry, Class<C> categoryClass, TransportVersion version) throws IOException Same ascopyNamedWriteable(NamedWriteable, NamedWriteableRegistry, Class)but also allows to provide aTransportVersionargument which will be used to write and read back the object.- Returns:
- Throws:
IOException
-
copyInstance
protected static <T extends Writeable> T copyInstance(T original, NamedWriteableRegistry namedWriteableRegistry, Writeable.Writer<T> writer, Writeable.Reader<T> reader, TransportVersion version) throws IOException - Throws:
IOException
-
parserConfig
protected final org.elasticsearch.xcontent.XContentParserConfiguration parserConfig() -
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.XContentParserConfiguration config, org.elasticsearch.xcontent.XContent xContent, BytesReference data) throws IOException Create a newXContentParser.- Throws:
IOException
-
createParserWithCompatibilityFor
protected final org.elasticsearch.xcontent.XContentParser createParserWithCompatibilityFor(org.elasticsearch.xcontent.XContent xContent, String data, org.elasticsearch.core.RestApiVersion restApiVersion) throws IOException - Throws:
IOException
-
xContentRegistry
protected org.elasticsearch.xcontent.NamedXContentRegistry xContentRegistry()TheNamedXContentRegistryto use for this test. Subclasses should override and use liberally. -
writableRegistry
TheNamedWriteableRegistryto use for this test. Subclasses should override and use liberally. -
mockScript
Create a "mock" script for use either withMockScriptEngineor anywhere where you need a script but don't really care about its contents. -
getSuiteFailureMarker
public static org.apache.lucene.tests.util.TestRuleMarkFailure 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
-
skipTestWaitingForLuceneFix
protected void skipTestWaitingForLuceneFix(org.apache.lucene.util.Version luceneVersionWithFix, String message) Call method at the beginning of a test to disable its execution until a given Lucene version is released and integrated into Elasticsearch- Parameters:
luceneVersionWithFix- the lucene release to wait formessage- an additional message or link with information on the fix
-
secureRandom
In non-FIPS mode, get a deterministic SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random(). In FIPS mode, get a non-deterministic SecureRandom DEFAULT/BCFIPS instance seeded by deterministic LuceneTestCase.random().- Returns:
- SecureRandom SHA1PRNG instance.
- Throws:
NoSuchAlgorithmException- SHA1PRNG or DEFAULT algorithm not found.NoSuchProviderException- BCFIPS algorithm not found.
-
secureRandom
public static SecureRandom secureRandom(byte[] seed) throws NoSuchAlgorithmException, NoSuchProviderException In non-FIPS mode, get a deterministic SecureRandom SHA1PRNG/SUN instance seeded by the input value. In FIPS mode, get a non-deterministic SecureRandom DEFAULT/BCFIPS instance seeded by the input value.- Parameters:
seed- Byte array to use for seeding the SecureRandom instance.- Returns:
- SecureRandom SHA1PRNG or DEFAULT/BCFIPS instance, depending on FIPS mode.
- Throws:
NoSuchAlgorithmException- SHA1PRNG or DEFAULT algorithm not found.NoSuchProviderException- BCFIPS algorithm not found.
-
secureRandomNonFips
Returns deterministic non-FIPS SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().- Returns:
- Deterministic non-FIPS SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().
- Throws:
NoSuchAlgorithmException- Exception if SHA1PRNG algorithm not found, such as missing SUN provider (unlikely).
-
secureRandomFips
Returns non-deterministic FIPS SecureRandom DEFAULT/BCFIPS instance. Seeded.- Returns:
- Non-deterministic FIPS SecureRandom DEFAULT/BCFIPS instance. Seeded.
- Throws:
NoSuchAlgorithmException- Exception if DEFAULT algorithm not found, such as missing BCFIPS provider.
-
secureRandomNonFips
Returns deterministic non-FIPS SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().- Returns:
- Deterministic non-FIPS SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().
- Throws:
NoSuchAlgorithmException- Exception if SHA1PRNG algorithm not found, such as missing SUN provider (unlikely).
-
secureRandomFips
Returns non-deterministic FIPS SecureRandom DEFAULT/BCFIPS instance. Seeded.- Returns:
- Non-deterministic FIPS SecureRandom DEFAULT/BCFIPS instance. Seeded.
- Throws:
NoSuchAlgorithmException- Exception if DEFAULT algorithm not found, such as missing BCFIPS provider.
-
safeAwait
Await on the givenCyclicBarrierwith a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting all exceptions into anAssertionErrorto trigger a test failure. -
safeAwait
Await on the givenCountDownLatchwith a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and asserting that the latch is indeed completed before the timeout. -
safeAwait
public static void safeAwait(CountDownLatch countDownLatch, org.elasticsearch.core.TimeValue timeout) Await on the givenCountDownLatchwith a supplied timeout, preserving the thread's interrupt status flag and asserting that the latch is indeed completed before the timeout.Prefer
safeAwait(CountDownLatch)(with the default 10s timeout) wherever possible. It's very unusual to need to block a test for more than 10s, and such slow tests are a big problem for overall test suite performance. In almost all cases it's possible to find a different way to write the test which doesn't need such a long wait. -
safeAcquire
Acquire a single permit from the givenSemaphore, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and asserting that the permit was successfully acquired. -
safeAcquire
Acquire the specified number of permits from the givenSemaphore, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and asserting that the permits were all successfully acquired. -
safeAwait
Wait for the successful completion of the givenSubscribableListener, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting all exceptions into anAssertionErrorto trigger a test failure.- Returns:
- The value with which the
listenerwas completed.
-
safeAwait
public static <T> T safeAwait(SubscribableListener<T> listener, org.elasticsearch.core.TimeValue timeout) Wait for the successful completion of the givenSubscribableListener, respecting the provided timeout, preserving the thread's interrupt status flag and converting all exceptions into anAssertionErrorto trigger a test failure.- Returns:
- The value with which the
listenerwas completed.
-
safeAwait
Call an async action (aConsumerof anActionListener), wait for it to complete the listener, and then return the result. Preserves the thread's interrupt status flag and converts all exceptions into anAssertionErrorto trigger a test failure.- Returns:
- The value with which the consumed listener was completed.
-
safeExecute
public static <T extends ActionResponse> T safeExecute(ElasticsearchClient client, ActionType<T> action, ActionRequest request) Execute the givenActionRequestusing the givenActionTypeand the givenElasticsearchClient, wait for it to complete with a timeout ofSAFE_AWAIT_TIMEOUT, and then return the result. An exceptional response, timeout or interrupt triggers a test failure. -
safeGet
Wait for the successful completion of the givenFuture, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting all exceptions into anAssertionErrorto trigger a test failure.- Returns:
- The value with which the
futurewas completed.
-
safeGet
Call aCheckedSupplier, converting all exceptions into anAssertionError. Useful for avoiding try/catch boilerplate or cumbersome propagation of checked exceptions around something that should never throw.- Returns:
- The value returned by the
supplier.
-
safeAwaitFailure
Wait for the exceptional completion of the givenSubscribableListener, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into anAssertionErrorto trigger a test failure.- Returns:
- The exception with which the
listenerwas completed exceptionally.
-
safeAwaitFailure
Wait for the exceptional completion of the given async action, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into anAssertionErrorto trigger a test failure.- Returns:
- The exception with which the
listenerwas completed exceptionally.
-
safeAwaitFailure
public static <T> Exception safeAwaitFailure(Class<T> responseType, Consumer<ActionListener<T>> consumer) Wait for the exceptional completion of the given async action, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into anAssertionErrorto trigger a test failure.- Parameters:
responseType- Class of listener response type, to aid type inference but otherwise ignored.- Returns:
- The exception with which the
listenerwas completed exceptionally.
-
safeAwaitFailure
public static <Response,ExpectedException extends Exception> ExpectedException safeAwaitFailure(Class<ExpectedException> exceptionType, Class<Response> responseType, Consumer<ActionListener<Response>> consumer) Wait for the exceptional completion of the given async action, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into anAssertionErrorto trigger a test failure.- Parameters:
exceptionType- Expected exception type. This method throws anAssertionErrorif a different type of exception is seen.responseType- Class of listener response type, to aid type inference but otherwise ignored.- Returns:
- The exception with which the
listenerwas completed exceptionally.
-
safeAwaitAndUnwrapFailure
public static <Response,ExpectedException extends Exception> ExpectedException safeAwaitAndUnwrapFailure(Class<ExpectedException> exceptionType, Class<Response> responseType, Consumer<ActionListener<Response>> consumer) Wait for the exceptional completion of the given async action, with a timeout ofSAFE_AWAIT_TIMEOUT, preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into anAssertionErrorto trigger a test failure. Any layers ofElasticsearchWrapperExceptionare removed from the thrown exception usingExceptionsHelper.unwrapCause(java.lang.Throwable).- Parameters:
exceptionType- Expected unwrapped exception type. This method throws anAssertionErrorif a different type of exception is seen.responseType- Class of listener response type, to aid type inference but otherwise ignored.- Returns:
- The unwrapped exception with which the
listenerwas completed exceptionally.
-
safeSleep
public static void safeSleep(org.elasticsearch.core.TimeValue timeValue) Send the current thread to sleep for the given duration, asserting that the sleep is not interrupted but preserving the thread's interrupt status flag in any case. -
safeSleep
public static void safeSleep(long millis) Send the current thread to sleep for the given number of milliseconds, asserting that the sleep is not interrupted but preserving the thread's interrupt status flag in any case. -
flushThreadPoolExecutor
Wait for all tasks currently running or enqueued on the given executor to complete. -
isTurkishLocale
protected static boolean isTurkishLocale() -
assertThat
public static <T> void assertThat(T actual, org.hamcrest.Matcher<? super T> matcher) -
assertThat
-
fail
-
fail
-
asInstanceOf
-
expectThrows
public static <T extends Throwable> T expectThrows(Class<T> expectedType, ActionFuture<? extends org.elasticsearch.core.RefCounted> future) -
expectThrows
public static <T extends Throwable> T expectThrows(Class<T> expectedType, RequestBuilder<?, ?> builder) -
expectThrows
public static <T extends Throwable> T expectThrows(Class<T> expectedType, org.hamcrest.Matcher<String> messageMatcher, org.apache.lucene.tests.util.LuceneTestCase.ThrowingRunnable runnable) Checks a specific exception class with matched message is thrown by the given runnable, and returns it. -
expectThrows
public static <T extends Throwable> T expectThrows(String reason, Class<T> expectedType, org.hamcrest.Matcher<String> messageMatcher, org.apache.lucene.tests.util.LuceneTestCase.ThrowingRunnable runnable) Checks a specific exception class with matched message is thrown by the given runnable, and returns it. -
startInParallel
Same asrunInParallel(int, IntConsumer)but also attempts to start all tasks at the same time by blocking execution on a barrier until all threads are started and ready to execute their task. -
runInParallel
RunnumberOfTasksparallel tasks that were created by the giventaskFactory. On of the tasks will be run on the calling thread, the rest will be run on a new thread.- Parameters:
numberOfTasks- number of tasks to run in paralleltaskFactory- task factory
-
ensureAllContextsReleased
-
newSearcher
public static org.apache.lucene.search.IndexSearcher newSearcher(org.apache.lucene.index.IndexReader r) Create a new searcher over the reader. This searcher might randomly use threads. Provides the same functionality asLuceneTestCase.newSearcher(IndexReader), with the only difference that concurrency will only ever be inter-segment and never intra-segment. -
newSearcher
public static org.apache.lucene.search.IndexSearcher newSearcher(org.apache.lucene.index.IndexReader r, boolean maybeWrap) Create a new searcher over the reader. This searcher might randomly use threads. Provides the same functionality asLuceneTestCase.newSearcher(IndexReader, boolean), with the only difference that concurrency will only ever be inter-segment and never intra-segment. -
newSearcher
public static org.apache.lucene.search.IndexSearcher newSearcher(org.apache.lucene.index.IndexReader r, boolean maybeWrap, boolean wrapWithAssertions) Create a new searcher over the reader. This searcher might randomly use threads. Provides the same functionality asLuceneTestCase.newSearcher(IndexReader, boolean, boolean), with the only difference that concurrency will only ever be inter-segment and never intra-segment. -
newSearcher
public static org.apache.lucene.search.IndexSearcher newSearcher(org.apache.lucene.index.IndexReader r, boolean maybeWrap, boolean wrapWithAssertions, boolean useThreads) Create a new searcher over the reader. Provides the same functionality asLuceneTestCase.newSearcher(IndexReader, boolean, boolean, boolean), with the only difference that concurrency will only ever be inter-segment and never intra-segment. -
projectStateFromProject
Constructs aProjectStatefor the givenProjectMetadata.Builder. -
projectStateFromProject
Constructs aProjectStatefor the givenProjectMetadata. -
projectStateWithEmptyProject
Constructs an emptyProjectStatewith one (empty) project. -
emptyProject
Constructs an emptyProjectMetadatawith a random ID.
-