Tests: Add warning header checks to QueryBuilder tests and QueryParseContextTests

This adds checks for expected warning headers to the query builder test
infrastructure. Tests that are adding deprecation warnings to the response
headers need to check those, otherwise the abstract base class for the test
class will complain at teardown.
This commit is contained in:
Christoph Büscher 2016-11-02 12:32:40 +01:00
parent a0c094d0c1
commit b3370de715
17 changed files with 186 additions and 32 deletions

View File

@ -20,6 +20,7 @@ package org.elasticsearch.transport;
import com.carrotsearch.hppc.IntHashSet;
import com.carrotsearch.hppc.IntSet;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.apache.lucene.util.IOUtils;
@ -53,8 +54,8 @@ import org.elasticsearch.common.network.NetworkUtils;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.transport.PortsRange;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.BigArrays;
@ -90,7 +91,6 @@ import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@ -366,6 +366,7 @@ public abstract class TcpTransport<Channel> extends AbstractLifecycleComponent i
return Arrays.asList(recovery, bulk, reg, state, ping);
}
@Override
public synchronized void close() throws IOException {
closeChannels(allChannels);
}

View File

@ -348,9 +348,14 @@ public class BoolQueryBuilderTests extends AbstractQueryTestCase<BoolQueryBuilde
assertEquals(query, 0, queryBuilder.filter().size());
assertEquals(query, 0, queryBuilder.mustNot().size());
assertEquals(query, 0, queryBuilder.should().size());
// we should have deprecation warning headers regardless of throwing an exception
checkWarningHeaders("query malformed, empty clause found at [1:27]",
"query malformed, empty clause found at [1:46]",
"query malformed, empty clause found at [1:100]");
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> parseQuery(query, ParseFieldMatcher.STRICT));
assertThat(ex.getMessage(), startsWith("query malformed, empty clause found at"));
checkWarningHeaders("query malformed, empty clause found at [1:27]");
}
/**

View File

@ -30,9 +30,9 @@ import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException;
import java.util.Optional;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.startsWith;;
import static org.hamcrest.CoreMatchers.nullValue;;
public class BoostingQueryBuilderTests extends AbstractQueryTestCase<BoostingQueryBuilder> {
@ -110,22 +110,27 @@ public class BoostingQueryBuilderTests extends AbstractQueryTestCase<BoostingQue
Optional<QueryBuilder> innerQueryBuilder = context.parseInnerQueryBuilder();
assertTrue(innerQueryBuilder.isPresent() == false);
checkWarningHeaders("query malformed, empty clause found at [1:36]");
query =
"{ \"boosting\" : {" +
" \"positive\" : { \"match_all\" : {} }, " +
" \"negative\" : { }, " +
" \"negative_boost\" : 23.0" +
" }" +
"{ \"boosting\" : {\n" +
" \"positive\" : { \"match_all\" : {} },\n" +
" \"negative\" : { },\n" +
" \"negative_boost\" : 23.0\n" +
" }\n" +
"}";
parser = XContentFactory.xContent(query).createParser(query);
context = createParseContext(parser, ParseFieldMatcher.EMPTY);
innerQueryBuilder = context.parseInnerQueryBuilder();
assertTrue(innerQueryBuilder.isPresent() == false);
checkWarningHeaders("query malformed, empty clause found at [3:20]");
parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext otherContext = createParseContext(parser, ParseFieldMatcher.STRICT);
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> otherContext.parseInnerQueryBuilder());
assertThat(ex.getMessage(), startsWith("query malformed, empty clause found at"));
assertThat(ex.getMessage(), equalTo("query malformed, empty clause found at [3:20]"));
checkWarningHeaders("query malformed, empty clause found at [3:20]");
}
public void testRewrite() throws IOException {

View File

@ -31,9 +31,9 @@ import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException;
import java.util.Optional;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.Matchers.containsString;
public class ConstantScoreQueryBuilderTests extends AbstractQueryTestCase<ConstantScoreQueryBuilder> {
@ -133,11 +133,13 @@ public class ConstantScoreQueryBuilderTests extends AbstractQueryTestCase<Consta
QueryParseContext context = createParseContext(parser, ParseFieldMatcher.EMPTY);
Optional<QueryBuilder> innerQueryBuilder = context.parseInnerQueryBuilder();
assertTrue(innerQueryBuilder.isPresent() == false);
checkWarningHeaders("query malformed, empty clause found at [1:40]");
parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext otherContext = createParseContext(parser, ParseFieldMatcher.STRICT);
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> otherContext.parseInnerQueryBuilder());
assertThat(ex.getMessage(), startsWith("query malformed, empty clause found at"));
assertThat(ex.getMessage(), equalTo("query malformed, empty clause found at [1:40]"));
checkWarningHeaders("query malformed, empty clause found at [1:40]");
}
}

View File

@ -99,6 +99,7 @@ public class DisMaxQueryBuilderTests extends AbstractQueryTestCase<DisMaxQueryBu
Query luceneQuery = queryBuilder.toQuery(context);
assertThat(luceneQuery, instanceOf(MatchNoDocsQuery.class));
assertThat(luceneQuery.toString(), equalTo("MatchNoDocsQuery(\"no clauses for dismax query.\")"));
checkWarningHeaders("query malformed, empty clause found at [1:78]");
}
public void testIllegalArguments() {

View File

@ -27,6 +27,8 @@ import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.test.AbstractQueryTestCase;
import org.junit.After;
import org.junit.internal.AssumptionViolatedException;
import java.io.IOException;
import java.util.HashMap;
@ -38,6 +40,20 @@ import static org.hamcrest.Matchers.instanceOf;
public class FuzzyQueryBuilderTests extends AbstractQueryTestCase<FuzzyQueryBuilder> {
private boolean testSkipped = false;
/**
* All tests create deprecation warnings when an new FuzzyQueryBuilder is created. Instead of having to check them once
* in every single test, this is done here after each test is run
*/
@After
void checkWarningHeaders() throws IOException {
// only check that warning headers got created for tests that satisfied certain assumptions and were thus not skipped
if (testSkipped == false) {
checkWarningHeaders("fuzzy query is deprecated. Instead use the [match] query with fuzziness parameter");
}
}
@Override
protected FuzzyQueryBuilder doCreateTestQueryBuilder() {
FuzzyQueryBuilder query = new FuzzyQueryBuilder(STRING_FIELD_NAME, getRandomValueForFieldName(STRING_FIELD_NAME));
@ -98,7 +114,13 @@ public class FuzzyQueryBuilderTests extends AbstractQueryTestCase<FuzzyQueryBuil
}
public void testToQueryWithStringField() throws IOException {
assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
try {
assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
} catch (AssumptionViolatedException e) {
// we need to know that this test was skipped in @After checkWarningHeaders(), because no warnings will be generated
testSkipped = true;
throw e;
}
String query = "{\n" +
" \"fuzzy\":{\n" +
" \"" + STRING_FIELD_NAME + "\":{\n" +
@ -121,7 +143,13 @@ public class FuzzyQueryBuilderTests extends AbstractQueryTestCase<FuzzyQueryBuil
}
public void testToQueryWithNumericField() throws IOException {
assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
try {
assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
} catch (AssumptionViolatedException e) {
// we need to know that this test was skipped in @After checkWarningHeaders(), because no warnings will be generated
testSkipped = true;
throw e;
}
String query = "{\n" +
" \"fuzzy\":{\n" +
" \"" + INT_FIELD_NAME + "\":{\n" +
@ -157,7 +185,16 @@ public class FuzzyQueryBuilderTests extends AbstractQueryTestCase<FuzzyQueryBuil
}
public void testParseFailsWithMultipleFields() throws IOException {
String json = "{\n" +
String json1 = "{\n" +
" \"fuzzy\" : {\n" +
" \"message1\" : {\n" +
" \"value\" : \"this is a test\"\n" +
" }\n" +
" }\n" +
"}";
parseQuery(json1); // should be all good
String json2 = "{\n" +
" \"fuzzy\" : {\n" +
" \"message1\" : {\n" +
" \"value\" : \"this is a test\"\n" +
@ -168,7 +205,7 @@ public class FuzzyQueryBuilderTests extends AbstractQueryTestCase<FuzzyQueryBuil
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json2));
assertEquals("[fuzzy] query doesn't support multiple fields, found [message1] and [message2]", e.getMessage());
String shortJson = "{\n" +

