Skip to content

armgit / solr

Public Imported from GitHub
0

Apache Solr open-source search software

SOLR-18354: Remove SolrTestCaseJ4.ignoreException/unIgnoreException/resetExceptionIgnores (#4787)

Serhiy Bzhezytskyy218ce981ba94
diff --git a/changelog/unreleased/SOLR-18354-remove-ignoreexception.yml b/changelog/unreleased/SOLR-18354-remove-ignoreexception.yml
new file mode 100644
index 00000000000..08eec71fe23
--- /dev/null
+++ b/changelog/unreleased/SOLR-18354-remove-ignoreexception.yml
@@ -0,0 +1,11 @@
+title: >
+ Removed the deprecated `SolrTestCaseJ4.ignoreException(String)`, `unIgnoreException(String)`, and
+ `resetExceptionIgnores()` methods. Use `ErrorLogMuter` instead (`try (ErrorLogMuter muter =
+ ErrorLogMuter.regex("pattern")) { ... }`). This affects test code written against the
+ `solr-test-framework` artifact.
+type: removed
+authors:
+ - name: Serhiy Bzhezytskyy
+links:
+ - name: SOLR-18354
+ url: https://issues.apache.org/jira/browse/SOLR-18354
diff --git a/solr/core/src/test/org/apache/solr/BasicFunctionalityTest.java b/solr/core/src/test/org/apache/solr/BasicFunctionalityTest.java
index ac1a824752f..67de5992183 100644
--- a/solr/core/src/test/org/apache/solr/BasicFunctionalityTest.java
+++ b/solr/core/src/test/org/apache/solr/BasicFunctionalityTest.java
@@ -53,6 +53,7 @@ import org.apache.solr.search.DocIterator;
import org.apache.solr.search.DocList;
import org.apache.solr.security.AuthorizationContext;
import org.apache.solr.util.BaseTestHarness;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.SolrMetricTestUtils;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -288,120 +289,127 @@ public class BasicFunctionalityTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testClientErrorOnMalformedDate() {
final String BAD_VALUE = "NOT_A_DATE";
- ignoreException(BAD_VALUE);
-
- final List<String> FIELDS = new ArrayList<>();
- for (String type :
- new String[] {"tdt", "tdt1", "tdtdv", "tdtdv1", "dt_dv", "dt_dvo", "dt", "dt1", "dt_os"}) {
- FIELDS.add("malformed_" + type);
- }
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(BAD_VALUE)) {
+
+ final List<String> FIELDS = new ArrayList<>();
+ for (String type :
+ new String[] {
+ "tdt", "tdt1", "tdtdv", "tdtdv1", "dt_dv", "dt_dvo", "dt", "dt1", "dt_os"
+ }) {
+ FIELDS.add("malformed_" + type);
+ }
- // test that malformed numerics cause client error not server error
- for (String field : FIELDS) {
- SolrException e1 =
- expectThrows(
- SolrException.class,
- "Didn't encounter an error trying to add a bad date: " + field,
- () -> h.update(add(doc("id", "100", field, BAD_VALUE))));
- String msg1 = e1.getMessage();
- assertTrue(
- "not an (update) client error on field: " + field + " : " + msg1,
- 400 <= e1.code() && e1.code() < 500);
- assertTrue(
- "(update) client error does not mention bad value: " + msg1, msg1.contains(BAD_VALUE));
- assertTrue("client error does not mention document id: " + msg1, msg1.contains("[doc=100]"));
- SchemaField sf = h.getCore().getLatestSchema().getField(field);
- if (!sf.hasDocValues() && !sf.indexed()) {
- continue;
+ // test that malformed numerics cause client error not server error
+ for (String field : FIELDS) {
+ SolrException e1 =
+ expectThrows(
+ SolrException.class,
+ "Didn't encounter an error trying to add a bad date: " + field,
+ () -> h.update(add(doc("id", "100", field, BAD_VALUE))));
+ String msg1 = e1.getMessage();
+ assertTrue(
+ "not an (update) client error on field: " + field + " : " + msg1,
+ 400 <= e1.code() && e1.code() < 500);
+ assertTrue(
+ "(update) client error does not mention bad value: " + msg1, msg1.contains(BAD_VALUE));
+ assertTrue(
+ "client error does not mention document id: " + msg1, msg1.contains("[doc=100]"));
+ SchemaField sf = h.getCore().getLatestSchema().getField(field);
+ if (!sf.hasDocValues() && !sf.indexed()) {
+ continue;
+ }
+ SolrException e2 =
+ expectThrows(
+ SolrException.class,
+ "Didn't encounter an error trying to add a bad date: " + field,
+ () -> h.query(req("q", field + ":" + BAD_VALUE)));
+ String msg2 = e2.toString();
+ assertTrue(
+ "not a (search) client error on field: " + field + " : " + msg2,
+ 400 <= e2.code() && e2.code() < 500);
+ assertTrue(
+ "(search) client error does not mention bad value: " + msg2, msg2.contains(BAD_VALUE));
+
+ SolrException e3 =
+ expectThrows(
+ SolrException.class,
+ "Didn't encounter an error trying to add a bad date: " + field,
+ () -> h.query(req("q", field + ":[NOW TO " + BAD_VALUE + "]")));
+ String msg3 = e3.toString();
+ assertTrue(
+ "not a (search) client error on field: " + field + " : " + msg3,
+ 400 <= e3.code() && e3.code() < 500);
+ assertTrue(
+ "(search) client error does not mention bad value: " + msg3, msg3.contains(BAD_VALUE));
}
- SolrException e2 =
- expectThrows(
- SolrException.class,
- "Didn't encounter an error trying to add a bad date: " + field,
- () -> h.query(req("q", field + ":" + BAD_VALUE)));
- String msg2 = e2.toString();
- assertTrue(
- "not a (search) client error on field: " + field + " : " + msg2,
- 400 <= e2.code() && e2.code() < 500);
- assertTrue(
- "(search) client error does not mention bad value: " + msg2, msg2.contains(BAD_VALUE));
-
- SolrException e3 =
- expectThrows(
- SolrException.class,
- "Didn't encounter an error trying to add a bad date: " + field,
- () -> h.query(req("q", field + ":[NOW TO " + BAD_VALUE + "]")));
- String msg3 = e3.toString();
- assertTrue(
- "not a (search) client error on field: " + field + " : " + msg3,
- 400 <= e3.code() && e3.code() < 500);
- assertTrue(
- "(search) client error does not mention bad value: " + msg3, msg3.contains(BAD_VALUE));
}
}
@Test
+ @SuppressWarnings("try")
public void testClientErrorOnMalformedNumbers() {
final String BAD_VALUE = "NOT_A_NUMBER";
- ignoreException(BAD_VALUE);
-
- final List<String> FIELDS = new ArrayList<>();
- for (String type :
- new String[] {
- "ti", "tf", "td", "tl",
- "i", "f", "d", "l",
- "i_dv", "f_dv", "d_dv", "l_dv",
- "i_dvo", "f_dvo", "d_dvo", "l_dvo",
- "i_os", "f_os", "d_os", "l_os"
- }) {
- FIELDS.add("malformed_" + type);
- }
-
- // test that malformed numerics cause client error not server error
- for (String field : FIELDS) {
- SolrException e1 =
- expectThrows(
- SolrException.class,
- "Didn't encounter an error trying to add a non-number: " + field,
- () -> h.update(add(doc("id", "100", field, BAD_VALUE))));
- String msg1 = e1.toString();
- assertTrue(
- "not an (update) client error on field: " + field + " : " + msg1,
- 400 <= e1.code() && e1.code() < 500);
- assertTrue(
- "(update) client error does not mention bad value: " + msg1, msg1.contains(BAD_VALUE));
- assertTrue("client error does not mention document id", msg1.contains("[doc=100]"));
- SchemaField sf = h.getCore().getLatestSchema().getField(field);
- if (!sf.hasDocValues() && !sf.indexed()) {
- continue;
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(BAD_VALUE)) {
+
+ final List<String> FIELDS = new ArrayList<>();
+ for (String type :
+ new String[] {
+ "ti", "tf", "td", "tl",
+ "i", "f", "d", "l",
+ "i_dv", "f_dv", "d_dv", "l_dv",
+ "i_dvo", "f_dvo", "d_dvo", "l_dvo",
+ "i_os", "f_os", "d_os", "l_os"
+ }) {
+ FIELDS.add("malformed_" + type);
}
- SolrException e2 =
- expectThrows(
- SolrException.class,
- "Didn't encounter an error trying to add a non-number: " + field,
- () -> h.query(req("q", field + ":" + BAD_VALUE)));
- String msg2 = e2.toString();
- assertTrue(
- "not a (search) client error on field: " + field + " : " + msg2,
- 400 <= e2.code() && e2.code() < 500);
- assertTrue(
- "(search) client error does not mention bad value: " + msg2, msg2.contains(BAD_VALUE));
-
- SolrException e3 =
- expectThrows(
- SolrException.class,
- "Didn't encounter an error trying to add a non-number: " + field,
- () -> h.query(req("q", field + ":[10 TO " + BAD_VALUE + "]")));
- String msg3 = e3.toString();
- assertTrue(
- "not a (search) client error on field: " + field + " : " + msg3,
- 400 <= e3.code() && e3.code() < 500);
- assertTrue(
- "(search) client error does not mention bad value: " + msg3, msg3.contains(BAD_VALUE));
+ // test that malformed numerics cause client error not server error
+ for (String field : FIELDS) {
+ SolrException e1 =
+ expectThrows(
+ SolrException.class,
+ "Didn't encounter an error trying to add a non-number: " + field,
+ () -> h.update(add(doc("id", "100", field, BAD_VALUE))));
+ String msg1 = e1.toString();
+ assertTrue(
+ "not an (update) client error on field: " + field + " : " + msg1,
+ 400 <= e1.code() && e1.code() < 500);
+ assertTrue(
+ "(update) client error does not mention bad value: " + msg1, msg1.contains(BAD_VALUE));
+ assertTrue("client error does not mention document id", msg1.contains("[doc=100]"));
+ SchemaField sf = h.getCore().getLatestSchema().getField(field);
+ if (!sf.hasDocValues() && !sf.indexed()) {
+ continue;
+ }
+
+ SolrException e2 =
+ expectThrows(
+ SolrException.class,
+ "Didn't encounter an error trying to add a non-number: " + field,
+ () -> h.query(req("q", field + ":" + BAD_VALUE)));
+ String msg2 = e2.toString();
+ assertTrue(
+ "not a (search) client error on field: " + field + " : " + msg2,
+ 400 <= e2.code() && e2.code() < 500);
+ assertTrue(
+ "(search) client error does not mention bad value: " + msg2, msg2.contains(BAD_VALUE));
+
+ SolrException e3 =
+ expectThrows(
+ SolrException.class,
+ "Didn't encounter an error trying to add a non-number: " + field,
+ () -> h.query(req("q", field + ":[10 TO " + BAD_VALUE + "]")));
+ String msg3 = e3.toString();
+ assertTrue(
+ "not a (search) client error on field: " + field + " : " + msg3,
+ 400 <= e3.code() && e3.code() < 500);
+ assertTrue(
+ "(search) client error does not mention bad value: " + msg3, msg3.contains(BAD_VALUE));
+ }
}
}
@@ -973,6 +981,7 @@ public class BasicFunctionalityTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testAbuseOfSort() {
assertU(
@@ -988,25 +997,25 @@ public class BasicFunctionalityTest extends SolrTestCaseJ4 {
assertU(commit());
- for (String f : Arrays.asList("sortabuse_not_uninvertible", "sortabuse_t")) {
- RuntimeException outerEx =
- expectThrows(
- RuntimeException.class,
- () -> {
- ignoreException("sortabuse");
- assertQ(
- "sort on something that shouldn't work",
- req("q", "*:*", "sort", f + " asc"),
- "*[count(//doc)=2]");
- });
- Throwable root = getRootCause(outerEx);
- assertEquals("sort exception root cause", SolrException.class, root.getClass());
- SolrException e = (SolrException) root;
- assertEquals(
- "incorrect error type",
- SolrException.ErrorCode.BAD_REQUEST,
- SolrException.ErrorCode.getErrorCode(e.code()));
- assertTrue("exception doesn't contain field name", e.getMessage().contains(f));
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("sortabuse")) {
+ for (String f : Arrays.asList("sortabuse_not_uninvertible", "sortabuse_t")) {
+ RuntimeException outerEx =
+ expectThrows(
+ RuntimeException.class,
+ () ->
+ assertQ(
+ "sort on something that shouldn't work",
+ req("q", "*:*", "sort", f + " asc"),
+ "*[count(//doc)=2]"));
+ Throwable root = getRootCause(outerEx);
+ assertEquals("sort exception root cause", SolrException.class, root.getClass());
+ SolrException e = (SolrException) root;
+ assertEquals(
+ "incorrect error type",
+ SolrException.ErrorCode.BAD_REQUEST,
+ SolrException.ErrorCode.getErrorCode(e.code()));
+ assertTrue("exception doesn't contain field name", e.getMessage().contains(f));
+ }
}
}
diff --git a/solr/core/src/test/org/apache/solr/CursorPagingTest.java b/solr/core/src/test/org/apache/solr/CursorPagingTest.java
index fafe2b18fca..44f56298a6f 100644
--- a/solr/core/src/test/org/apache/solr/CursorPagingTest.java
+++ b/solr/core/src/test/org/apache/solr/CursorPagingTest.java
@@ -48,6 +48,7 @@ import org.apache.solr.common.params.SolrParams;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.search.CursorMark;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.LogLevel;
import org.apache.solr.util.SolrMetricTestUtils;
import org.junit.After;
@@ -1155,22 +1156,15 @@ public class CursorPagingTest extends SolrTestCaseJ4 {
}
/** execute a local request, verify that we get an expected error */
+ @SuppressWarnings("try")
public void assertFail(SolrParams p, ErrorCode expCode, String expSubstr) {
- try {
- SolrException e =
- expectThrows(
- SolrException.class,
- () -> {
- ignoreException(expSubstr);
- assertJQ(req(p));
- });
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(expSubstr)) {
+ SolrException e = expectThrows(SolrException.class, () -> assertJQ(req(p)));
assertEquals(expCode.code, e.code());
assertTrue(
"Expected substr not found: " + expSubstr + " <!< " + e.getMessage(),
e.getMessage().contains(expSubstr));
- } finally {
- unIgnoreException(expSubstr);
}
}
diff --git a/solr/core/src/test/org/apache/solr/TestCursorMarkWithoutUniqueKey.java b/solr/core/src/test/org/apache/solr/TestCursorMarkWithoutUniqueKey.java
index 7517070d657..7b6ff73c58b 100644
--- a/solr/core/src/test/org/apache/solr/TestCursorMarkWithoutUniqueKey.java
+++ b/solr/core/src/test/org/apache/solr/TestCursorMarkWithoutUniqueKey.java
@@ -19,6 +19,7 @@ package org.apache.solr;
import static org.apache.solr.common.params.CursorMarkParams.CURSOR_MARK_START;
import org.apache.solr.schema.SchemaField;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.After;
import org.junit.Before;
@@ -47,21 +48,19 @@ public class TestCursorMarkWithoutUniqueKey extends SolrTestCaseJ4 {
deleteCore();
}
+ @SuppressWarnings("try")
public void test() {
assertU(adoc("fld", "val"));
assertU(commit());
- try {
- ignoreException(
- "Cursor functionality is not available unless the IndexSchema defines a uniqueKey field");
+ try (ErrorLogMuter ignored =
+ ErrorLogMuter.regex(
+ "Cursor functionality is not available unless the IndexSchema defines a uniqueKey field")) {
expectThrows(
RuntimeException.class,
"No exception when querying with a cursorMark with no uniqueKey defined.",
() -> assertQ(req("q", "*:*", "sort", "fld desc", "cursorMark", CURSOR_MARK_START)));
- } finally {
- unIgnoreException(
- "Cursor functionality is not available unless the IndexSchema defines a uniqueKey field");
}
}
}
diff --git a/solr/core/src/test/org/apache/solr/TestDistributedGrouping.java b/solr/core/src/test/org/apache/solr/TestDistributedGrouping.java
index 55b336bb074..28fab47d83b 100644
--- a/solr/core/src/test/org/apache/solr/TestDistributedGrouping.java
+++ b/solr/core/src/test/org/apache/solr/TestDistributedGrouping.java
@@ -34,6 +34,7 @@ import org.apache.solr.handler.component.ShardRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.search.grouping.distributed.requestfactory.TopGroupsShardRequestFactory;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -69,7 +70,7 @@ public class TestDistributedGrouping extends BaseDistributedSearchTestCase {
String oddField = "oddField_s1";
@Test
- @SuppressWarnings({"unchecked"})
+ @SuppressWarnings({"unchecked", "try"})
public void test() throws Exception {
del("*:*");
commit();
@@ -878,24 +879,25 @@ public class TestDistributedGrouping extends BaseDistributedSearchTestCase {
"sort",
i1 + " asc, id asc");
- ignoreException("'group.offset' parameter cannot be negative");
- SolrException exception =
- expectThrows(
- SolrException.class,
- () ->
- query(
- "q",
- "*:*",
- "group",
- "true",
- "group.query",
- t1 + ":kings OR " + t1 + ":eggs",
- "group.offset",
- "-1"));
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, exception.code());
- assertThat(
- exception.getMessage(), containsString("'group.offset' parameter cannot be negative"));
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored =
+ ErrorLogMuter.regex("'group.offset' parameter cannot be negative")) {
+ SolrException exception =
+ expectThrows(
+ SolrException.class,
+ () ->
+ query(
+ "q",
+ "*:*",
+ "group",
+ "true",
+ "group.query",
+ t1 + ":kings OR " + t1 + ":eggs",
+ "group.offset",
+ "-1"));
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, exception.code());
+ assertThat(
+ exception.getMessage(), containsString("'group.offset' parameter cannot be negative"));
+ }
query(
"q",
diff --git a/solr/core/src/test/org/apache/solr/TestDistributedSearch.java b/solr/core/src/test/org/apache/solr/TestDistributedSearch.java
index bcadbec3583..7e85272f7df 100644
--- a/solr/core/src/test/org/apache/solr/TestDistributedSearch.java
+++ b/solr/core/src/test/org/apache/solr/TestDistributedSearch.java
@@ -59,6 +59,7 @@ import org.apache.solr.handler.component.TrackingShardHandlerFactory;
import org.apache.solr.handler.component.TrackingShardHandlerFactory.RequestTrackingQueue;
import org.apache.solr.handler.component.TrackingShardHandlerFactory.ShardRequestAndParams;
import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
@@ -1516,8 +1517,6 @@ public class TestDistributedSearch extends BaseDistributedSearchTestCase {
// SOLR 3161 ensure shards.qt=/update fails (anything but search handler really)
// Also see TestRemoteStreaming#testQtUpdateFails()
- unIgnoreException("isShard is only acceptable");
-
// test debugging
// handle.put("explain", UNORDERED);
handle.put("explain", SKIPVAL); // internal docids differ, idf differs w/o global idf
@@ -2058,49 +2057,48 @@ public class TestDistributedSearch extends BaseDistributedSearchTestCase {
control.getHeader().get(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
}
+ @SuppressWarnings("try")
private void validateCommonQueryParameters() {
- ignoreException("parameter cannot be negative");
-
- SolrException e1 =
- expectThrows(
- SolrException.class,
- () -> {
- SolrQuery query = new SolrQuery();
- query.setParam("start", "non_numeric_value").setQuery("*");
- QueryResponse resp = query(query);
- });
- assertEquals(ErrorCode.BAD_REQUEST.code, e1.code());
-
- SolrException e2 =
- expectThrows(
- SolrException.class,
- () -> {
- SolrQuery query = new SolrQuery();
- query.setStart(-1).setQuery("*");
- QueryResponse resp = query(query);
- });
- assertEquals(ErrorCode.BAD_REQUEST.code, e2.code());
-
- SolrException e3 =
- expectThrows(
- SolrException.class,
- () -> {
- SolrQuery query = new SolrQuery();
- query.setRows(-1).setStart(0).setQuery("*");
- QueryResponse resp = query(query);
- });
- assertEquals(ErrorCode.BAD_REQUEST.code, e3.code());
-
- SolrException e4 =
- expectThrows(
- SolrException.class,
- () -> {
- SolrQuery query = new SolrQuery();
- query.setParam("rows", "non_numeric_value").setQuery("*");
- QueryResponse resp = query(query);
- });
- assertEquals(ErrorCode.BAD_REQUEST.code, e4.code());
-
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("parameter cannot be negative")) {
+ SolrException e1 =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ SolrQuery query = new SolrQuery();
+ query.setParam("start", "non_numeric_value").setQuery("*");
+ QueryResponse resp = query(query);
+ });
+ assertEquals(ErrorCode.BAD_REQUEST.code, e1.code());
+
+ SolrException e2 =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ SolrQuery query = new SolrQuery();
+ query.setStart(-1).setQuery("*");
+ QueryResponse resp = query(query);
+ });
+ assertEquals(ErrorCode.BAD_REQUEST.code, e2.code());
+
+ SolrException e3 =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ SolrQuery query = new SolrQuery();
+ query.setRows(-1).setStart(0).setQuery("*");
+ QueryResponse resp = query(query);
+ });
+ assertEquals(ErrorCode.BAD_REQUEST.code, e3.code());
+
+ SolrException e4 =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ SolrQuery query = new SolrQuery();
+ query.setParam("rows", "non_numeric_value").setQuery("*");
+ QueryResponse resp = query(query);
+ });
+ assertEquals(ErrorCode.BAD_REQUEST.code, e4.code());
+ }
}
}
diff --git a/solr/core/src/test/org/apache/solr/TestTolerantSearch.java b/solr/core/src/test/org/apache/solr/TestTolerantSearch.java
index 1c3e23aa613..208f61e09cd 100644
--- a/solr/core/src/test/org/apache/solr/TestTolerantSearch.java
+++ b/solr/core/src/test/org/apache/solr/TestTolerantSearch.java
@@ -33,6 +33,7 @@ import org.apache.solr.common.util.NamedList;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.JavaBinResponseWriter;
import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.SolrJettyTestRule;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -113,11 +114,10 @@ public class TestTolerantSearch extends SolrTestCaseJ4 {
public static void destroyThings() throws Exception {
collection1 = null;
collection2 = null;
- resetExceptionIgnores();
systemClearPropertySolrEnableUrlAllowList();
}
- @SuppressWarnings("unchecked")
+ @SuppressWarnings({"unchecked", "try"})
public void testGetFieldsPhaseError() throws SolrServerException, IOException {
BadResponseWriter.failOnGetFields = true;
BadResponseWriter.failOnGetTopIds = false;
@@ -141,33 +141,32 @@ public class TestTolerantSearch extends SolrTestCaseJ4 {
query.addFacetField("id");
query.setFacet(true);
- ignoreException("Dummy exception in BadResponseWriter");
-
- expectThrows(SolrException.class, () -> collection1.query(query));
-
- query.set(ShardParams.SHARDS_TOLERANT, "true");
- QueryResponse response = collection1.query(query);
- assertTrue(
- response
- .getResponseHeader()
- .getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
- NamedList<Object> shardsInfo =
- ((NamedList<Object>) response.getResponse().get(ShardParams.SHARDS_INFO));
- boolean foundError = false;
- for (var infoEntry : shardsInfo) {
- if (infoEntry.getKey().contains("collection2")) {
- assertNotNull(((NamedList<Object>) infoEntry.getValue()).get("error"));
- foundError = true;
- break;
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Dummy exception in BadResponseWriter")) {
+ expectThrows(SolrException.class, () -> collection1.query(query));
+
+ query.set(ShardParams.SHARDS_TOLERANT, "true");
+ QueryResponse response = collection1.query(query);
+ assertTrue(
+ response
+ .getResponseHeader()
+ .getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
+ NamedList<Object> shardsInfo =
+ ((NamedList<Object>) response.getResponse().get(ShardParams.SHARDS_INFO));
+ boolean foundError = false;
+ for (var infoEntry : shardsInfo) {
+ if (infoEntry.getKey().contains("collection2")) {
+ assertNotNull(((NamedList<Object>) infoEntry.getValue()).get("error"));
+ foundError = true;
+ break;
+ }
}
+ assertTrue(foundError);
+ assertEquals("1", response.getResults().get(0).getFieldValue("id"));
+ assertEquals("batman", response.getResults().get(0).getFirstValue("subject"));
}
- assertTrue(foundError);
- assertEquals("1", response.getResults().get(0).getFieldValue("id"));
- assertEquals("batman", response.getResults().get(0).getFirstValue("subject"));
- unIgnoreException("Dummy exception in BadResponseWriter");
}
- @SuppressWarnings("unchecked")
+ @SuppressWarnings({"unchecked", "try"})
public void testGetTopIdsPhaseError() throws SolrServerException, IOException {
BadResponseWriter.failOnGetTopIds = true;
BadResponseWriter.failOnGetFields = false;
@@ -191,34 +190,33 @@ public class TestTolerantSearch extends SolrTestCaseJ4 {
query.addFacetField("id");
query.setFacet(true);
- ignoreException("Dummy exception in BadResponseWriter");
-
- expectThrows(Exception.class, () -> collection1.query(query));
-
- query.set(ShardParams.SHARDS_TOLERANT, "true");
- QueryResponse response = collection1.query(query);
- assertTrue(
- response
- .getResponseHeader()
- .getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
- NamedList<Object> shardsInfo =
- ((NamedList<Object>) response.getResponse().get(ShardParams.SHARDS_INFO));
- boolean foundError = false;
- for (var infoEntry : shardsInfo) {
- if (infoEntry.getKey().contains("collection2")) {
- assertNotNull(((NamedList<Object>) infoEntry.getValue()).get("error"));
- foundError = true;
- break;
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Dummy exception in BadResponseWriter")) {
+ expectThrows(Exception.class, () -> collection1.query(query));
+
+ query.set(ShardParams.SHARDS_TOLERANT, "true");
+ QueryResponse response = collection1.query(query);
+ assertTrue(
+ response
+ .getResponseHeader()
+ .getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
+ NamedList<Object> shardsInfo =
+ ((NamedList<Object>) response.getResponse().get(ShardParams.SHARDS_INFO));
+ boolean foundError = false;
+ for (var infoEntry : shardsInfo) {
+ if (infoEntry.getKey().contains("collection2")) {
+ assertNotNull(((NamedList<Object>) infoEntry.getValue()).get("error"));
+ foundError = true;
+ break;
+ }
}
+ assertTrue(foundError);
+ assertFalse("" + response, response.getResults().isEmpty());
+ assertEquals("1", response.getResults().get(0).getFieldValue("id"));
+ assertEquals("batman", response.getResults().get(0).getFirstValue("subject"));
}
- assertTrue(foundError);
- assertFalse("" + response, response.getResults().isEmpty());
- assertEquals("1", response.getResults().get(0).getFieldValue("id"));
- assertEquals("batman", response.getResults().get(0).getFirstValue("subject"));
- unIgnoreException("Dummy exception in BadResponseWriter");
}
- @SuppressWarnings("unchecked")
+ @SuppressWarnings({"unchecked", "try"})
public void testAllShardsFail() throws SolrServerException, IOException {
BadResponseWriter.failOnGetTopIds = false;
BadResponseWriter.failOnGetFields = false;
@@ -242,13 +240,13 @@ public class TestTolerantSearch extends SolrTestCaseJ4 {
query.addFacetField("id");
query.setFacet(true);
- ignoreException("Dummy exception in BadResponseWriter");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Dummy exception in BadResponseWriter")) {
+ expectThrows(SolrException.class, () -> collection1.query(query));
- expectThrows(SolrException.class, () -> collection1.query(query));
+ query.set(ShardParams.SHARDS_TOLERANT, "true");
- query.set(ShardParams.SHARDS_TOLERANT, "true");
-
- expectThrows(SolrException.class, () -> collection1.query(query));
+ expectThrows(SolrException.class, () -> collection1.query(query));
+ }
}
public static class BadResponseWriter extends JavaBinResponseWriter {
diff --git a/solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java b/solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java
index 18e4d92ba4b..7f2fa3b1de1 100644
--- a/solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java
@@ -49,6 +49,7 @@ import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.TimeSource;
import org.apache.solr.common.util.Utils;
import org.apache.solr.embedded.JettySolrRunner;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.TimeOut;
import org.apache.zookeeper.KeeperException;
import org.eclipse.jetty.client.ContentResponse;
@@ -981,6 +982,7 @@ public class AliasIntegrationTest extends SolrCloudTestCase {
}
@Test
+ @SuppressWarnings("try")
public void testErrorChecks() throws Exception {
CollectionAdminRequest.createCollection("testErrorChecks-collection", "conf", 2, 1)
.process(cluster.getSolrClient());
@@ -991,63 +993,64 @@ public class AliasIntegrationTest extends SolrCloudTestCase {
"testErrorChecks-collection",
clusterShape(2, 2));
- ignoreException(".");
-
- // Invalid Alias name
- SolrException e =
- expectThrows(
- SolrException.class,
- () ->
- CollectionAdminRequest.createAlias("test:alias", "testErrorChecks-collection")
- .process(cluster.getSolrClient()));
- assertEquals(
- SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code()));
-
- // Target collection doesn't exists
- e =
- expectThrows(
- SolrException.class,
- () ->
- CollectionAdminRequest.createAlias("testalias", "doesnotexist")
- .process(cluster.getSolrClient()));
- assertEquals(
- SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code()));
- assertTrue(
- e.getMessage()
- .contains(
- "Can't create collection alias for collections='doesnotexist', 'doesnotexist' is not an existing collection or alias"));
-
- // One of the target collections doesn't exist
- e =
- expectThrows(
- SolrException.class,
- () ->
- CollectionAdminRequest.createAlias(
- "testalias", "testErrorChecks-collection,doesnotexist")
- .process(cluster.getSolrClient()));
- assertEquals(
- SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code()));
- assertTrue(
- e.getMessage()
- .contains(
- "Can't create collection alias for collections='testErrorChecks-collection,doesnotexist', 'doesnotexist' is not an existing collection or alias"));
-
- // Valid
- CollectionAdminRequest.createAlias("testalias", "testErrorChecks-collection")
- .process(cluster.getSolrClient());
- // TODO dubious; remove?
- CollectionAdminRequest.createAlias("testalias2", "testalias").process(cluster.getSolrClient());
-
- // Alias + invalid
- e =
- expectThrows(
- SolrException.class,
- () ->
- CollectionAdminRequest.createAlias("testalias3", "testalias2,doesnotexist")
- .process(cluster.getSolrClient()));
- assertEquals(
- SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code()));
- unIgnoreException(".");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(".")) {
+
+ // Invalid Alias name
+ SolrException e =
+ expectThrows(
+ SolrException.class,
+ () ->
+ CollectionAdminRequest.createAlias("test:alias", "testErrorChecks-collection")
+ .process(cluster.getSolrClient()));
+ assertEquals(
+ SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code()));
+
+ // Target collection doesn't exists
+ e =
+ expectThrows(
+ SolrException.class,
+ () ->
+ CollectionAdminRequest.createAlias("testalias", "doesnotexist")
+ .process(cluster.getSolrClient()));
+ assertEquals(
+ SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code()));
+ assertTrue(
+ e.getMessage()
+ .contains(
+ "Can't create collection alias for collections='doesnotexist', 'doesnotexist' is not an existing collection or alias"));
+
+ // One of the target collections doesn't exist
+ e =
+ expectThrows(
+ SolrException.class,
+ () ->
+ CollectionAdminRequest.createAlias(
+ "testalias", "testErrorChecks-collection,doesnotexist")
+ .process(cluster.getSolrClient()));
+ assertEquals(
+ SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code()));
+ assertTrue(
+ e.getMessage()
+ .contains(
+ "Can't create collection alias for collections='testErrorChecks-collection,doesnotexist', 'doesnotexist' is not an existing collection or alias"));
+
+ // Valid
+ CollectionAdminRequest.createAlias("testalias", "testErrorChecks-collection")
+ .process(cluster.getSolrClient());
+ // TODO dubious; remove?
+ CollectionAdminRequest.createAlias("testalias2", "testalias")
+ .process(cluster.getSolrClient());
+
+ // Alias + invalid
+ e =
+ expectThrows(
+ SolrException.class,
+ () ->
+ CollectionAdminRequest.createAlias("testalias3", "testalias2,doesnotexist")
+ .process(cluster.getSolrClient()));
+ assertEquals(
+ SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code()));
+ }
CollectionAdminRequest.deleteAlias("testalias").process(cluster.getSolrClient());
CollectionAdminRequest.deleteAlias("testalias2").process(cluster.getSolrClient());
diff --git a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
index 88be1ee8861..a21f4938228 100644
--- a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
@@ -83,6 +83,7 @@ import org.apache.solr.common.util.ExecutorUtil;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SolrNamedThreadFactory;
import org.apache.solr.embedded.JettySolrRunner;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.TestInjection;
import org.apache.solr.util.TestInjection.Hook;
import org.junit.BeforeClass;
@@ -1223,6 +1224,7 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {
// cloud level test mainly needed just to make sure that versions and errors are propagated
// correctly
+ @SuppressWarnings("try")
private void doOptimisticLockingAndUpdating() throws Exception {
log.info("### STARTING doOptimisticLockingAndUpdating");
printLayout();
@@ -1230,12 +1232,12 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {
final SolrInputDocument sd = sdoc("id", 1000, "_version_", -1);
indexDoc(sd);
- ignoreException("version conflict");
- for (SolrClient client : clients) {
- SolrException e = expectThrows(SolrException.class, () -> client.add(sd));
- assertEquals(409, e.code());
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("version conflict")) {
+ for (SolrClient client : clients) {
+ SolrException e = expectThrows(SolrException.class, () -> client.add(sd));
+ assertEquals(409, e.code());
+ }
}
- unIgnoreException("version conflict");
// TODO: test deletes. SolrJ needs a good way to pass version for delete...
diff --git a/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.java b/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.java
index 03c2bac7a3d..962dbfe2446 100644
--- a/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.java
@@ -84,8 +84,6 @@ public class ChaosMonkeyNothingIsSafeTest extends AbstractFullDistribZkTestBase
@Override
public void distribSetUp() throws Exception {
super.distribSetUp();
- // can help to hide this when testing and looking at logs
- // ignoreException("shard update error");
useFactory("solr.StandardDirectoryFactory");
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeWithPullReplicasTest.java b/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeWithPullReplicasTest.java
index e80b765af89..b2616a80afb 100644
--- a/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeWithPullReplicasTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeWithPullReplicasTest.java
@@ -99,8 +99,6 @@ public class ChaosMonkeyNothingIsSafeWithPullReplicasTest extends AbstractFullDi
@Override
public void distribSetUp() throws Exception {
super.distribSetUp();
- // can help to hide this when testing and looking at logs
- // ignoreException("shard update error");
useFactory("solr.StandardDirectoryFactory");
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/DistribCursorPagingTest.java b/solr/core/src/test/org/apache/solr/cloud/DistribCursorPagingTest.java
index 767fda28230..f7f2317bc0d 100644
--- a/solr/core/src/test/org/apache/solr/cloud/DistribCursorPagingTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/DistribCursorPagingTest.java
@@ -48,6 +48,7 @@ import org.apache.solr.common.params.GroupParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.search.CursorMark;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.Test;
/**
@@ -691,10 +692,10 @@ public class DistribCursorPagingTest extends AbstractFullDistribZkTestBase {
}
/** execute a request, verify that we get an expected error */
+ @SuppressWarnings("try")
public void assertFail(SolrParams p, ErrorCode expCode, String expSubstr) throws Exception {
- try {
- ignoreException(expSubstr);
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(expSubstr)) {
query(p);
fail("no exception matching expected: " + expCode.code + ": " + expSubstr);
} catch (SolrException e) {
@@ -702,8 +703,6 @@ public class DistribCursorPagingTest extends AbstractFullDistribZkTestBase {
assertTrue(
"Expected substr not found: " + expSubstr + " <!< " + e.getMessage(),
e.getMessage().contains(expSubstr));
- } finally {
- unIgnoreException(expSubstr);
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/DistribJoinFromCollectionTest.java b/solr/core/src/test/org/apache/solr/cloud/DistribJoinFromCollectionTest.java
index 8a14d00ace8..8f639395d9b 100644
--- a/solr/core/src/test/org/apache/solr/cloud/DistribJoinFromCollectionTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/DistribJoinFromCollectionTest.java
@@ -53,7 +53,6 @@ public class DistribJoinFromCollectionTest extends SolrCloudTestCase {
private static final String[] scoreModes = {"avg", "max", "min", "total"};
- // resetExceptionIgnores();
private static String toColl = "to_2x2";
private static String fromColl = "from_1x4";
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java
index 29c17139d2a..c7ece98ae62 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java
@@ -94,6 +94,7 @@ import org.apache.solr.security.AuthorizationPlugin;
import org.apache.solr.security.AuthorizationResponse;
import org.apache.solr.security.BasicAuthPlugin;
import org.apache.solr.security.SimplePrincipal;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.ExternalPaths;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -329,19 +330,21 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
}
@Test
+ @SuppressWarnings("try")
public void testUploadErrors() throws Exception {
ByteBuffer emptyData = ByteBuffer.allocate(0);
- ignoreException("The configuration name should be provided");
// Checking error when no configuration name is specified in request
- Map<?, ?> map =
- postDataAndGetResponse(
- cluster.getJettySolrRunners().getFirst(),
- "/admin/configs?action=UPLOAD",
- emptyData,
- null,
- false);
- unIgnoreException("The configuration name should be provided");
+ Map<?, ?> map;
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("The configuration name should be provided")) {
+ map =
+ postDataAndGetResponse(
+ cluster.getJettySolrRunners().getFirst(),
+ "/admin/configs?action=UPLOAD",
+ emptyData,
+ null,
+ false);
+ }
assertEquals(400, getStatusCode(map));
SolrZkClient zkClient =
@@ -363,15 +366,15 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
CreateMode.PERSISTENT);
// Checking error when configuration name specified already exists
- ignoreException("already exists");
- map =
- postDataAndGetResponse(
- cluster.getJettySolrRunners().getFirst(),
- "/admin/configs?action=UPLOAD&name=myconf",
- emptyData,
- null,
- false);
- unIgnoreException("already exists`");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("already exists")) {
+ map =
+ postDataAndGetResponse(
+ cluster.getJettySolrRunners().getFirst(),
+ "/admin/configs?action=UPLOAD&name=myconf",
+ emptyData,
+ null,
+ false);
+ }
assertEquals(400, getStatusCode(map));
assertTrue(
"Expected file doesnt exist in zk. It's possibly overwritten",
@@ -403,15 +406,16 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
testUploadDisabled(true);
}
+ @SuppressWarnings("try")
public void testUploadDisabled(boolean v2) throws Exception {
try (SolrZkClient zkClient =
- new SolrZkClient.Builder()
- .withUrl(cluster.getZkServer().getZkAddress())
- .withTimeout(AbstractZkTestCase.TIMEOUT, TimeUnit.MILLISECONDS)
- .withConnTimeOut(45000, TimeUnit.MILLISECONDS)
- .build()) {
+ new SolrZkClient.Builder()
+ .withUrl(cluster.getZkServer().getZkAddress())
+ .withTimeout(AbstractZkTestCase.TIMEOUT, TimeUnit.MILLISECONDS)
+ .withConnTimeOut(45000, TimeUnit.MILLISECONDS)
+ .build();
+ ErrorLogMuter ignored = ErrorLogMuter.regex("Configset upload feature is disabled")) {
- ignoreException("Configset upload feature is disabled");
for (boolean enabled : new boolean[] {true, false}) {
System.setProperty("solr.configset.upload.enabled", String.valueOf(enabled));
@@ -424,7 +428,6 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
enabled ? 0l : 400l,
statusCode);
}
- unIgnoreException("Configset upload feature is disabled");
}
}
@@ -482,6 +485,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
testOverwrite(true);
}
+ @SuppressWarnings("try")
public void testOverwrite(boolean v2) throws Exception {
String configsetName = "regular";
String configsetSuffix = "testOverwrite-1-" + v2;
@@ -494,12 +498,14 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
.build()) {
int solrconfigZkVersion =
getConfigZNodeVersion(zkClient, configsetName, configsetSuffix, "solrconfig.xml");
- ignoreException("The configuration regulartestOverwrite-1 already exists in zookeeper");
- assertEquals(
- "Can't overwrite an existing configset unless the overwrite parameter is set",
- 400,
- uploadConfigSet(configsetName, configsetSuffix, null, false, false, v2, false, false));
- unIgnoreException("The configuration regulartestOverwrite-1 already exists in zookeeper");
+ try (ErrorLogMuter ignored =
+ ErrorLogMuter.regex(
+ "The configuration regulartestOverwrite-1 already exists in zookeeper")) {
+ assertEquals(
+ "Can't overwrite an existing configset unless the overwrite parameter is set",
+ 400,
+ uploadConfigSet(configsetName, configsetSuffix, null, false, false, v2, false, false));
+ }
assertEquals(
"Expecting version to remain equal",
solrconfigZkVersion,
@@ -597,6 +603,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
// V2 API not tested: single file uploads always overwrite (no overwrite parameter)
+ @SuppressWarnings("try")
public void testSingleFileOverwrite(boolean v2) throws Exception {
String configsetName = "regular";
String configsetSuffix = "testSinglePathOverwrite-1-" + v2;
@@ -609,20 +616,22 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
.build()) {
int solrconfigZkVersion =
getConfigZNodeVersion(zkClient, configsetName, configsetSuffix, "solrconfig.xml");
- ignoreException("The configuration regulartestOverwrite-1 already exists in zookeeper");
- assertEquals(
- "Can't overwrite an existing configset unless the overwrite parameter is set",
- 400,
- uploadSingleConfigSetFile(
- configsetName,
- configsetSuffix,
- null,
- "solr/configsets/upload/regular/solrconfig.xml",
- "solrconfig.xml",
- false,
- false,
- v2));
- unIgnoreException("The configuration regulartestOverwrite-1 already exists in zookeeper");
+ try (ErrorLogMuter ignored =
+ ErrorLogMuter.regex(
+ "The configuration regulartestOverwrite-1 already exists in zookeeper")) {
+ assertEquals(
+ "Can't overwrite an existing configset unless the overwrite parameter is set",
+ 400,
+ uploadSingleConfigSetFile(
+ configsetName,
+ configsetSuffix,
+ null,
+ "solr/configsets/upload/regular/solrconfig.xml",
+ "solrconfig.xml",
+ false,
+ false,
+ v2));
+ }
assertEquals(
"Expecting version to remain equal",
solrconfigZkVersion,
@@ -741,17 +750,20 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
// Single file uploads do not support cleanup parameter
// V2 API not tested: single file uploads do not support cleanup parameter
@Test
+ @SuppressWarnings("try")
public void testSingleWithCleanup() throws Exception {
String configsetName = "regular";
String configsetSuffix = "testSinglePathCleanup-1";
uploadConfigSetWithAssertions(configsetName, configsetSuffix, null);
try (SolrZkClient zkClient =
- new SolrZkClient.Builder()
- .withUrl(cluster.getZkServer().getZkAddress())
- .withTimeout(AbstractZkTestCase.TIMEOUT, TimeUnit.MILLISECONDS)
- .withConnTimeOut(45000, TimeUnit.MILLISECONDS)
- .build()) {
- ignoreException("ConfigSet uploads do not allow cleanup=true when filePath is used.");
+ new SolrZkClient.Builder()
+ .withUrl(cluster.getZkServer().getZkAddress())
+ .withTimeout(AbstractZkTestCase.TIMEOUT, TimeUnit.MILLISECONDS)
+ .withConnTimeOut(45000, TimeUnit.MILLISECONDS)
+ .build();
+ ErrorLogMuter ignored =
+ ErrorLogMuter.regex(
+ "ConfigSet uploads do not allow cleanup=true when filePath is used.")) {
assertEquals(
400,
uploadSingleConfigSetFile(
@@ -768,7 +780,6 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
zkClient.exists(
"/configs/" + configsetName + configsetSuffix + "/test/upload/path/solrconfig.xml"));
assertConfigsetFiles(configsetName, configsetSuffix, zkClient);
- unIgnoreException("ConfigSet uploads do not allow cleanup=true when filePath is used.");
}
}
@@ -782,6 +793,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
testSingleFileForbiddenType(true);
}
+ @SuppressWarnings("try")
public void testSingleFileForbiddenType(boolean v2) throws Exception {
String configsetName = "regular";
String configsetSuffix = "testSingleFileForbiddenType-1-" + v2;
@@ -793,28 +805,28 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
.withConnTimeOut(45000, TimeUnit.MILLISECONDS)
.build()) {
for (String fileType : ConfigSetService.DEFAULT_FORBIDDEN_FILE_TYPES) {
- ignoreException("is forbidden for use in configSets");
- assertEquals(
- "Can't upload a configset file with a forbidden type: " + fileType,
- 400,
- uploadSingleConfigSetFile(
- configsetName,
- configsetSuffix,
- "solr",
- "solr/configsets/upload/regular/solrconfig.xml",
- "/test/different/path/solrconfig." + fileType,
- false,
- false,
- v2));
- assertFalse(
- "New file should not exist, since the filetype is forbidden: " + fileType,
- zkClient.exists(
- "/configs/"
- + configsetName
- + configsetSuffix
- + "/test/different/path/solrconfig."
- + fileType));
- unIgnoreException("is forbidden for use in configSets");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("is forbidden for use in configSets")) {
+ assertEquals(
+ "Can't upload a configset file with a forbidden type: " + fileType,
+ 400,
+ uploadSingleConfigSetFile(
+ configsetName,
+ configsetSuffix,
+ "solr",
+ "solr/configsets/upload/regular/solrconfig.xml",
+ "/test/different/path/solrconfig." + fileType,
+ false,
+ false,
+ v2));
+ assertFalse(
+ "New file should not exist, since the filetype is forbidden: " + fileType,
+ zkClient.exists(
+ "/configs/"
+ + configsetName
+ + configsetSuffix
+ + "/test/different/path/solrconfig."
+ + fileType));
+ }
}
}
}
@@ -823,6 +835,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
// V2 API not tested: single file uploads do not support cleanup parameter
+ @SuppressWarnings("try")
public void testSingleFileUpload(boolean v2) throws Exception {
String configsetName = "regular";
String configsetSuffix = "testSinglePathUpload-1-" + v2;
@@ -895,28 +908,30 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
assertConfigsetFiles(configsetName, configsetSuffix, zkClient);
// Make sure that cleanup flag validation works correctly.
- ignoreException("ConfigSet uploads do not allow cleanup=true when filePath is used.");
- extraFileZkVersion =
- getConfigZNodeVersion(
- zkClient, configsetName, configsetSuffix, "test/different/path/solrconfig.xml");
- assertEquals(
- 400,
- uploadSingleConfigSetFile(
- configsetName,
- configsetSuffix,
- "solr",
- "solr/configsets/upload/regular/solrconfig.xml",
- "/test/different/path/solrconfig.xml",
- true,
- true,
- v2));
- assertEquals(
- "Expecting version to stay the same",
- extraFileZkVersion,
- getConfigZNodeVersion(
- zkClient, configsetName, configsetSuffix, "test/different/path/solrconfig.xml"));
- assertConfigsetFiles(configsetName, configsetSuffix, zkClient);
- unIgnoreException("ConfigSet uploads do not allow cleanup=true when filePath is used.");
+ try (ErrorLogMuter ignored =
+ ErrorLogMuter.regex(
+ "ConfigSet uploads do not allow cleanup=true when filePath is used.")) {
+ extraFileZkVersion =
+ getConfigZNodeVersion(
+ zkClient, configsetName, configsetSuffix, "test/different/path/solrconfig.xml");
+ assertEquals(
+ 400,
+ uploadSingleConfigSetFile(
+ configsetName,
+ configsetSuffix,
+ "solr",
+ "solr/configsets/upload/regular/solrconfig.xml",
+ "/test/different/path/solrconfig.xml",
+ true,
+ true,
+ v2));
+ assertEquals(
+ "Expecting version to stay the same",
+ extraFileZkVersion,
+ getConfigZNodeVersion(
+ zkClient, configsetName, configsetSuffix, "test/different/path/solrconfig.xml"));
+ assertConfigsetFiles(configsetName, configsetSuffix, zkClient);
+ }
}
}
@@ -1647,14 +1662,15 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
solrClient.close();
}
+ @SuppressWarnings("try")
private void verifyException(
SolrClient solrClient, ConfigSetAdminRequest<?, ?> request, String errorContains) {
- ignoreException(errorContains);
- Exception e = expectThrows(Exception.class, () -> solrClient.request(request));
- assertTrue(
- "Expected exception message to contain: " + errorContains + " got: " + e.getMessage(),
- e.getMessage().contains(errorContains));
- unIgnoreException(errorContains);
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(errorContains)) {
+ Exception e = expectThrows(Exception.class, () -> solrClient.request(request));
+ assertTrue(
+ "Expected exception message to contain: " + errorContains + " got: " + e.getMessage(),
+ e.getMessage().contains(errorContains));
+ }
}
@Test
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java b/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java
index 331b2b7e9f2..1d8166e119b 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java
@@ -55,6 +55,7 @@ import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.SolrCore;
import org.apache.solr.embedded.JettySolrRunner;
import org.apache.solr.update.UpdateLog;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.LogLevel;
import org.apache.solr.util.SolrMetricTestUtils;
import org.apache.solr.util.TestInjection;
@@ -565,7 +566,7 @@ public class TestPullReplica extends SolrCloudTestCase {
/*
* validate that replication still happens on a new leader
*/
- @SuppressWarnings({"try"})
+ @SuppressWarnings("try")
private void doTestNoLeader(boolean removeReplica) throws Exception {
CollectionAdminRequest.createCollection(collectionName, "conf", 1, 1, 0, 1)
.process(cluster.getSolrClient());
@@ -586,81 +587,84 @@ public class TestPullReplica extends SolrCloudTestCase {
waitForNumDocsInAllReplicas(1, getReplicas(docCollection, EnumSet.of(Replica.Type.PULL)));
// Delete leader replica from shard1
- ignoreException("No registered leader was found"); // These are expected
- JettySolrRunner leaderJetty = null;
- if (removeReplica) {
- CollectionAdminRequest.deleteReplica(collectionName, "shard1", s.getLeader().getName())
- .process(cluster.getSolrClient());
- } else {
- leaderJetty = cluster.getReplicaJetty(s.getLeader());
- leaderJetty.stop();
- waitForState("Leader replica not removed", collectionName, clusterShape(1, 1));
- // Wait for cluster state to be updated
- waitForState(
- "Replica state not updated in cluster state",
- collectionName,
- clusterStateReflectsActiveAndDownReplicas());
- }
- docCollection = assertNumberOfReplicas(0, 0, 1, true, true);
+ Replica leader;
+ try (ErrorLogMuter ignored =
+ ErrorLogMuter.regex("No registered leader was found")) { // These are expected
+ JettySolrRunner leaderJetty = null;
+ if (removeReplica) {
+ CollectionAdminRequest.deleteReplica(collectionName, "shard1", s.getLeader().getName())
+ .process(cluster.getSolrClient());
+ } else {
+ leaderJetty = cluster.getReplicaJetty(s.getLeader());
+ leaderJetty.stop();
+ waitForState("Leader replica not removed", collectionName, clusterShape(1, 1));
+ // Wait for cluster state to be updated
+ waitForState(
+ "Replica state not updated in cluster state",
+ collectionName,
+ clusterStateReflectsActiveAndDownReplicas());
+ }
+ docCollection = assertNumberOfReplicas(0, 0, 1, true, true);
- // Check that there is no leader for the shard
- Replica leader = docCollection.getSlice("shard1").getLeader();
- assertTrue(
- leader == null
- || !leader.isActive(cluster.getSolrClient().getClusterState().getLiveNodes()));
+ // Check that there is no leader for the shard
+ leader = docCollection.getSlice("shard1").getLeader();
+ assertTrue(
+ leader == null
+ || !leader.isActive(cluster.getSolrClient().getClusterState().getLiveNodes()));
- // Pull replica on the other hand should be active
- Replica pullReplica =
- docCollection.getSlice("shard1").getReplicas(EnumSet.of(Replica.Type.PULL)).get(0);
- assertTrue(pullReplica.isActive(cluster.getSolrClient().getClusterState().getLiveNodes()));
+ // Pull replica on the other hand should be active
+ Replica pullReplica =
+ docCollection.getSlice("shard1").getReplicas(EnumSet.of(Replica.Type.PULL)).get(0);
+ assertTrue(pullReplica.isActive(cluster.getSolrClient().getClusterState().getLiveNodes()));
- long highestTerm = 0L;
- try (ZkShardTerms zkShardTerms = new ZkShardTerms(collectionName, "shard1", zkClient())) {
- highestTerm = zkShardTerms.getHighestTerm();
- }
- // add document, this should fail since there is no leader. Pull replica should not accept the
- // update
- expectThrows(
- SolrException.class,
- () ->
- cluster
- .getSolrClient()
- .add(collectionName, new SolrInputDocument("id", "2", "foo", "zoo")));
- if (removeReplica) {
+ long highestTerm = 0L;
try (ZkShardTerms zkShardTerms = new ZkShardTerms(collectionName, "shard1", zkClient())) {
- assertEquals(highestTerm, zkShardTerms.getHighestTerm());
+ highestTerm = zkShardTerms.getHighestTerm();
}
- }
-
- // Also fails if I send the update to the pull replica explicitly
- try (SolrClient pullReplicaClient =
- getHttpSolrClient(getReplicas(docCollection, EnumSet.of(Replica.Type.PULL)).get(0))) {
+ // add document, this should fail since there is no leader. Pull replica should not accept the
+ // update
expectThrows(
SolrException.class,
() ->
- pullReplicaClient.add(
- collectionName, new SolrInputDocument("id", "2", "foo", "zoo")));
- }
- if (removeReplica) {
- try (ZkShardTerms zkShardTerms = new ZkShardTerms(collectionName, "shard1", zkClient())) {
- assertEquals(highestTerm, zkShardTerms.getHighestTerm());
+ cluster
+ .getSolrClient()
+ .add(collectionName, new SolrInputDocument("id", "2", "foo", "zoo")));
+ if (removeReplica) {
+ try (ZkShardTerms zkShardTerms = new ZkShardTerms(collectionName, "shard1", zkClient())) {
+ assertEquals(highestTerm, zkShardTerms.getHighestTerm());
+ }
}
- }
- // Queries should still work
- waitForNumDocsInAllReplicas(1, getReplicas(docCollection, EnumSet.of(Replica.Type.PULL)));
- // Add nrt replica back. Since there is no nrt now, new nrt will have no docs. There will be
- // data loss, since it will become the leader and pull replicas will replicate from it.
- // Maybe we want to change this. Replicate from pull replicas is not a good idea, since they are
- // by definition out of date.
- if (removeReplica) {
- CollectionAdminRequest.addReplicaToShard(collectionName, "shard1", Replica.Type.NRT)
- .process(cluster.getSolrClient());
- } else {
- leaderJetty.start();
- }
- waitForState("Expected collection to be 1x2", collectionName, clusterShape(1, 2));
- unIgnoreException("No registered leader was found"); // Should have a leader from now on
+ // Also fails if I send the update to the pull replica explicitly
+ try (SolrClient pullReplicaClient =
+ getHttpSolrClient(getReplicas(docCollection, EnumSet.of(Replica.Type.PULL)).get(0))) {
+ expectThrows(
+ SolrException.class,
+ () ->
+ pullReplicaClient.add(
+ collectionName, new SolrInputDocument("id", "2", "foo", "zoo")));
+ }
+ if (removeReplica) {
+ try (ZkShardTerms zkShardTerms = new ZkShardTerms(collectionName, "shard1", zkClient())) {
+ assertEquals(highestTerm, zkShardTerms.getHighestTerm());
+ }
+ }
+
+ // Queries should still work
+ waitForNumDocsInAllReplicas(1, getReplicas(docCollection, EnumSet.of(Replica.Type.PULL)));
+ // Add nrt replica back. Since there is no nrt now, new nrt will have no docs. There will be
+ // data loss, since it will become the leader and pull replicas will replicate from it.
+ // Maybe we want to change this. Replicate from pull replicas is not a good idea, since they
+ // are
+ // by definition out of date.
+ if (removeReplica) {
+ CollectionAdminRequest.addReplicaToShard(collectionName, "shard1", Replica.Type.NRT)
+ .process(cluster.getSolrClient());
+ } else {
+ leaderJetty.start();
+ }
+ waitForState("Expected collection to be 1x2", collectionName, clusterShape(1, 2));
+ } // Should have a leader from now on
// Validate that the new nrt replica is the leader now
cluster.getZkStateReader().forceUpdateCollection(collectionName);
diff --git a/solr/core/src/test/org/apache/solr/core/PluginInfoTest.java b/solr/core/src/test/org/apache/solr/core/PluginInfoTest.java
index 538a0fca4a1..239527a9aeb 100644
--- a/solr/core/src/test/org/apache/solr/core/PluginInfoTest.java
+++ b/solr/core/src/test/org/apache/solr/core/PluginInfoTest.java
@@ -17,8 +17,8 @@
package org.apache.solr.core;
import java.util.List;
-import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.util.DOMUtilTestBase;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.Test;
import org.w3c.dom.Node;
@@ -61,10 +61,10 @@ public class PluginInfoTest extends DOMUtilTestBase {
// This is in fact a DOMUtil test, but it is here for completeness
@Test
+ @SuppressWarnings("try")
public void testNameRequired() throws Exception {
Node nodeWithNoName = getNode("<plugin></plugin>", "plugin");
- try {
- SolrTestCaseJ4.ignoreException("missing mandatory attribute");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("missing mandatory attribute")) {
RuntimeException thrown =
expectThrows(
RuntimeException.class,
@@ -72,8 +72,6 @@ public class PluginInfoTest extends DOMUtilTestBase {
PluginInfo pi = new PluginInfo(nodeWithNoName, "Node with No name", true, false);
});
assertTrue(thrown.getMessage().contains("missing mandatory attribute"));
- } finally {
- SolrTestCaseJ4.resetExceptionIgnores();
}
Node nodeWithAName = getNode("<plugin name=\"myName\" />", "plugin");
@@ -82,10 +80,10 @@ public class PluginInfoTest extends DOMUtilTestBase {
}
@Test
+ @SuppressWarnings("try")
public void testClassRequired() throws Exception {
Node nodeWithNoClass = getNode("<plugin></plugin>", "plugin");
- try {
- SolrTestCaseJ4.ignoreException("missing mandatory attribute");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("missing mandatory attribute")) {
RuntimeException thrown =
expectThrows(
RuntimeException.class,
@@ -93,8 +91,6 @@ public class PluginInfoTest extends DOMUtilTestBase {
PluginInfo pi = new PluginInfo(nodeWithNoClass, "Node with No Class", false, true);
});
assertTrue(thrown.getMessage().contains("missing mandatory attribute"));
- } finally {
- SolrTestCaseJ4.resetExceptionIgnores();
}
Node nodeWithAClass = getNode("<plugin class=\"myName\" />", "plugin");
diff --git a/solr/core/src/test/org/apache/solr/core/SolrCoreCheckLockOnStartupTest.java b/solr/core/src/test/org/apache/solr/core/SolrCoreCheckLockOnStartupTest.java
index 716bbac8f0c..736fcf29506 100644
--- a/solr/core/src/test/org/apache/solr/core/SolrCoreCheckLockOnStartupTest.java
+++ b/solr/core/src/test/org/apache/solr/core/SolrCoreCheckLockOnStartupTest.java
@@ -27,6 +27,7 @@ import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.NativeFSLockFactory;
import org.apache.lucene.store.SimpleFSLockFactory;
import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -50,6 +51,7 @@ public class SolrCoreCheckLockOnStartupTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testSimpleLockErrorOnStartup() throws Exception {
Directory directory =
@@ -57,8 +59,7 @@ public class SolrCoreCheckLockOnStartupTest extends SolrTestCaseJ4 {
// creates a new IndexWriter without releasing the lock yet
IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(null));
- ignoreException("locked");
- try {
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("locked")) {
System.setProperty("solr.tests.lockType", DirectoryFactory.LOCK_TYPE_SIMPLE);
// opening a new core on the same index
initCore("solrconfig-basic.xml", "schema.xml");
@@ -66,7 +67,6 @@ public class SolrCoreCheckLockOnStartupTest extends SolrTestCaseJ4 {
fail("Expected " + LockObtainFailedException.class.getSimpleName());
} finally {
System.clearProperty("solr.tests.lockType");
- unIgnoreException("locked");
indexWriter.close();
directory.close();
deleteCore();
@@ -74,6 +74,7 @@ public class SolrCoreCheckLockOnStartupTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testNativeLockErrorOnStartup() throws Exception {
Path indexDir = initAndGetDataDir().resolve("index");
@@ -84,8 +85,7 @@ public class SolrCoreCheckLockOnStartupTest extends SolrTestCaseJ4 {
// creates a new IndexWriter without releasing the lock yet
IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(null));
- ignoreException("locked");
- try {
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("locked")) {
System.setProperty("solr.tests.lockType", DirectoryFactory.LOCK_TYPE_NATIVE);
// opening a new core on the same index
initCore("solrconfig-basic.xml", "schema.xml");
@@ -93,7 +93,6 @@ public class SolrCoreCheckLockOnStartupTest extends SolrTestCaseJ4 {
fail("Expected " + LockObtainFailedException.class.getSimpleName());
} finally {
System.clearProperty("solr.tests.lockType");
- unIgnoreException("locked");
indexWriter.close();
directory.close();
deleteCore();
diff --git a/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java b/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java
index 221da96aee2..a2ad9385c8f 100644
--- a/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java
+++ b/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java
@@ -44,6 +44,7 @@ import org.apache.solr.handler.admin.ConfigSetsHandler;
import org.apache.solr.handler.admin.CoreAdminHandler;
import org.apache.solr.handler.admin.InfoHandler;
import org.apache.solr.servlet.CoreContainerProvider;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.ModuleUtils;
import org.junit.Assume;
import org.junit.BeforeClass;
@@ -836,6 +837,7 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testCoreInitFailuresFromEmptyContainer() throws Exception {
// reused state
Map<String, CoreContainer.CoreLoadFailure> failures = null;
@@ -858,13 +860,15 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// -----
// try to add a collection with a configset that doesn't exist
- ignoreException(Pattern.quote("bogus_path"));
- SolrException thrown =
- expectThrows(
- SolrException.class,
- () -> {
- cc.create("bogus", Map.of("configSet", "bogus_path"));
- });
+ SolrException thrown;
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(Pattern.quote("bogus_path"))) {
+ thrown =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ cc.create("bogus", Map.of("configSet", "bogus_path"));
+ });
+ }
Throwable rootCause = SolrException.getRootCause(thrown);
assertTrue(
"init exception doesn't mention bogus dir: " + rootCause.getMessage(),
@@ -903,6 +907,7 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testCoreInitFailuresOnReload() throws Exception {
// reused state
@@ -988,13 +993,14 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// -----
// try to add a collection with a path that doesn't exist
- ignoreException(Pattern.quote("bogus_path"));
- thrown =
- expectThrows(
- SolrException.class,
- () -> {
- cc.create("bogus", Map.of("configSet", "bogus_path"));
- });
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(Pattern.quote("bogus_path"))) {
+ thrown =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ cc.create("bogus", Map.of("configSet", "bogus_path"));
+ });
+ }
assertTrue(
"init exception doesn't mention bogus dir: " + thrown.getCause().getCause().getMessage(),
0 < thrown.getCause().getCause().getMessage().indexOf("bogus_path"));
@@ -1040,14 +1046,15 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
"This is giberish, not valid XML <",
StandardCharsets.UTF_8);
- ignoreException(Pattern.quote("SAX"));
- thrown =
- expectThrows(
- SolrException.class,
- "corrupt solrconfig.xml failed to trigger exception from reload",
- () -> {
- cc.reload("col_bad");
- });
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(Pattern.quote("SAX"))) {
+ thrown =
+ expectThrows(
+ SolrException.class,
+ "corrupt solrconfig.xml failed to trigger exception from reload",
+ () -> {
+ cc.reload("col_bad");
+ });
+ }
Throwable rootException = getWrappedException(thrown);
assertTrue(
"We're supposed to have a wrapped SAXParserException here, but we don't",
diff --git a/solr/core/src/test/org/apache/solr/core/TestLazyCores.java b/solr/core/src/test/org/apache/solr/core/TestLazyCores.java
index da305ed6cbc..10d3e2012d2 100644
--- a/solr/core/src/test/org/apache/solr/core/TestLazyCores.java
+++ b/solr/core/src/test/org/apache/solr/core/TestLazyCores.java
@@ -37,6 +37,7 @@ import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.CommitUpdateCommand;
import org.apache.solr.update.UpdateHandler;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.ReadOnlyCoresLocator;
import org.junit.Test;
@@ -401,47 +402,48 @@ public class TestLazyCores extends SolrTestCaseJ4 {
// Write out the cores' config files, both bad schema files, bad config files and some good
// cores.
+ @SuppressWarnings("try")
private CoreContainer initGoodAndBad(
List<String> goodCores, List<String> badSchemaCores, List<String> badConfigCores)
throws Exception {
solrHomeDirectory = createTempDir();
// Don't pollute the log with exception traces when they're expected.
- ignoreException(Pattern.quote("SAXParseException"));
-
- // Create the cores that should be fine.
- for (String coreName : goodCores) {
- Path coreRoot = solrHomeDirectory.resolve(coreName);
- copyMinConf(coreRoot, "name=" + coreName);
- }
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(Pattern.quote("SAXParseException"))) {
+ // Create the cores that should be fine.
+ for (String coreName : goodCores) {
+ Path coreRoot = solrHomeDirectory.resolve(coreName);
+ copyMinConf(coreRoot, "name=" + coreName);
+ }
- // Collect the files that we'll write to the config directories.
- Path top = SolrTestCaseJ4.TEST_HOME().resolve("collection1").resolve("conf");
- String min_schema = Files.readString(top.resolve("schema-tiny.xml"), StandardCharsets.UTF_8);
- String min_config =
- Files.readString(top.resolve("solrconfig-minimal.xml"), StandardCharsets.UTF_8);
- String rand_snip =
- Files.readString(
- top.resolve("solrconfig.snippet.randomindexconfig.xml"), StandardCharsets.UTF_8);
-
- // Now purposely mess up the config files, introducing stupid syntax errors.
- String bad_config = min_config.replace("<requestHandler", "<reqsthalr");
- String bad_schema = min_schema.replace("<field", "<filed");
-
- // Create the cores with bad configs
- for (String coreName : badConfigCores) {
- writeCustomConfig(coreName, bad_config, min_schema, rand_snip);
- }
+ // Collect the files that we'll write to the config directories.
+ Path top = SolrTestCaseJ4.TEST_HOME().resolve("collection1").resolve("conf");
+ String min_schema = Files.readString(top.resolve("schema-tiny.xml"), StandardCharsets.UTF_8);
+ String min_config =
+ Files.readString(top.resolve("solrconfig-minimal.xml"), StandardCharsets.UTF_8);
+ String rand_snip =
+ Files.readString(
+ top.resolve("solrconfig.snippet.randomindexconfig.xml"), StandardCharsets.UTF_8);
+
+ // Now purposely mess up the config files, introducing stupid syntax errors.
+ String bad_config = min_config.replace("<requestHandler", "<reqsthalr");
+ String bad_schema = min_schema.replace("<field", "<filed");
+
+ // Create the cores with bad configs
+ for (String coreName : badConfigCores) {
+ writeCustomConfig(coreName, bad_config, min_schema, rand_snip);
+ }
- // Create the cores with bad schemas.
- for (String coreName : badSchemaCores) {
- writeCustomConfig(coreName, min_config, bad_schema, rand_snip);
- }
+ // Create the cores with bad schemas.
+ for (String coreName : badSchemaCores) {
+ writeCustomConfig(coreName, min_config, bad_schema, rand_snip);
+ }
- NodeConfig config = SolrXmlConfig.fromString(solrHomeDirectory, "<solr/>");
+ NodeConfig config = SolrXmlConfig.fromString(solrHomeDirectory, "<solr/>");
- // OK this should succeed, but at the end we should have recorded a series of errors.
- return createCoreContainer(config, new CorePropertiesLocator(config));
+ // OK this should succeed, but at the end we should have recorded a series of errors.
+ return createCoreContainer(config, new CorePropertiesLocator(config));
+ }
}
// We want to see that the core "heals itself" if an un-corrupted file is written to the
diff --git a/solr/core/src/test/org/apache/solr/handler/JsonLoaderTest.java b/solr/core/src/test/org/apache/solr/handler/JsonLoaderTest.java
index 41ca734d01f..04726e2f3a9 100644
--- a/solr/core/src/test/org/apache/solr/handler/JsonLoaderTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/JsonLoaderTest.java
@@ -35,6 +35,7 @@ import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.CommitUpdateCommand;
import org.apache.solr.update.DeleteUpdateCommand;
import org.apache.solr.update.processor.BufferingRequestProcessor;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.RandomNoReverseMergePolicyFactory;
import org.junit.BeforeClass;
import org.junit.ClassRule;
@@ -737,31 +738,30 @@ public class JsonLoaderTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testAddBigIntegerValueToTrieField() {
// Adding a BigInteger to a long field should fail
// BigInteger.longValue() returns only the low-order 64 bits.
- ignoreException("big_integer_t");
-
- SolrException ex =
- expectThrows(
- SolrException.class,
- () -> {
- updateJ(json("[{'id':'1','big_integer_tl':12345678901234567890}]"), null);
- });
- assertTrue(ex.getCause() instanceof NumberFormatException);
-
- // Adding a BigInteger to an integer field should fail
- // BigInteger.intValue() returns only the low-order 32 bits.
- ex =
- expectThrows(
- SolrException.class,
- () -> {
- updateJ(json("[{'id':'1','big_integer_ti':12345678901234567890}]"), null);
- });
- assertTrue(ex.getCause() instanceof NumberFormatException);
-
- unIgnoreException("big_integer_t");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("big_integer_t")) {
+ SolrException ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ updateJ(json("[{'id':'1','big_integer_tl':12345678901234567890}]"), null);
+ });
+ assertTrue(ex.getCause() instanceof NumberFormatException);
+
+ // Adding a BigInteger to an integer field should fail
+ // BigInteger.intValue() returns only the low-order 32 bits.
+ ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ updateJ(json("[{'id':'1','big_integer_ti':12345678901234567890}]"), null);
+ });
+ assertTrue(ex.getCause() instanceof NumberFormatException);
+ }
}
@Test
diff --git a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java
index 66627c22583..0c85bbee765 100644
--- a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java
@@ -49,6 +49,7 @@ import org.apache.solr.embedded.JettySolrRunner;
import org.apache.solr.handler.admin.CoreAdminHandler.CoreAdminAsyncTracker;
import org.apache.solr.handler.admin.CoreAdminHandler.CoreAdminAsyncTracker.TaskObject;
import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -132,6 +133,7 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testCoreAdminHandler() throws Exception {
final Path workDir = createTempDir();
@@ -194,26 +196,25 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
assertEquals(cd.getCoreProperty("foo", null), "baz");
// attempt to create a bogus core and confirm failure
- ignoreException("Could not load config");
- se =
- expectThrows(
- SolrException.class,
- () -> {
- admin.handleRequestBody(
- req(
- CoreAdminParams.ACTION,
- CoreAdminParams.CoreAdminAction.CREATE.toString(),
- CoreAdminParams.NAME,
- "bogus_dir_core",
- CoreAdminParams.INSTANCE_DIR,
- "dir_does_not_exist_127896"),
- new SolrQueryResponse());
- });
- // :NOOP:
- // :TODO: CoreAdminHandler's exception messages are terrible, otherwise we could assert
- // something useful here
-
- unIgnoreException("Could not load config");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Could not load config")) {
+ se =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ admin.handleRequestBody(
+ req(
+ CoreAdminParams.ACTION,
+ CoreAdminParams.CoreAdminAction.CREATE.toString(),
+ CoreAdminParams.NAME,
+ "bogus_dir_core",
+ CoreAdminParams.INSTANCE_DIR,
+ "dir_does_not_exist_127896"),
+ new SolrQueryResponse());
+ });
+ // :NOOP:
+ // :TODO: CoreAdminHandler's exception messages are terrible, otherwise we could assert
+ // something useful here
+ }
// check specifically for status of the failed core name
resp = new SolrQueryResponse();
diff --git a/solr/core/src/test/org/apache/solr/handler/admin/CoreMergeIndexesAdminHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/admin/CoreMergeIndexesAdminHandlerTest.java
index 698ca31b74a..deb56a5cd14 100644
--- a/solr/core/src/test/org/apache/solr/handler/admin/CoreMergeIndexesAdminHandlerTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/admin/CoreMergeIndexesAdminHandlerTest.java
@@ -28,6 +28,7 @@ import org.apache.solr.core.DirectoryFactory;
import org.apache.solr.core.MockFSDirectoryFactory;
import org.apache.solr.core.SolrCore;
import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -62,6 +63,7 @@ public class CoreMergeIndexesAdminHandlerTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testMergeIndexesCoreAdminHandler() throws Exception {
final Path workDir = createTempDir();
@@ -73,9 +75,8 @@ public class CoreMergeIndexesAdminHandlerTest extends SolrTestCaseJ4 {
DirectoryFactory df = core.getDirectoryFactory();
FailingDirectoryFactory dirFactory = (FailingDirectoryFactory) df;
- try {
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(WRAPPED_FAILING_MSG)) {
dirFactory.fail = true;
- ignoreException(WRAPPED_FAILING_MSG);
SolrException e =
expectThrows(
SolrException.class,
@@ -93,8 +94,6 @@ public class CoreMergeIndexesAdminHandlerTest extends SolrTestCaseJ4 {
assertEquals(
FailingDirectoryFactory.FailingDirectoryFactoryException.class,
e.getCause().getClass());
- } finally {
- unIgnoreException(WRAPPED_FAILING_MSG);
}
dirFactory.fail = false;
}
diff --git a/solr/core/src/test/org/apache/solr/handler/component/BadComponentTest.java b/solr/core/src/test/org/apache/solr/handler/component/BadComponentTest.java
index 9331efa1497..3e3fb3ea7b0 100644
--- a/solr/core/src/test/org/apache/solr/handler/component/BadComponentTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/component/BadComponentTest.java
@@ -17,21 +17,21 @@
package org.apache.solr.handler.component;
import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.After;
import org.junit.Test;
/** SOLR-1730, tests what happens when a component fails to initialize properly */
public class BadComponentTest extends SolrTestCaseJ4 {
@Test
+ @SuppressWarnings("try")
public void testBadElevate() throws Exception {
- try {
- ignoreException(".*constructing.*");
- ignoreException(".*QueryElevationComponent.*");
+ try (ErrorLogMuter constructing = ErrorLogMuter.regex(".*constructing.*");
+ ErrorLogMuter queryElevationComponent =
+ ErrorLogMuter.regex(".*QueryElevationComponent.*")) {
System.setProperty("elevate.file", "foo.xml");
initCore("solrconfig-elevate.xml", "schema12.xml");
assertTrue(hasInitException("QueryElevationComponent"));
- } finally {
- resetExceptionIgnores();
}
}
diff --git a/solr/core/src/test/org/apache/solr/handler/component/DistributedDebugComponentTest.java b/solr/core/src/test/org/apache/solr/handler/component/DistributedDebugComponentTest.java
index 5953a970cd0..4eefff1ee97 100644
--- a/solr/core/src/test/org/apache/solr/handler/component/DistributedDebugComponentTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/component/DistributedDebugComponentTest.java
@@ -38,6 +38,7 @@ import org.apache.solr.common.params.ShardParams;
import org.apache.solr.common.util.EnvUtils;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.ExternalPaths;
import org.apache.solr.util.SolrJettyTestRule;
import org.junit.AfterClass;
@@ -93,7 +94,6 @@ public class DistributedDebugComponentTest extends SolrTestCaseJ4 {
public static void destroyThings() {
collection1 = null;
collection2 = null;
- resetExceptionIgnores();
systemClearPropertySolrEnableUrlAllowList();
}
@@ -392,6 +392,7 @@ public class DistributedDebugComponentTest extends SolrTestCaseJ4 {
(NamedList<?>) distribResponse.getDebugMap().get("timing"));
}
+ @SuppressWarnings("try")
public void testTolerantSearch() throws SolrServerException, IOException {
String badShard = DEAD_HOST_1 + "/solr/collection1";
SolrQuery query = new SolrQuery();
@@ -406,27 +407,27 @@ public class DistributedDebugComponentTest extends SolrTestCaseJ4 {
for (int i = 0; i < (TEST_NIGHTLY ? 500 : 200); i++) {
// verify that the request would fail if shards.tolerant=false
query.set(ShardParams.SHARDS_TOLERANT, "false");
- ignoreException("Server refused connection");
- expectThrows(SolrException.class, () -> collection1.query(query));
-
- // verify that the request would succeed if shards.tolerant=true
- query.set(ShardParams.SHARDS_TOLERANT, "true");
- QueryResponse response = collection1.query(query);
- assertTrue(
- (Boolean)
- response
- .getResponseHeader()
- .get(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
- @SuppressWarnings("unchecked")
- NamedList<String> badShardTrack =
- (((NamedList<NamedList<NamedList<String>>>) response.getDebugMap().get("track"))
- .get("EXECUTE_QUERY"))
- .get(badShard);
- assertEquals("Unexpected response size for shard", 1, badShardTrack.size());
- Entry<String, String> exception = badShardTrack.iterator().next();
- assertEquals("Expected key 'Exception' not found", "Exception", exception.getKey());
- assertNotNull("Exception message should not be null", exception.getValue());
- unIgnoreException("Server refused connection");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Server refused connection")) {
+ expectThrows(SolrException.class, () -> collection1.query(query));
+
+ // verify that the request would succeed if shards.tolerant=true
+ query.set(ShardParams.SHARDS_TOLERANT, "true");
+ QueryResponse response = collection1.query(query);
+ assertTrue(
+ (Boolean)
+ response
+ .getResponseHeader()
+ .get(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
+ @SuppressWarnings("unchecked")
+ NamedList<String> badShardTrack =
+ (((NamedList<NamedList<NamedList<String>>>) response.getDebugMap().get("track"))
+ .get("EXECUTE_QUERY"))
+ .get(badShard);
+ assertEquals("Unexpected response size for shard", 1, badShardTrack.size());
+ Entry<String, String> exception = badShardTrack.iterator().next();
+ assertEquals("Expected key 'Exception' not found", "Exception", exception.getKey());
+ assertNotNull("Exception message should not be null", exception.getValue());
+ }
}
}
diff --git a/solr/core/src/test/org/apache/solr/handler/component/DistributedExpandComponentTest.java b/solr/core/src/test/org/apache/solr/handler/component/DistributedExpandComponentTest.java
index 2516726f694..1abfb006288 100644
--- a/solr/core/src/test/org/apache/solr/handler/component/DistributedExpandComponentTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/component/DistributedExpandComponentTest.java
@@ -25,6 +25,7 @@ import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
/**
@@ -57,6 +58,7 @@ public class DistributedExpandComponentTest extends BaseDistributedSearchTestCas
"4"); // NOTE: using 0 to explicitly confim we don't assume null
}
+ @SuppressWarnings("try")
private void _test(
final String group, final String aaa, final String bbb, final String ccc, final String ddd)
throws Exception {
@@ -248,11 +250,12 @@ public class DistributedExpandComponentTest extends BaseDistributedSearchTestCas
"fq", "{!collapse cost=1000 field=" + group + "}", "{!collapse cost=200 field=test_i}");
query(baseParams);
- ignoreException("missing expand field");
- SolrException e = expectThrows(SolrException.class, () -> query("q", "*:*", "expand", "true"));
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertTrue(e.getMessage().contains("missing expand field"));
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("missing expand field")) {
+ SolrException e =
+ expectThrows(SolrException.class, () -> query("q", "*:*", "expand", "true"));
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertTrue(e.getMessage().contains("missing expand field"));
+ }
// Since none of these queries will match any doc w/null in the group field, it shouldn't matter
// what nullPolicy is used...
diff --git a/solr/core/src/test/org/apache/solr/handler/component/SearchHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/component/SearchHandlerTest.java
index 79592e3bc4c..9a69ae4fccb 100644
--- a/solr/core/src/test/org/apache/solr/handler/component/SearchHandlerTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/component/SearchHandlerTest.java
@@ -36,6 +36,7 @@ import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.SolrCore;
import org.apache.solr.embedded.JettyConfig;
import org.apache.solr.embedded.JettySolrRunner;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -166,6 +167,7 @@ public class SearchHandlerTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testRequireZkConnected() throws Exception {
MiniSolrCloudCluster miniCluster =
new MiniSolrCloudCluster(5, createTempDir(), JettyConfig.builder().build());
@@ -204,14 +206,15 @@ public class SearchHandlerTest extends SolrTestCaseJ4 {
req = new QueryRequest(params); // TODO Can be removed when SOLR-17314 fixed
// Use the replica's core URL to avoid ZK communication
var solrClient = disconnectedJetty.getSolrClient();
- ignoreException("ZooKeeper is not connected");
- disconnectedJetty.getCoreContainer().getZkController().getZkClient().close();
- try {
- req.process(solrClient, disconnectedReplica.getCoreName());
- fail(
- "An exception should be thrown when ZooKeeper is not connected and shards.tolerant=requireZkConnected");
- } catch (Exception e) {
- assertTrue(e.getMessage().contains("ZooKeeper is not connected"));
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("ZooKeeper is not connected")) {
+ disconnectedJetty.getCoreContainer().getZkController().getZkClient().close();
+ try {
+ req.process(solrClient, disconnectedReplica.getCoreName());
+ fail(
+ "An exception should be thrown when ZooKeeper is not connected and shards.tolerant=requireZkConnected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("ZooKeeper is not connected"));
+ }
}
} finally {
miniCluster.shutdown();
@@ -219,13 +222,15 @@ public class SearchHandlerTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testRequireZkConnectedDistrib() throws Exception {
MiniSolrCloudCluster miniCluster =
new MiniSolrCloudCluster(2, createTempDir(), JettyConfig.builder().build());
final CloudSolrClient cloudSolrClient = miniCluster.getSolrClient();
- try {
+ try (ErrorLogMuter zkNotConnected = ErrorLogMuter.regex("ZooKeeper is not connected");
+ ErrorLogMuter noActiveServers = ErrorLogMuter.regex("no active servers hosting shard:")) {
assertNotNull(miniCluster.getZkServer());
List<JettySolrRunner> jettys = miniCluster.getJettySolrRunners();
assertEquals(2, jettys.size());
@@ -261,8 +266,6 @@ public class SearchHandlerTest extends SolrTestCaseJ4 {
}
Replica connectedReplica = connectedSlice.getReplicas().iterator().next();
var solrClient = miniCluster.getReplicaJetty(connectedReplica).getSolrClient();
- ignoreException("ZooKeeper is not connected");
- ignoreException("no active servers hosting shard:");
JettySolrRunner disconnectedJetty = miniCluster.getReplicaJetty(disconnectedReplica);
disconnectedJetty.getCoreContainer().getZkController().getZkClient().close();
try {
@@ -277,8 +280,6 @@ public class SearchHandlerTest extends SolrTestCaseJ4 {
}
} finally {
miniCluster.shutdown();
- unIgnoreException("no active servers hosting shard:");
- unIgnoreException("ZooKeeper is not connected");
}
}
diff --git a/solr/core/src/test/org/apache/solr/handler/component/ShardsAllowListTest.java b/solr/core/src/test/org/apache/solr/handler/component/ShardsAllowListTest.java
index 8e9e74de9e2..23a219eb68e 100644
--- a/solr/core/src/test/org/apache/solr/handler/component/ShardsAllowListTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/component/ShardsAllowListTest.java
@@ -36,6 +36,7 @@ import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.embedded.JettySolrRunner;
import org.apache.solr.security.AllowListUrlChecker;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -256,20 +257,18 @@ public class ShardsAllowListTest extends MultiSolrCloudTestCase {
.getAllowListUrlChecker();
}
+ @SuppressWarnings("try")
private void assertForbidden(String query, String shards, MiniSolrCloudCluster cluster)
throws IOException {
String expectedExceptionMessage =
"nor in the configured '" + AllowListUrlChecker.URL_ALLOW_LIST + "'";
- ignoreException(expectedExceptionMessage);
- try {
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(expectedExceptionMessage)) {
numDocs(query, shards, cluster);
fail("Expecting failure for shards parameter: '" + shards + "'");
} catch (SolrServerException e) {
assertThat(e.getCause(), instanceOf(RemoteSolrException.class));
assertThat(((SolrException) e.getCause()).code(), is(SolrException.ErrorCode.FORBIDDEN.code));
assertThat(e.getCause().getMessage(), containsString(expectedExceptionMessage));
- } finally {
- unIgnoreException(expectedExceptionMessage);
}
}
diff --git a/solr/core/src/test/org/apache/solr/handler/component/StatsComponentTest.java b/solr/core/src/test/org/apache/solr/handler/component/StatsComponentTest.java
index 033901bf2f6..19cb861923e 100644
--- a/solr/core/src/test/org/apache/solr/handler/component/StatsComponentTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/component/StatsComponentTest.java
@@ -55,6 +55,7 @@ import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryRequestBase;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.SchemaField;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.hll.HLL;
import org.junit.BeforeClass;
@@ -2120,116 +2121,119 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
* @see #testCardinality
* @see #testHllOptions
*/
+ @SuppressWarnings("try")
public void testHllOptionsErrors() {
String[] baseParams = new String[] {"q", "*:*", "stats", "true", "indent", "true", "rows", "0"};
SolrCore core = h.getCore();
SchemaField foo_s = core.getLatestSchema().getField("foo_s");
SchemaField foo_i = core.getLatestSchema().getField("foo_i");
- ignoreException("hllPreHashed");
- for (SchemaField field : new SchemaField[] {foo_s, foo_i}) {
- // whitebox - field
+ try (ErrorLogMuter hllPreHashed = ErrorLogMuter.regex("hllPreHashed");
+ ErrorLogMuter accuracy = ErrorLogMuter.regex("accuracy");
+ ErrorLogMuter hllLog2m = ErrorLogMuter.regex("hllLog2m must be");
+ ErrorLogMuter hllRegwidth = ErrorLogMuter.regex("hllRegwidth must be")) {
+ for (SchemaField field : new SchemaField[] {foo_s, foo_i}) {
+ // whitebox - field
+ SolrException ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ HllOptions.parseHllOptions(
+ params("cardinality", "true", "hllPreHashed", "true"), field);
+ });
+ assertTrue(
+ "MSG: " + ex.getMessage(),
+ ex.getMessage().contains("hllPreHashed is only supported with Long"));
+ // blackbox - field
+ assertQEx(
+ "hllPreHashed " + field.getName(),
+ "hllPreHashed is only supported with Long",
+ req(
+ params("stats.field", "{!cardinality=true hllPreHashed=true}" + field.getName()),
+ baseParams),
+ ErrorCode.BAD_REQUEST);
+ }
+
+ // whitebox - function
SolrException ex =
expectThrows(
SolrException.class,
() -> {
HllOptions.parseHllOptions(
- params("cardinality", "true", "hllPreHashed", "true"), field);
+ params("cardinality", "true", "hllPreHashed", "true"), null);
});
assertTrue(
"MSG: " + ex.getMessage(),
ex.getMessage().contains("hllPreHashed is only supported with Long"));
- // blackbox - field
+
+ // blackbox - function
assertQEx(
- "hllPreHashed " + field.getName(),
+ "hllPreHashed function",
"hllPreHashed is only supported with Long",
req(
- params("stats.field", "{!cardinality=true hllPreHashed=true}" + field.getName()),
+ params("stats.field", "{!func cardinality=true hllPreHashed=true}sum(foo_i,foo_l)"),
baseParams),
ErrorCode.BAD_REQUEST);
- }
-
- // whitebox - function
- SolrException ex =
- expectThrows(
- SolrException.class,
- () -> {
- HllOptions.parseHllOptions(
- params("cardinality", "true", "hllPreHashed", "true"), null);
- });
- assertTrue(
- "MSG: " + ex.getMessage(),
- ex.getMessage().contains("hllPreHashed is only supported with Long"));
-
- // blackbox - function
- assertQEx(
- "hllPreHashed function",
- "hllPreHashed is only supported with Long",
- req(
- params("stats.field", "{!func cardinality=true hllPreHashed=true}sum(foo_i,foo_l)"),
- baseParams),
- ErrorCode.BAD_REQUEST);
- ignoreException("accuracy");
- for (String invalid : new String[] {"-1", "1.1", "100"}) {
- // whitebox
- ex =
- expectThrows(
- SolrException.class,
- () -> {
- HllOptions.parseHllOptions(params("cardinality", invalid), foo_s);
- });
- assertTrue("MSG: " + ex.getMessage(), ex.getMessage().contains("number between 0 and 1"));
- // blackbox
- assertQEx(
- "cardinality=" + invalid,
- "number between 0 and 1",
- req(params("stats.field", "{!cardinality=" + invalid + "}foo_s"), baseParams),
- ErrorCode.BAD_REQUEST);
- }
-
- ignoreException("hllLog2m must be");
- for (int invalid : new int[] {HLL.MINIMUM_LOG2M_PARAM - 1, HLL.MAXIMUM_LOG2M_PARAM + 11}) {
- // whitebox
- ex =
- expectThrows(
- SolrException.class,
- () -> {
- HllOptions.parseHllOptions(
- params("cardinality", "true", "hllLog2m", "" + invalid), foo_s);
- });
- assertTrue("MSG: " + ex.getMessage(), ex.getMessage().contains("hllLog2m must be"));
-
- // blackbox
- assertQEx(
- "hllLog2m=" + invalid,
- "hllLog2m must be",
- req(
- params("stats.field", "{!cardinality=true hllLog2m=" + invalid + "}foo_s"),
- baseParams),
- ErrorCode.BAD_REQUEST);
- }
+ for (String invalid : new String[] {"-1", "1.1", "100"}) {
+ // whitebox
+ ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ HllOptions.parseHllOptions(params("cardinality", invalid), foo_s);
+ });
+ assertTrue("MSG: " + ex.getMessage(), ex.getMessage().contains("number between 0 and 1"));
+ // blackbox
+ assertQEx(
+ "cardinality=" + invalid,
+ "number between 0 and 1",
+ req(params("stats.field", "{!cardinality=" + invalid + "}foo_s"), baseParams),
+ ErrorCode.BAD_REQUEST);
+ }
- ignoreException("hllRegwidth must be");
- for (int invalid : new int[] {HLL.MINIMUM_REGWIDTH_PARAM - 1, HLL.MAXIMUM_REGWIDTH_PARAM + 1}) {
- // whitebox
- ex =
- expectThrows(
- SolrException.class,
- () -> {
- HllOptions.parseHllOptions(
- params("cardinality", "true", "hllRegwidth", "" + invalid), foo_s);
- });
- assertTrue("MSG: " + ex.getMessage(), ex.getMessage().contains("hllRegwidth must be"));
+ for (int invalid : new int[] {HLL.MINIMUM_LOG2M_PARAM - 1, HLL.MAXIMUM_LOG2M_PARAM + 11}) {
+ // whitebox
+ ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ HllOptions.parseHllOptions(
+ params("cardinality", "true", "hllLog2m", "" + invalid), foo_s);
+ });
+ assertTrue("MSG: " + ex.getMessage(), ex.getMessage().contains("hllLog2m must be"));
+
+ // blackbox
+ assertQEx(
+ "hllLog2m=" + invalid,
+ "hllLog2m must be",
+ req(
+ params("stats.field", "{!cardinality=true hllLog2m=" + invalid + "}foo_s"),
+ baseParams),
+ ErrorCode.BAD_REQUEST);
+ }
- // blackbox
- assertQEx(
- "hllRegwidth=" + invalid,
- "hllRegwidth must be",
- req(
- params("stats.field", "{!cardinality=true hllRegwidth=" + invalid + "}foo_s"),
- baseParams),
- ErrorCode.BAD_REQUEST);
+ for (int invalid :
+ new int[] {HLL.MINIMUM_REGWIDTH_PARAM - 1, HLL.MAXIMUM_REGWIDTH_PARAM + 1}) {
+ // whitebox
+ ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ HllOptions.parseHllOptions(
+ params("cardinality", "true", "hllRegwidth", "" + invalid), foo_s);
+ });
+ assertTrue("MSG: " + ex.getMessage(), ex.getMessage().contains("hllRegwidth must be"));
+
+ // blackbox
+ assertQEx(
+ "hllRegwidth=" + invalid,
+ "hllRegwidth must be",
+ req(
+ params("stats.field", "{!cardinality=true hllRegwidth=" + invalid + "}foo_s"),
+ baseParams),
+ ErrorCode.BAD_REQUEST);
+ }
}
}
diff --git a/solr/core/src/test/org/apache/solr/handler/component/TestExpandComponent.java b/solr/core/src/test/org/apache/solr/handler/component/TestExpandComponent.java
index f3269419a8a..31753b42077 100644
--- a/solr/core/src/test/org/apache/solr/handler/component/TestExpandComponent.java
+++ b/solr/core/src/test/org/apache/solr/handler/component/TestExpandComponent.java
@@ -22,6 +22,7 @@ import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.search.CollapsingQParserPlugin;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -946,6 +947,7 @@ public class TestExpandComponent extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testErrorCases() {
String[] doc = {
"id",
@@ -979,51 +981,17 @@ public class TestExpandComponent extends SolrTestCaseJ4 {
};
assertU(adoc(doc1));
- ignoreException("missing expand field");
- ignoreException("Expected identifier at pos 2");
- ignoreException("Can't determine a Sort Order");
- ignoreException("Expand not supported for fieldType:'text'");
+ try (ErrorLogMuter missingExpandField = ErrorLogMuter.regex("missing expand field");
+ ErrorLogMuter expectedIdentifier = ErrorLogMuter.regex("Expected identifier at pos 2");
+ ErrorLogMuter sortOrder = ErrorLogMuter.regex("Can't determine a Sort Order");
+ ErrorLogMuter expandNotSupported =
+ ErrorLogMuter.regex("Expand not supported for fieldType:'text'")) {
- // expand with grouping
- SolrException e =
- expectThrows(
- SolrException.class,
- () -> {
- h.query(
- req(
- "q",
- "*:*",
- "expand",
- "true",
- "expand.field",
- "id",
- "group",
- "true",
- "group.field",
- "id"));
- });
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertEquals("Can not use expand with Grouping enabled", e.getMessage());
-
- // no expand field
- e = expectThrows(SolrException.class, () -> h.query(req("q", "*:*", "expand", "true")));
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertEquals("missing expand field", e.getMessage());
-
- // query and filter syntax errors
- e =
- expectThrows(
- SolrException.class,
- () ->
- h.query(
- req("q", "*:*", "expand", "true", "expand.field", "term_s", "expand.q", "{!")));
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertTrue(e.getMessage().contains("Expected identifier at pos 2 str='{!'"));
-
- e =
- expectThrows(
- SolrException.class,
- () ->
+ // expand with grouping
+ SolrException e =
+ expectThrows(
+ SolrException.class,
+ () -> {
h.query(
req(
"q",
@@ -1031,71 +999,114 @@ public class TestExpandComponent extends SolrTestCaseJ4 {
"expand",
"true",
"expand.field",
- "term_s",
- "expand.q",
- "*:*",
- "expand.fq",
- "{!")));
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertTrue(e.getMessage().contains("Expected identifier at pos 2 str='{!'"));
-
- e =
- expectThrows(
- SolrException.class,
- () ->
- h.query(
- req(
- "q",
- "*:*",
- "expand",
+ "id",
+ "group",
"true",
- "expand.field",
- "term_s",
- "expand.q",
- "*:*",
- "expand.fq",
- "{!")));
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertTrue(e.getMessage().contains("Expected identifier at pos 2 str='{!'"));
+ "group.field",
+ "id"));
+ });
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertEquals("Can not use expand with Grouping enabled", e.getMessage());
- e =
- expectThrows(
- SolrException.class,
- () ->
- h.query(
- req(
- "q",
- "*:*",
- "expand",
- "true",
- "expand.field",
- "term_s",
- "expand.q",
- "*:*",
- "expand.sort",
- "bleh")));
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertTrue(
- e.getMessage().contains("Can't determine a Sort Order (asc or desc) in sort spec 'bleh'"));
+ // no expand field
+ e = expectThrows(SolrException.class, () -> h.query(req("q", "*:*", "expand", "true")));
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertEquals("missing expand field", e.getMessage());
- e =
- expectThrows(
- SolrException.class,
- () ->
- h.query(
- req(
- "q",
- "*:*",
- "expand",
- "true",
- "expand.field",
- "text_t",
- "expand.q",
- "*:*")));
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertEquals("Expand not supported for fieldType:'text'", e.getMessage());
+ // query and filter syntax errors
+ e =
+ expectThrows(
+ SolrException.class,
+ () ->
+ h.query(
+ req(
+ "q",
+ "*:*",
+ "expand",
+ "true",
+ "expand.field",
+ "term_s",
+ "expand.q",
+ "{!")));
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertTrue(e.getMessage().contains("Expected identifier at pos 2 str='{!'"));
- resetExceptionIgnores();
+ e =
+ expectThrows(
+ SolrException.class,
+ () ->
+ h.query(
+ req(
+ "q",
+ "*:*",
+ "expand",
+ "true",
+ "expand.field",
+ "term_s",
+ "expand.q",
+ "*:*",
+ "expand.fq",
+ "{!")));
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertTrue(e.getMessage().contains("Expected identifier at pos 2 str='{!'"));
+
+ e =
+ expectThrows(
+ SolrException.class,
+ () ->
+ h.query(
+ req(
+ "q",
+ "*:*",
+ "expand",
+ "true",
+ "expand.field",
+ "term_s",
+ "expand.q",
+ "*:*",
+ "expand.fq",
+ "{!")));
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertTrue(e.getMessage().contains("Expected identifier at pos 2 str='{!'"));
+
+ e =
+ expectThrows(
+ SolrException.class,
+ () ->
+ h.query(
+ req(
+ "q",
+ "*:*",
+ "expand",
+ "true",
+ "expand.field",
+ "term_s",
+ "expand.q",
+ "*:*",
+ "expand.sort",
+ "bleh")));
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertTrue(
+ e.getMessage()
+ .contains("Can't determine a Sort Order (asc or desc) in sort spec 'bleh'"));
+
+ e =
+ expectThrows(
+ SolrException.class,
+ () ->
+ h.query(
+ req(
+ "q",
+ "*:*",
+ "expand",
+ "true",
+ "expand.field",
+ "text_t",
+ "expand.q",
+ "*:*")));
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertEquals("Expand not supported for fieldType:'text'", e.getMessage());
+ }
}
/**
diff --git a/solr/core/src/test/org/apache/solr/request/SimpleFacetsTest.java b/solr/core/src/test/org/apache/solr/request/SimpleFacetsTest.java
index 78bce90d2e3..3f6b0d5f21c 100644
--- a/solr/core/src/test/org/apache/solr/request/SimpleFacetsTest.java
+++ b/solr/core/src/test/org/apache/solr/request/SimpleFacetsTest.java
@@ -39,6 +39,7 @@ import org.apache.solr.common.util.NamedList;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.NumberType;
import org.apache.solr.schema.SchemaField;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.TimeZoneUtils;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -4546,10 +4547,10 @@ public class SimpleFacetsTest extends SolrTestCaseJ4 {
assertTrue(ex.getMessage().contains("Interval Faceting can't be used with group.facet"));
}
+ @SuppressWarnings("try")
public void testRangeFacetingBadRequest() {
String field = "range_facet_l";
- ignoreException(".");
- try {
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(".")) {
for (FacetRangeMethod method : FacetRangeMethod.values()) {
assertQEx(
"Test facet.range bad requests",
@@ -4723,8 +4724,6 @@ public class SimpleFacetsTest extends SolrTestCaseJ4 {
"foo"),
ErrorCode.BAD_REQUEST);
}
- } finally {
- resetExceptionIgnores();
}
}
diff --git a/solr/core/src/test/org/apache/solr/schema/CurrencyFieldTypeTest.java b/solr/core/src/test/org/apache/solr/schema/CurrencyFieldTypeTest.java
index 2bc21777d19..115deafac7d 100644
--- a/solr/core/src/test/org/apache/solr/schema/CurrencyFieldTypeTest.java
+++ b/solr/core/src/test/org/apache/solr/schema/CurrencyFieldTypeTest.java
@@ -28,6 +28,7 @@ import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.core.SolrCore;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.RTimer;
import org.junit.Assume;
import org.junit.BeforeClass;
@@ -240,14 +241,15 @@ public class CurrencyFieldTypeTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testBogusCurrency() {
- ignoreException("HOSS");
-
- // bogus currency
- assertQEx(
- "Expected exception for invalid currency",
- req("fl", "*,score", "q", fieldName + ":[3,HOSS TO *]"),
- 400);
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("HOSS")) {
+ // bogus currency
+ assertQEx(
+ "Expected exception for invalid currency",
+ req("fl", "*,score", "q", fieldName + ":[3,HOSS TO *]"),
+ 400);
+ }
}
@Test
diff --git a/solr/core/src/test/org/apache/solr/schema/EnumFieldTest.java b/solr/core/src/test/org/apache/solr/schema/EnumFieldTest.java
index 1899655c4ce..ee432a64902 100644
--- a/solr/core/src/test/org/apache/solr/schema/EnumFieldTest.java
+++ b/solr/core/src/test/org/apache/solr/schema/EnumFieldTest.java
@@ -28,6 +28,7 @@ import org.apache.solr.common.util.NamedList;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.search.SolrQueryParser;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -265,37 +266,46 @@ public class EnumFieldTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testBogusEnumIndexing() {
assumeFalse(
"Skipping testing of EnumFieldType without docValues, which is unsupported.",
System.getProperty("solr.tests.numeric.dv").equals("false"));
- ignoreException("Unknown value for enum field: " + FIELD_NAME + ", value: blabla");
- ignoreException("Unknown value for enum field: " + FIELD_NAME + ", value: 145");
- ignoreException("Unknown value for enum field: " + FIELD_NAME + ", value: -4");
-
- clearIndex();
-
- assertFailedU(adoc("id", "0", FIELD_NAME, "blabla"));
- assertFailedU(adoc("id", "0", FIELD_NAME, "145"));
- assertFailedU(adoc("id", "0", FIELD_NAME, "-4"));
+ try (ErrorLogMuter blabla =
+ ErrorLogMuter.regex("Unknown value for enum field: " + FIELD_NAME + ", value: blabla");
+ ErrorLogMuter n145 =
+ ErrorLogMuter.regex("Unknown value for enum field: " + FIELD_NAME + ", value: 145");
+ ErrorLogMuter neg4 =
+ ErrorLogMuter.regex("Unknown value for enum field: " + FIELD_NAME + ", value: -4")) {
+ clearIndex();
+
+ assertFailedU(adoc("id", "0", FIELD_NAME, "blabla"));
+ assertFailedU(adoc("id", "0", FIELD_NAME, "145"));
+ assertFailedU(adoc("id", "0", FIELD_NAME, "-4"));
+ }
}
@Test
+ @SuppressWarnings("try")
public void testMultivaluedBogusEnumIndexing() {
assumeFalse(
"Skipping testing of EnumFieldType without docValues, which is unsupported.",
System.getProperty("solr.tests.numeric.dv").equals("false"));
- ignoreException("Unknown value for enum field: " + MV_FIELD_NAME + ", value: blabla");
- ignoreException("Unknown value for enum field: " + MV_FIELD_NAME + ", value: 145");
- ignoreException("Unknown value for enum field: " + MV_FIELD_NAME + ", value: -4");
-
- clearIndex();
-
- assertFailedU(adoc("id", "0", MV_FIELD_NAME, "blabla", MV_FIELD_NAME, "High"));
- assertFailedU(adoc("id", "0", MV_FIELD_NAME, "145", MV_FIELD_NAME, "Low"));
- assertFailedU(adoc("id", "0", MV_FIELD_NAME, "-4", MV_FIELD_NAME, "Critical"));
+ try (ErrorLogMuter blabla =
+ ErrorLogMuter.regex(
+ "Unknown value for enum field: " + MV_FIELD_NAME + ", value: blabla");
+ ErrorLogMuter n145 =
+ ErrorLogMuter.regex("Unknown value for enum field: " + MV_FIELD_NAME + ", value: 145");
+ ErrorLogMuter neg4 =
+ ErrorLogMuter.regex("Unknown value for enum field: " + MV_FIELD_NAME + ", value: -4")) {
+ clearIndex();
+
+ assertFailedU(adoc("id", "0", MV_FIELD_NAME, "blabla", MV_FIELD_NAME, "High"));
+ assertFailedU(adoc("id", "0", MV_FIELD_NAME, "145", MV_FIELD_NAME, "Low"));
+ assertFailedU(adoc("id", "0", MV_FIELD_NAME, "-4", MV_FIELD_NAME, "Critical"));
+ }
}
@Test
diff --git a/solr/core/src/test/org/apache/solr/schema/PolyFieldTest.java b/solr/core/src/test/org/apache/solr/schema/PolyFieldTest.java
index 1be999ab371..c1ae9b74724 100644
--- a/solr/core/src/test/org/apache/solr/schema/PolyFieldTest.java
+++ b/solr/core/src/test/org/apache/solr/schema/PolyFieldTest.java
@@ -25,6 +25,7 @@ import org.apache.lucene.search.Query;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException;
import org.apache.solr.core.SolrCore;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -127,6 +128,7 @@ public class PolyFieldTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testSearching() {
for (int i = 0; i < 50; i++) {
assertU(
@@ -152,12 +154,12 @@ public class PolyFieldTest extends SolrTestCaseJ4 {
assertQ(req("fl", "*,score", "q", "homed:[1,1000 TO 2000,35000]"), "\"//*[@numFound='2']\"");
// bad
- ignoreException("dimension");
- assertQEx(
- "Query should throw an exception due to incorrect dimensions",
- req("fl", "*,score", "q", "homed:[1 TO 2000]"),
- SolrException.ErrorCode.BAD_REQUEST);
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("dimension")) {
+ assertQEx(
+ "Query should throw an exception due to incorrect dimensions",
+ req("fl", "*,score", "q", "homed:[1 TO 2000]"),
+ SolrException.ErrorCode.BAD_REQUEST);
+ }
clearIndex();
}
diff --git a/solr/core/src/test/org/apache/solr/schema/RequiredFieldsTest.java b/solr/core/src/test/org/apache/solr/schema/RequiredFieldsTest.java
index f001a510b7a..6ce9a5b1fb5 100644
--- a/solr/core/src/test/org/apache/solr/schema/RequiredFieldsTest.java
+++ b/solr/core/src/test/org/apache/solr/schema/RequiredFieldsTest.java
@@ -19,6 +19,7 @@ package org.apache.solr.schema;
import java.util.Collection;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.core.SolrCore;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -52,6 +53,7 @@ public class RequiredFieldsTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testRequiredFieldsSingleAdd() {
SolrCore core = h.getCore();
// Add a single document
@@ -88,11 +90,11 @@ public class RequiredFieldsTest extends SolrTestCaseJ4 {
// Add another document without a required name, which has no default
assertNull(core.getLatestSchema().getField("name").getDefaultValue());
- ignoreException("missing required field");
- assertFailedU(
- "adding doc without required field",
- adoc("id", "531", "subject", "no name document", "field_t", "what's inside?"));
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("missing required field")) {
+ assertFailedU(
+ "adding doc without required field",
+ adoc("id", "531", "subject", "no name document", "field_t", "what's inside?"));
+ }
assertU(commit());
// Check to make sure this submission did not succeed
@@ -100,6 +102,7 @@ public class RequiredFieldsTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testAddMultipleDocumentsWithErrors() {
// Add three documents at once to make sure the baseline succeeds
assertU(
@@ -190,32 +193,32 @@ public class RequiredFieldsTest extends SolrTestCaseJ4 {
// Check that only docs before the error should be in the index
assertQ("should find one", req("name:baddef"), "//result[@numFound=1]");
- ignoreException("missing required field");
// Add three documents at once, with the middle one missing a required field that has no default
- assertFailedU(
- "adding 3 docs, with 2nd one missing required field",
- "<add>"
- + doc(
- "id",
- "701",
- "name",
- "noname batch one",
- "field_t",
- "what's inside?",
- "subject",
- "info")
- + doc("id", "702", "field_t", "what's inside?", "subject", "info")
- + doc(
- "id",
- "703",
- "name",
- "noname batch batch three",
- "field_t",
- "what's inside?",
- "subject",
- "info")
- + "</add>");
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("missing required field")) {
+ assertFailedU(
+ "adding 3 docs, with 2nd one missing required field",
+ "<add>"
+ + doc(
+ "id",
+ "701",
+ "name",
+ "noname batch one",
+ "field_t",
+ "what's inside?",
+ "subject",
+ "info")
+ + doc("id", "702", "field_t", "what's inside?", "subject", "info")
+ + doc(
+ "id",
+ "703",
+ "name",
+ "noname batch batch three",
+ "field_t",
+ "what's inside?",
+ "subject",
+ "info")
+ + "</add>");
+ }
assertU(commit());
diff --git a/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.java b/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.java
index e60f6d23da9..55834502229 100644
--- a/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.java
+++ b/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.java
@@ -38,6 +38,7 @@ import org.apache.solr.core.CoreContainer;
import org.apache.solr.handler.admin.CoreAdminHandler;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.After;
import org.junit.Before;
import org.slf4j.Logger;
@@ -173,11 +174,11 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
statusByCore.get(collection).schema);
}
+ @SuppressWarnings("try")
public void testAddFieldWhenNotMutable() throws Exception {
assertSchemaResource(collection, "managed-schema.xml");
String errString = "This ManagedIndexSchema is not mutable.";
- ignoreException(Pattern.quote(errString));
- try {
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(Pattern.quote(errString))) {
IndexSchema oldSchema = h.getCore().getLatestSchema();
String fieldName = "new_field";
String fieldType = "string";
@@ -196,8 +197,6 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
SolrException.ErrorCode.SERVER_ERROR,
"Unexpected error, expected error matching: " + errString,
e);
- } finally {
- resetExceptionIgnores();
}
}
@@ -233,6 +232,7 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
"<field name=\"new_field\" type=\"string\" stored=\"false\"/>"));
}
+ @SuppressWarnings("try")
public void testAddedFieldIndexableAndQueryable() throws Exception {
assertSchemaResource(collection, "managed-schema.xml");
deleteCore();
@@ -249,8 +249,7 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
clearIndex();
String errString = "unknown field 'new_field'";
- ignoreException(Pattern.quote(errString));
- try {
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(Pattern.quote(errString))) {
assertU(adoc("new_field", "thing1 thing2", "str", "X"));
fail();
} catch (Exception e) {
@@ -263,8 +262,6 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
SolrException.ErrorCode.SERVER_ERROR,
"Unexpected error, expected error matching: " + errString,
e);
- } finally {
- resetExceptionIgnores();
}
assertU(commit());
assertQ(req("new_field:thing1"), "//*[@numFound='0']");
@@ -284,6 +281,7 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
assertQ(req("new_field:thing1"), "//*[@numFound='1']");
}
+ @SuppressWarnings("try")
public void testAddFieldWhenItAlreadyExists() throws Exception {
deleteCore();
Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");
@@ -297,8 +295,7 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
h.getCore().getLatestSchema().getFieldOrNull("str"));
String errString = "Field 'str' already exists.";
- ignoreException(Pattern.quote(errString));
- try {
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(Pattern.quote(errString))) {
Map<String, Object> options = new HashMap<>();
IndexSchema oldSchema = h.getCore().getLatestSchema();
String fieldName = "str";
@@ -317,11 +314,10 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
SolrException.ErrorCode.SERVER_ERROR,
"Unexpected error, expected error matching: " + errString,
e);
- } finally {
- resetExceptionIgnores();
}
}
+ @SuppressWarnings("try")
public void testAddSameFieldTwice() throws Exception {
deleteCore();
Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");
@@ -340,8 +336,7 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
h.getCore().setLatestSchema(newSchema);
String errString = "Field 'new_field' already exists.";
- ignoreException(Pattern.quote(errString));
- try {
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(Pattern.quote(errString))) {
newSchema = newSchema.addField(newField);
h.getCore().setLatestSchema(newSchema);
fail("Should fail when adding the same field twice");
@@ -355,11 +350,10 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
SolrException.ErrorCode.SERVER_ERROR,
"Unexpected error, expected error matching: " + errString,
e);
- } finally {
- resetExceptionIgnores();
}
}
+ @SuppressWarnings("try")
public void testAddDynamicField() throws Exception {
deleteCore();
Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");
@@ -373,8 +367,7 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
h.getCore().getLatestSchema().getFieldOrNull("*_s"));
String errString = "Can't add dynamic field '*_s'.";
- ignoreException(Pattern.quote(errString));
- try {
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(Pattern.quote(errString))) {
Map<String, Object> options = new HashMap<>();
IndexSchema oldSchema = h.getCore().getLatestSchema();
String fieldName = "*_s";
@@ -393,8 +386,6 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {
SolrException.ErrorCode.SERVER_ERROR,
"Unexpected error, expected error matching: " + errString,
e);
- } finally {
- resetExceptionIgnores();
}
}
diff --git a/solr/core/src/test/org/apache/solr/schema/TestOmitPositions.java b/solr/core/src/test/org/apache/solr/schema/TestOmitPositions.java
index cd891279375..3c11006c5d2 100644
--- a/solr/core/src/test/org/apache/solr/schema/TestOmitPositions.java
+++ b/solr/core/src/test/org/apache/solr/schema/TestOmitPositions.java
@@ -17,6 +17,7 @@
package org.apache.solr.schema;
import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
public class TestOmitPositions extends SolrTestCaseJ4 {
@@ -53,13 +54,13 @@ public class TestOmitPositions extends SolrTestCaseJ4 {
"//result/doc[2]/str[@name='id'][.=1]");
}
+ @SuppressWarnings("try")
public void testPositions() {
// no results should be found:
// lucene 3.x: silent failure
// lucene 4.x: illegal state exception, field was indexed without positions
- ignoreException("was indexed without position data");
- try {
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("was indexed without position data")) {
assertQ(
"phrase query: ",
req("fl", "id", "q", "nopositionstext:\"test test\""),
@@ -68,6 +69,5 @@ public class TestOmitPositions extends SolrTestCaseJ4 {
assertTrue(expected.getCause() instanceof IllegalStateException);
// in lucene 4.0, queries don't silently fail
}
- resetExceptionIgnores();
}
}
diff --git a/solr/core/src/test/org/apache/solr/schema/TestSortableTextField.java b/solr/core/src/test/org/apache/solr/schema/TestSortableTextField.java
index de2c5c64bea..cc041c700e6 100644
--- a/solr/core/src/test/org/apache/solr/schema/TestSortableTextField.java
+++ b/solr/core/src/test/org/apache/solr/schema/TestSortableTextField.java
@@ -37,6 +37,7 @@ import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.search.SolrIndexSearcher;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.RefCounted;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -419,9 +420,8 @@ public class TestSortableTextField extends SolrTestCaseJ4 {
}
/** test how various permutations of useDocValuesAsStored and maxCharsForDocValues interact */
+ @SuppressWarnings("try")
public void testUseDocValuesAsStored() {
- ignoreException("when useDocValuesAsStored=true \\(length=");
-
// first things first...
// unlike most field types, SortableTextField should default to useDocValuesAsStored==false
// (check a handful that should have the default behavior)
@@ -489,12 +489,16 @@ public class TestSortableTextField extends SolrTestCaseJ4 {
// if useDocValuesAsStored==true and maxCharsForDocValues=N then longer values should fail
final String doc = adoc("id", docid, name, "apple pear orange");
- SolrException ex =
- expectThrows(
- SolrException.class,
- () -> {
- assertU(doc);
- });
+ SolrException ex;
+ try (ErrorLogMuter ignored =
+ ErrorLogMuter.regex("when useDocValuesAsStored=true \\(length=")) {
+ ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ assertU(doc);
+ });
+ }
for (String expect :
Arrays.asList(
"field " + name,
diff --git a/solr/core/src/test/org/apache/solr/search/CurrencyRangeFacetCloudTest.java b/solr/core/src/test/org/apache/solr/search/CurrencyRangeFacetCloudTest.java
index 5df58d9e0f2..f1da5ee20fe 100644
--- a/solr/core/src/test/org/apache/solr/search/CurrencyRangeFacetCloudTest.java
+++ b/solr/core/src/test/org/apache/solr/search/CurrencyRangeFacetCloudTest.java
@@ -31,6 +31,7 @@ import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.CoreAdminParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.schema.CurrencyFieldTypeTest;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -357,59 +358,61 @@ public class CurrencyRangeFacetCloudTest extends SolrCloudTestCase {
}
}
+ @SuppressWarnings("try")
public void testFacetRangeCleanErrorOnMissmatchCurrency() {
final String expected = "Cannot compare CurrencyValues when their currencies are not equal";
- ignoreException(expected);
-
- // test to check clean error when start/end have diff currency (facet.range)
- final SolrQuery solrQuery =
- new SolrQuery(
- "q",
- "*:*",
- "rows",
- "0",
- "facet",
- "true",
- "facet.range",
- FIELD,
- "f." + FIELD + ".facet.range.start",
- "0,EUR",
- "f." + FIELD + ".facet.range.gap",
- "10,EUR",
- "f." + FIELD + ".facet.range.end",
- "100,USD");
- final SolrException ex =
- expectThrows(
- SolrException.class,
- () -> {
- final QueryResponse rsp = cluster.getSolrClient(COLLECTION).query(solrQuery);
- });
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
- assertTrue(ex.getMessage(), ex.getMessage().contains(expected));
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(expected)) {
+ // test to check clean error when start/end have diff currency (facet.range)
+ final SolrQuery solrQuery =
+ new SolrQuery(
+ "q",
+ "*:*",
+ "rows",
+ "0",
+ "facet",
+ "true",
+ "facet.range",
+ FIELD,
+ "f." + FIELD + ".facet.range.start",
+ "0,EUR",
+ "f." + FIELD + ".facet.range.gap",
+ "10,EUR",
+ "f." + FIELD + ".facet.range.end",
+ "100,USD");
+ final SolrException ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ final QueryResponse rsp = cluster.getSolrClient(COLLECTION).query(solrQuery);
+ });
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
+ assertTrue(ex.getMessage(), ex.getMessage().contains(expected));
+ }
}
+ @SuppressWarnings("try")
public void testJsonFacetCleanErrorOnMissmatchCurrency() {
final String expected = "Cannot compare CurrencyValues when their currencies are not equal";
- ignoreException(expected);
-
- // test to check clean error when start/end have diff currency (json.facet)
- final SolrQuery solrQuery =
- new SolrQuery(
- "q",
- "*:*",
- "json.facet",
- "{ x:{ type:range, field:"
- + FIELD
- + ", "
- + " start:'0,EUR', gap:'10,EUR', end:'100,USD' } }");
- final SolrException ex =
- expectThrows(
- SolrException.class,
- () -> {
- final QueryResponse rsp = cluster.getSolrClient(COLLECTION).query(solrQuery);
- });
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
- assertTrue(ex.getMessage(), ex.getMessage().contains(expected));
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(expected)) {
+ // test to check clean error when start/end have diff currency (json.facet)
+ final SolrQuery solrQuery =
+ new SolrQuery(
+ "q",
+ "*:*",
+ "json.facet",
+ "{ x:{ type:range, field:"
+ + FIELD
+ + ", "
+ + " start:'0,EUR', gap:'10,EUR', end:'100,USD' } }");
+ final SolrException ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ final QueryResponse rsp = cluster.getSolrClient(COLLECTION).query(solrQuery);
+ });
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
+ assertTrue(ex.getMessage(), ex.getMessage().contains(expected));
+ }
}
@Test
diff --git a/solr/core/src/test/org/apache/solr/search/TestAddFieldRealTimeGet.java b/solr/core/src/test/org/apache/solr/search/TestAddFieldRealTimeGet.java
index 65555dc4560..cde5d92de29 100644
--- a/solr/core/src/test/org/apache/solr/search/TestAddFieldRealTimeGet.java
+++ b/solr/core/src/test/org/apache/solr/search/TestAddFieldRealTimeGet.java
@@ -23,6 +23,7 @@ import org.apache.commons.io.file.PathUtils;
import org.apache.lucene.tests.mockfile.FilterPath;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.Before;
public class TestAddFieldRealTimeGet extends TestRTGBase {
@@ -50,6 +51,7 @@ public class TestAddFieldRealTimeGet extends TestRTGBase {
initCore(configFileName, schemaFileName, tmpSolrHome);
}
+ @SuppressWarnings("try")
public void test() throws Exception {
clearIndex();
assertU(commit());
@@ -58,11 +60,11 @@ public class TestAddFieldRealTimeGet extends TestRTGBase {
String newFieldType = "string";
String newFieldValue = "xyz";
- ignoreException("unknown field");
- assertFailedU(
- "Should fail due to unknown field '" + newFieldName + "'",
- adoc("id", "1", newFieldName, newFieldValue));
- unIgnoreException("unknown field");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("unknown field")) {
+ assertFailedU(
+ "Should fail due to unknown field '" + newFieldName + "'",
+ adoc("id", "1", newFieldName, newFieldValue));
+ }
IndexSchema schema = h.getCore().getLatestSchema();
SchemaField newField = schema.newField(newFieldName, newFieldType, Map.of());
diff --git a/solr/core/src/test/org/apache/solr/search/TestExtendedDismaxParser.java b/solr/core/src/test/org/apache/solr/search/TestExtendedDismaxParser.java
index 19b5117488f..cf80ef4eb24 100644
--- a/solr/core/src/test/org/apache/solr/search/TestExtendedDismaxParser.java
+++ b/solr/core/src/test/org/apache/solr/search/TestExtendedDismaxParser.java
@@ -52,6 +52,7 @@ import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.Utils;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.util.BaseTestHarness;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.SolrPluginUtils;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -976,26 +977,23 @@ public class TestExtendedDismaxParser extends SolrTestCaseJ4 {
}
/** SOLR-13203 * */
+ @SuppressWarnings("try")
public void testUfDynamicField() {
- try {
- ignoreException("dynamic field");
-
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("dynamic field")) {
SolrException exception =
expectThrows(
SolrException.class, () -> h.query(req("uf", "fl=trait*,id", "defType", "edismax")));
assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, exception.code());
assertEquals("dynamic field name must start or end with *", exception.getMessage());
- } finally {
- resetExceptionIgnores();
}
// simple test to validate dynamic uf parsing works
assertQ(req("uf", "trait* id", "defType", "edismax"));
}
+ @SuppressWarnings("try")
public void testCyclicAliasing() {
- try {
- ignoreException(".*Field aliases lead to a cycle.*");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(".*Field aliases lead to a cycle.*")) {
SolrException e =
expectThrows(
@@ -1110,8 +1108,6 @@ public class TestExtendedDismaxParser extends SolrTestCaseJ4 {
"f.myalias.qf",
"who")));
assertCyclicDetectionErrorMessage(e);
- } finally {
- resetExceptionIgnores();
}
}
diff --git a/solr/core/src/test/org/apache/solr/search/TestFoldingMultitermQuery.java b/solr/core/src/test/org/apache/solr/search/TestFoldingMultitermQuery.java
index d8edc3af40f..5534a6c4039 100644
--- a/solr/core/src/test/org/apache/solr/search/TestFoldingMultitermQuery.java
+++ b/solr/core/src/test/org/apache/solr/search/TestFoldingMultitermQuery.java
@@ -18,6 +18,7 @@ package org.apache.solr.search;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -320,17 +321,15 @@ public class TestFoldingMultitermQuery extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testMultiBad() {
- try {
- ignoreException("analyzer returned too many terms");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("analyzer returned too many terms")) {
Exception expected =
expectThrows(
Exception.class,
"Should throw exception when token evaluates to more than one term",
() -> assertQ(req("q", "content_multi_bad:" + "abCD*")));
assertTrue(expected.getCause() instanceof SolrException);
- } finally {
- resetExceptionIgnores();
}
}
diff --git a/solr/core/src/test/org/apache/solr/search/TestQueryTypes.java b/solr/core/src/test/org/apache/solr/search/TestQueryTypes.java
index 9f5ac1f75fa..705e66fb6f8 100644
--- a/solr/core/src/test/org/apache/solr/search/TestQueryTypes.java
+++ b/solr/core/src/test/org/apache/solr/search/TestQueryTypes.java
@@ -19,6 +19,7 @@ package org.apache.solr.search;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.CommonParams;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -33,6 +34,7 @@ public class TestQueryTypes extends SolrTestCaseJ4 {
return "basic";
}
+ @SuppressWarnings("try")
public void testQueryTypes() {
assertU(adoc("id", "0"));
assertU(adoc("id", "1", "v_t", "Hello Dude"));
@@ -382,8 +384,7 @@ public class TestQueryTypes extends SolrTestCaseJ4 {
"//result[@numFound='1']",
"//*[@name='id'][.='1']");
- try {
- ignoreException("No\\ default\\, and no switch case");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("No\\ default\\, and no switch case")) {
RuntimeException exp =
expectThrows(
RuntimeException.class,
@@ -399,8 +400,6 @@ public class TestQueryTypes extends SolrTestCaseJ4 {
assertTrue(
"Error doesn't include bad switch case: " + e.getMessage(),
e.getMessage().contains("asdf"));
- } finally {
- resetExceptionIgnores();
}
// dismax query from std request handler
diff --git a/solr/core/src/test/org/apache/solr/search/TestReRankQParserPlugin.java b/solr/core/src/test/org/apache/solr/search/TestReRankQParserPlugin.java
index e674c92eb41..0524e72b672 100644
--- a/solr/core/src/test/org/apache/solr/search/TestReRankQParserPlugin.java
+++ b/solr/core/src/test/org/apache/solr/search/TestReRankQParserPlugin.java
@@ -34,6 +34,7 @@ import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestInfo;
import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.SolrMetricTestUtils;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -1100,6 +1101,7 @@ public class TestReRankQParserPlugin extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testRerankQueryParsingShouldFailWithoutMandatoryReRankQueryParameter() {
assertU(delQ("*:*"));
assertU(commit());
@@ -1132,16 +1134,16 @@ public class TestReRankQParserPlugin extends SolrTestCaseJ4 {
params.add("start", "0");
params.add("rows", "2");
- ignoreException("reRankQuery parameter is mandatory");
- SolrException se =
- expectThrows(
- SolrException.class,
- "A syntax error should be thrown when "
- + ReRankQParserPlugin.RERANK_QUERY
- + " parameter is not specified",
- () -> h.query(req(params)));
- assertEquals(se.code(), SolrException.ErrorCode.BAD_REQUEST.code);
- unIgnoreException("reRankQuery parameter is mandatory");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("reRankQuery parameter is mandatory")) {
+ SolrException se =
+ expectThrows(
+ SolrException.class,
+ "A syntax error should be thrown when "
+ + ReRankQParserPlugin.RERANK_QUERY
+ + " parameter is not specified",
+ () -> h.query(req(params)));
+ assertEquals(se.code(), SolrException.ErrorCode.BAD_REQUEST.code);
+ }
}
@Test
diff --git a/solr/core/src/test/org/apache/solr/search/TestRecovery.java b/solr/core/src/test/org/apache/solr/search/TestRecovery.java
index 2a40116c231..6bdc5ed6e08 100644
--- a/solr/core/src/test/org/apache/solr/search/TestRecovery.java
+++ b/solr/core/src/test/org/apache/solr/search/TestRecovery.java
@@ -46,6 +46,7 @@ import org.apache.solr.schema.IndexSchema;
import org.apache.solr.update.UpdateHandler;
import org.apache.solr.update.UpdateLog;
import org.apache.solr.update.processor.DistributedUpdateProcessor.DistribPhase;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.SolrMetricTestUtils;
import org.apache.solr.util.TestInjection;
import org.apache.solr.util.TimeOut;
@@ -1456,7 +1457,7 @@ public class TestRecovery extends SolrTestCaseJ4 {
}
@Test
- @SuppressWarnings("JdkObsolete")
+ @SuppressWarnings({"JdkObsolete", "try"})
public void testRemoveOldLogs() throws Exception {
try {
TestInjection.skipIndexWriterCommitOnClose = true;
@@ -1596,13 +1597,14 @@ public class TestRecovery extends SolrTestCaseJ4 {
"This is a trashed log file that really shouldn't work at all, but we'll see...");
}
- ignoreException("Failure to open existing");
- createCore();
- // we should still be able to get the list of versions (not including the trashed log file)
- assertJQ(
- reqWithPath("/get", "getVersions", "" + maxReq),
- "/versions==" + versions.subList(0, Math.min(maxReq, expectedToRetain)));
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Failure to open existing")) {
+ createCore();
+ // we should still be able to get the list of versions (not including the trashed log
+ // file)
+ assertJQ(
+ reqWithPath("/get", "getVersions", "" + maxReq),
+ "/versions==" + versions.subList(0, Math.min(maxReq, expectedToRetain)));
+ }
} finally {
UpdateLog.testing_logReplayHook = null;
@@ -1616,6 +1618,7 @@ public class TestRecovery extends SolrTestCaseJ4 {
// that were not cut off.
//
@Test
+ @SuppressWarnings("try")
public void testTruncatedLog() throws Exception {
try {
TestInjection.skipIndexWriterCommitOnClose = true;
@@ -1657,10 +1660,10 @@ public class TestRecovery extends SolrTestCaseJ4 {
logReplay.release(1000);
logReplayFinish.drainPermits();
// this is what the corrupted log currently produces... subject to change.
- ignoreException("OutOfBoundsException");
- createCore();
- assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("OutOfBoundsException")) {
+ createCore();
+ assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));
+ }
assertJQ(req("q", "*:*"), "/response/numFound==3");
//
@@ -1695,6 +1698,7 @@ public class TestRecovery extends SolrTestCaseJ4 {
// test that a corrupt tlog doesn't stop us from coming up
//
@Test
+ @SuppressWarnings("try")
public void testCorruptLog() throws Exception {
try {
TestInjection.skipIndexWriterCommitOnClose = true;
@@ -1721,9 +1725,9 @@ public class TestRecovery extends SolrTestCaseJ4 {
}
// this is what the corrupted log currently produces... subject to change.
- ignoreException("Failure to open existing log file");
- createCore();
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Failure to open existing log file")) {
+ createCore();
+ }
// just make sure it responds
assertJQ(req("q", "*:*"), "/response/numFound==0");
@@ -1766,6 +1770,7 @@ public class TestRecovery extends SolrTestCaseJ4 {
// in rare circumstances, two logs can be left uncapped (lacking a commit at the end signifying
// that all the content in the log was committed)
@Test
+ @SuppressWarnings("try")
public void testRecoveryMultipleLogs() throws Exception {
try {
TestInjection.skipIndexWriterCommitOnClose = true;
@@ -1836,10 +1841,10 @@ public class TestRecovery extends SolrTestCaseJ4 {
logReplay.release(1000);
logReplayFinish.drainPermits();
// this is what the corrupted log currently produces... subject to change.
- ignoreException("OutOfBoundsException");
- createCore();
- assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("OutOfBoundsException")) {
+ createCore();
+ assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));
+ }
assertJQ(req("q", "*:*"), "/response/numFound==6");
} finally {
diff --git a/solr/core/src/test/org/apache/solr/search/TestSolr4Spatial.java b/solr/core/src/test/org/apache/solr/search/TestSolr4Spatial.java
index 01e58f42e77..5238c9f6882 100644
--- a/solr/core/src/test/org/apache/solr/search/TestSolr4Spatial.java
+++ b/solr/core/src/test/org/apache/solr/search/TestSolr4Spatial.java
@@ -26,6 +26,7 @@ import org.apache.solr.legacy.BBoxStrategy;
import org.apache.solr.schema.BBoxField;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.SpatialUtils;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -80,6 +81,7 @@ public class TestSolr4Spatial extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testBadShapeParse400() {
assertQEx(
null,
@@ -118,14 +120,14 @@ public class TestSolr4Spatial extends SolrTestCaseJ4 {
"{!field f=" + fieldName + "}Intersectssss"),
400);
- ignoreException("NonexistentShape");
- SolrException e =
- expectThrows(
- SolrException.class,
- "should throw exception on non existent shape",
- () -> assertU(adoc("id", "-1", fieldName, "NonexistentShape")));
- assertEquals(400, e.code());
- unIgnoreException("NonexistentShape");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("NonexistentShape")) {
+ SolrException e =
+ expectThrows(
+ SolrException.class,
+ "should throw exception on non existent shape",
+ () -> assertU(adoc("id", "-1", fieldName, "NonexistentShape")));
+ assertEquals(400, e.code());
+ }
}
private void setupDocs() {
diff --git a/solr/core/src/test/org/apache/solr/search/TestSolrQueryParser.java b/solr/core/src/test/org/apache/solr/search/TestSolrQueryParser.java
index deef7f49d49..ac460daaa2d 100644
--- a/solr/core/src/test/org/apache/solr/search/TestSolrQueryParser.java
+++ b/solr/core/src/test/org/apache/solr/search/TestSolrQueryParser.java
@@ -58,6 +58,7 @@ import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.NumberType;
import org.apache.solr.schema.SchemaField;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.SolrMetricTestUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -476,6 +477,7 @@ public class TestSolrQueryParser extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testManyClauses_Solr() throws Exception {
final String a = "1 a 2 b 3 c 10 d 11 12 "; // 10 terms
@@ -484,12 +486,14 @@ public class TestSolrQueryParser extends SolrTestCaseJ4 {
final String too_long = "id:(" + a + a + a + a + a + ")";
final String expectedMsg = "Too many clauses";
- ignoreException(expectedMsg);
- SolrException e =
- expectThrows(
- SolrException.class,
- "expected SolrException",
- () -> assertJQ(req("q", too_long), "/response/numFound==6"));
+ SolrException e;
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(expectedMsg)) {
+ e =
+ expectThrows(
+ SolrException.class,
+ "expected SolrException",
+ () -> assertJQ(req("q", too_long), "/response/numFound==6"));
+ }
assertThat(e.getMessage(), containsString(expectedMsg));
// but should still work as a filter query since TermsQuery can be used...
@@ -499,6 +503,7 @@ public class TestSolrQueryParser extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testManyClauses_Lucene() throws Exception {
final int numZ = IndexSearcher.getMaxClauseCount();
@@ -515,12 +520,14 @@ public class TestSolrQueryParser extends SolrTestCaseJ4 {
final String way_too_long = sb.toString();
final String expectedMsg = "too many boolean clauses";
- ignoreException(expectedMsg);
- SolrException e =
- expectThrows(
- SolrException.class,
- "expected SolrException",
- () -> assertJQ(req("q", way_too_long), "/response/numFound==6"));
+ SolrException e;
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(expectedMsg)) {
+ e =
+ expectThrows(
+ SolrException.class,
+ "expected SolrException",
+ () -> assertJQ(req("q", way_too_long), "/response/numFound==6"));
+ }
assertThat(e.getMessage(), containsString(expectedMsg));
assertNotNull(e.getCause());
diff --git a/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetJoinDomain.java b/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetJoinDomain.java
index 2853d1c7c3f..1d0c4aaccf1 100644
--- a/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetJoinDomain.java
+++ b/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetJoinDomain.java
@@ -45,6 +45,7 @@ import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.IOUtils;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.embedded.JettySolrRunner;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
@@ -198,32 +199,32 @@ public class TestCloudJSONFacetJoinDomain extends SolrCloudTestCase {
}
/** Sanity check that malformed requests produce errors */
+ @SuppressWarnings("try")
public void testMalformedGivesError() {
-
- ignoreException(".*'join' domain change.*");
-
- for (String join :
- Arrays.asList(
- "bogus",
- "{ }",
- "{ from:null, to:foo_s }",
- "{ from:foo_s }",
- "{ from:foo_s, to:foo_s, bogus:'what what?' }",
- "{ to:foo_s, bogus:'what what?' }")) {
- SolrException e =
- expectThrows(
- SolrException.class,
- () -> {
- final SolrParams req =
- params(
- "q",
- "*:*",
- "json.facet",
- "{ x : { type:terms, field:x_s, domain: { join:" + join + " } } }");
- getRandClient(random()).request(new QueryRequest(req));
- });
- assertEquals(join + " -> " + e, SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertTrue(join + " -> " + e, e.getMessage().contains("'join' domain change"));
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(".*'join' domain change.*")) {
+ for (String join :
+ Arrays.asList(
+ "bogus",
+ "{ }",
+ "{ from:null, to:foo_s }",
+ "{ from:foo_s }",
+ "{ from:foo_s, to:foo_s, bogus:'what what?' }",
+ "{ to:foo_s, bogus:'what what?' }")) {
+ SolrException e =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ final SolrParams req =
+ params(
+ "q",
+ "*:*",
+ "json.facet",
+ "{ x : { type:terms, field:x_s, domain: { join:" + join + " } } }");
+ getRandClient(random()).request(new QueryRequest(req));
+ });
+ assertEquals(join + " -> " + e, SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertTrue(join + " -> " + e, e.getMessage().contains("'join' domain change"));
+ }
}
}
diff --git a/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetErrors.java b/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetErrors.java
index ddbcdb23562..891ddd21d21 100644
--- a/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetErrors.java
+++ b/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetErrors.java
@@ -23,6 +23,7 @@ import org.apache.solr.JSONTestUtil;
import org.apache.solr.SolrTestCaseHS;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.SolrParams;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -577,52 +578,51 @@ public class TestJsonFacetErrors extends SolrTestCaseHS {
}
@Test
+ @SuppressWarnings("try")
public void testAggErrors() {
- ignoreException("aggregation");
-
- SolrException e =
- expectThrows(
- SolrException.class,
- () -> {
- h.query(req("q", "*:*", "json.facet", "{bleh:'div(2,4)'}"));
- });
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertThat(
- e.getMessage(),
- containsString(
- "Expected multi-doc aggregation from 'div' but got per-doc function in input ('div(2,4)"));
-
- e =
- expectThrows(
- SolrException.class,
- () -> {
- h.query(req("q", "*:*", "json.facet", "{b:'agg(div(2,4))'}"));
- });
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertThat(
- e.getMessage(),
- containsString(
- "Expected multi-doc aggregation from 'div' but got per-doc function in input ('agg(div(2,4))"));
-
- e =
- expectThrows(
- SolrException.class,
- () -> {
- h.query(req("q", "*:*", "json.facet", "{b:'agg(bleh(2,4))'}"));
- });
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertThat(
- e.getMessage(), containsString("Unknown aggregation 'bleh' in input ('agg(bleh(2,4))"));
-
- e =
- expectThrows(
- SolrException.class,
- () -> {
- h.query(req("q", "*:*", "json.facet", "{b:'bleh(2,4)'}"));
- });
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
- assertThat(e.getMessage(), containsString("Unknown aggregation 'bleh' in input ('bleh(2,4)"));
-
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("aggregation")) {
+ SolrException e =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ h.query(req("q", "*:*", "json.facet", "{bleh:'div(2,4)'}"));
+ });
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertThat(
+ e.getMessage(),
+ containsString(
+ "Expected multi-doc aggregation from 'div' but got per-doc function in input ('div(2,4)"));
+
+ e =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ h.query(req("q", "*:*", "json.facet", "{b:'agg(div(2,4))'}"));
+ });
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertThat(
+ e.getMessage(),
+ containsString(
+ "Expected multi-doc aggregation from 'div' but got per-doc function in input ('agg(div(2,4))"));
+
+ e =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ h.query(req("q", "*:*", "json.facet", "{b:'agg(bleh(2,4))'}"));
+ });
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertThat(
+ e.getMessage(), containsString("Unknown aggregation 'bleh' in input ('agg(bleh(2,4))"));
+
+ e =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ h.query(req("q", "*:*", "json.facet", "{b:'bleh(2,4)'}"));
+ });
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
+ assertThat(e.getMessage(), containsString("Unknown aggregation 'bleh' in input ('bleh(2,4)"));
+ }
}
}
diff --git a/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacets.java b/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacets.java
index ee6bd9b3543..7a6d7954c07 100644
--- a/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacets.java
+++ b/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacets.java
@@ -39,6 +39,7 @@ import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.macro.MacroExpander;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.hll.HLL;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -447,6 +448,7 @@ public class TestJsonFacets extends SolrTestCaseHS {
}
@Test
+ @SuppressWarnings("try")
public void testExplicitQueryDomain() throws Exception {
Client client = Client.localClient();
indexSimple(client);
@@ -528,24 +530,26 @@ public class TestJsonFacets extends SolrTestCaseHS {
}
{ // an (effectively) empty query should produce an error
- ignoreException("'query' domain can not be null");
- ignoreException("'query' domain must not evaluate to an empty list");
- for (String raw : Arrays.asList("null", "[ ]", "{param:bogus}")) {
- expectThrows(
- SolrException.class,
- () -> {
- assertJQ(
- req(
- "rows",
- "0",
- "q",
- "num_i:[0 TO *]",
- "json.facet",
- "{w: {type:terms, field:'where_s', "
- + " facet: { c: { type:terms, field:'cat_s', domain: { query: "
- + raw
- + " }}}}}"));
- });
+ try (ErrorLogMuter queryDomainNull = ErrorLogMuter.regex("'query' domain can not be null");
+ ErrorLogMuter queryDomainEmpty =
+ ErrorLogMuter.regex("'query' domain must not evaluate to an empty list")) {
+ for (String raw : Arrays.asList("null", "[ ]", "{param:bogus}")) {
+ expectThrows(
+ SolrException.class,
+ () -> {
+ assertJQ(
+ req(
+ "rows",
+ "0",
+ "q",
+ "num_i:[0 TO *]",
+ "json.facet",
+ "{w: {type:terms, field:'where_s', "
+ + " facet: { c: { type:terms, field:'cat_s', domain: { query: "
+ + raw
+ + " }}}}}"));
+ });
+ }
}
}
}
diff --git a/solr/core/src/test/org/apache/solr/search/join/ShardToShardJoinAbstract.java b/solr/core/src/test/org/apache/solr/search/join/ShardToShardJoinAbstract.java
index 682c19dbf3f..6e5596f2b30 100644
--- a/solr/core/src/test/org/apache/solr/search/join/ShardToShardJoinAbstract.java
+++ b/solr/core/src/test/org/apache/solr/search/join/ShardToShardJoinAbstract.java
@@ -59,7 +59,6 @@ public abstract class ShardToShardJoinAbstract extends SolrCloudTestCase {
private static final String[] scoreModes = {"avg", "max", "min", "total"};
- // resetExceptionIgnores();
protected static String toColl = "parent";
protected static String fromColl = "children";
diff --git a/solr/core/src/test/org/apache/solr/search/json/TestJsonRequest.java b/solr/core/src/test/org/apache/solr/search/json/TestJsonRequest.java
index 628dd73766c..2264752251a 100644
--- a/solr/core/src/test/org/apache/solr/search/json/TestJsonRequest.java
+++ b/solr/core/src/test/org/apache/solr/search/json/TestJsonRequest.java
@@ -30,6 +30,7 @@ import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.search.CaffeineCache;
import org.apache.solr.search.DocSet;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -89,17 +90,18 @@ public class TestJsonRequest extends SolrTestCaseHS {
doJsonRequest(client, true);
}
+ @SuppressWarnings("try")
public static void doJsonRequest(Client client, boolean isDistrib) throws Exception {
addDocs(client);
- ignoreException("Expected JSON");
-
// test json param
client.testJQ(params("json", "{query:'cat_s:A'}"), "response/numFound==2");
// invalid value
- SolrException ex =
- expectThrows(SolrException.class, () -> client.testJQ(params("q", "*:*", "json", "5")));
+ SolrException ex;
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Expected JSON")) {
+ ex = expectThrows(SolrException.class, () -> client.testJQ(params("q", "*:*", "json", "5")));
+ }
assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
assertThat(ex.getMessage(), containsString("Expected JSON Object but got Long=5"));
@@ -559,8 +561,6 @@ public class TestJsonRequest extends SolrTestCaseHS {
"response/numFound==2");
});
assertThat(e.getMessage(), containsString("foobar"));
-
- resetExceptionIgnores();
}
private static void doParamRefDslTest(Client client) throws Exception {
diff --git a/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java b/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java
index 725e19a794f..725f4cfcd0f 100644
--- a/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java
+++ b/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java
@@ -38,6 +38,7 @@ import org.apache.solr.index.TieredMergePolicyFactory;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryRequestBase;
import org.apache.solr.search.SolrIndexSearcher;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.LogLevel;
import org.apache.solr.util.SolrMetricTestUtils;
import org.junit.Before;
@@ -69,6 +70,7 @@ public class DirectUpdateHandlerTest extends SolrTestCaseJ4 {
}
@Test
+ @SuppressWarnings("try")
public void testRequireUniqueKey() {
// Add a valid document
assertU(adoc("id", "1"));
@@ -77,9 +79,9 @@ public class DirectUpdateHandlerTest extends SolrTestCaseJ4 {
assertFailedU(adoc("id", "2", "id", "ignore_exception", "text", "foo"));
// No id should fail
- ignoreException("id");
- assertFailedU(adoc("text", "foo"));
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("id")) {
+ assertFailedU(adoc("text", "foo"));
+ }
}
@Test
diff --git a/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.java b/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.java
index aeb41353204..b3d532f3b33 100644
--- a/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.java
+++ b/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.java
@@ -54,6 +54,7 @@ import org.apache.solr.update.SolrCmdDistributor.StdNode;
import org.apache.solr.update.processor.DistributedUpdateProcessor;
import org.apache.solr.update.processor.DistributedUpdateProcessor.LeaderRequestReplicationTracker;
import org.apache.solr.update.processor.DistributedUpdateProcessor.RollupRequestReplicationTracker;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.TestInjection;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -674,13 +675,14 @@ public class SolrCmdDistributorTest extends BaseDistributedSearchTestCase {
}
}
+ @SuppressWarnings("try")
private void testNodeWontRetryBadRequest(NodeType nodeType) throws Exception {
- ignoreException("Bad Request");
final var solrclient = clients.getFirst();
long numFoundBefore = solrclient.query(new SolrQuery("*:*")).getResults().getNumFound();
final MockStreamingSolrClients streamingClients =
new MockStreamingSolrClients(updateShardHandler);
- try (SolrCmdDistributor cmdDistrib = new SolrCmdDistributor(streamingClients, 0)) {
+ try (SolrCmdDistributor cmdDistrib = new SolrCmdDistributor(streamingClients, 0);
+ ErrorLogMuter ignored = ErrorLogMuter.regex("Bad Request")) {
streamingClients.setExp(Exp.BAD_REQUEST);
ArrayList<Node> nodes = new ArrayList<>();
ZkNodeProps nodeProps =
@@ -732,7 +734,6 @@ public class SolrCmdDistributorTest extends BaseDistributedSearchTestCase {
// we will get java.net.SocketException: Network is unreachable, which we don't retry on
assertEquals(numFoundBefore, numFoundAfter);
assertEquals(1, cmdDistrib.getErrors().size());
- unIgnoreException("Bad Request");
}
}
diff --git a/solr/core/src/test/org/apache/solr/update/TestAtomicUpdateErrorCases.java b/solr/core/src/test/org/apache/solr/update/TestAtomicUpdateErrorCases.java
index a92220171d8..b808744baf2 100644
--- a/solr/core/src/test/org/apache/solr/update/TestAtomicUpdateErrorCases.java
+++ b/solr/core/src/test/org/apache/solr/update/TestAtomicUpdateErrorCases.java
@@ -18,9 +18,11 @@ package org.apache.solr.update;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException;
+import org.apache.solr.util.ErrorLogMuter;
public class TestAtomicUpdateErrorCases extends SolrTestCaseJ4 {
+ @SuppressWarnings("try")
public void testUpdateNoTLog() throws Exception {
try {
System.setProperty("solr.index.updatelog.enabled", "false");
@@ -39,19 +41,21 @@ public class TestAtomicUpdateErrorCases extends SolrTestCaseJ4 {
assertU(commit());
// updating docs should fail
- ignoreException("updateLog");
- SolrException ex =
- expectThrows(
- SolrException.class,
- () -> addAndGetVersion(sdoc("id", "1", "val_i", map("inc", -666)), null));
+ SolrException ex;
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("updateLog")) {
+ ex =
+ expectThrows(
+ SolrException.class,
+ () -> addAndGetVersion(sdoc("id", "1", "val_i", map("inc", -666)), null));
+ }
assertEquals(400, ex.code());
assertTrue(ex.getMessage().contains("unless <updateLog/> is configured"));
- resetExceptionIgnores();
} finally {
deleteCore();
}
}
+ @SuppressWarnings("try")
public void testUpdateNoDistribProcessor() throws Exception {
try {
initCore("solrconfig-tlog.xml", "schema15.xml");
@@ -64,19 +68,20 @@ public class TestAtomicUpdateErrorCases extends SolrTestCaseJ4 {
addAndGetVersion(sdoc("id", "1", "val_i", "42"), params("update.chain", "nodistrib"));
assertU(commit());
- ignoreException("DistributedUpdateProcessorFactory");
// updating docs should fail
- SolrException ex =
- expectThrows(
- SolrException.class,
- () -> {
- addAndGetVersion(
- sdoc("id", "1", "val_i", map("inc", -666)),
- params("update.chain", "nodistrib"));
- });
+ SolrException ex;
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("DistributedUpdateProcessorFactory")) {
+ ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ addAndGetVersion(
+ sdoc("id", "1", "val_i", map("inc", -666)),
+ params("update.chain", "nodistrib"));
+ });
+ }
assertEquals(400, ex.code());
assertTrue(ex.getMessage().contains("DistributedUpdateProcessorFactory"));
- resetExceptionIgnores();
} finally {
deleteCore();
}
diff --git a/solr/core/src/test/org/apache/solr/update/TestUpdate.java b/solr/core/src/test/org/apache/solr/update/TestUpdate.java
index 576fbcee26a..1842b74575e 100644
--- a/solr/core/src/test/org/apache/solr/update/TestUpdate.java
+++ b/solr/core/src/test/org/apache/solr/update/TestUpdate.java
@@ -20,6 +20,7 @@ import java.util.concurrent.Callable;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -45,6 +46,7 @@ public class TestUpdate extends SolrTestCaseJ4 {
});
}
+ @SuppressWarnings("try")
public void doUpdateTest(Callable<Void> afterUpdate) throws Exception {
clearIndex();
afterUpdate.call();
@@ -233,14 +235,14 @@ public class TestUpdate extends SolrTestCaseJ4 {
"=={'doc':{'id':'1', 'val_i':5, 'val2_i':-2000000004, 'val2_d':-1.2345678901e+100, 'val2_l':4999999996}}");
// test that updating a unique id results in failure.
- ignoreException("Invalid update of id field");
- se =
- expectThrows(
- SolrException.class,
- () ->
- addAndGetVersion(
- sdoc("id", map("set", "1"), "val_is", map("inc", "2000000000")), null));
- resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Invalid update of id field")) {
+ se =
+ expectThrows(
+ SolrException.class,
+ () ->
+ addAndGetVersion(
+ sdoc("id", map("set", "1"), "val_is", map("inc", "2000000000")), null));
+ }
assertEquals(400, se.code());
assertTrue(
se.getMessage().contains("Updating unique key, version or route field is not allowed"));
diff --git a/solr/core/src/test/org/apache/solr/update/processor/FieldMutatingUpdateProcessorTest.java b/solr/core/src/test/org/apache/solr/update/processor/FieldMutatingUpdateProcessorTest.java
index bca3918786f..d2f4a2fb435 100644
--- a/solr/core/src/test/org/apache/solr/update/processor/FieldMutatingUpdateProcessorTest.java
+++ b/solr/core/src/test/org/apache/solr/update/processor/FieldMutatingUpdateProcessorTest.java
@@ -23,6 +23,7 @@ import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrInputField;
import org.apache.solr.schema.IndexSchema;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.BeforeClass;
/**
@@ -503,6 +504,7 @@ public class FieldMutatingUpdateProcessorTest extends UpdateProcessorTestBase {
assertEquals("last", d.getFieldValue("foo_s"));
}
+ @SuppressWarnings("try")
public void testMinValue() throws Exception {
SolrInputDocument d = null;
@@ -526,8 +528,7 @@ public class FieldMutatingUpdateProcessorTest extends UpdateProcessorTestBase {
// failure when un-comparable
SolrException error = null;
- try {
- ignoreException(".*Unable to mutate field.*");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(".*Unable to mutate field.*")) {
d =
processAdd(
"min-value",
@@ -538,13 +539,12 @@ public class FieldMutatingUpdateProcessorTest extends UpdateProcessorTestBase {
f("yak_t", "aaa", "bbb")));
} catch (SolrException e) {
error = e;
- } finally {
- resetExceptionIgnores();
}
assertNotNull("no error on un-comparable values", error);
assertTrue("error doesn't mention field name", error.getMessage().contains("foo_s"));
}
+ @SuppressWarnings("try")
public void testMaxValue() throws Exception {
SolrInputDocument d = null;
@@ -568,8 +568,7 @@ public class FieldMutatingUpdateProcessorTest extends UpdateProcessorTestBase {
// failure when un-comparable
SolrException error = null;
- try {
- ignoreException(".*Unable to mutate field.*");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(".*Unable to mutate field.*")) {
d =
processAdd(
"min-value",
@@ -580,8 +579,6 @@ public class FieldMutatingUpdateProcessorTest extends UpdateProcessorTestBase {
f("yak_t", "aaa", "bbb")));
} catch (SolrException e) {
error = e;
- } finally {
- resetExceptionIgnores();
}
assertNotNull("no error on un-comparable values", error);
assertTrue("error doesn't mention field name", error.getMessage().contains("foo_s"));
diff --git a/solr/core/src/test/org/apache/solr/update/processor/TestDocBasedVersionConstraints.java b/solr/core/src/test/org/apache/solr/update/processor/TestDocBasedVersionConstraints.java
index 875176a09df..5b69ae0d37c 100644
--- a/solr/core/src/test/org/apache/solr/update/processor/TestDocBasedVersionConstraints.java
+++ b/solr/core/src/test/org/apache/solr/update/processor/TestDocBasedVersionConstraints.java
@@ -36,6 +36,7 @@ import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SolrNamedThreadFactory;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -401,6 +402,7 @@ public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
assertJQ(req("q", "+id:aaa +name:Y2"), "/response/numFound==1");
}
+ @SuppressWarnings("try")
public void testMultipleVersionDeletes() throws Exception {
updateJ(
jsonAdd(sdoc("id", "aaa", "name", "a1", "my_version_l", "1001", "my_version_f", "1.0")),
@@ -440,18 +442,22 @@ public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
assertEquals(409, ex.code());
// And just verify if we pass version 1, we still error if version 2 isn't found.
- ignoreException("Delete by ID must specify doc version param");
- ex =
- expectThrows(
- SolrException.class,
- () -> {
- deleteAndGetVersion(
- "aaa",
- params(
- "del_version", "1001", "update.chain", "external-version-failhard-multiple"));
- });
- assertEquals(400, ex.code());
- unIgnoreException("Delete by ID must specify doc version param");
+ try (ErrorLogMuter ignored =
+ ErrorLogMuter.regex("Delete by ID must specify doc version param")) {
+ ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ deleteAndGetVersion(
+ "aaa",
+ params(
+ "del_version",
+ "1001",
+ "update.chain",
+ "external-version-failhard-multiple"));
+ });
+ assertEquals(400, ex.code());
+ }
// Verify we are still unchanged
assertU(commit());
@@ -604,6 +610,7 @@ public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
}
}
+ @SuppressWarnings("try")
public void testMissingVersionOnOldDocs() throws Exception {
String version = "2";
@@ -625,17 +632,21 @@ public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
json("[{\"id\": \"a\", \"name\": \"a1\", \"my_version_l\": " + newVersion + "}]"),
params("update.chain", "external-version-constraint"));
- ignoreException("Doc exists in index, but has null versionField: my_version_l");
- SolrException ex =
- expectThrows(
- SolrException.class,
- () -> {
- updateJ(
- json("[{\"id\": \"b\", \"name\": \"b1\", \"my_version_l\": " + newVersion + "}]"),
- params("update.chain", "external-version-constraint"));
- });
- assertEquals("Doc exists in index, but has null versionField: my_version_l", ex.getMessage());
- unIgnoreException("Doc exists in index, but has null versionField: my_version_l");
+ try (ErrorLogMuter ignored =
+ ErrorLogMuter.regex("Doc exists in index, but has null versionField: my_version_l")) {
+ SolrException ex =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ updateJ(
+ json(
+ "[{\"id\": \"b\", \"name\": \"b1\", \"my_version_l\": "
+ + newVersion
+ + "}]"),
+ params("update.chain", "external-version-constraint"));
+ });
+ assertEquals("Doc exists in index, but has null versionField: my_version_l", ex.getMessage());
+ }
assertU(commit());
assertJQ(req("q", "*:*"), "/response/numFound==2");
diff --git a/solr/core/src/test/org/apache/solr/update/processor/TolerantUpdateProcessorTest.java b/solr/core/src/test/org/apache/solr/update/processor/TolerantUpdateProcessorTest.java
index bdeb67d6598..421f2885881 100644
--- a/solr/core/src/test/org/apache/solr/update/processor/TolerantUpdateProcessorTest.java
+++ b/solr/core/src/test/org/apache/solr/update/processor/TolerantUpdateProcessorTest.java
@@ -44,6 +44,7 @@ import org.apache.solr.request.SolrQueryRequestBase;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.util.BaseTestHarness;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -59,6 +60,9 @@ public class TolerantUpdateProcessorTest extends UpdateProcessorTestBase {
/** IDs of the invalid documents in <code>docs</code> */
private static String[] badIds = null;
+ private ErrorLogMuter errorAddingFieldMuter;
+ private ErrorLogMuter missingUniqueKeyMuter;
+
@BeforeClass
public static void beforeClass() throws Exception {
initCore("solrconfig-update-processor-chains.xml", "schema12.xml");
@@ -75,8 +79,8 @@ public class TolerantUpdateProcessorTest extends UpdateProcessorTestBase {
public void setUp() throws Exception {
super.setUp();
// expected exception messages
- ignoreException("Error adding field");
- ignoreException("Document is missing mandatory uniqueKey field");
+ errorAddingFieldMuter = ErrorLogMuter.regex("Error adding field");
+ missingUniqueKeyMuter = ErrorLogMuter.regex("Document is missing mandatory uniqueKey field");
if (docs == null) {
docs = new ArrayList<>(20);
badIds = new String[10];
@@ -92,7 +96,8 @@ public class TolerantUpdateProcessorTest extends UpdateProcessorTestBase {
@Override
public void tearDown() throws Exception {
- resetExceptionIgnores();
+ errorAddingFieldMuter.close();
+ missingUniqueKeyMuter.close();
assertU(delQ("*:*"));
assertU(commit());
assertQ(req("q", "*:*"), "//result[@numFound='0']");
@@ -276,52 +281,56 @@ public class TolerantUpdateProcessorTest extends UpdateProcessorTestBase {
}
@Test
+ @SuppressWarnings("try")
public void testInvalidDelete() throws XPathExpressionException, SAXException {
- ignoreException("undefined field invalidfield");
- String response =
- update("tolerant-chain-max-errors-10", adoc("id", "1", "text", "the quick brown fox"));
- assertNull(
- BaseTestHarness.validateXPath(
- response,
- "//int[@name='status']=0",
- "//arr[@name='errors']",
- "count(//arr[@name='errors']/lst)=0"));
-
- response = update("tolerant-chain-max-errors-10", delQ("invalidfield:1"));
- assertNull(
- BaseTestHarness.validateXPath(
- response,
- "//int[@name='status']=0",
- "count(//arr[@name='errors']/lst)=1",
- "//arr[@name='errors']/lst/str[@name='type']/text()='DELQ'",
- "//arr[@name='errors']/lst/str[@name='id']/text()='invalidfield:1'",
- "//arr[@name='errors']/lst/str[@name='message']/text()='undefined field invalidfield'"));
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("undefined field invalidfield")) {
+ String response =
+ update("tolerant-chain-max-errors-10", adoc("id", "1", "text", "the quick brown fox"));
+ assertNull(
+ BaseTestHarness.validateXPath(
+ response,
+ "//int[@name='status']=0",
+ "//arr[@name='errors']",
+ "count(//arr[@name='errors']/lst)=0"));
+
+ response = update("tolerant-chain-max-errors-10", delQ("invalidfield:1"));
+ assertNull(
+ BaseTestHarness.validateXPath(
+ response,
+ "//int[@name='status']=0",
+ "count(//arr[@name='errors']/lst)=1",
+ "//arr[@name='errors']/lst/str[@name='type']/text()='DELQ'",
+ "//arr[@name='errors']/lst/str[@name='id']/text()='invalidfield:1'",
+ "//arr[@name='errors']/lst/str[@name='message']/text()='undefined field invalidfield'"));
+ }
}
@Test
+ @SuppressWarnings("try")
public void testValidDelete() throws XPathExpressionException, SAXException {
- ignoreException("undefined field invalidfield");
- String response =
- update("tolerant-chain-max-errors-10", adoc("id", "1", "text", "the quick brown fox"));
- assertNull(
- BaseTestHarness.validateXPath(
- response,
- "//int[@name='status']=0",
- "//arr[@name='errors']",
- "count(//arr[@name='errors']/lst)=0"));
-
- assertU(commit());
- assertQ(req("q", "*:*"), "//result[@numFound='1']");
-
- response = update("tolerant-chain-max-errors-10", delQ("id:1"));
- assertNull(
- BaseTestHarness.validateXPath(
- response,
- "//int[@name='status']=0",
- "//arr[@name='errors']",
- "count(//arr[@name='errors']/lst)=0"));
- assertU(commit());
- assertQ(req("q", "*:*"), "//result[@numFound='0']");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("undefined field invalidfield")) {
+ String response =
+ update("tolerant-chain-max-errors-10", adoc("id", "1", "text", "the quick brown fox"));
+ assertNull(
+ BaseTestHarness.validateXPath(
+ response,
+ "//int[@name='status']=0",
+ "//arr[@name='errors']",
+ "count(//arr[@name='errors']/lst)=0"));
+
+ assertU(commit());
+ assertQ(req("q", "*:*"), "//result[@numFound='1']");
+
+ response = update("tolerant-chain-max-errors-10", delQ("id:1"));
+ assertNull(
+ BaseTestHarness.validateXPath(
+ response,
+ "//int[@name='status']=0",
+ "//arr[@name='errors']",
+ "count(//arr[@name='errors']/lst)=0"));
+ assertU(commit());
+ assertQ(req("q", "*:*"), "//result[@numFound='0']");
+ }
}
@Test
diff --git a/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/ExtractingRequestHandlerTestAbstract.java b/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/ExtractingRequestHandlerTestAbstract.java
index 805ed278625..a0bd9b4d77a 100644
--- a/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/ExtractingRequestHandlerTestAbstract.java
+++ b/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/ExtractingRequestHandlerTestAbstract.java
@@ -29,6 +29,7 @@ import org.apache.solr.request.SolrQueryRequestBase;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.processor.BufferingRequestProcessor;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -313,14 +314,15 @@ public abstract class ExtractingRequestHandlerTestAbstract extends SolrTestCaseJ
}
@Test
+ @SuppressWarnings("try")
public void testDefaultField() throws Exception {
ExtractingRequestHandler handler =
(ExtractingRequestHandler) h.getCore().getRequestHandler("/update/extract");
assertNotNull("handler is null and it shouldn't be", handler);
- try {
- ignoreException("unknown field 'a'");
- ignoreException("unknown field 'meta'"); // TODO: should this exception be happening?
+ // TODO: should the "unknown field 'meta'" exception be happening?
+ try (ErrorLogMuter unknownFieldA = ErrorLogMuter.regex("unknown field 'a'");
+ ErrorLogMuter unknownFieldMeta = ErrorLogMuter.regex("unknown field 'meta'")) {
expectThrows(
SolrException.class,
() ->
@@ -336,8 +338,6 @@ public abstract class ExtractingRequestHandlerTestAbstract extends SolrTestCaseJ
"commit",
"true" // test immediate commit
));
- } finally {
- resetExceptionIgnores();
}
loadLocal(
diff --git a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.java b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.java
index 81351e5b4a9..6b45f5eff86 100644
--- a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.java
+++ b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.java
@@ -22,6 +22,7 @@ import java.util.regex.Pattern;
import javax.script.ScriptEngineManager;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.core.CoreContainer;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.Assume;
public class TestBadScriptingUpdateProcessorConfig extends SolrTestCaseJ4 {
@@ -62,6 +63,7 @@ public class TestBadScriptingUpdateProcessorConfig extends SolrTestCaseJ4 {
* errString, asserts that initializing a core with these files causes an error matching the
* specified errString ot be thrown.
*/
+ @SuppressWarnings("try")
protected final void assertConfigs(
final String solrconfigFile,
final String schemaFile,
@@ -69,9 +71,7 @@ public class TestBadScriptingUpdateProcessorConfig extends SolrTestCaseJ4 {
final String errString)
throws Exception {
- ignoreException(Pattern.quote(errString));
- try {
-
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(Pattern.quote(errString))) {
if (null == solrHome) {
initCore(solrconfigFile, schemaFile);
} else {
@@ -88,7 +88,6 @@ public class TestBadScriptingUpdateProcessorConfig extends SolrTestCaseJ4 {
throw e;
} finally {
deleteCore();
- resetExceptionIgnores();
}
fail("Did not encounter any exception from: " + solrconfigFile + " using " + schemaFile);
}
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
index c791c7fe7eb..f1314c29b92 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
@@ -84,6 +84,7 @@ import org.apache.solr.common.util.ContentStreamBase;
import org.apache.solr.common.util.EnvUtils;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.Pair;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.ExternalPaths;
import org.apache.solr.util.RTimer;
import org.junit.BeforeClass;
@@ -1551,6 +1552,7 @@ public abstract class SolrExampleTests extends SolrExampleTestsBase {
}
@Test
+ @SuppressWarnings("try")
public void testPivotFacetsStatsNotSupported() throws Exception {
SolrClient client = getSolrClient();
@@ -1573,43 +1575,44 @@ public abstract class SolrExampleTests extends SolrExampleTestsBase {
client.commit();
}
- ignoreException("is not currently supported");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("is not currently supported")) {
- // boolean field
- SolrQuery query = new SolrQuery("*:*");
- query.addFacetPivotField("{!stats=s1}features,manu");
- query.addGetFieldStatistics("{!key=inStock_val tag=s1}inStock");
+ // boolean field
+ SolrQuery query = new SolrQuery("*:*");
+ query.addFacetPivotField("{!stats=s1}features,manu");
+ query.addGetFieldStatistics("{!key=inStock_val tag=s1}inStock");
- SolrException e = expectThrows(SolrException.class, () -> client.query(query));
- assertEquals(
- "Pivot facet on boolean is not currently supported, bad request returned", 400, e.code());
- assertTrue(e.getMessage().contains("is not currently supported"));
- assertTrue(e.getMessage().contains("boolean"));
-
- // asking for multiple stat tags -- see SOLR-6663
- SolrQuery query2 = new SolrQuery("*:*");
- query2.addFacetPivotField("{!stats=tag1,tag2}features,manu");
- query2.addGetFieldStatistics("{!tag=tag1}price", "{!tag=tag2}popularity");
- query2.setFacetMinCount(0);
- query2.setRows(0);
-
- e = expectThrows(SolrException.class, () -> client.query(query2));
- assertEquals(400, e.code());
- assertTrue(e.getMessage().contains("stats"));
- assertTrue(e.getMessage().contains("comma"));
- assertTrue(e.getMessage().contains("tag"));
-
- // text field
- SolrQuery query3 = new SolrQuery("*:*");
- query3.addFacetPivotField("{!stats=s1}features,manu");
- query3.addGetFieldStatistics("{!tag=s1}features");
- query3.setFacetMinCount(0);
- query3.setRows(0);
- e = expectThrows(SolrException.class, () -> client.query(query3));
- assertEquals(
- "Pivot facet on string is not currently supported, bad request returned", 400, e.code());
- assertTrue(e.getMessage().contains("is not currently supported"));
- assertTrue(e.getMessage().contains("text_general"));
+ SolrException e = expectThrows(SolrException.class, () -> client.query(query));
+ assertEquals(
+ "Pivot facet on boolean is not currently supported, bad request returned", 400, e.code());
+ assertTrue(e.getMessage().contains("is not currently supported"));
+ assertTrue(e.getMessage().contains("boolean"));
+
+ // asking for multiple stat tags -- see SOLR-6663
+ SolrQuery query2 = new SolrQuery("*:*");
+ query2.addFacetPivotField("{!stats=tag1,tag2}features,manu");
+ query2.addGetFieldStatistics("{!tag=tag1}price", "{!tag=tag2}popularity");
+ query2.setFacetMinCount(0);
+ query2.setRows(0);
+
+ e = expectThrows(SolrException.class, () -> client.query(query2));
+ assertEquals(400, e.code());
+ assertTrue(e.getMessage().contains("stats"));
+ assertTrue(e.getMessage().contains("comma"));
+ assertTrue(e.getMessage().contains("tag"));
+
+ // text field
+ SolrQuery query3 = new SolrQuery("*:*");
+ query3.addFacetPivotField("{!stats=s1}features,manu");
+ query3.addGetFieldStatistics("{!tag=s1}features");
+ query3.setFacetMinCount(0);
+ query3.setRows(0);
+ e = expectThrows(SolrException.class, () -> client.query(query3));
+ assertEquals(
+ "Pivot facet on string is not currently supported, bad request returned", 400, e.code());
+ assertTrue(e.getMessage().contains("is not currently supported"));
+ assertTrue(e.getMessage().contains("text_general"));
+ }
}
@Test
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/TestSolrProperties.java b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/TestSolrProperties.java
index ba713f3e9bc..0c46c15fc50 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/TestSolrProperties.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/TestSolrProperties.java
@@ -16,7 +16,6 @@
*/
package org.apache.solr.client.solrj.embedded;
-import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest.ACTION;
import org.apache.solr.client.solrj.request.CoreAdminRequest;
@@ -25,12 +24,14 @@ import org.apache.solr.client.solrj.request.SolrQuery;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.CoreAdminResponse;
import org.apache.solr.common.SolrInputDocument;
+import org.apache.solr.util.ErrorLogMuter;
import org.junit.Test;
/** Test properties in configuration files. */
public class TestSolrProperties extends AbstractEmbeddedSolrServerTestCase {
@Test
+ @SuppressWarnings("try")
public void testProperties() throws Exception {
UpdateRequest up = new UpdateRequest();
@@ -49,10 +50,10 @@ public class TestSolrProperties extends AbstractEmbeddedSolrServerTestCase {
up.add(doc);
up.process(getSolrCore0());
- SolrTestCaseJ4.ignoreException("unknown field");
-
// You can't add it to core1
- expectThrows(Exception.class, () -> up.process(getSolrCore1()));
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("unknown field")) {
+ expectThrows(Exception.class, () -> up.process(getSolrCore1()));
+ }
// Add to core1
doc.setField("id", "BBB");
@@ -62,9 +63,9 @@ public class TestSolrProperties extends AbstractEmbeddedSolrServerTestCase {
up.process(getSolrCore1());
// You can't add it to core1
- SolrTestCaseJ4.ignoreException("core0");
- expectThrows(Exception.class, () -> up.process(getSolrCore0()));
- SolrTestCaseJ4.resetExceptionIgnores();
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("core0")) {
+ expectThrows(Exception.class, () -> up.process(getSolrCore0()));
+ }
// now Make sure AAA is in 0 and BBB in 1
SolrQuery q = new SolrQuery();
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientTestBase.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientTestBase.java
index 319d82a1c6a..1b09625c0e3 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientTestBase.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientTestBase.java
@@ -57,6 +57,7 @@ import org.apache.solr.common.util.EnvUtils;
import org.apache.solr.common.util.IOUtils;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.embedded.JettyConfig;
+import org.apache.solr.util.ErrorLogMuter;
import org.apache.solr.util.ExternalPaths;
import org.apache.solr.util.ServletFixtures.DebugServlet;
import org.apache.solr.util.ServletFixtures.RedirectServlet;
@@ -470,15 +471,14 @@ public abstract class HttpSolrClientTestBase extends SolrTestCaseJ4 {
IOUtils.closeQuietly((InputStream) stream);
}
+ @SuppressWarnings("try")
protected void testSetCredentialsExplicitly(HttpSolrClient client) {
QueryRequest r = new QueryRequest(new SolrQuery("quick brown fox"));
- try {
- ignoreException("Error from server");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Error from server")) {
client.request(r);
} catch (Exception e) {
// expected
}
- unIgnoreException("Error from server");
assertTrue(DebugServlet.headers.size() > 0);
String authorizationHeader = DebugServlet.headers.get("authorization");
assertNotNull(
@@ -490,16 +490,15 @@ public abstract class HttpSolrClientTestBase extends SolrTestCaseJ4 {
authorizationHeader);
}
+ @SuppressWarnings("try")
protected void testPerRequestCredentials(HttpSolrClient client) {
QueryRequest r = new QueryRequest(new SolrQuery("quick brown fox"));
r.setBasicAuthCredentials("foo3", "per-request");
- try {
- ignoreException("Error from server");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Error from server")) {
client.request(r);
} catch (Exception e) {
// expected
}
- unIgnoreException("Error from server");
assertTrue(DebugServlet.headers.size() > 0);
String authorizationHeader = DebugServlet.headers.get("authorization");
assertNotNull(
@@ -512,29 +511,27 @@ public abstract class HttpSolrClientTestBase extends SolrTestCaseJ4 {
authorizationHeader);
}
+ @SuppressWarnings("try")
protected void testNoCredentials(HttpSolrClient client) {
QueryRequest r = new QueryRequest(new SolrQuery("quick brown fox"));
- try {
- ignoreException("Error from server");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Error from server")) {
client.request(r);
} catch (Exception e) {
// expected
}
- unIgnoreException("Error from server");
assertFalse(
"Expecting no authorization header but got: " + DebugServlet.headers,
DebugServlet.headers.containsKey("authorization"));
}
+ @SuppressWarnings("try")
protected void testUseOptionalCredentials(HttpSolrClient client) {
QueryRequest r = new QueryRequest(new SolrQuery("quick brown fox"));
- try {
- ignoreException("Error from server");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Error from server")) {
client.request(r);
} catch (Exception e) {
// expected
}
- unIgnoreException("Error from server");
assertTrue(DebugServlet.headers.size() > 0);
String authorizationHeader = DebugServlet.headers.get("authorization");
assertNotNull(
@@ -546,16 +543,15 @@ public abstract class HttpSolrClientTestBase extends SolrTestCaseJ4 {
authorizationHeader);
}
+ @SuppressWarnings("try")
protected void testUseOptionalCredentialsWithNull(HttpSolrClient client) {
// username foo, password with embedded colon separator is "expli:cit".
QueryRequest r = new QueryRequest(new SolrQuery("quick brown fox"));
- try {
- ignoreException("Error from server");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex("Error from server")) {
client.request(r);
} catch (Exception e) {
// expected
}
- unIgnoreException("Error from server");
assertTrue(DebugServlet.headers.size() > 0);
String authorizationHeader = DebugServlet.headers.get("authorization");
assertNull(
diff --git a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java
index 2cc6ea7ce5a..895ce0e529c 100644
--- a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java
+++ b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java
@@ -267,7 +267,6 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {
public void distribSetUp() throws Exception {
distribSetUpCalled = true;
- SolrTestCaseJ4.resetExceptionIgnores(); // ignore anything with ignore_exception in it
testDir = createTempDir();
}
diff --git a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java
index b3c50f8e151..3ea838e7754 100644
--- a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java
+++ b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java
@@ -62,7 +62,6 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
@@ -97,7 +96,6 @@ import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.params.UpdateParams;
import org.apache.solr.common.util.ContentStreamBase;
import org.apache.solr.common.util.ExecutorUtil;
-import org.apache.solr.common.util.IOUtils;
import org.apache.solr.common.util.RetryUtil;
import org.apache.solr.common.util.SolrNamedThreadFactory;
import org.apache.solr.common.util.Utils;
@@ -239,7 +237,11 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {
@BeforeClass
public static void setupTestCases() {
- resetExceptionIgnores();
+ if (ignoreExceptionMuter != null) {
+ // defensive: a previous test class may have failed to tear down cleanly
+ ignoreExceptionMuter.close();
+ ignoreExceptionMuter = null;
+ }
testExecutor =
new ExecutorUtil.MDCAwareThreadPoolExecutor(
@@ -274,7 +276,7 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {
System.setProperty("solr.metrics.otlpExporterInterval", "1000");
startTrackingSearchers();
- ignoreException("ignore_exception");
+ ignoreExceptionMuter = ErrorLogMuter.regex("ignore_exception");
newRandomConfig();
sslConfig = buildSSLConfig();
@@ -303,7 +305,10 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {
testExecutor = null;
}
- resetExceptionIgnores();
+ if (ignoreExceptionMuter != null) {
+ ignoreExceptionMuter.close();
+ ignoreExceptionMuter = null;
+ }
resetFactory();
coreName = DEFAULT_TEST_CORENAME;
@@ -574,51 +579,11 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {
}
}
- private static final Map<String, ErrorLogMuter> errorMuters = new ConcurrentHashMap<>();
-
- /**
- * Causes any ERROR log messages matching with a substring matching the regex pattern to be
- * filtered out by the ROOT logger
- *
- * @see #resetExceptionIgnores
- * @deprecated use a {@link ErrorLogMuter} instead
- */
- @Deprecated
- public static void ignoreException(String pattern) {
- errorMuters.computeIfAbsent(pattern, (pat) -> ErrorLogMuter.regex(pat));
- }
-
/**
- * @see #ignoreException
- * @deprecated use a {@link ErrorLogMuter} instead
+ * Registered by {@link #setupTestCases} / {@link #initCore()}, closed by {@link
+ * #teardownTestCases}.
*/
- @Deprecated
- public static void unIgnoreException(String pattern) {
- errorMuters.computeIfPresent(
- pattern,
- (pat, muter) -> {
- IOUtils.closeQuietly(muter);
- return null;
- });
- }
-
- /**
- * Clears all exception patterns, immediately re-registering {@code "ignore_exception"}. {@link
- * SolrTestCaseJ4} calls this in both {@link BeforeClass} {@link AfterClass} so usually tests
- * don't need to call this.
- *
- * @see #ignoreException
- * @deprecated use a {@link ErrorLogMuter} instead
- */
- @Deprecated
- public static void resetExceptionIgnores() {
- errorMuters.forEach(
- (k, muter) -> {
- IOUtils.closeQuietly(muter);
- errorMuters.remove(k);
- });
- ignoreException("ignore_exception");
- }
+ private static ErrorLogMuter ignoreExceptionMuter;
protected static String getClassName() {
return getTestClass().getName();
@@ -681,7 +646,9 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {
public static void initCore() throws Exception {
log.info("####initCore");
- ignoreException("ignore_exception");
+ if (ignoreExceptionMuter == null) {
+ ignoreExceptionMuter = ErrorLogMuter.regex("ignore_exception");
+ }
String configFile = getSolrConfigFile();
if (configFile != null) {
@@ -1066,32 +1033,28 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {
}
/** Makes sure a query throws a SolrException with the listed response code */
+ @SuppressWarnings("try")
public static void assertQEx(String message, SolrQueryRequest req, int code) {
- try {
- ignoreException(".");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(".")) {
h.query(req);
fail(message);
} catch (SolrException sex) {
assertEquals(code, sex.code());
} catch (Exception e2) {
throw new RuntimeException("Exception during query", e2);
- } finally {
- unIgnoreException(".");
}
}
/** Makes sure a query throws a SolrException with the listed response code */
+ @SuppressWarnings("try")
public static void assertQEx(String message, SolrQueryRequest req, SolrException.ErrorCode code) {
- try {
- ignoreException(".");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(".")) {
h.query(req);
fail(message);
} catch (SolrException e) {
assertEquals(code.code, e.code());
} catch (Exception e2) {
throw new RuntimeException("Exception during query", e2);
- } finally {
- unIgnoreException(".");
}
}
@@ -1104,13 +1067,13 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {
* @param req Solr request
* @param code expected error code for the query
*/
+ @SuppressWarnings("try")
public static void assertQEx(
String failMessage,
String exceptionMessage,
SolrQueryRequest req,
SolrException.ErrorCode code) {
- try {
- ignoreException(".");
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(".")) {
h.query(req);
fail(failMessage);
} catch (SolrException e) {
@@ -1124,8 +1087,6 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {
e.getMessage() != null && e.getMessage().contains(exceptionMessage));
} catch (Exception e2) {
throw new RuntimeException("Exception during query", e2);
- } finally {
- unIgnoreException(".");
}
}
diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java
index 46455bbc093..1d98717c67d 100644
--- a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java
+++ b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java
@@ -281,8 +281,6 @@ public abstract class AbstractFullDistribZkTestBase extends BaseDistributedSearc
if (schema == null) schema = "schema.xml";
zkServer.buildZooKeeper(getCloudSolrConfig(), schema);
- // ignoreException(".*");
-
cloudInit = false;
if (sliceCount > 0) {
@@ -2185,8 +2183,6 @@ public abstract class AbstractFullDistribZkTestBase extends BaseDistributedSearc
closeRestTestHarnesses(); // TODO: close here or later?
} finally {
- resetExceptionIgnores();
-
try {
zkServer.shutdown();
} catch (Exception e) {
diff --git a/solr/test-framework/src/java/org/apache/solr/core/AbstractBadConfigTestBase.java b/solr/test-framework/src/java/org/apache/solr/core/AbstractBadConfigTestBase.java
index a7db8a4667c..b9385491c38 100644
--- a/solr/test-framework/src/java/org/apache/solr/core/AbstractBadConfigTestBase.java
+++ b/solr/test-framework/src/java/org/apache/solr/core/AbstractBadConfigTestBase.java
@@ -20,6 +20,7 @@ import java.nio.file.Path;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.util.ErrorLogMuter;
public abstract class AbstractBadConfigTestBase extends SolrTestCaseJ4 {
@@ -39,6 +40,7 @@ public abstract class AbstractBadConfigTestBase extends SolrTestCaseJ4 {
* errString, asserts that initializing a core with these files causes an error matching the
* specified errString ot be thrown.
*/
+ @SuppressWarnings("try")
protected final void assertConfigs(
final String solrconfigFile,
final String schemaFile,
@@ -46,9 +48,7 @@ public abstract class AbstractBadConfigTestBase extends SolrTestCaseJ4 {
final String errString)
throws Exception {
- ignoreException(Pattern.quote(errString));
- try {
-
+ try (ErrorLogMuter ignored = ErrorLogMuter.regex(Pattern.quote(errString))) {
if (null == solrHome) {
initCore(solrconfigFile, schemaFile);
} else {
@@ -65,7 +65,6 @@ public abstract class AbstractBadConfigTestBase extends SolrTestCaseJ4 {
throw e;
} finally {
deleteCore();
- resetExceptionIgnores();
}
fail("Did not encounter any exception from: " + solrconfigFile + " using " + schemaFile);
}
diff --git a/solr/test-framework/src/test/org/apache/solr/util/TestErrorLogMuter.java b/solr/test-framework/src/test/org/apache/solr/util/TestErrorLogMuter.java
index 452bc7e3d1c..5c7b997ac41 100644
--- a/solr/test-framework/src/test/org/apache/solr/util/TestErrorLogMuter.java
+++ b/solr/test-framework/src/test/org/apache/solr/util/TestErrorLogMuter.java
@@ -102,43 +102,4 @@ public class TestErrorLogMuter extends SolrTestCaseJ4 {
assertEquals(0, rootErrorCheck.getCount());
}
}
-
- @LogLevel("=WARN")
- public void testDeprecatedBaseClassMethods() {
-
- // NOTE: using the same queue for both interceptors (mainly as proof that you can)
- try (LogListener rootWarnCheck = LogListener.warn("");
- LogListener rootErrorCheck = LogListener.error("").setQueue(rootWarnCheck.getQueue())) {
-
- log.error("this matches the default ignore_exception pattern");
- log.error("something matching foo that should make it"); // E1
- assertEquals(1, rootErrorCheck.getCount());
- assertThat(rootErrorCheck.pollMessage(), containsString("should make it"));
- ignoreException("foo");
- log.error("something matching foo that should NOT make it");
- ignoreException("foo");
- ignoreException("ba+r");
- log.error("something matching foo that should still NOT make it");
- log.error("something matching baaaar that should NOT make it");
- log.warn(
- "A warning should be fine even if it matches ignore_exception and foo and bar"); // W1
- assertEquals(1, rootErrorCheck.getCount());
- assertEquals(1, rootWarnCheck.getCount());
- assertThat(rootErrorCheck.pollMessage(), containsString("should be fine"));
- unIgnoreException("foo");
- log.error("another thing matching foo that should make it"); // E2
- assertEquals(2, rootErrorCheck.getCount());
- assertThat(rootErrorCheck.pollMessage(), containsString("another thing"));
- log.error("something matching baaaar that should still NOT make it");
- assertEquals(2, rootErrorCheck.getCount());
- resetExceptionIgnores();
- log.error("this still matches the default ignore_exception pattern");
- log.error("but something matching baaaar should make it now"); // E3
- assertThat(rootErrorCheck.pollMessage(), containsString("should make it now"));
-
- // the root logger must have only gotten the non-muted messages...
- assertEquals(3, rootErrorCheck.getCount());
- assertEquals(1, rootWarnCheck.getCount());
- }
- }
}