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.GeohashGenerator, ESTestCase.TestAnalysis
-
Nested classes/interfaces inherited from class org.apache.lucene.util.LuceneTestCase
org.apache.lucene.util.LuceneTestCase.AwaitsFix, org.apache.lucene.util.LuceneTestCase.BadApple, org.apache.lucene.util.LuceneTestCase.Monster, org.apache.lucene.util.LuceneTestCase.Nightly, org.apache.lucene.util.LuceneTestCase.Slow, org.apache.lucene.util.LuceneTestCase.SuppressCodecs, org.apache.lucene.util.LuceneTestCase.SuppressFileSystems, org.apache.lucene.util.LuceneTestCase.SuppressFsync, org.apache.lucene.util.LuceneTestCase.SuppressReproduceLine, org.apache.lucene.util.LuceneTestCase.SuppressSysoutChecks, org.apache.lucene.util.LuceneTestCase.SuppressTempFileChecks, org.apache.lucene.util.LuceneTestCase.ThrowingRunnable, org.apache.lucene.util.LuceneTestCase.Weekly
-
-
Field Summary
-
Fields inherited from class org.elasticsearch.test.AbstractBuilderTestCase
BOOLEAN_FIELD_NAME, DATE_ALIAS_FIELD_NAME, DATE_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, MAPPED_FIELD_NAMES, MAPPED_LEAF_FIELD_NAMES, OBJECT_FIELD_NAME, randomTypes, STRING_ALIAS_FIELD_NAME, STRING_FIELD_NAME, STRING_FIELD_NAME_2
-
Fields inherited from class org.elasticsearch.test.ESTestCase
checkIndexFailed, deprecationLogger, failureAndSuccessEvents, JAVA_TIMEZONE_IDS, JAVA_ZONE_IDS, JODA_TIMEZONE_IDS, logger
-
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
Constructors Constructor Description AbstractQueryTestCase()
-
Method Summary
Modifier and Type Method Description protected void
assertParsedQuery(java.lang.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(Query query, java.lang.String field, java.lang.String value, float fieldBoost)
protected void
assertTermQuery(Query query, java.lang.String field, java.lang.String value)
protected boolean
builderGeneratesCacheableQueries()
Whether the queries produced by this builder are expected to be cacheable.protected QB
changeNameOrBoost(QB original)
static void
checkGeneratedJson(java.lang.String expected, QueryBuilder source)
Call this method to check a valid json string representing the query under test against it's generated json.QB
createTestQueryBuilder()
QB
createTestQueryBuilder(boolean supportsBoost, boolean supportsQueryName)
protected abstract void
doAssertLuceneQuery(QB queryBuilder, Query query, SearchContext context)
Checks the result ofQueryBuilder.toQuery(QueryShardContext)
given the originalQueryBuilder
andQueryShardContext
.protected abstract QB
doCreateTestQueryBuilder()
Create the query that is being testedprotected java.util.Map<java.lang.String,QB>
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)
.protected java.util.Set<java.lang.String>
getObjectsHoldingArbitraryContent()
Returns a set of object names that won't trigger any exception (uncluding their children) when testing that unknown objects cause parse exceptions throughtestUnknownObjectException()
.protected static java.lang.String
getRandomFieldName()
Helper method to return a mapped or a random fieldprotected static java.lang.String
getRandomQueryText()
protected static java.lang.String
getRandomRewriteMethod()
Helper method to return a random rewrite methodprotected static java.lang.Object
getRandomValueForFieldName(java.lang.String fieldName)
create a random value for eitherAbstractBuilderTestCase.BOOLEAN_FIELD_NAME
,AbstractBuilderTestCase.INT_FIELD_NAME
,AbstractBuilderTestCase.DOUBLE_FIELD_NAME
,AbstractBuilderTestCase.STRING_FIELD_NAME
orAbstractBuilderTestCase.DATE_FIELD_NAME
, or a String value by defaultprotected boolean
isCacheable(QB queryBuilder)
boolean
isTextField(java.lang.String fieldName)
QB
mutateInstance(QB instance)
protected QueryBuilder
parseQuery(java.lang.String queryAsString)
protected static QueryBuilder
parseQuery(XContentParser parser)
protected QueryBuilder
parseQuery(AbstractQueryBuilder<?> builder)
protected static java.lang.String
randomAnalyzer()
protected static Fuzziness
randomFuzziness(java.lang.String fieldName)
protected static java.lang.String
randomMinimumShouldMatch()
protected Query
rewrite(Query query)
protected QueryBuilder
rewriteAndFetch(QueryBuilder builder, QueryRewriteContext context)
protected java.lang.String[]
shuffleProtectedFields()
Subclasses can override this method and return an array of fieldnames which should be protected from recursive random shuffling in thetestFromXContent()
test caseprotected 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.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.void
testEqualsAndHashcode()
void
testFromXContent()
Generic test that creates new query from the test query and checks both for equality and asserts equality on the two queries.void
testMustRewrite()
This test ensures that queries that need to be rewritten have dedicated tests.void
testNegativeBoosts()
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.void
testSerialization()
Test serialization and deserialization of the test query.void
testToQuery()
Test creates theQuery
from theQueryBuilder
under test and delegates the assertions being made on the result to the implementing subclass.void
testUnknownField()
Test that unknown field trigger ParsingException.void
testUnknownObjectException()
Test that adding an additional object within each object of the otherwise correct query always triggers some kind of parse exception.void
testValidOutput()
Generic test that checks that theStrings.toString()
method renders the XContent correctly.-
Methods inherited from class org.elasticsearch.test.AbstractBuilderTestCase
afterClass, afterTest, beforeClass, beforeTest, createShardContext, createShardContext, createTestIndexSettings, createUniqueRandomName, executeGet, executeMultiTermVectors, expectedFieldName, getCurrentTypes, getIndex, getMapping, getPlugins, getSearchContext, indexSettings, initializeAdditionalMappings, isSingleType, namedWriteableRegistry, xContentRegistry
-
Methods inherited from class org.elasticsearch.test.ESTestCase
after, afterIfFailed, afterIfSuccessful, assertAllIndicesRemovedAndDeletionCompleted, assertArrayEquals, assertBusy, assertBusy, assertEquals, assertEqualsWithErrorMessageFromXContent, assertPathHasBeenCleared, assertSettingDeprecationsAndWarnings, assertSettingDeprecationsAndWarnings, assertWarnings, awaitBusy, awaitBusy, before, between, buildNewFakeTransportAddress, checkStaticState, copyInstance, copyStreamable, copyWriteable, copyWriteable, createParser, createParser, createParser, createParser, createParser, createTestAnalysis, createTestAnalysis, createTestAnalysis, enableJodaDeprecationWarningsCheck, enableWarningsCheck, ensureAllSearchContextsReleased, ensureCheckIndexPassed, ensureSupportedLocale, frequently, generateRandomStringArray, generateRandomStringArray, getBwcIndicesPath, getDataPath, getSuiteFailureMarker, getTestTransportPlugin, getTestTransportType, inFipsJvm, iterations, maybeSet, mockScript, newNodeEnvironment, newNodeEnvironment, newTestIndicesModule, newTestScriptModule, randomAlphaOfLength, randomAlphaOfLengthBetween, randomArray, randomArray, randomBoolean, randomByte, randomByteArrayOfLength, randomDateTimeZone, randomDouble, randomDoubleBetween, randomFloat, randomFrom, randomFrom, randomFrom, randomFrom, randomFrom, randomGeohash, randomInt, randomInt, randomIntBetween, randomLong, randomLongBetween, randomNonNegativeLong, randomPositiveTimeValue, randomRealisticUnicodeOfCodepointLength, randomRealisticUnicodeOfCodepointLengthBetween, randomRealisticUnicodeOfLength, randomRealisticUnicodeOfLengthBetween, randomShort, randomSubsetOf, randomSubsetOf, randomSubsetOf, randomTimeValue, randomTimeValue, randomTimeValue, randomTimeZone, randomUnicodeOfCodepointLength, randomUnicodeOfCodepointLengthBetween, randomUnicodeOfLength, randomUnicodeOfLengthBetween, randomUnique, randomValueOtherThan, randomValueOtherThanMany, randomZone, resetCheckIndexStatus, resetPortCounter, restoreContentType, restoreFileSystem, scaledRandomIntBetween, setContentType, setFileSystem, settings, shuffleMap, shuffleXContent, shuffleXContent, spinForAtLeastNMilliseconds, spinForAtLeastOneMillisecond, terminate, terminate, tmpPaths, toShuffledXContent, toShuffledXContent, writableRegistry
-
Methods inherited from class org.apache.lucene.util.LuceneTestCase
addVirusChecker, assertDeletedDocsEquals, assertDocsAndPositionsEnumEquals, assertDocsEnumEquals, assertDocsSkippingEquals, assertDocValuesEquals, assertDocValuesEquals, assertFieldInfosEquals, assertFieldsEquals, assertFieldStatisticsEquals, assertNormsEquals, assertPointsEquals, assertPositionsSkippingEquals, assertReaderEquals, assertReaderStatisticsEquals, assertStoredFieldEquals, assertStoredFieldsEquals, assertTermsEnumEquals, assertTermsEquals, assertTermsStatisticsEquals, assertTermStatsEquals, assertTermVectorsEquals, asSet, assumeFalse, assumeNoException, assumeTrue, assumeWorkingMMapOnWindows, atLeast, atLeast, closeAfterSuite, closeAfterTest, collate, createTempDir, createTempDir, createTempFile, createTempFile, dumpArray, dumpIterator, expectThrows, expectThrows, expectThrows, expectThrowsAnyOf, expectThrowsAnyOf, getBaseTempDirForTestClass, getDataInputStream, getOnlyLeafReader, getTestClass, getTestName, hasWorkingMMapOnWindows, isTestThread, localeForLanguageTag, maybeChangeLiveIndexWriterConfig, maybeWrapReader, newAlcoholicMergePolicy, newAlcoholicMergePolicy, 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, 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
-
-
-
-
Method Detail
-
createTestQueryBuilder
public final QB createTestQueryBuilder()
-
createTestQueryBuilder
public final QB createTestQueryBuilder(boolean supportsBoost, boolean supportsQueryName)
-
doCreateTestQueryBuilder
protected abstract QB doCreateTestQueryBuilder()
Create the query that is being tested
-
testNegativeBoosts
public void testNegativeBoosts()
-
testFromXContent
public void testFromXContent() throws java.io.IOException
Generic test that creates new query from the test query and checks both for equality and asserts equality on the two queries.- Throws:
java.io.IOException
-
shuffleProtectedFields
protected java.lang.String[] 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
public void testUnknownField() throws java.io.IOException
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:
java.io.IOException
-
testUnknownObjectException
public final void testUnknownObjectException() throws java.io.IOException
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:
java.io.IOException
-
getObjectsHoldingArbitraryContent
protected java.util.Set<java.lang.String> getObjectsHoldingArbitraryContent()
Returns a set of object names that won't trigger any exception (uncluding their children) when testing that unknown objects cause parse exceptions throughtestUnknownObjectException()
. Default is an empty set. 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). In such cases no exception would get thrown.
-
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
protected java.util.Map<java.lang.String,QB> 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(java.lang.String queryAsString, QueryBuilder expectedQuery) throws java.io.IOException
Parses the query provided as string argument and compares it with the expected result provided as argument as aQueryBuilder
- Throws:
java.io.IOException
-
parseQuery
protected QueryBuilder parseQuery(AbstractQueryBuilder<?> builder) throws java.io.IOException
- Throws:
java.io.IOException
-
parseQuery
protected QueryBuilder parseQuery(java.lang.String queryAsString) throws java.io.IOException
- Throws:
java.io.IOException
-
parseQuery
protected static QueryBuilder parseQuery(XContentParser parser) throws java.io.IOException
- Throws:
java.io.IOException
-
builderGeneratesCacheableQueries
protected boolean builderGeneratesCacheableQueries()
Whether the queries produced by this builder are expected to be cacheable.
-
testToQuery
public void testToQuery() throws java.io.IOException
Test creates theQuery
from theQueryBuilder
under test and delegates the assertions being made on the result to the implementing subclass.- Throws:
java.io.IOException
-
isCacheable
protected boolean isCacheable(QB queryBuilder)
-
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, Query query, SearchContext context) throws java.io.IOException
Checks the result ofQueryBuilder.toQuery(QueryShardContext)
given the originalQueryBuilder
andQueryShardContext
. Contains the query specific checks to be implemented by subclasses.- Throws:
java.io.IOException
-
assertTermOrBoostQuery
protected void assertTermOrBoostQuery(Query query, java.lang.String field, java.lang.String value, float fieldBoost)
-
assertTermQuery
protected void assertTermQuery(Query query, java.lang.String field, java.lang.String value)
-
testSerialization
public void testSerialization() throws java.io.IOException
Test serialization and deserialization of the test query.- Throws:
java.io.IOException
-
assertSerialization
protected QueryBuilder assertSerialization(QueryBuilder testQuery) throws java.io.IOException
- Throws:
java.io.IOException
-
assertSerialization
protected QueryBuilder assertSerialization(QueryBuilder testQuery, Version version) throws java.io.IOException
Serialize the given query builder and asserts that both are equal- Throws:
java.io.IOException
-
testEqualsAndHashcode
public void testEqualsAndHashcode()
-
mutateInstance
public QB mutateInstance(QB instance) throws java.io.IOException
- Throws:
java.io.IOException
-
testValidOutput
public void testValidOutput() throws java.io.IOException
Generic test that checks that theStrings.toString()
method renders the XContent correctly.- Throws:
java.io.IOException
-
changeNameOrBoost
protected QB changeNameOrBoost(QB original) throws java.io.IOException
- Throws:
java.io.IOException
-
getRandomValueForFieldName
protected static java.lang.Object getRandomValueForFieldName(java.lang.String fieldName)
create a random value for eitherAbstractBuilderTestCase.BOOLEAN_FIELD_NAME
,AbstractBuilderTestCase.INT_FIELD_NAME
,AbstractBuilderTestCase.DOUBLE_FIELD_NAME
,AbstractBuilderTestCase.STRING_FIELD_NAME
orAbstractBuilderTestCase.DATE_FIELD_NAME
, or a String value by default
-
getRandomQueryText
protected static java.lang.String getRandomQueryText()
-
getRandomFieldName
protected static java.lang.String getRandomFieldName()
Helper method to return a mapped or a random field
-
getRandomRewriteMethod
protected static java.lang.String getRandomRewriteMethod()
Helper method to return a random rewrite method
-
randomFuzziness
protected static Fuzziness randomFuzziness(java.lang.String fieldName)
-
randomAnalyzer
protected static java.lang.String randomAnalyzer()
-
randomMinimumShouldMatch
protected static java.lang.String randomMinimumShouldMatch()
-
checkGeneratedJson
public static void checkGeneratedJson(java.lang.String expected, QueryBuilder source) throws java.io.IOException
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:
java.io.IOException
-
testMustRewrite
public void testMustRewrite() throws java.io.IOException
This test ensures that queries that need to be rewritten have dedicated tests. These queries must override this method accordingly.- Throws:
java.io.IOException
-
rewrite
protected Query rewrite(Query query) throws java.io.IOException
- Throws:
java.io.IOException
-
rewriteAndFetch
protected QueryBuilder rewriteAndFetch(QueryBuilder builder, QueryRewriteContext context) throws java.io.IOException
- Throws:
java.io.IOException
-
isTextField
public boolean isTextField(java.lang.String fieldName)
-
-