View File

@ -20,6 +20,7 @@
package org.elasticsearch.index.query;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import org.apache.lucene.queries.TermsQuery;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
@ -58,7 +59,6 @@ import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.startsWith;
public class HasChildQueryBuilderTests extends AbstractQueryTestCase<HasChildQueryBuilder> {
protected static final String PARENT_TYPE = "parent";
@ -241,7 +241,8 @@ public class HasChildQueryBuilderTests extends AbstractQueryTestCase<HasChildQue
parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext otherContext = createParseContext(parser, ParseFieldMatcher.STRICT);
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> otherContext.parseInnerQueryBuilder());
assertThat(ex.getMessage(), startsWith("query malformed, empty clause found at"));
assertThat(ex.getMessage(), equalTo("query malformed, empty clause found at [3:17]"));
checkWarningHeaders("query malformed, empty clause found at [3:17]");
}
public void testToQueryInnerQueryType() throws IOException {

View File

@ -45,7 +45,6 @@ import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.startsWith;
public class HasParentQueryBuilderTests extends AbstractQueryTestCase<HasParentQueryBuilder> {
protected static final String PARENT_TYPE = "parent";
@ -157,6 +156,7 @@ public class HasParentQueryBuilderTests extends AbstractQueryTestCase<HasParentQ
HasParentQueryBuilder queryBuilder = (HasParentQueryBuilder) parseQuery(builder.string(), ParseFieldMatcher.EMPTY);
assertEquals("foo", queryBuilder.type());
checkWarningHeaders("Deprecated field [type] used, expected [parent_type] instead");
}
public void testToQueryInnerQueryType() throws IOException {
@ -221,10 +221,13 @@ public class HasParentQueryBuilderTests extends AbstractQueryTestCase<HasParentQ
Optional<QueryBuilder> innerQueryBuilder = context.parseInnerQueryBuilder();
assertTrue(innerQueryBuilder.isPresent() == false);
checkWarningHeaders("query malformed, empty clause found at [3:17]");
parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext otherContext = createParseContext(parser, ParseFieldMatcher.STRICT);
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> otherContext.parseInnerQueryBuilder());
assertThat(ex.getMessage(), startsWith("query malformed, empty clause found at"));
assertThat(ex.getMessage(), equalTo("query malformed, empty clause found at [3:17]"));
checkWarningHeaders("query malformed, empty clause found at [3:17]");
}
public void testIgnoreUnmapped() throws IOException {

View File

@ -140,6 +140,7 @@ public class IdsQueryBuilderTests extends AbstractQueryTestCase<IdsQueryBuilder>
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(contentString));
assertEquals("Deprecated field [_type] used, expected [type] instead", e.getMessage());
checkWarningHeaders("Deprecated field [_type] used, expected [type] instead");
//array of types can also be called type rather than types
final String contentString2 = "{\n" +
@ -153,5 +154,6 @@ public class IdsQueryBuilderTests extends AbstractQueryTestCase<IdsQueryBuilder>
e = expectThrows(IllegalArgumentException.class, () -> parseQuery(contentString2));
assertEquals("Deprecated field [types] used, expected [type] instead", e.getMessage());
checkWarningHeaders("Deprecated field [_type] used, expected [type] instead");
}
}

