Package org.elasticsearch.test
Class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>>
java.lang.Object
org.junit.Assert
org.apache.lucene.util.LuceneTestCase
org.elasticsearch.test.ESTestCase
org.elasticsearch.test.AbstractBuilderTestCase
org.elasticsearch.test.AbstractQueryTestCase<QB>
public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>>
extends AbstractBuilderTestCase
-
Nested Class Summary
Nested classes/interfaces inherited from class org.elasticsearch.test.ESTestCase
ESTestCase.DeprecationWarning, ESTestCase.GeohashGenerator, ESTestCase.TestAnalysis
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
Fields inherited from class org.elasticsearch.test.AbstractBuilderTestCase
BINARY_FIELD_NAME, BOOLEAN_FIELD_NAME, DATE_ALIAS_FIELD_NAME, DATE_FIELD_NAME, DATE_NANOS_FIELD_NAME, DATE_RANGE_FIELD_NAME, DOUBLE_FIELD_NAME, GEO_POINT_ALIAS_FIELD_NAME, GEO_POINT_FIELD_NAME, GEO_SHAPE_FIELD_NAME, INT_ALIAS_FIELD_NAME, INT_FIELD_NAME, INT_RANGE_FIELD_NAME, KEYWORD_FIELD_NAME, MAPPED_FIELD_NAMES, MAPPED_LEAF_FIELD_NAMES, OBJECT_FIELD_NAME, TEXT_ALIAS_FIELD_NAME, TEXT_FIELD_NAME
Fields inherited from class org.elasticsearch.test.ESTestCase
checkIndexFailures, DEFAULT_NAMED_WRITABLE_REGISTRY, DEFAULT_TEST_WORKER_ID, failureAndSuccessEvents, FIPS_SYSPROP, JAVA_TIMEZONE_IDS, JAVA_ZONE_IDS, JODA_TIMEZONE_IDS, logger, MIN_PRIVATE_PORT, TEST_WORKER_SYS_PROPERTY, TEST_WORKER_VM_ID
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 TypeMethodDescriptionprotected void
assertParsedQuery
(String queryAsString, QueryBuilder expectedQuery) Parses the query provided as string argument and compares it with the expected result provided as argument as aQueryBuilder
protected QueryBuilder
assertSerialization
(QueryBuilder testQuery) protected QueryBuilder
assertSerialization
(QueryBuilder testQuery, Version version) Serialize the given query builder and asserts that both are equalprotected void
assertTermOrBoostQuery
(org.apache.lucene.search.Query query, String field, String value, float fieldBoost) protected void
assertTermQuery
(org.apache.lucene.search.Query query, String field, String value) protected boolean
Whether the queries produced by this builder are expected to be cacheable.protected QB
changeNameOrBoost
(QB original) static void
checkGeneratedJson
(String expected, QueryBuilder source) Call this method to check a valid json string representing the query under test against it's generated json.final QB
final QB
createTestQueryBuilder
(boolean supportsBoost, boolean supportsQueryName) protected abstract void
doAssertLuceneQuery
(QB queryBuilder, org.apache.lucene.search.Query query, SearchExecutionContext context) Checks the result ofQueryBuilder.toQuery(SearchExecutionContext)
given the originalQueryBuilder
andSearchExecutionContext
.protected abstract QB
Create the query that is being testedReturns alternate string representation of the query that need to be tested as they are never used as output ofToXContent.toXContent(XContentBuilder, ToXContent.Params)
.Returns a map where the keys are object names that won't trigger a standard exception (an exception that contains the string "unknown field [newField]") throughtestUnknownObjectException()
.protected static String
Helper method to return a mapped or a random fieldprotected static String
protected static String
Helper method to return a random rewrite methodprotected static Object
getRandomValueForFieldName
(String fieldName) create a random value for eitherAbstractBuilderTestCase.BOOLEAN_FIELD_NAME
,AbstractBuilderTestCase.INT_FIELD_NAME
,AbstractBuilderTestCase.DOUBLE_FIELD_NAME
,AbstractBuilderTestCase.TEXT_FIELD_NAME
orAbstractBuilderTestCase.DATE_FIELD_NAME
orAbstractBuilderTestCase.DATE_NANOS_FIELD_NAME
or a String value by defaultboolean
isTextField
(String fieldName) mutateInstance
(QB instance) protected QueryBuilder
parseQuery
(String queryAsString) protected QueryBuilder
parseQuery
(AbstractQueryBuilder<?> builder) protected QueryBuilder
parseQuery
(org.elasticsearch.xcontent.XContentParser parser) protected static String
protected static Fuzziness
randomFuzziness
(String fieldName) protected static String
protected org.apache.lucene.search.Query
rewrite
(org.apache.lucene.search.Query query) protected QueryBuilder
rewriteAndFetch
(QueryBuilder builder, QueryRewriteContext context) protected QueryBuilder
rewriteQuery
(QB queryBuilder, QueryRewriteContext rewriteContext) protected String[]
Subclasses can override this method and return an array of fieldnames which should be protected from recursive random shuffling in thetestFromXContent()
test caseprotected boolean
Few queries allow you to set the boost on the Java API, although the corresponding parser doesn't parse it as it isn't supported.protected boolean
Few queries allow you to set the query name on the Java API, although the corresponding parser doesn't parse it as it isn't supported.void
Check that a query is generally cacheable.void
void
Generic test that creates new query from the test query and checks both for equality and asserts equality on the two queries.void
This test ensures that queries that need to be rewritten have dedicated tests.void
final void
Test that wraps the randomly generated query into an array as follows: { "query_name" : [{}]} This causes unexpected situations in parser code that may not be handled properly.void
Test serialization and deserialization of the test query.void
Test creates theQuery
from theQueryBuilder
under test and delegates the assertions being made on the result to the implementing subclass.void
Test that unknown field trigger ParsingException.void
Test that adding an additional object within each object of the otherwise correct query always triggers some kind of parse exception.void
Generic test that checks that theStrings.toString()
method renders the XContent correctly.Methods inherited from class org.elasticsearch.test.AbstractBuilderTestCase
afterClass, afterTest, beforeClass, beforeTest, createSearchExecutionContext, createSearchExecutionContext, createShardContextWithNoType, createTestIndexSettings, createUniqueRandomName, executeGet, executeMultiTermVectors, expectedFieldName, getExtraPlugins, getIndex, getMapperService, getPlugins, indexSettings, initializeAdditionalMappings, namedWriteableRegistry, xContentRegistry
Methods inherited from class org.elasticsearch.test.ESTestCase
after, afterIfFailed, afterIfSuccessful, allowedWarnings, assertArrayEquals, assertBusy, assertBusy, assertEquals, assertSettingDeprecationsAndWarnings, assertWarnings, assertWarnings, assertWarnings, before, between, buildEnvSettings, buildNewFakeTransportAddress, checkStaticState, clearAdditionalRoles, copyInstance, copyNamedWriteable, copyNamedWriteable, copyWriteable, copyWriteable, createDefaultIndexAnalyzers, createParser, createParser, createParser, createParser, createParser, createParser, createTestAnalysis, createTestAnalysis, createTestAnalysis, enableJodaDeprecationWarningsCheck, enableWarningsCheck, ensureAllSearchContextsReleased, ensureCheckIndexPassed, ensureNoWarnings, ensureSupportedLocale, filteredWarnings, frequently, generateRandomStringArray, generateRandomStringArray, getDataPath, getPortRange, getSuiteFailureMarker, getTestTransportPlugin, getTestTransportType, getWorkerBasePort, inFipsJvm, iterations, maybeSet, mockScript, newEnvironment, newEnvironment, newNodeEnvironment, newNodeEnvironment, randomAlphaOfLength, randomAlphaOfLengthBetween, randomArray, randomArray, randomBigInteger, randomBoolean, randomByte, randomByteArrayOfLength, randomDateFormatterPattern, randomDateTimeZone, randomDouble, randomDoubleBetween, randomFloat, randomFrom, randomFrom, randomFrom, randomFrom, randomFrom, randomFrom, randomGeohash, randomInt, randomInt, randomIntBetween, randomIp, randomList, randomList, randomLong, randomLongBetween, randomMap, randomMillisUpToYear9999, randomNonEmptySubsetOf, randomNonNegativeByte, randomNonNegativeLong, randomPositiveTimeValue, randomRealisticUnicodeOfCodepointLength, randomRealisticUnicodeOfCodepointLengthBetween, randomRealisticUnicodeOfLength, randomRealisticUnicodeOfLengthBetween, randomShort, randomSubsetOf, randomSubsetOf, randomSubsetOf, randomTimeValue, randomTimeValue, randomTimeValue, randomTimeZone, randomUnicodeOfCodepointLength, randomUnicodeOfCodepointLengthBetween, randomUnicodeOfLength, randomUnicodeOfLengthBetween, randomUnique, randomValueOtherThan, randomValueOtherThanMany, randomZone, removeHeaderWarningAppender, resetCheckIndexStatus, resetPortCounter, restoreContentType, restoreFileSystem, safeAwait, scaledRandomIntBetween, setContentType, setFileSystem, setHeaderWarningAppender, settings, shuffleMap, shuffleXContent, shuffleXContent, spinForAtLeastNMilliseconds, spinForAtLeastOneMillisecond, terminate, terminate, tmpPaths, toShuffledXContent, waitUntil, waitUntil, writableRegistry
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
-
Constructor Details
-
AbstractQueryTestCase
public AbstractQueryTestCase()
-
-
Method Details
-
createTestQueryBuilder
-
createTestQueryBuilder
-
doCreateTestQueryBuilder
Create the query that is being tested -
testNegativeBoosts
public void testNegativeBoosts() -
testFromXContent
Generic test that creates new query from the test query and checks both for equality and asserts equality on the two queries.- Throws:
IOException
-
shuffleProtectedFields
Subclasses can override this method and return an array of fieldnames which should be protected from recursive random shuffling in thetestFromXContent()
test case -
testUnknownField
Test that unknown field trigger ParsingException. To find the right position in the root query, we add a marker as `queryName` which all query builders support. The added bogus field after that should trigger the exception. Queries that allow arbitrary field names at this level need to override this test.- Throws:
IOException
-
testUnknownObjectException
Test that adding an additional object within each object of the otherwise correct query always triggers some kind of parse exception. Some specific objects do not cause any exception as they can hold arbitrary content; they can be declared by overridinggetObjectsHoldingArbitraryContent()
.- Throws:
IOException
-
getObjectsHoldingArbitraryContent
Returns a map where the keys are object names that won't trigger a standard exception (an exception that contains the string "unknown field [newField]") throughtestUnknownObjectException()
. The value is a string that is contained in the thrown exception or null in the case that no exception is thrown (including their children). Default is an empty Map. Can be overridden by subclasses that test queries which contain objects that get parsed on the data nodes (e.g. score functions) or objects that can contain arbitrary content (e.g. documents for percolate or more like this query, params for scripts) and/or expect some content(e.g documents with geojson geometries). -
testQueryWrappedInArray
public final void testQueryWrappedInArray()Test that wraps the randomly generated query into an array as follows: { "query_name" : [{}]} This causes unexpected situations in parser code that may not be handled properly. -
getAlternateVersions
Returns alternate string representation of the query that need to be tested as they are never used as output ofToXContent.toXContent(XContentBuilder, ToXContent.Params)
. By default there are no alternate versions. -
assertParsedQuery
protected void assertParsedQuery(String queryAsString, QueryBuilder expectedQuery) throws IOException Parses the query provided as string argument and compares it with the expected result provided as argument as aQueryBuilder
- Throws:
IOException
-
parseQuery
- Throws:
IOException
-
parseQuery
- Throws:
IOException
-
parseQuery
protected QueryBuilder parseQuery(org.elasticsearch.xcontent.XContentParser parser) throws IOException - Throws:
IOException
-
builderGeneratesCacheableQueries
protected boolean builderGeneratesCacheableQueries()Whether the queries produced by this builder are expected to be cacheable. -
testToQuery
Test creates theQuery
from theQueryBuilder
under test and delegates the assertions being made on the result to the implementing subclass.- Throws:
IOException
-
rewriteQuery
protected QueryBuilder rewriteQuery(QB queryBuilder, QueryRewriteContext rewriteContext) throws IOException - Throws:
IOException
-
supportsBoost
protected boolean supportsBoost()Few queries allow you to set the boost on the Java API, although the corresponding parser doesn't parse it as it isn't supported. This method allows to disable boost related tests for those queries. Those queries are easy to identify: their parsers don't parseboost
as they don't apply to the specific query: wrapper query andmatch_none
. -
supportsQueryName
protected boolean supportsQueryName()Few queries allow you to set the query name on the Java API, although the corresponding parser doesn't parse it as it isn't supported. This method allows to disable query name related tests for those queries. Those queries are easy to identify: their parsers don't parse_name
as they don't apply to the specific query: wrapper query andmatch_none
. -
doAssertLuceneQuery
protected abstract void doAssertLuceneQuery(QB queryBuilder, org.apache.lucene.search.Query query, SearchExecutionContext context) throws IOException Checks the result ofQueryBuilder.toQuery(SearchExecutionContext)
given the originalQueryBuilder
andSearchExecutionContext
. Contains the query specific checks to be implemented by subclasses.- Throws:
IOException
-
assertTermOrBoostQuery
-
assertTermQuery
-
testSerialization
Test serialization and deserialization of the test query.- Throws:
IOException
-
assertSerialization
- Throws:
IOException
-
assertSerialization
protected QueryBuilder assertSerialization(QueryBuilder testQuery, Version version) throws IOException Serialize the given query builder and asserts that both are equal- Throws:
IOException
-
testEqualsAndHashcode
public void testEqualsAndHashcode() -
mutateInstance
- Throws:
IOException
-
testValidOutput
Generic test that checks that theStrings.toString()
method renders the XContent correctly.- Throws:
IOException
-
changeNameOrBoost
- Throws:
IOException
-
getRandomValueForFieldName
create a random value for eitherAbstractBuilderTestCase.BOOLEAN_FIELD_NAME
,AbstractBuilderTestCase.INT_FIELD_NAME
,AbstractBuilderTestCase.DOUBLE_FIELD_NAME
,AbstractBuilderTestCase.TEXT_FIELD_NAME
orAbstractBuilderTestCase.DATE_FIELD_NAME
orAbstractBuilderTestCase.DATE_NANOS_FIELD_NAME
or a String value by default -
getRandomQueryText
-
getRandomFieldName
Helper method to return a mapped or a random field -
getRandomRewriteMethod
Helper method to return a random rewrite method -
randomFuzziness
-
randomAnalyzer
-
randomMinimumShouldMatch
-
checkGeneratedJson
Call this method to check a valid json string representing the query under test against it's generated json. Note: By the time of this writing (Nov 2015) all queries are taken from the query dsl reference docs mirroring examples there. Here's how the queries were generated:- Take a reference documentation example.
- Stick it into the createParseableQueryJson method of the respective query test.
- Manually check that what the QueryBuilder generates equals the input json ignoring default options.
- Put the manual checks into the assertQueryParsedFromJson method.
- Now copy the generated json including default options into createParseableQueryJson
- By now the roundtrip check for the json should be happy.
- Throws:
IOException
-
testMustRewrite
This test ensures that queries that need to be rewritten have dedicated tests. These queries must override this method accordingly.- Throws:
IOException
-
rewrite
protected org.apache.lucene.search.Query rewrite(org.apache.lucene.search.Query query) throws IOException - Throws:
IOException
-
rewriteAndFetch
-
isTextField
-
testCacheability
Check that a query is generally cacheable. Tests for query builders that are not always cacheable should overwrite this method and make sure the different cases are always tested- Throws:
IOException
-