View File

@ -22,11 +22,21 @@ package org.elasticsearch.index.query;
import org.apache.lucene.search.Query;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.test.AbstractQueryTestCase;
import org.junit.After;
import java.io.IOException;
public class IndicesQueryBuilderTests extends AbstractQueryTestCase<IndicesQueryBuilder> {
/**
* All tests create deprecation warnings when an new {@link IndicesQueryBuilder} is created.
* Instead of having to check them once in every single test, this is done here after each test is run
*/
@After
void checkWarningHeaders() throws IOException {
checkWarningHeaders("indices query is deprecated. Instead search on the '_index' field");
}
@Override
protected IndicesQueryBuilder doCreateTestQueryBuilder() {
String[] indices;

View File

@ -313,6 +313,9 @@ public class MatchQueryBuilderTests extends AbstractQueryTestCase<MatchQueryBuil
assertSerialization(qb);
checkWarningHeaders("Deprecated field [type] used, replaced by [match_phrase and match_phrase_prefix query]",
"Deprecated field [slop] used, replaced by [match_phrase query]");
// Now check with strict parsing an exception is thrown
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(json, ParseFieldMatcher.STRICT));
assertThat(e.getMessage(),
@ -346,6 +349,9 @@ public class MatchQueryBuilderTests extends AbstractQueryTestCase<MatchQueryBuil
assertSerialization(qb);
checkWarningHeaders("Deprecated field [type] used, replaced by [match_phrase and match_phrase_prefix query]",
"Deprecated field [slop] used, replaced by [match_phrase query]");
// Now check with strict parsing an exception is thrown
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(json, ParseFieldMatcher.STRICT));
assertThat(e.getMessage(),
@ -372,6 +378,8 @@ public class MatchQueryBuilderTests extends AbstractQueryTestCase<MatchQueryBuil
"}";
MatchQueryBuilder qb = (MatchQueryBuilder) parseQuery(json, ParseFieldMatcher.EMPTY);
assertThat(qb, equalTo(expectedQB));
checkWarningHeaders("Deprecated field [" + type + "] used, expected [match] instead",
"Deprecated field [slop] used, replaced by [match_phrase query]");
// Now check with strict parsing an exception is thrown
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(json, ParseFieldMatcher.STRICT));

View File

@ -367,5 +367,7 @@ public class MoreLikeThisQueryBuilderTests extends AbstractQueryTestCase<MoreLik
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(deprecatedJson));
assertEquals("Deprecated field [mlt] used, expected [more_like_this] instead", e.getMessage());
checkWarningHeaders("Deprecated field [mlt] used, expected [more_like_this] instead");
}
}

View File

@ -21,20 +21,27 @@ package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.search.SearchModule;
import org.elasticsearch.test.ESTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import static java.util.Collections.emptyList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
public class QueryParseContextTests extends ESTestCase {
@ -45,6 +52,20 @@ public class QueryParseContextTests extends ESTestCase {
indicesQueriesRegistry = new SearchModule(Settings.EMPTY, false, emptyList()).getQueryParserRegistry();
}
private ThreadContext threadContext;
@Before
public void beforeTest() throws IOException {
this.threadContext = new ThreadContext(Settings.EMPTY);
DeprecationLogger.setThreadContext(threadContext);
}
@After
public void teardown() throws IOException {
DeprecationLogger.removeThreadContext(this.threadContext);
this.threadContext.close();
}
public void testParseTopLevelBuilder() throws IOException {
QueryBuilder query = new MatchQueryBuilder("foo", "bar");
String requestBody = "{ \"query\" : " + query.toString() + "}";
@ -89,6 +110,9 @@ public class QueryParseContextTests extends ESTestCase {
QueryParseContext context = new QueryParseContext(indicesQueriesRegistry, parser, ParseFieldMatcher.EMPTY);
Optional<QueryBuilder> emptyQuery = context.parseInnerQueryBuilder();
assertFalse(emptyQuery.isPresent());
final List<String> warnings = threadContext.getResponseHeaders().get(DeprecationLogger.DEPRECATION_HEADER);
assertThat(warnings, hasSize(1));
assertThat(warnings, hasItem(equalTo("query malformed, empty clause found at [1:2]")));
}
}
@ -107,6 +131,9 @@ public class QueryParseContextTests extends ESTestCase {
QueryParseContext context = new QueryParseContext(indicesQueriesRegistry, parser, ParseFieldMatcher.STRICT);
IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> context.parseInnerQueryBuilder());
assertEquals("query malformed, empty clause found at [1:2]", exception.getMessage());
final List<String> warnings = threadContext.getResponseHeaders().get(DeprecationLogger.DEPRECATION_HEADER);
assertThat(warnings, hasSize(1));
assertThat(warnings, hasItem(equalTo("query malformed, empty clause found at [1:2]")));
}
source = "{ \"foo\" : \"bar\" }";
@ -122,6 +149,9 @@ public class QueryParseContextTests extends ESTestCase {
ParsingException exception = expectThrows(ParsingException.class, () -> context.parseInnerQueryBuilder());
assertEquals("no [query] registered for [foo]", exception.getMessage());
}
final List<String> warnings = threadContext.getResponseHeaders().get(DeprecationLogger.DEPRECATION_HEADER);
assertThat(warnings, hasSize(1));
assertThat(warnings, hasItem(equalTo("query malformed, empty clause found at [1:2]")));
}
}

View File

@ -21,6 +21,7 @@ package org.elasticsearch.index.query;
import com.carrotsearch.randomizedtesting.generators.RandomNumbers;
import com.carrotsearch.randomizedtesting.generators.RandomStrings;
import org.elasticsearch.test.AbstractQueryTestCase;
import java.util.Random;
@ -61,7 +62,7 @@ public class RandomQueryBuilder {
// for now, only use String Rangequeries for MultiTerm test, numeric and date makes little sense
// see issue #12123 for discussion
MultiTermQueryBuilder multiTermQueryBuilder;
switch(RandomNumbers.randomIntBetween(r, 0, 3)) {
switch(RandomNumbers.randomIntBetween(r, 0, 2)) {
case 0:
RangeQueryBuilder stringRangeQuery = new RangeQueryBuilder(AbstractQueryTestCase.STRING_FIELD_NAME);
stringRangeQuery.from("a" + RandomStrings.randomAsciiOfLengthBetween(r, 1, 10));
@ -69,12 +70,9 @@ public class RandomQueryBuilder {
multiTermQueryBuilder = stringRangeQuery;
break;
case 1:
multiTermQueryBuilder = new FuzzyQueryBuilder(AbstractQueryTestCase.STRING_FIELD_NAME, RandomStrings.randomAsciiOfLengthBetween(r, 1, 10));
break;
case 2:
multiTermQueryBuilder = new PrefixQueryBuilderTests().createTestQueryBuilder();
break;
case 3:
case 2:
multiTermQueryBuilder = new WildcardQueryBuilderTests().createTestQueryBuilder();
break;
default:

View File

@ -20,6 +20,7 @@
package org.elasticsearch.index.query.functionscore;
import com.fasterxml.jackson.core.JsonParseException;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
@ -589,13 +590,13 @@ public class FunctionScoreQueryBuilderTests extends AbstractQueryTestCase<Functi
String json =
"{\n" +
" \"function_score\" : {\n" +
" \"query\" : { },\n" +
" \"query\" : { \"match_all\" : {} },\n" +
" \"functions\" : [ {\n" +
" \"filter\" : { },\n" +
" \"filter\" : { \"match_all\" : {}},\n" +
" \"weight\" : 23.0,\n" +
" \"random_score\" : { }\n" +
" }, {\n" +
" \"filter\" : { },\n" +
" \"filter\" : { \"match_all\" : {}},\n" +
" \"weight\" : 5.0\n" +
" } ],\n" +
" \"score_mode\" : \"multiply\",\n" +
@ -613,11 +614,11 @@ public class FunctionScoreQueryBuilderTests extends AbstractQueryTestCase<Functi
" \"function_score\" : {\n" +
" \"query\" : { \"match_all\" : {} },\n" +
" \"functions\" : [ {\n" +
" \"filter\" : { },\n" +
" \"filter\" : { \"match_all\" : {}},\n" +
" \"weight\" : 23.0,\n" +
" \"random_score\" : { }\n" +
" }, {\n" +
" \"filter\" : { },\n" +
" \"filter\" : { \"match_all\" : {}},\n" +
" \"weight\" : 5.0\n" +
" } ],\n" +
" \"score_mode\" : \"multiply\",\n" +

View File

@ -39,6 +39,7 @@ import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.test.AbstractQueryTestCase;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
@ -56,6 +57,14 @@ public class TemplateQueryBuilderTests extends AbstractQueryTestCase<TemplateQue
*/
private QueryBuilder templateBase;
/**
* All tests create deprecation warnings when an new {@link TemplateQueryBuilder} is created.
* Instead of having to check them once in every single test, this is done here after each test is run
*/
@After void checkWarningHeaders() throws IOException {
checkWarningHeaders("[template] query is deprecated, use search template api instead");
}
@Override
protected Collection<Class<? extends Plugin>> getPlugins() {
return Arrays.asList(MustachePlugin.class, CustomScriptPlugin.class);

View File

@ -52,11 +52,13 @@ import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
@ -123,10 +125,12 @@ import java.util.concurrent.ExecutionException;
import static java.util.Collections.emptyList;
import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.either;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>> extends ESTestCase {
@ -155,6 +159,10 @@ public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>>
private static String[] currentTypes;
private static String[] randomTypes;
/**
* used to check warning headers of the deprecation logger
*/
private ThreadContext threadContext;
protected static Index getIndex() {
return index;
@ -209,6 +217,20 @@ public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>>
serviceHolder = new ServiceHolder(nodeSettings, indexSettings, getPlugins(), this);
}
serviceHolder.clientInvocationHandler.delegate = this;
this.threadContext = new ThreadContext(Settings.EMPTY);
DeprecationLogger.setThreadContext(threadContext);
}
/**
* Check that there are no unaccounted warning headers. These should be checked with {@link #checkWarningHeaders(String...)} in the
* appropriate test
*/
@After
public void teardown() throws IOException {
final List<String> warnings = threadContext.getResponseHeaders().get(DeprecationLogger.DEPRECATION_HEADER);
assertNull("unexpected warning headers", warnings);
DeprecationLogger.removeThreadContext(this.threadContext);
this.threadContext.close();
}
private static SearchContext getSearchContext(String[] types, QueryShardContext context) {
@ -1009,6 +1031,23 @@ public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>>
return query;
}
protected void checkWarningHeaders(String... messages) {
final List<String> warnings = threadContext.getResponseHeaders().get(DeprecationLogger.DEPRECATION_HEADER);
assertThat(warnings, hasSize(messages.length));
for (String msg : messages) {
assertThat(warnings, hasItem(equalTo(msg)));
}
// "clear" current warning headers by setting a new ThreadContext
DeprecationLogger.removeThreadContext(this.threadContext);
try {
this.threadContext.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
this.threadContext = new ThreadContext(Settings.EMPTY);
DeprecationLogger.setThreadContext(this.threadContext);
}
private static class ServiceHolder implements Closeable {
private final IndicesQueriesRegistry indicesQueriesRegistry;