SOLR-12555: use expectThrows() to verify the ex thrown in tests

This commit is contained in:
Munendra S N 2019-08-03 13:00:49 +05:30
parent b54f43686a
commit 488c75fb55
89 changed files with 1216 additions and 2269 deletions

View File

@ -16,6 +16,7 @@
*/ */
package org.apache.solr.handler.dataimport; package org.apache.solr.handler.dataimport;
import javax.sql.DataSource;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -33,17 +34,21 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import javax.sql.DataSource;
import org.apache.solr.common.util.SuppressForbidden; import org.apache.solr.common.util.SuppressForbidden;
import org.apache.solr.handler.dataimport.JdbcDataSource.ResultSetIterator; import org.apache.solr.handler.dataimport.JdbcDataSource.ResultSetIterator;
import static org.mockito.Mockito.*;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** /**
* <p> * <p>
* Test for JdbcDataSource * Test for JdbcDataSource
@ -205,11 +210,9 @@ public class TestJdbcDataSource extends AbstractDataImportHandlerTestCase {
SQLException sqlException = new SQLException("fake"); SQLException sqlException = new SQLException("fake");
when(dataSource.getConnection()).thenThrow(sqlException); when(dataSource.getConnection()).thenThrow(sqlException);
try { SQLException ex = expectThrows(SQLException.class,
jdbcDataSource.createConnectionFactory(context, props).call(); () -> jdbcDataSource.createConnectionFactory(context, props).call());
} catch (SQLException ex) { assertSame(sqlException, ex);
assertSame(sqlException, ex);
}
verify(dataSource).getConnection(); verify(dataSource).getConnection();
} }
@ -224,11 +227,10 @@ public class TestJdbcDataSource extends AbstractDataImportHandlerTestCase {
when(dataSource.getConnection()).thenReturn(connection); when(dataSource.getConnection()).thenReturn(connection);
doThrow(sqlException).when(connection).setAutoCommit(false); doThrow(sqlException).when(connection).setAutoCommit(false);
try { DataImportHandlerException ex = expectThrows(DataImportHandlerException.class,
jdbcDataSource.createConnectionFactory(context, props).call(); () -> jdbcDataSource.createConnectionFactory(context, props).call());
} catch (DataImportHandlerException ex) { assertSame(sqlException, ex.getCause());
assertSame(sqlException, ex.getCause());
}
verify(dataSource).getConnection(); verify(dataSource).getConnection();
verify(connection).setAutoCommit(false); verify(connection).setAutoCommit(false);
verify(connection).close(); verify(connection).close();
@ -249,12 +251,9 @@ public class TestJdbcDataSource extends AbstractDataImportHandlerTestCase {
.thenReturn(statement); .thenReturn(statement);
when(statement.execute("query")).thenThrow(sqlException); when(statement.execute("query")).thenThrow(sqlException);
try { DataImportHandlerException ex = expectThrows(DataImportHandlerException.class,
jdbcDataSource.getData("query"); () -> jdbcDataSource.getData("query"));
fail("exception expected"); assertSame(sqlException, ex.getCause());
} catch (DataImportHandlerException ex) {
assertSame(sqlException, ex.getCause());
}
verify(dataSource).getConnection(); verify(dataSource).getConnection();
verify(connection).setAutoCommit(false); verify(connection).setAutoCommit(false);

View File

@ -19,7 +19,6 @@ package org.apache.solr.handler.dataimport;
import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
@ -28,7 +27,6 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import org.apache.solr.common.util.SuppressForbidden; import org.apache.solr.common.util.SuppressForbidden;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -91,36 +89,22 @@ public class TestSimplePropertiesWriter extends AbstractDIHJdbcTestCase {
Date docDate= df.parse((String) props.get("last_index_time")); Date docDate= df.parse((String) props.get("last_index_time"));
int year = currentYearFromDatabase(); int year = currentYearFromDatabase();
Assert.assertTrue("This date: " + errMsgFormat.format(oneSecondAgo) + " should be prior to the document date: " + errMsgFormat.format(docDate), docDate.getTime() - oneSecondAgo.getTime() > 0); assertTrue("This date: " + errMsgFormat.format(oneSecondAgo) + " should be prior to the document date: " + errMsgFormat.format(docDate), docDate.getTime() - oneSecondAgo.getTime() > 0);
Assert.assertTrue("This date: " + errMsgFormat.format(oneSecondAgo) + " should be prior to the entity date: " + errMsgFormat.format(entityDate), entityDate.getTime() - oneSecondAgo.getTime() > 0); assertTrue("This date: " + errMsgFormat.format(oneSecondAgo) + " should be prior to the entity date: " + errMsgFormat.format(entityDate), entityDate.getTime() - oneSecondAgo.getTime() > 0);
assertQ(req("*:*"), "//*[@numFound='1']", "//doc/str[@name=\"ayear_s\"]=\"" + year + "\""); assertQ(req("*:*"), "//*[@numFound='1']", "//doc/str[@name=\"ayear_s\"]=\"" + year + "\"");
} }
} }
private int currentYearFromDatabase() throws Exception { private int currentYearFromDatabase() throws Exception {
Connection conn = null; try (
Statement s = null; Connection conn = newConnection();
ResultSet rs = null; Statement s = conn.createStatement();
try { ResultSet rs = s.executeQuery("select year(current_timestamp) from sysibm.sysdummy1");
conn = newConnection(); ){
s = conn.createStatement();
rs = s.executeQuery("select year(current_timestamp) from sysibm.sysdummy1");
if (rs.next()) { if (rs.next()) {
return rs.getInt(1); return rs.getInt(1);
} }
Assert.fail("We should have gotten a row from the db."); fail("We should have gotten a row from the db.");
} catch (SQLException e) {
throw e;
} finally {
try {
rs.close();
} catch (Exception ex) {}
try {
s.close();
} catch (Exception ex) {}
try {
conn.close();
} catch (Exception ex) {}
} }
return 0; return 0;
} }

View File

@ -16,19 +16,6 @@
*/ */
package org.apache.solr.handler.dataimport; package org.apache.solr.handler.dataimport;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.util.IOUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles;
@ -42,6 +29,19 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Properties; import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.util.IOUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* End-to-end test of SolrEntityProcessor. "Real" test using embedded Solr * End-to-end test of SolrEntityProcessor. "Real" test using embedded Solr
*/ */
@ -196,13 +196,7 @@ public class TestSolrEntityProcessorEndToEnd extends AbstractDataImportHandlerTe
assertQ(req("*:*"), "//result[@numFound='7']"); assertQ(req("*:*"), "//result[@numFound='7']");
assertQ(req("id:1"), "//result[@numFound='1']"); assertQ(req("id:1"), "//result[@numFound='1']");
try { assertQ(req("id:1"), "count(//result/doc/arr[@name='desc'])=0");
assertQ(req("id:1"), "//result/doc/arr[@name='desc']");
fail("The document has a field with name desc");
} catch(Exception e) {
}
} }
/** /**

View File

@ -227,20 +227,20 @@ public class ExtractingRequestHandlerTest extends SolrTestCaseJ4 {
@Test @Test
public void testDefaultField() throws Exception { public void testDefaultField() throws Exception {
ExtractingRequestHandler handler = (ExtractingRequestHandler) h.getCore().getRequestHandler("/update/extract"); ExtractingRequestHandler handler = (ExtractingRequestHandler) h.getCore().getRequestHandler("/update/extract");
assertTrue("handler is null and it shouldn't be", handler != null); assertNotNull("handler is null and it shouldn't be", handler);
try { try {
ignoreException("unknown field 'a'"); ignoreException("unknown field 'a'");
ignoreException("unknown field 'meta'"); // TODO: should this exception be happening? ignoreException("unknown field 'meta'"); // TODO: should this exception be happening?
loadLocal("extraction/simple.html", expectThrows(SolrException.class, () -> {
"literal.id","simple2", loadLocal("extraction/simple.html",
"lowernames", "true", "literal.id", "simple2",
"captureAttr", "true", "lowernames", "true",
//"fmap.content_type", "abcxyz", "captureAttr", "true",
"commit", "true" // test immediate commit //"fmap.content_type", "abcxyz",
); "commit", "true" // test immediate commit
fail("Should throw SolrException"); );
} catch (SolrException e) { });
//do nothing
} finally { } finally {
resetExceptionIgnores(); resetExceptionIgnores();
} }
@ -296,16 +296,17 @@ public class ExtractingRequestHandlerTest extends SolrTestCaseJ4 {
assertQ(req("extractionLiteralMV:two"), "//*[@numFound='1']"); assertQ(req("extractionLiteralMV:two"), "//*[@numFound='1']");
try { try {
// TODO: original author did not specify why an exception should be thrown... how to fix?
loadLocal("extraction/version_control.xml", "fmap.created", "extractedDate", "fmap.producer", "extractedProducer", loadLocal("extraction/version_control.xml", "fmap.created", "extractedDate", "fmap.producer", "extractedProducer",
"fmap.creator", "extractedCreator", "fmap.Keywords", "extractedKeywords", "fmap.creator", "extractedCreator", "fmap.Keywords", "extractedKeywords",
"fmap.Author", "extractedAuthor", "fmap.Author", "extractedAuthor",
"fmap.content", "extractedContent", "fmap.content", "extractedContent",
"literal.id", "two", "literal.id", "two",
"fmap.language", "extractedLanguage", "fmap.language", "extractedLanguage",
"literal.extractionLiteral", "one", "literal.extractionLiteral", "one",
"literal.extractionLiteral", "two", "literal.extractionLiteral", "two",
"fmap.X-Parsed-By", "ignored_parser", "fmap.X-Parsed-By", "ignored_parser",
"fmap.Last-Modified", "extractedDate" "fmap.Last-Modified", "extractedDate"
); );
// TODO: original author did not specify why an exception should be thrown... how to fix? // TODO: original author did not specify why an exception should be thrown... how to fix?
// assertTrue("Exception should have been thrown", false); // assertTrue("Exception should have been thrown", false);
@ -549,12 +550,9 @@ public class ExtractingRequestHandlerTest extends SolrTestCaseJ4 {
h.getCore().getRequestHandler("/update/extract"); h.getCore().getRequestHandler("/update/extract");
assertTrue("handler is null and it shouldn't be", handler != null); assertTrue("handler is null and it shouldn't be", handler != null);
try{ expectThrows(Exception.class, () -> {
loadLocal("extraction/password-is-solrcell.docx", loadLocal("extraction/password-is-solrcell.docx", "literal.id", "one");
"literal.id", "one"); });
fail("TikaException is expected because of trying to extract text from password protected word file without supplying a password.");
}
catch(Exception expected){}
assertU(commit()); assertU(commit());
assertQ(req("*:*"), "//result[@numFound=0]"); assertQ(req("*:*"), "//result[@numFound=0]");
@ -581,25 +579,21 @@ public class ExtractingRequestHandlerTest extends SolrTestCaseJ4 {
ExtractingRequestHandler handler = (ExtractingRequestHandler) h.getCore().getRequestHandler("/update/extract"); ExtractingRequestHandler handler = (ExtractingRequestHandler) h.getCore().getRequestHandler("/update/extract");
assertTrue("handler is null and it shouldn't be", handler != null); assertTrue("handler is null and it shouldn't be", handler != null);
try{ expectThrows(Exception.class, () -> {
// Load plain text specifying another mime type, should fail // Load plain text specifying another mime type, should fail
loadLocal("extraction/version_control.txt", loadLocal("extraction/version_control.txt",
"literal.id", "one", "literal.id", "one",
ExtractingParams.STREAM_TYPE, "application/pdf" ExtractingParams.STREAM_TYPE, "application/pdf"
); );
fail("SolrException is expected because wrong parser specified for the file type"); });
}
catch(Exception expected){}
try{ expectThrows(Exception.class, () -> {
// Load plain text specifying non existing mimetype, should fail // Load plain text specifying non existing mimetype, should fail
loadLocal("extraction/version_control.txt", loadLocal("extraction/version_control.txt",
"literal.id", "one", "literal.id", "one",
ExtractingParams.STREAM_TYPE, "foo/bar" ExtractingParams.STREAM_TYPE, "foo/bar"
); );
fail("SolrException is expected because nonexsisting parser specified"); });
}
catch(Exception expected){}
} }
public void testLiteralsOverride() throws Exception { public void testLiteralsOverride() throws Exception {

View File

@ -51,25 +51,20 @@ public class TestValueFeature extends TestRerankBase {
public void testValueFeatureWithEmptyValue() throws Exception { public void testValueFeatureWithEmptyValue() throws Exception {
final RuntimeException expectedException = final RuntimeException expectedException =
new RuntimeException("mismatch: '0'!='500' @ responseHeader/status"); new RuntimeException("mismatch: '0'!='500' @ responseHeader/status");
try { RuntimeException e = expectThrows(RuntimeException.class, () -> {
loadFeature("c2", ValueFeature.class.getName(), "{\"value\":\"\"}"); loadFeature("c2", ValueFeature.class.getName(), "{\"value\":\"\"}");
fail("testValueFeatureWithEmptyValue failed to throw exception: "+expectedException); });
} catch (RuntimeException actualException) { assertEquals(expectedException.toString(), e.toString());
assertEquals(expectedException.toString(), actualException.toString());
}
} }
@Test @Test
public void testValueFeatureWithWhitespaceValue() throws Exception { public void testValueFeatureWithWhitespaceValue() throws Exception {
final RuntimeException expectedException = final RuntimeException expectedException =
new RuntimeException("mismatch: '0'!='500' @ responseHeader/status"); new RuntimeException("mismatch: '0'!='500' @ responseHeader/status");
try { RuntimeException e = expectThrows(RuntimeException.class, () -> {
loadFeature("c2", ValueFeature.class.getName(), loadFeature("c2", ValueFeature.class.getName(), "{\"value\":\" \"}");
"{\"value\":\" \"}"); });
fail("testValueFeatureWithWhitespaceValue failed to throw exception: "+expectedException); assertEquals(expectedException.toString(), e.toString());
} catch (RuntimeException actualException) {
assertEquals(expectedException.toString(), actualException.toString());
}
} }
@Test @Test

View File

@ -93,18 +93,16 @@ public class TestLinearModel extends TestRerankBase {
public void nullFeatureWeightsTest() { public void nullFeatureWeightsTest() {
final ModelException expectedException = final ModelException expectedException =
new ModelException("Model test2 doesn't contain any weights"); new ModelException("Model test2 doesn't contain any weights");
try {
final List<Feature> features = getFeatures(new String[] final List<Feature> features = getFeatures(new String[]
{"constant1", "constant5"}); {"constant1", "constant5"});
final List<Normalizer> norms = final List<Normalizer> norms =
new ArrayList<Normalizer>( new ArrayList<>(Collections.nCopies(features.size(),IdentityNormalizer.INSTANCE));
Collections.nCopies(features.size(),IdentityNormalizer.INSTANCE)); ModelException ex = expectThrows(ModelException.class, () -> {
createLinearModel("test2", createLinearModel("test2",
features, norms, "test", fstore.getFeatures(), null); features, norms, "test", fstore.getFeatures(), null);
fail("unexpectedly got here instead of catching "+expectedException); });
} catch (ModelException actualException) { assertEquals(expectedException.toString(), ex.toString());
assertEquals(expectedException.toString(), actualException.toString());
}
} }
@Test @Test
@ -112,55 +110,48 @@ public class TestLinearModel extends TestRerankBase {
final SolrException expectedException = final SolrException expectedException =
new SolrException(SolrException.ErrorCode.BAD_REQUEST, new SolrException(SolrException.ErrorCode.BAD_REQUEST,
ModelException.class.getName()+": model 'test3' already exists. Please use a different name"); ModelException.class.getName()+": model 'test3' already exists. Please use a different name");
try {
final List<Feature> features = getFeatures(new String[]
{"constant1", "constant5"});
final List<Normalizer> norms =
new ArrayList<Normalizer>(
Collections.nCopies(features.size(),IdentityNormalizer.INSTANCE));
final Map<String,Object> weights = new HashMap<>();
weights.put("constant1", 1d);
weights.put("constant5", 1d);
Map<String,Object> params = new HashMap<String,Object>(); final List<Feature> features = getFeatures(new String[]
params.put("weights", weights); {"constant1", "constant5"});
final List<Normalizer> norms =
new ArrayList<>(Collections.nCopies(features.size(),IdentityNormalizer.INSTANCE));
final Map<String,Object> weights = new HashMap<>();
weights.put("constant1", 1d);
weights.put("constant5", 1d);
Map<String,Object> params = new HashMap<>();
params.put("weights", weights);
SolrException ex = expectThrows(SolrException.class, () -> {
final LTRScoringModel ltrScoringModel = createLinearModel("test3", final LTRScoringModel ltrScoringModel = createLinearModel("test3",
features, norms, "test", fstore.getFeatures(), features, norms, "test", fstore.getFeatures(), params);
params);
store.addModel(ltrScoringModel); store.addModel(ltrScoringModel);
final LTRScoringModel m = store.getModel("test3"); final LTRScoringModel m = store.getModel("test3");
assertEquals(ltrScoringModel, m); assertEquals(ltrScoringModel, m);
store.addModel(ltrScoringModel); store.addModel(ltrScoringModel);
fail("unexpectedly got here instead of catching "+expectedException); });
} catch (SolrException actualException) { assertEquals(expectedException.toString(), ex.toString());
assertEquals(expectedException.toString(), actualException.toString());
}
} }
@Test @Test
public void duplicateFeatureTest() { public void duplicateFeatureTest() {
final ModelException expectedException = final ModelException expectedException =
new ModelException("duplicated feature constant1 in model test4"); new ModelException("duplicated feature constant1 in model test4");
try { final List<Feature> features = getFeatures(new String[]
final List<Feature> features = getFeatures(new String[] {"constant1", "constant1"});
{"constant1", "constant1"}); final List<Normalizer> norms =
final List<Normalizer> norms = new ArrayList<>(Collections.nCopies(features.size(),IdentityNormalizer.INSTANCE));
new ArrayList<Normalizer>( final Map<String,Object> weights = new HashMap<>();
Collections.nCopies(features.size(),IdentityNormalizer.INSTANCE)); weights.put("constant1", 1d);
final Map<String,Object> weights = new HashMap<>(); weights.put("constant5", 1d);
weights.put("constant1", 1d);
weights.put("constant5", 1d);
Map<String,Object> params = new HashMap<String,Object>(); Map<String,Object> params = new HashMap<>();
params.put("weights", weights); params.put("weights", weights);
ModelException ex = expectThrows(ModelException.class, () -> {
final LTRScoringModel ltrScoringModel = createLinearModel("test4", final LTRScoringModel ltrScoringModel = createLinearModel("test4",
features, norms, "test", fstore.getFeatures(), features, norms, "test", fstore.getFeatures(), params);
params);
store.addModel(ltrScoringModel); store.addModel(ltrScoringModel);
fail("unexpectedly got here instead of catching "+expectedException); });
} catch (ModelException actualException) { assertEquals(expectedException.toString(), ex.toString());
assertEquals(expectedException.toString(), actualException.toString());
}
} }
@ -168,50 +159,44 @@ public class TestLinearModel extends TestRerankBase {
public void missingFeatureWeightTest() { public void missingFeatureWeightTest() {
final ModelException expectedException = final ModelException expectedException =
new ModelException("Model test5 lacks weight(s) for [constant5]"); new ModelException("Model test5 lacks weight(s) for [constant5]");
try { final List<Feature> features = getFeatures(new String[]
final List<Feature> features = getFeatures(new String[] {"constant1", "constant5"});
{"constant1", "constant5"}); final List<Normalizer> norms =
final List<Normalizer> norms = new ArrayList<>(Collections.nCopies(features.size(),IdentityNormalizer.INSTANCE));
new ArrayList<Normalizer>(
Collections.nCopies(features.size(),IdentityNormalizer.INSTANCE));
final Map<String,Object> weights = new HashMap<>();
weights.put("constant1", 1d);
weights.put("constant5missing", 1d);
Map<String,Object> params = new HashMap<String,Object>(); final Map<String,Object> weights = new HashMap<>();
params.put("weights", weights); weights.put("constant1", 1d);
weights.put("constant5missing", 1d);
Map<String,Object> params = new HashMap<>();
params.put("weights", weights);
ModelException ex = expectThrows(ModelException.class, () -> {
createLinearModel("test5", createLinearModel("test5",
features, norms, "test", fstore.getFeatures(), features, norms, "test", fstore.getFeatures(), params);
params); });
fail("unexpectedly got here instead of catching "+expectedException); assertEquals(expectedException.toString(), ex.toString());
} catch (ModelException actualException) {
assertEquals(expectedException.toString(), actualException.toString());
}
} }
@Test @Test
public void emptyFeaturesTest() { public void emptyFeaturesTest() {
final ModelException expectedException = final ModelException expectedException =
new ModelException("no features declared for model test6"); new ModelException("no features declared for model test6");
try { final List<Feature> features = getFeatures(new String[] {});
final List<Feature> features = getFeatures(new String[] {}); final List<Normalizer> norms =
final List<Normalizer> norms = new ArrayList<>(Collections.nCopies(features.size(),IdentityNormalizer.INSTANCE));
new ArrayList<Normalizer>( final Map<String,Object> weights = new HashMap<>();
Collections.nCopies(features.size(),IdentityNormalizer.INSTANCE)); weights.put("constant1", 1d);
final Map<String,Object> weights = new HashMap<>(); weights.put("constant5missing", 1d);
weights.put("constant1", 1d);
weights.put("constant5missing", 1d);
Map<String,Object> params = new HashMap<String,Object>(); Map<String,Object> params = new HashMap<>();
params.put("weights", weights); params.put("weights", weights);
ModelException ex = expectThrows(ModelException.class, () -> {
final LTRScoringModel ltrScoringModel = createLinearModel("test6", final LTRScoringModel ltrScoringModel = createLinearModel("test6",
features, norms, "test", fstore.getFeatures(), features, norms, "test", fstore.getFeatures(),
params); params);
store.addModel(ltrScoringModel); store.addModel(ltrScoringModel);
fail("unexpectedly got here instead of catching "+expectedException); });
} catch (ModelException actualException) { assertEquals(expectedException.toString(), ex.toString());
assertEquals(expectedException.toString(), actualException.toString());
}
} }
} }

View File

@ -16,14 +16,14 @@
*/ */
package org.apache.solr.ltr.model; package org.apache.solr.ltr.model;
import static org.hamcrest.core.StringContains.containsString;
import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.ltr.TestRerankBase; import org.apache.solr.ltr.TestRerankBase;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.core.StringContains.containsString;
public class TestMultipleAdditiveTreesModel extends TestRerankBase { public class TestMultipleAdditiveTreesModel extends TestRerankBase {
@ -123,124 +123,107 @@ public class TestMultipleAdditiveTreesModel extends TestRerankBase {
public void multipleAdditiveTreesTestNoParams() throws Exception { public void multipleAdditiveTreesTestNoParams() throws Exception {
final ModelException expectedException = final ModelException expectedException =
new ModelException("no trees declared for model multipleadditivetreesmodel_no_params"); new ModelException("no trees declared for model multipleadditivetreesmodel_no_params");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("multipleadditivetreesmodel_no_params.json", createModelFromFiles("multipleadditivetreesmodel_no_params.json",
"multipleadditivetreesmodel_features.json"); "multipleadditivetreesmodel_features.json");
fail("multipleAdditiveTreesTestNoParams failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
public void multipleAdditiveTreesTestEmptyParams() throws Exception { public void multipleAdditiveTreesTestEmptyParams() throws Exception {
final ModelException expectedException = final ModelException expectedException =
new ModelException("no trees declared for model multipleadditivetreesmodel_no_trees"); new ModelException("no trees declared for model multipleadditivetreesmodel_no_trees");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("multipleadditivetreesmodel_no_trees.json", createModelFromFiles("multipleadditivetreesmodel_no_trees.json",
"multipleadditivetreesmodel_features.json"); "multipleadditivetreesmodel_features.json");
fail("multipleAdditiveTreesTestEmptyParams failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
public void multipleAdditiveTreesTestNoWeight() throws Exception { public void multipleAdditiveTreesTestNoWeight() throws Exception {
final ModelException expectedException = final ModelException expectedException =
new ModelException("MultipleAdditiveTreesModel tree doesn't contain a weight"); new ModelException("MultipleAdditiveTreesModel tree doesn't contain a weight");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("multipleadditivetreesmodel_no_weight.json", createModelFromFiles("multipleadditivetreesmodel_no_weight.json",
"multipleadditivetreesmodel_features.json"); "multipleadditivetreesmodel_features.json");
fail("multipleAdditiveTreesTestNoWeight failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
public void multipleAdditiveTreesTestTreesParamDoesNotContatinTree() throws Exception { public void multipleAdditiveTreesTestTreesParamDoesNotContatinTree() throws Exception {
final ModelException expectedException = final ModelException expectedException =
new ModelException("MultipleAdditiveTreesModel tree doesn't contain a tree"); new ModelException("MultipleAdditiveTreesModel tree doesn't contain a tree");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("multipleadditivetreesmodel_no_tree.json", createModelFromFiles("multipleadditivetreesmodel_no_tree.json",
"multipleadditivetreesmodel_features.json"); "multipleadditivetreesmodel_features.json");
fail("multipleAdditiveTreesTestTreesParamDoesNotContatinTree failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
public void multipleAdditiveTreesTestNoFeaturesSpecified() throws Exception { public void multipleAdditiveTreesTestNoFeaturesSpecified() throws Exception {
final ModelException expectedException = final ModelException expectedException =
new ModelException("no features declared for model multipleadditivetreesmodel_no_features"); new ModelException("no features declared for model multipleadditivetreesmodel_no_features");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("multipleadditivetreesmodel_no_features.json", createModelFromFiles("multipleadditivetreesmodel_no_features.json",
"multipleadditivetreesmodel_features.json"); "multipleadditivetreesmodel_features.json");
fail("multipleAdditiveTreesTestNoFeaturesSpecified failed to throw exception: "+expectedException); });
} catch (ModelException actualException) { Throwable rootError = getRootCause(ex);
assertEquals(expectedException.toString(), actualException.toString()); assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
public void multipleAdditiveTreesTestNoRight() throws Exception { public void multipleAdditiveTreesTestNoRight() throws Exception {
final ModelException expectedException = final ModelException expectedException =
new ModelException("MultipleAdditiveTreesModel tree node is missing right"); new ModelException("MultipleAdditiveTreesModel tree node is missing right");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("multipleadditivetreesmodel_no_right.json", createModelFromFiles("multipleadditivetreesmodel_no_right.json",
"multipleadditivetreesmodel_features.json"); "multipleadditivetreesmodel_features.json");
fail("multipleAdditiveTreesTestNoRight failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
public void multipleAdditiveTreesTestNoLeft() throws Exception { public void multipleAdditiveTreesTestNoLeft() throws Exception {
final ModelException expectedException = final ModelException expectedException =
new ModelException("MultipleAdditiveTreesModel tree node is missing left"); new ModelException("MultipleAdditiveTreesModel tree node is missing left");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("multipleadditivetreesmodel_no_left.json", createModelFromFiles("multipleadditivetreesmodel_no_left.json",
"multipleadditivetreesmodel_features.json"); "multipleadditivetreesmodel_features.json");
fail("multipleAdditiveTreesTestNoLeft failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
public void multipleAdditiveTreesTestNoThreshold() throws Exception { public void multipleAdditiveTreesTestNoThreshold() throws Exception {
final ModelException expectedException = final ModelException expectedException =
new ModelException("MultipleAdditiveTreesModel tree node is missing threshold"); new ModelException("MultipleAdditiveTreesModel tree node is missing threshold");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("multipleadditivetreesmodel_no_threshold.json", createModelFromFiles("multipleadditivetreesmodel_no_threshold.json",
"multipleadditivetreesmodel_features.json"); "multipleadditivetreesmodel_features.json");
fail("multipleAdditiveTreesTestNoThreshold failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
public void multipleAdditiveTreesTestMissingTreeFeature() throws Exception { public void multipleAdditiveTreesTestMissingTreeFeature() throws Exception {
final ModelException expectedException = final ModelException expectedException =
new ModelException("MultipleAdditiveTreesModel tree node is leaf with left=-100.0 and right=75.0"); new ModelException("MultipleAdditiveTreesModel tree node is leaf with left=-100.0 and right=75.0");
try {
createModelFromFiles("multipleadditivetreesmodel_no_feature.json", ModelException ex = expectThrows(ModelException.class, () -> {
"multipleadditivetreesmodel_features.json"); createModelFromFiles("multipleadditivetreesmodel_no_feature.json",
fail("multipleAdditiveTreesTestMissingTreeFeature failed to throw exception: "+expectedException); "multipleadditivetreesmodel_features.json");
} catch (ModelException actualException) { });
assertEquals(expectedException.toString(), actualException.toString()); assertEquals(expectedException.toString(), ex.toString());
}
} }
} }

View File

@ -205,14 +205,12 @@ public class TestNeuralNetworkModel extends TestRerankBase {
public void badActivationTest() throws Exception { public void badActivationTest() throws Exception {
final ModelException expectedException = final ModelException expectedException =
new ModelException("Invalid activation function (\"sig\") in layer 0 of model \"neuralnetworkmodel_bad_activation\"."); new ModelException("Invalid activation function (\"sig\") in layer 0 of model \"neuralnetworkmodel_bad_activation\".");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("neuralnetworkmodel_bad_activation.json", createModelFromFiles("neuralnetworkmodel_bad_activation.json",
"neuralnetworkmodel_features.json"); "neuralnetworkmodel_features.json");
fail("badActivationTest failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
@ -220,14 +218,12 @@ public class TestNeuralNetworkModel extends TestRerankBase {
final ModelException expectedException = final ModelException expectedException =
new ModelException("Dimension mismatch in model \"neuralnetworkmodel_mismatch_bias\". " + new ModelException("Dimension mismatch in model \"neuralnetworkmodel_mismatch_bias\". " +
"Layer 0 has 2 bias weights but 3 weight matrix rows."); "Layer 0 has 2 bias weights but 3 weight matrix rows.");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("neuralnetworkmodel_mismatch_bias.json", createModelFromFiles("neuralnetworkmodel_mismatch_bias.json",
"neuralnetworkmodel_features.json"); "neuralnetworkmodel_features.json");
fail("biasDimensionMismatchTest failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
@ -235,14 +231,12 @@ public class TestNeuralNetworkModel extends TestRerankBase {
final ModelException expectedException = final ModelException expectedException =
new ModelException("Dimension mismatch in model \"neuralnetworkmodel_mismatch_input\". The input has " + new ModelException("Dimension mismatch in model \"neuralnetworkmodel_mismatch_input\". The input has " +
"4 features, but the weight matrix for layer 0 has 3 columns."); "4 features, but the weight matrix for layer 0 has 3 columns.");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("neuralnetworkmodel_mismatch_input.json", createModelFromFiles("neuralnetworkmodel_mismatch_input.json",
"neuralnetworkmodel_features.json"); "neuralnetworkmodel_features.json");
fail("inputDimensionMismatchTest failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
@ -250,14 +244,12 @@ public class TestNeuralNetworkModel extends TestRerankBase {
final ModelException expectedException = final ModelException expectedException =
new ModelException("Dimension mismatch in model \"neuralnetworkmodel_mismatch_layers\". The weight matrix " + new ModelException("Dimension mismatch in model \"neuralnetworkmodel_mismatch_layers\". The weight matrix " +
"for layer 0 has 2 rows, but the weight matrix for layer 1 has 3 columns."); "for layer 0 has 2 rows, but the weight matrix for layer 1 has 3 columns.");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("neuralnetworkmodel_mismatch_layers.json", createModelFromFiles("neuralnetworkmodel_mismatch_layers.json",
"neuralnetworkmodel_features.json"); "neuralnetworkmodel_features.json");
fail("layerDimensionMismatchTest failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test
@ -265,14 +257,12 @@ public class TestNeuralNetworkModel extends TestRerankBase {
final ModelException expectedException = final ModelException expectedException =
new ModelException("Dimension mismatch in model \"neuralnetworkmodel_too_many_rows\". " + new ModelException("Dimension mismatch in model \"neuralnetworkmodel_too_many_rows\". " +
"Layer 1 has 1 bias weights but 2 weight matrix rows."); "Layer 1 has 1 bias weights but 2 weight matrix rows.");
try { Exception ex = expectThrows(Exception.class, () -> {
createModelFromFiles("neuralnetworkmodel_too_many_rows.json", createModelFromFiles("neuralnetworkmodel_too_many_rows.json",
"neuralnetworkmodel_features.json"); "neuralnetworkmodel_features.json");
fail("layerDimensionMismatchTest failed to throw exception: "+expectedException); });
} catch (Exception actualException) { Throwable rootError = getRootCause(ex);
Throwable rootError = getRootCause(actualException); assertEquals(expectedException.toString(), rootError.toString());
assertEquals(expectedException.toString(), rootError.toString());
}
} }
@Test @Test

View File

@ -63,31 +63,19 @@ public class TestWrapperModel extends TestRerankBase {
@Test @Test
public void testValidate() throws Exception { public void testValidate() throws Exception {
WrapperModel wrapperModel = new StubWrapperModel("testModel"); WrapperModel wrapperModel = new StubWrapperModel("testModel");
try { wrapperModel.validate();
wrapperModel.validate();
} catch (ModelException e) {
fail("Validation must succeed if no wrapped model is set");
}
// wrapper model with features // wrapper model with features
WrapperModel wrapperModelWithFeatures = new StubWrapperModel("testModel", WrapperModel wrapperModelWithFeatures = new StubWrapperModel("testModel",
Collections.singletonList(new ValueFeature("val", Collections.emptyMap())), Collections.emptyList()); Collections.singletonList(new ValueFeature("val", Collections.emptyMap())), Collections.emptyList());
try { ModelException e = expectThrows(ModelException.class, wrapperModelWithFeatures::validate);
wrapperModelWithFeatures.validate(); assertEquals("features must be empty for the wrapper model testModel", e.getMessage());
fail("Validation must fail if features of the wrapper model isn't empty");
} catch (ModelException e) {
assertEquals("features must be empty for the wrapper model testModel", e.getMessage());
}
// wrapper model with norms // wrapper model with norms
WrapperModel wrapperModelWithNorms = new StubWrapperModel("testModel", WrapperModel wrapperModelWithNorms = new StubWrapperModel("testModel",
Collections.emptyList(), Collections.singletonList(IdentityNormalizer.INSTANCE)); Collections.emptyList(), Collections.singletonList(IdentityNormalizer.INSTANCE));
try { e = expectThrows(ModelException.class, wrapperModelWithNorms::validate);
wrapperModelWithNorms.validate(); assertEquals("norms must be empty for the wrapper model testModel", e.getMessage());
fail("Validation must fail if norms of the wrapper model isn't empty");
} catch (ModelException e) {
assertEquals("norms must be empty for the wrapper model testModel", e.getMessage());
}
assumeWorkingMockito(); assumeWorkingMockito();
@ -102,11 +90,7 @@ public class TestWrapperModel extends TestRerankBase {
IdentityNormalizer.INSTANCE, IdentityNormalizer.INSTANCE,
IdentityNormalizer.INSTANCE) IdentityNormalizer.INSTANCE)
); );
try { wrapperModel.updateModel(wrappedModel);
wrapperModel.updateModel(wrappedModel);
} catch (ModelException e) {
fail("Validation must succeed if the wrapped model is valid");
}
} }
// update invalid model (feature store mismatch) // update invalid model (feature store mismatch)
@ -120,12 +104,8 @@ public class TestWrapperModel extends TestRerankBase {
IdentityNormalizer.INSTANCE, IdentityNormalizer.INSTANCE,
IdentityNormalizer.INSTANCE) IdentityNormalizer.INSTANCE)
); );
try { e = expectThrows(ModelException.class, () -> wrapperModel.updateModel(wrappedModel));
wrapperModel.updateModel(wrappedModel); assertEquals("wrapper feature store name (_DEFAULT_) must match the wrapped feature store name (wrappedFeatureStore)", e.getMessage());
fail("Validation must fail if wrapped model feature store differs from wrapper model feature store");
} catch (ModelException e) {
assertEquals("wrapper feature store name (_DEFAULT_) must match the wrapped feature store name (wrappedFeatureStore)", e.getMessage());
}
} }
// update invalid model (no features) // update invalid model (no features)
@ -137,12 +117,8 @@ public class TestWrapperModel extends TestRerankBase {
IdentityNormalizer.INSTANCE, IdentityNormalizer.INSTANCE,
IdentityNormalizer.INSTANCE) IdentityNormalizer.INSTANCE)
); );
try { e = expectThrows(ModelException.class, () -> wrapperModel.updateModel(wrappedModel));
wrapperModel.updateModel(wrappedModel); assertEquals("no features declared for model testModel", e.getMessage());
fail("Validation must fail if the wrapped model is invalid");
} catch (ModelException e) {
assertEquals("no features declared for model testModel", e.getMessage());
}
} }
// update invalid model (no norms) // update invalid model (no norms)
@ -154,12 +130,8 @@ public class TestWrapperModel extends TestRerankBase {
new ValueFeature("v2", Collections.emptyMap())), new ValueFeature("v2", Collections.emptyMap())),
Collections.emptyList() Collections.emptyList()
); );
try { e = expectThrows(ModelException.class, () -> wrapperModel.updateModel(wrappedModel));
wrapperModel.updateModel(wrappedModel); assertEquals("counted 2 features and 0 norms in model testModel", e.getMessage());
fail("Validation must fail if the wrapped model is invalid");
} catch (ModelException e) {
assertEquals("counted 2 features and 0 norms in model testModel", e.getMessage());
}
} }
} }

View File

@ -16,16 +16,16 @@
*/ */
package org.apache.solr.ltr.norm; package org.apache.solr.ltr.norm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.core.SolrResourceLoader; import org.apache.solr.core.SolrResourceLoader;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TestMinMaxNormalizer { public class TestMinMaxNormalizer {
private final SolrResourceLoader solrResourceLoader = new SolrResourceLoader(); private final SolrResourceLoader solrResourceLoader = new SolrResourceLoader();
@ -87,14 +87,10 @@ public class TestMinMaxNormalizer {
final NormalizerException expectedException = final NormalizerException expectedException =
new NormalizerException("MinMax Normalizer delta must not be zero " new NormalizerException("MinMax Normalizer delta must not be zero "
+ "| min = 10.0,max = 10.0,delta = 0.0"); + "| min = 10.0,max = 10.0,delta = 0.0");
try { NormalizerException ex = SolrTestCaseJ4.expectThrows(NormalizerException.class,
implTestMinMax(params, () -> implTestMinMax(params, 10.0f, 10.0f)
10.0f, );
10.0f); assertEquals(expectedException.toString(), ex.toString());
fail("testMinMaxNormalizerMinEqualToMax failed to throw exception: "+expectedException);
} catch(NormalizerException actualException) {
assertEquals(expectedException.toString(), actualException.toString());
}
} }
@Test @Test

View File

@ -16,16 +16,16 @@
*/ */
package org.apache.solr.ltr.norm; package org.apache.solr.ltr.norm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.core.SolrResourceLoader; import org.apache.solr.core.SolrResourceLoader;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TestStandardNormalizer { public class TestStandardNormalizer {
private final SolrResourceLoader solrResourceLoader = new SolrResourceLoader(); private final SolrResourceLoader solrResourceLoader = new SolrResourceLoader();
@ -58,14 +58,10 @@ public class TestStandardNormalizer {
final NormalizerException expectedException = final NormalizerException expectedException =
new NormalizerException("Standard Normalizer standard deviation must be positive " new NormalizerException("Standard Normalizer standard deviation must be positive "
+ "| avg = 0.0,std = 0.0"); + "| avg = 0.0,std = 0.0");
try { NormalizerException ex = SolrTestCaseJ4.expectThrows(NormalizerException.class,
implTestStandard(params, () -> implTestStandard(params, 0.0f, 0.0f)
0.0f, );
0.0f); assertEquals(expectedException.toString(), ex.toString());
fail("testInvalidSTD failed to throw exception: "+expectedException);
} catch(NormalizerException actualException) {
assertEquals(expectedException.toString(), actualException.toString());
}
} }
@Test @Test
@ -75,14 +71,11 @@ public class TestStandardNormalizer {
final NormalizerException expectedException = final NormalizerException expectedException =
new NormalizerException("Standard Normalizer standard deviation must be positive " new NormalizerException("Standard Normalizer standard deviation must be positive "
+ "| avg = 0.0,std = -1.0"); + "| avg = 0.0,std = -1.0");
try {
implTestStandard(params, NormalizerException ex = SolrTestCaseJ4.expectThrows(NormalizerException.class,
0.0f, () -> implTestStandard(params, 0.0f, -1f)
-1f); );
fail("testInvalidSTD2 failed to throw exception: "+expectedException); assertEquals(expectedException.toString(), ex.toString());
} catch(NormalizerException actualException) {
assertEquals(expectedException.toString(), actualException.toString());
}
} }
@Test @Test
@ -93,14 +86,11 @@ public class TestStandardNormalizer {
final NormalizerException expectedException = final NormalizerException expectedException =
new NormalizerException("Standard Normalizer standard deviation must be positive " new NormalizerException("Standard Normalizer standard deviation must be positive "
+ "| avg = 1.0,std = 0.0"); + "| avg = 1.0,std = 0.0");
try {
implTestStandard(params, NormalizerException ex = SolrTestCaseJ4.expectThrows(NormalizerException.class,
1f, () -> implTestStandard(params, 1f, 0f)
0f); );
fail("testInvalidSTD3 failed to throw exception: "+expectedException); assertEquals(expectedException.toString(), ex.toString());
} catch(NormalizerException actualException) {
assertEquals(expectedException.toString(), actualException.toString());
}
} }
@Test @Test

View File

@ -129,20 +129,15 @@ public class TestManagedFeatureStore extends SolrTestCaseJ4 {
} }
@Test @Test
public void getInvalidInstanceTest() public void getInvalidInstanceTest() {
{
final String nonExistingClassName = "org.apache.solr.ltr.feature.LOLFeature"; final String nonExistingClassName = "org.apache.solr.ltr.feature.LOLFeature";
final ClassNotFoundException expectedException = final ClassNotFoundException expectedException =
new ClassNotFoundException(nonExistingClassName); new ClassNotFoundException(nonExistingClassName);
try { Exception ex = expectThrows(Exception.class, () -> {
fstore.addFeature(createMap("test", fstore.addFeature(createMap("test", nonExistingClassName, null), "testFstore2");
nonExistingClassName, null), });
"testFstore2"); Throwable rootError = getRootCause(ex);
fail("getInvalidInstanceTest failed to throw exception: "+expectedException); assertEquals(expectedException.toString(), rootError.toString());
} catch (Exception actualException) {
Throwable rootError = getRootCause(actualException);
assertEquals(expectedException.toString(), rootError.toString());
}
} }
} }

View File

@ -16,20 +16,20 @@
*/ */
package org.apache.solr.velocity; package org.apache.solr.velocity;
import java.io.IOException;
import java.io.StringWriter;
import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException;
import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.NamedList;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.QueryResponseWriter; import org.apache.solr.response.QueryResponseWriter;
import org.apache.solr.response.SolrParamResourceLoader; import org.apache.solr.response.SolrParamResourceLoader;
import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.response.VelocityResponseWriter; import org.apache.solr.response.VelocityResponseWriter;
import org.apache.solr.request.SolrQueryRequest;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.io.StringWriter;
public class VelocityResponseWriterTest extends SolrTestCaseJ4 { public class VelocityResponseWriterTest extends SolrTestCaseJ4 {
@BeforeClass @BeforeClass
public static void beforeClass() throws Exception { public static void beforeClass() throws Exception {
@ -66,12 +66,7 @@ public class VelocityResponseWriterTest extends SolrTestCaseJ4 {
SolrParamResourceLoader.TEMPLATE_PARAM_PREFIX+"custom","$response.response.response_data"); SolrParamResourceLoader.TEMPLATE_PARAM_PREFIX+"custom","$response.response.response_data");
SolrQueryResponse rsp = new SolrQueryResponse(); SolrQueryResponse rsp = new SolrQueryResponse();
StringWriter buf = new StringWriter(); StringWriter buf = new StringWriter();
try { expectThrows(IOException.class, () -> vrw.write(buf, req, rsp));
vrw.write(buf, req, rsp);
fail("Should have thrown exception due to missing template");
} catch (IOException e) {
// expected exception
}
} }
@Test @Test

View File

@ -24,10 +24,8 @@ import java.util.Map;
import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.api.ApiBag; import org.apache.solr.api.ApiBag;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.client.solrj.request.schema.SchemaRequest;
import org.apache.solr.client.solrj.response.schema.SchemaResponse; import org.apache.solr.client.solrj.response.schema.SchemaResponse;
import org.apache.solr.client.solrj.response.schema.SchemaResponse.FieldResponse;
import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.Before; import org.junit.Before;
@ -73,15 +71,9 @@ public class TestEmbeddedSolrServerSchemaAPI extends SolrTestCaseJ4 {
} }
@Before @Before
public void thereIsNoFieldYet() throws SolrServerException, IOException{ public void thereIsNoFieldYet() {
try{ SolrException ex = expectThrows(SolrException.class, () -> new SchemaRequest.Field(fieldName).process(server));
FieldResponse process = new SchemaRequest.Field(fieldName) assertTrue(ex.getMessage().contains("No") && ex.getMessage().contains("VerificationTest"));
.process(server);
fail(""+process);
}catch(SolrException e){
assertTrue(e.getMessage().contains("No")
&& e.getMessage().contains("VerificationTest"));
}
} }
@Test @Test

View File

@ -95,6 +95,7 @@ public class PluginInfoTest extends DOMUtilTestBase {
PluginInfo pi2 = new PluginInfo(nodeWithAClass, "Node with a Class", false, true); PluginInfo pi2 = new PluginInfo(nodeWithAClass, "Node with a Class", false, true);
assertTrue(pi2.className.equals("myName")); assertTrue(pi2.className.equals("myName"));
} }
@Test @Test
public void testIsEnabled() throws Exception { public void testIsEnabled() throws Exception {
Node node = getNode("<plugin enable=\"true\" />", "plugin"); Node node = getNode("<plugin enable=\"true\" />", "plugin");
@ -105,6 +106,7 @@ public class PluginInfoTest extends DOMUtilTestBase {
assertFalse(pi.isEnabled()); assertFalse(pi.isEnabled());
} }
@Test @Test
public void testIsDefault() throws Exception { public void testIsDefault() throws Exception {
Node node = getNode("<plugin default=\"true\" />", "plugin"); Node node = getNode("<plugin default=\"true\" />", "plugin");
@ -115,6 +117,7 @@ public class PluginInfoTest extends DOMUtilTestBase {
assertFalse(pi.isDefault()); assertFalse(pi.isDefault());
} }
@Test @Test
public void testNoChildren() throws Exception{ public void testNoChildren() throws Exception{
Node node = getNode(configWithNoChildren, "/plugin"); Node node = getNode(configWithNoChildren, "/plugin");
@ -143,9 +146,8 @@ public class PluginInfoTest extends DOMUtilTestBase {
PluginInfo pi2 = new PluginInfo(node2, "with No Children", false, false); PluginInfo pi2 = new PluginInfo(node2, "with No Children", false, false);
PluginInfo noChild = pi2.getChild("long"); PluginInfo noChild = pi2.getChild("long");
assertNull(noChild); assertNull(noChild);
} }
@Test @Test
public void testChildren() throws Exception { public void testChildren() throws Exception {
Node node = getNode(configWith2Children, "plugin"); Node node = getNode(configWith2Children, "plugin");
@ -157,6 +159,7 @@ public class PluginInfoTest extends DOMUtilTestBase {
assertTrue( childInfo instanceof PluginInfo ); assertTrue( childInfo instanceof PluginInfo );
} }
} }
@Test @Test
public void testInitArgsCount() throws Exception { public void testInitArgsCount() throws Exception {
Node node = getNode(configWithNoChildren, "plugin"); Node node = getNode(configWithNoChildren, "plugin");

View File

@ -156,15 +156,9 @@ public class FieldAnalysisRequestHandlerTest extends AnalysisRequestHandlerTestB
params.remove(CommonParams.Q); params.remove(CommonParams.Q);
params.remove(AnalysisParams.QUERY); params.remove(AnalysisParams.QUERY);
params.remove(AnalysisParams.FIELD_VALUE); params.remove(AnalysisParams.FIELD_VALUE);
try { try (SolrQueryRequest solrQueryRequest = new LocalSolrQueryRequest(h.getCore(), params)) {
request = handler.resolveAnalysisRequest(req); SolrException ex = expectThrows(SolrException.class, () -> handler.resolveAnalysisRequest(solrQueryRequest));
fail("Analysis request must fail if all of q, analysis.query or analysis.value are absent"); assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
} catch (SolrException e) {
if (e.code() != SolrException.ErrorCode.BAD_REQUEST.code) {
fail("Unexpected exception");
}
} catch (Exception e) {
fail("Unexpected exception");
} }
req.close(); req.close();

View File

@ -93,7 +93,7 @@ public class JsonLoaderTest extends SolrTestCaseJ4 {
// //
add = p.addCommands.get(1); add = p.addCommands.get(1);
assertEquals("SolrInputDocument(fields: [f1=[v1, v2], f2=null])", add.solrDoc.toString()); assertEquals("SolrInputDocument(fields: [f1=[v1, v2], f2=null])", add.solrDoc.toString());
assertEquals(false, add.overwrite); assertFalse(add.overwrite);
// parse the commit commands // parse the commit commands
assertEquals( 2, p.commitCommands.size() ); assertEquals( 2, p.commitCommands.size() );
@ -112,21 +112,21 @@ public class JsonLoaderTest extends SolrTestCaseJ4 {
assertEquals( 4, p.deleteCommands.size() ); assertEquals( 4, p.deleteCommands.size() );
DeleteUpdateCommand delete = p.deleteCommands.get( 0 ); DeleteUpdateCommand delete = p.deleteCommands.get( 0 );
assertEquals( delete.id, "ID" ); assertEquals( delete.id, "ID" );
assertEquals( delete.query, null ); assertNull( delete.query );
assertEquals( delete.commitWithin, -1); assertEquals( delete.commitWithin, -1);
delete = p.deleteCommands.get( 1 ); delete = p.deleteCommands.get( 1 );
assertEquals( delete.id, "ID" ); assertEquals( delete.id, "ID" );
assertEquals( delete.query, null ); assertNull( delete.query );
assertEquals( delete.commitWithin, 500); assertEquals( delete.commitWithin, 500);
delete = p.deleteCommands.get( 2 ); delete = p.deleteCommands.get( 2 );
assertEquals( delete.id, null ); assertNull( delete.id );
assertEquals( delete.query, "QUERY" ); assertEquals( delete.query, "QUERY" );
assertEquals( delete.commitWithin, -1); assertEquals( delete.commitWithin, -1);
delete = p.deleteCommands.get( 3 ); delete = p.deleteCommands.get( 3 );
assertEquals( delete.id, null ); assertNull( delete.id );
assertEquals( delete.query, "QUERY" ); assertEquals( delete.query, "QUERY" );
assertEquals( delete.commitWithin, 500); assertEquals( delete.commitWithin, 500);
@ -153,36 +153,31 @@ public class JsonLoaderTest extends SolrTestCaseJ4 {
SolrInputField f = d.getField( "id" ); SolrInputField f = d.getField( "id" );
assertEquals("1", f.getValue()); assertEquals("1", f.getValue());
assertEquals(add.commitWithin, 100); assertEquals(add.commitWithin, 100);
assertEquals(add.overwrite, false); assertFalse(add.overwrite);
add = p.addCommands.get(1); add = p.addCommands.get(1);
d = add.solrDoc; d = add.solrDoc;
f = d.getField( "id" ); f = d.getField( "id" );
assertEquals("2", f.getValue()); assertEquals("2", f.getValue());
assertEquals(add.commitWithin, 100); assertEquals(add.commitWithin, 100);
assertEquals(add.overwrite, false); assertFalse(add.overwrite);
req.close(); req.close();
} }
@Test @Test
public void testInvalidJsonProducesBadRequestSolrException() throws Exception public void testInvalidJsonProducesBadRequestSolrException() throws Exception {
{
SolrQueryResponse rsp = new SolrQueryResponse(); SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null); BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader(); JsonLoader loader = new JsonLoader();
String invalidJsonString = "}{"; String invalidJsonString = "}{";
try(SolrQueryRequest req = req()) { SolrException ex = expectThrows(SolrException.class, () -> {
try { loader.load(req(), rsp, new ContentStreamBase.StringStream(invalidJsonString), p);
loader.load(req, rsp, new ContentStreamBase.StringStream(invalidJsonString), p); });
fail("Expected invalid JSON to produce a SolrException."); assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
} catch (SolrException expectedException) { assertTrue(ex.getMessage().contains("Cannot parse"));
assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, expectedException.code()); assertTrue(ex.getMessage().contains("JSON"));
assertTrue(expectedException.getMessage().contains("Cannot parse"));
assertTrue(expectedException.getMessage().contains("JSON"));
}
}
} }
public void testSimpleFormatInAdd() throws Exception public void testSimpleFormatInAdd() throws Exception
@ -201,14 +196,14 @@ public class JsonLoaderTest extends SolrTestCaseJ4 {
SolrInputField f = d.getField( "id" ); SolrInputField f = d.getField( "id" );
assertEquals("1", f.getValue()); assertEquals("1", f.getValue());
assertEquals(add.commitWithin, -1); assertEquals(add.commitWithin, -1);
assertEquals(add.overwrite, true); assertTrue(add.overwrite);
add = p.addCommands.get(1); add = p.addCommands.get(1);
d = add.solrDoc; d = add.solrDoc;
f = d.getField( "id" ); f = d.getField( "id" );
assertEquals("2", f.getValue()); assertEquals("2", f.getValue());
assertEquals(add.commitWithin, -1); assertEquals(add.commitWithin, -1);
assertEquals(add.overwrite, true); assertTrue(add.overwrite);
req.close(); req.close();
} }
@ -636,25 +631,17 @@ public class JsonLoaderTest extends SolrTestCaseJ4 {
ignoreException("big_integer_t"); ignoreException("big_integer_t");
try { SolrException ex = expectThrows(SolrException.class, () -> {
updateJ(json( "[{'id':'1','big_integer_tl':12345678901234567890}]" ), null); updateJ(json( "[{'id':'1','big_integer_tl':12345678901234567890}]" ), null);
fail("A BigInteger value should overflow a long field"); });
} catch (SolrException e) { assertTrue(ex.getCause() instanceof NumberFormatException);
if ( ! (e.getCause() instanceof NumberFormatException)) {
throw e;
}
}
// Adding a BigInteger to an integer field should fail // Adding a BigInteger to an integer field should fail
// BigInteger.intValue() returns only the low-order 32 bits. // BigInteger.intValue() returns only the low-order 32 bits.
try { ex = expectThrows(SolrException.class, () -> {
updateJ(json( "[{'id':'1','big_integer_ti':12345678901234567890}]" ), null); updateJ(json( "[{'id':'1','big_integer_ti':12345678901234567890}]" ), null);
fail("A BigInteger value should overflow an integer field"); });
} catch (SolrException e) { assertTrue(ex.getCause() instanceof NumberFormatException);
if ( ! (e.getCause() instanceof NumberFormatException)) {
throw e;
}
}
unIgnoreException("big_integer_t"); unIgnoreException("big_integer_t");
} }
@ -1007,5 +994,4 @@ public class JsonLoaderTest extends SolrTestCaseJ4 {
} }
} }

View File

@ -162,13 +162,8 @@ public class PingRequestHandlerTest extends SolrTestCaseJ4 {
} }
public void testBadActionRaisesException() throws Exception { public void testBadActionRaisesException() throws Exception {
SolrException se = expectThrows(SolrException.class, () -> makeRequest(handler, req("action", "badaction")));
try { assertEquals(SolrException.ErrorCode.BAD_REQUEST.code,se.code());
SolrQueryResponse rsp = makeRequest(handler, req("action", "badaction"));
fail("Should have thrown a SolrException for the bad action");
} catch (SolrException se){
assertEquals(SolrException.ErrorCode.BAD_REQUEST.code,se.code());
}
} }
public void testPingInClusterWithNoHealthCheck() throws Exception { public void testPingInClusterWithNoHealthCheck() throws Exception {

View File

@ -1512,10 +1512,8 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
List<String> params = Arrays.asList(ReplicationHandler.FILE, ReplicationHandler.CONF_FILE_SHORT, ReplicationHandler.TLOG_FILE); List<String> params = Arrays.asList(ReplicationHandler.FILE, ReplicationHandler.CONF_FILE_SHORT, ReplicationHandler.TLOG_FILE);
for (String param : params) { for (String param : params) {
for (String filename : illegalFilenames) { for (String filename : illegalFilenames) {
try { expectThrows(Exception.class, () ->
invokeReplicationCommand(masterJetty.getLocalPort(), "filecontent&" + param + "=" + filename); invokeReplicationCommand(masterJetty.getLocalPort(), "filecontent&" + param + "=" + filename));
fail("Should have thrown exception on illegal path for param " + param + " and file name " + filename);
} catch (Exception e) {}
} }
} }
} }

View File

@ -139,8 +139,6 @@ public class TestRestoreCore extends SolrJettyTestBase {
Thread.sleep(1000); Thread.sleep(1000);
} }
int numRestoreTests = nDocs > 0 ? TestUtil.nextInt(random(), 1, 5) : 1; int numRestoreTests = nDocs > 0 ? TestUtil.nextInt(random(), 1, 5) : 1;
for (int attempts=0; attempts<numRestoreTests; attempts++) { for (int attempts=0; attempts<numRestoreTests; attempts++) {

View File

@ -54,12 +54,8 @@ public class TestSQLHandlerNonCloud extends SolrJettyTestBase {
String url = jetty.getBaseUrl() + "/" + DEFAULT_TEST_COLLECTION_NAME; String url = jetty.getBaseUrl() + "/" + DEFAULT_TEST_COLLECTION_NAME;
SolrStream solrStream = new SolrStream(url, sParams); SolrStream solrStream = new SolrStream(url, sParams);
try { IOException ex = expectThrows(IOException.class, () -> getTuples(solrStream));
getTuples(solrStream); assertTrue(ex.getMessage().contains(SQLHandler.sqlNonCloudErrorMsg));
fail(SQLHandler.sqlNonCloudErrorMsg);
} catch (IOException e) {
assertTrue(e.getMessage().contains(SQLHandler.sqlNonCloudErrorMsg));
}
} }
private List<Tuple> getTuples(TupleStream tupleStream) throws IOException { private List<Tuple> getTuples(TupleStream tupleStream) throws IOException {

View File

@ -71,13 +71,9 @@ public class V2ApiIntegrationTest extends SolrCloudTestCase {
.withPayload(payload) .withPayload(payload)
.build(); .build();
v2Request.setResponseParser(responseParser); v2Request.setResponseParser(responseParser);
try { HttpSolrClient.RemoteSolrException ex = expectThrows(HttpSolrClient.RemoteSolrException.class,
v2Request.process(cluster.getSolrClient()); () -> v2Request.process(cluster.getSolrClient()));
fail("expected an exception with error code: "+expectedCode); assertEquals(expectedCode, ex.code());
} catch (HttpSolrClient.RemoteExecutionException e) {
assertEquals(expectedCode, e.code());
}
} }
@Test @Test

View File

@ -164,8 +164,7 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {
assertNull("Exception on create", resp.getException()); assertNull("Exception on create", resp.getException());
// Try to create another core with a different name, but the same instance dir // Try to create another core with a different name, but the same instance dir
SolrQueryResponse resp2 = new SolrQueryResponse(); SolrException e = expectThrows(SolrException.class, () -> {
try {
admin.handleRequestBody admin.handleRequestBody
(req(CoreAdminParams.ACTION, (req(CoreAdminParams.ACTION,
CoreAdminParams.CoreAdminAction.CREATE.toString(), CoreAdminParams.CoreAdminAction.CREATE.toString(),
@ -174,13 +173,9 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {
CoreAdminParams.CONFIG, "solrconfig_ren.xml", CoreAdminParams.CONFIG, "solrconfig_ren.xml",
CoreAdminParams.SCHEMA, "schema_ren.xml", CoreAdminParams.SCHEMA, "schema_ren.xml",
CoreAdminParams.DATA_DIR, data.getAbsolutePath()), CoreAdminParams.DATA_DIR, data.getAbsolutePath()),
resp2); new SolrQueryResponse());
fail("Creating two cores with a shared instance dir should throw an exception"); });
} assertTrue(e.getMessage().contains("already defined there"));
catch (SolrException e) {
assertTrue(e.getMessage().contains("already defined there"));
}
} }
@Test @Test

View File

@ -138,17 +138,16 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
SolrQueryResponse resp = new SolrQueryResponse(); SolrQueryResponse resp = new SolrQueryResponse();
// Sneaking in a test for using a bad core name // Sneaking in a test for using a bad core name
try { SolrException se = expectThrows(SolrException.class, () -> {
admin.handleRequestBody admin.handleRequestBody
(req(CoreAdminParams.ACTION, (req(CoreAdminParams.ACTION,
CoreAdminParams.CoreAdminAction.CREATE.toString(), CoreAdminParams.CoreAdminAction.CREATE.toString(),
CoreAdminParams.INSTANCE_DIR, instPropFile.getAbsolutePath(), CoreAdminParams.INSTANCE_DIR, instPropFile.getAbsolutePath(),
CoreAdminParams.NAME, "ugly$core=name"), CoreAdminParams.NAME, "ugly$core=name"),
resp); new SolrQueryResponse());
});
assertTrue("Expected error message for bad core name.", se.toString().contains("Invalid core"));
} catch (SolrException se) {
assertTrue("Expected error message for bad core name.", se.toString().contains("Invalid core"));
}
CoreDescriptor cd = cores.getCoreDescriptor("ugly$core=name"); CoreDescriptor cd = cores.getCoreDescriptor("ugly$core=name");
assertNull("Should NOT have added this core!", cd); assertNull("Should NOT have added this core!", cd);
@ -171,19 +170,17 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
// attempt to create a bogus core and confirm failure // attempt to create a bogus core and confirm failure
ignoreException("Could not load config"); ignoreException("Could not load config");
try { se = expectThrows(SolrException.class, () -> {
resp = new SolrQueryResponse();
admin.handleRequestBody admin.handleRequestBody
(req(CoreAdminParams.ACTION, (req(CoreAdminParams.ACTION,
CoreAdminParams.CoreAdminAction.CREATE.toString(), CoreAdminParams.CoreAdminAction.CREATE.toString(),
CoreAdminParams.NAME, "bogus_dir_core", CoreAdminParams.NAME, "bogus_dir_core",
CoreAdminParams.INSTANCE_DIR, "dir_does_not_exist_127896"), CoreAdminParams.INSTANCE_DIR, "dir_does_not_exist_127896"),
resp); new SolrQueryResponse());
fail("bogus collection created ok"); });
} catch (SolrException e) { // :NOOP:
// :NOOP: // :TODO: CoreAdminHandler's exception messages are terrible, otherwise we could assert something useful here
// :TODO: CoreAdminHandler's exception messages are terrible, otherwise we could assert something useful here
}
unIgnoreException("Could not load config"); unIgnoreException("Could not load config");
// check specifically for status of the failed core name // check specifically for status of the failed core name
@ -228,16 +225,15 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
assertNotNull("Core should have been renamed!", cd); assertNotNull("Core should have been renamed!", cd);
// Rename it something bogus and see if you get an exception, the old core is still there and the bogus one isn't // Rename it something bogus and see if you get an exception, the old core is still there and the bogus one isn't
try { se = expectThrows(SolrException.class, () -> {
admin.handleRequestBody admin.handleRequestBody
(req(CoreAdminParams.ACTION, (req(CoreAdminParams.ACTION,
CoreAdminParams.CoreAdminAction.RENAME.toString(), CoreAdminParams.CoreAdminAction.RENAME.toString(),
CoreAdminParams.CORE, "rename_me", CoreAdminParams.CORE, "rename_me",
CoreAdminParams.OTHER, "bad$name"), CoreAdminParams.OTHER, "bad$name"),
resp); new SolrQueryResponse());
} catch (SolrException e) { // why the heck does create return a SolrException (admittedly wrapping an IAE) });
assertTrue("Expected error message for bad core name.", e.getMessage().contains("Invalid core")); assertTrue("Expected error message for bad core name.", se.getMessage().contains("Invalid core"));
}
cd = cores.getCoreDescriptor("bad$name"); cd = cores.getCoreDescriptor("bad$name");
assertNull("Core should NOT exist!", cd); assertNull("Core should NOT exist!", cd);
@ -245,8 +241,6 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
cd = cores.getCoreDescriptor("rename_me"); cd = cores.getCoreDescriptor("rename_me");
assertNotNull("Core should have been renamed!", cd); assertNotNull("Core should have been renamed!", cd);
// :TODO: because of SOLR-3665 we can't ask for status from all cores // :TODO: because of SOLR-3665 we can't ask for status from all cores
} }
@ -385,11 +379,8 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
FileUtils.copyFile(new File(top, "bad-error-solrconfig.xml"), new File(subHome, "solrconfig.xml")); FileUtils.copyFile(new File(top, "bad-error-solrconfig.xml"), new File(subHome, "solrconfig.xml"));
try (HttpSolrClient client = getHttpSolrClient(runner.getBaseUrl().toString(), DEFAULT_CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT)) { try (HttpSolrClient client = getHttpSolrClient(runner.getBaseUrl().toString(), DEFAULT_CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT)) {
try { // this is expected because we put a bad solrconfig -- ignore
CoreAdminRequest.reloadCore("corex", client); expectThrows(Exception.class, () -> CoreAdminRequest.reloadCore("corex", client));
} catch (Exception e) {
// this is expected because we put a bad solrconfig -- ignore
}
CoreAdminRequest.Unload req = new CoreAdminRequest.Unload(false); CoreAdminRequest.Unload req = new CoreAdminRequest.Unload(false);
req.setDeleteDataDir(true); req.setDeleteDataDir(true);
@ -408,31 +399,22 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
final CoreAdminHandler admin = new CoreAdminHandler(h.getCoreContainer()); final CoreAdminHandler admin = new CoreAdminHandler(h.getCoreContainer());
SolrQueryResponse resp = new SolrQueryResponse(); SolrQueryResponse resp = new SolrQueryResponse();
try { SolrException e = expectThrows(SolrException.class, () -> {
admin.handleRequestBody( admin.handleRequestBody(
req(CoreAdminParams.ACTION, req(CoreAdminParams.ACTION,
CoreAdminParams.CoreAdminAction.RELOAD.toString(), CoreAdminParams.CoreAdminAction.RELOAD.toString(),
CoreAdminParams.CORE, "non-existent-core") CoreAdminParams.CORE, "non-existent-core")
, resp); , resp);
fail("Was able to successfully reload non-existent-core"); });
} catch (Exception e) { assertEquals("Expected error message for non-existent core.", "No such core: non-existent-core", e.getMessage());
assertEquals("Expected error message for non-existent core.", "No such core: non-existent-core", e.getMessage());
}
// test null core // test null core
try { e = expectThrows(SolrException.class, () -> {
admin.handleRequestBody( admin.handleRequestBody(
req(CoreAdminParams.ACTION, req(CoreAdminParams.ACTION,
CoreAdminParams.CoreAdminAction.RELOAD.toString()) CoreAdminParams.CoreAdminAction.RELOAD.toString())
, resp); , resp);
fail("Was able to successfully reload null core"); });
} assertEquals("Expected error message for non-existent core.", "Missing required parameter: core", e.getMessage());
catch (Exception e) {
if (!(e instanceof SolrException)) {
fail("Expected SolrException but got " + e);
}
assertEquals("Expected error message for non-existent core.", "Missing required parameter: core", e.getMessage());
}
} }
} }

View File

@ -16,11 +16,9 @@
*/ */
package org.apache.solr.handler.admin; package org.apache.solr.handler.admin;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Map; import java.util.Map;
import com.google.common.collect.Maps;
import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.SolrException.ErrorCode;
@ -31,7 +29,8 @@ import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import com.google.common.collect.Maps; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CoreAdminOperationTest extends SolrTestCaseJ4 { public class CoreAdminOperationTest extends SolrTestCaseJ4 {
@ -61,100 +60,68 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.STATUS_OP.execute(callInfo));
CoreAdminOperation.STATUS_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected core-status execution to fail with exception");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testUnloadUnexpectedFailuresResultIn500SolrException() throws Exception { public void testUnloadUnexpectedFailuresResultIn500SolrException() throws Exception {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.UNLOAD_OP.execute(callInfo));
CoreAdminOperation.UNLOAD_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected core-unload execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testUnloadMissingCoreNameResultsIn400SolrException() throws Exception { public void testUnloadMissingCoreNameResultsIn400SolrException() throws Exception {
whenCoreAdminOpHasParams(Maps.newHashMap()); whenCoreAdminOpHasParams(Maps.newHashMap());
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.UNLOAD_OP.execute(callInfo));
CoreAdminOperation.UNLOAD_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected core-unload execution to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testReloadUnexpectedFailuresResultIn500SolrException() { public void testReloadUnexpectedFailuresResultIn500SolrException() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.RELOAD_OP.execute(callInfo));
CoreAdminOperation.RELOAD_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected core-reload execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testReloadMissingCoreNameResultsIn400SolrException() { public void testReloadMissingCoreNameResultsIn400SolrException() {
whenCoreAdminOpHasParams(Maps.newHashMap()); whenCoreAdminOpHasParams(Maps.newHashMap());
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.RELOAD_OP.execute(callInfo));
CoreAdminOperation.RELOAD_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected core-reload execution to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testCreateUnexpectedFailuresResultIn500SolrException() { public void testCreateUnexpectedFailuresResultIn500SolrException() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.CREATE_OP.execute(callInfo));
CoreAdminOperation.CREATE_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected core-create execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testCreateMissingCoreNameResultsIn400SolrException() { public void testCreateMissingCoreNameResultsIn400SolrException() {
whenCoreAdminOpHasParams(Maps.newHashMap()); whenCoreAdminOpHasParams(Maps.newHashMap());
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.CREATE_OP.execute(callInfo));
CoreAdminOperation.CREATE_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected core-create execution to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testSwapUnexpectedFailuresResultIn500SolrException() { public void testSwapUnexpectedFailuresResultIn500SolrException() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.SWAP_OP.execute(callInfo));
CoreAdminOperation.SWAP_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected core-swap execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
@ -162,13 +129,9 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
final Map<String, String> params = Maps.newHashMap(); final Map<String, String> params = Maps.newHashMap();
params.put("other", "some-core-name"); params.put("other", "some-core-name");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.SWAP_OP.execute(callInfo));
CoreAdminOperation.SWAP_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected core-swap execution to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
@ -176,26 +139,18 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
final Map<String, String> params = Maps.newHashMap(); final Map<String, String> params = Maps.newHashMap();
params.put("core", "some-core-name"); params.put("core", "some-core-name");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.SWAP_OP.execute(callInfo));
CoreAdminOperation.SWAP_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected core-swap execution to fail when no 'other' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testRenameUnexpectedFailuresResultIn500SolrException() { public void testRenameUnexpectedFailuresResultIn500SolrException() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.RENAME_OP.execute(callInfo));
CoreAdminOperation.RENAME_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected core-rename execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
@ -203,13 +158,9 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
final Map<String, String> params = Maps.newHashMap(); final Map<String, String> params = Maps.newHashMap();
params.put("other", "some-core-name"); params.put("other", "some-core-name");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.RENAME_OP.execute(callInfo));
CoreAdminOperation.RENAME_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected core-rename execution to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
@ -217,26 +168,18 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
final Map<String, String> params = Maps.newHashMap(); final Map<String, String> params = Maps.newHashMap();
params.put("core", "some-core-name"); params.put("core", "some-core-name");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.RENAME_OP.execute(callInfo));
CoreAdminOperation.RENAME_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected core-rename execution to fail when no 'other' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testMergeUnexpectedFailuresResultIn500SolrException() { public void testMergeUnexpectedFailuresResultIn500SolrException() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.MERGEINDEXES_OP.execute(callInfo));
CoreAdminOperation.MERGEINDEXES_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected core-merge execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
@ -244,203 +187,138 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
final Map<String, String> params = Maps.newHashMap(); final Map<String, String> params = Maps.newHashMap();
params.put("indexDir", "some/index/dir"); params.put("indexDir", "some/index/dir");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.MERGEINDEXES_OP.execute(callInfo));
CoreAdminOperation.MERGEINDEXES_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected core-merge execution to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testSplitUnexpectedFailuresResultIn500SolrException() { public void testSplitUnexpectedFailuresResultIn500SolrException() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.SPLIT_OP.execute(callInfo));
CoreAdminOperation.SPLIT_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected split execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testSplitMissingCoreParamResultsIn400SolrException() { public void testSplitMissingCoreParamResultsIn400SolrException() {
whenCoreAdminOpHasParams(Maps.newHashMap()); whenCoreAdminOpHasParams(Maps.newHashMap());
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.SPLIT_OP.execute(callInfo));
CoreAdminOperation.SPLIT_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected split execution to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testPrepRecoveryUnexpectedFailuresResultIn500SolrException() { public void testPrepRecoveryUnexpectedFailuresResultIn500SolrException() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.PREPRECOVERY_OP.execute(callInfo));
CoreAdminOperation.PREPRECOVERY_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected preprecovery execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testRequestRecoveryUnexpectedFailuresResultIn500Exception() { public void testRequestRecoveryUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.REQUESTRECOVERY_OP.execute(callInfo));
CoreAdminOperation.REQUESTRECOVERY_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected request-recovery execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testRequestRecoveryMissingCoreParamResultsIn400SolrException() { public void testRequestRecoveryMissingCoreParamResultsIn400SolrException() {
whenCoreAdminOpHasParams(Maps.newHashMap()); whenCoreAdminOpHasParams(Maps.newHashMap());
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.REQUESTRECOVERY_OP.execute(callInfo));
CoreAdminOperation.REQUESTRECOVERY_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected request-recovery execution to fail when no 'core' param present");
} catch (Exception thrown) {
thrown.printStackTrace();
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testRequestSyncUnexpectedFailuresResultIn500Exception() { public void testRequestSyncUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.REQUESTSYNCSHARD_OP.execute(callInfo));
CoreAdminOperation.REQUESTSYNCSHARD_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected request-sync execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testRequestSyncMissingCoreParamResultsIn400SolrException() { public void testRequestSyncMissingCoreParamResultsIn400SolrException() {
whenCoreAdminOpHasParams(Maps.newHashMap()); whenCoreAdminOpHasParams(Maps.newHashMap());
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.REQUESTSYNCSHARD_OP.execute(callInfo));
CoreAdminOperation.REQUESTSYNCSHARD_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected request-sync execution to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testRequestBufferUpdatesUnexpectedFailuresResultIn500Exception() { public void testRequestBufferUpdatesUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.REQUESTBUFFERUPDATES_OP.execute(callInfo));
CoreAdminOperation.REQUESTBUFFERUPDATES_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected request-buffer-updates execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testRequestBufferUpdatesMissingCoreParamResultsIn400SolrException() { public void testRequestBufferUpdatesMissingCoreParamResultsIn400SolrException() {
whenCoreAdminOpHasParams(Maps.newHashMap()); whenCoreAdminOpHasParams(Maps.newHashMap());
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.REQUESTBUFFERUPDATES_OP.execute(callInfo));
CoreAdminOperation.REQUESTBUFFERUPDATES_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected request-buffer-updates execution to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testRequestApplyUpdatesUnexpectedFailuresResultIn500Exception() { public void testRequestApplyUpdatesUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.REQUESTAPPLYUPDATES_OP.execute(callInfo));
CoreAdminOperation.REQUESTAPPLYUPDATES_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected request-apply-updates execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testRequestApplyUpdatesMissingCoreParamResultsIn400SolrException() { public void testRequestApplyUpdatesMissingCoreParamResultsIn400SolrException() {
whenCoreAdminOpHasParams(Maps.newHashMap()); whenCoreAdminOpHasParams(Maps.newHashMap());
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.REQUESTAPPLYUPDATES_OP.execute(callInfo));
CoreAdminOperation.REQUESTAPPLYUPDATES_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected request-apply-updates execution to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testOverseerOpUnexpectedFailuresResultIn500Exception() { public void testOverseerOpUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.OVERSEEROP_OP.execute(callInfo));
CoreAdminOperation.OVERSEEROP_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.SERVER_ERROR.code);
fail("Expected overseerop execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.SERVER_ERROR.code);
}
} }
@Test @Test
public void testRequestStatusUnexpectedFailuresResultIn500Exception() { public void testRequestStatusUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.REQUESTSTATUS_OP.execute(callInfo));
CoreAdminOperation.REQUESTSTATUS_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected request-status execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testRequestStatusMissingRequestIdParamResultsIn400SolrException() { public void testRequestStatusMissingRequestIdParamResultsIn400SolrException() {
whenCoreAdminOpHasParams(Maps.newHashMap()); whenCoreAdminOpHasParams(Maps.newHashMap());
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.REQUESTSTATUS_OP.execute(callInfo));
CoreAdminOperation.REQUESTSTATUS_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected request-status execution to fail when no 'requestid' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testRejoinLeaderElectionUnexpectedFailuresResultIn500Exception() { public void testRejoinLeaderElectionUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.REJOINLEADERELECTION_OP.execute(callInfo));
CoreAdminOperation.REJOINLEADERELECTION_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.SERVER_ERROR.code);
fail("Expected rejoin-leader-election execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.SERVER_ERROR.code);
}
} }
@ -448,38 +326,26 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
public void testInvokeUnexpectedFailuresResultIn500Exception() { public void testInvokeUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.INVOKE_OP.execute(callInfo));
CoreAdminOperation.INVOKE_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected invoke execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testInvokeMissingClassParamResultsIn400SolrException() { public void testInvokeMissingClassParamResultsIn400SolrException() {
whenCoreAdminOpHasParams(Maps.newHashMap()); whenCoreAdminOpHasParams(Maps.newHashMap());
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.INVOKE_OP.execute(callInfo));
CoreAdminOperation.INVOKE_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected invoke to fail when no 'class' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testBackupUnexpectedFailuresResultIn500Exception() { public void testBackupUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.BACKUPCORE_OP.execute(callInfo));
CoreAdminOperation.BACKUPCORE_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected backup-core execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
@ -488,12 +354,8 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
params.put("name", "any-name-param"); params.put("name", "any-name-param");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.BACKUPCORE_OP.execute(callInfo));
CoreAdminOperation.BACKUPCORE_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected backup-core to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
@ -502,25 +364,17 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
params.put("core", "any-core-param"); params.put("core", "any-core-param");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.BACKUPCORE_OP.execute(callInfo));
CoreAdminOperation.BACKUPCORE_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected backup-core to fail when no 'name' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testRestoreUnexpectedFailuresResultIn500Exception() { public void testRestoreUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.RESTORECORE_OP.execute(callInfo));
CoreAdminOperation.RESTORECORE_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected restore-core execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
@ -529,12 +383,8 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
params.put("name", "any-name-param"); params.put("name", "any-name-param");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.RESTORECORE_OP.execute(callInfo));
CoreAdminOperation.RESTORECORE_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected restore-core to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
@ -543,25 +393,17 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
params.put("core", "any-core-param"); params.put("core", "any-core-param");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.RESTORECORE_OP.execute(callInfo));
CoreAdminOperation.RESTORECORE_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected restore-core to fail when no 'name' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testCreateSnapshotUnexpectedFailuresResultIn500Exception() { public void testCreateSnapshotUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.CREATESNAPSHOT_OP.execute(callInfo));
CoreAdminOperation.CREATESNAPSHOT_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected create-snapshot execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
@ -570,12 +412,8 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
params.put("commitName", "anyCommitName"); params.put("commitName", "anyCommitName");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.CREATESNAPSHOT_OP.execute(callInfo));
CoreAdminOperation.CREATESNAPSHOT_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected create-snapshot to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
@ -584,25 +422,17 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
params.put("core", "any-core-param"); params.put("core", "any-core-param");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.CREATESNAPSHOT_OP.execute(callInfo));
CoreAdminOperation.CREATESNAPSHOT_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected create-snapshot to fail when no 'commitName' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testDeleteSnapshotUnexpectedFailuresResultIn500Exception() { public void testDeleteSnapshotUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.DELETESNAPSHOT_OP.execute(callInfo));
CoreAdminOperation.DELETESNAPSHOT_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected delete-snapshot execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
@ -611,12 +441,8 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
params.put("commitName", "anyCommitName"); params.put("commitName", "anyCommitName");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.DELETESNAPSHOT_OP.execute(callInfo));
CoreAdminOperation.DELETESNAPSHOT_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected delete-snapshot to fail when no 'core' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
@ -625,37 +451,25 @@ public class CoreAdminOperationTest extends SolrTestCaseJ4 {
params.put("core", "any-core-param"); params.put("core", "any-core-param");
whenCoreAdminOpHasParams(params); whenCoreAdminOpHasParams(params);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.DELETESNAPSHOT_OP.execute(callInfo));
CoreAdminOperation.DELETESNAPSHOT_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected delete-snapshot to fail when no 'commitName' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
@Test @Test
public void testListSnapshotUnexpectedFailuresResultIn500Exception() { public void testListSnapshotUnexpectedFailuresResultIn500Exception() {
final Throwable cause = new NullPointerException(); final Throwable cause = new NullPointerException();
whenUnexpectedErrorOccursDuringCoreAdminOp(cause); whenUnexpectedErrorOccursDuringCoreAdminOp(cause);
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.LISTSNAPSHOTS_OP.execute(callInfo));
CoreAdminOperation.LISTSNAPSHOTS_OP.execute(callInfo); assertSolrExceptionWithCodeAndCause(ex, ErrorCode.SERVER_ERROR.code, cause);
fail("Expected list-snapshot execution to fail with exception.");
} catch (Exception thrown) {
assertSolrExceptionWithCodeAndCause(thrown, ErrorCode.SERVER_ERROR.code, cause);
}
} }
@Test @Test
public void testListSnapshotMissingCoreParamResultsIn400SolrException() { public void testListSnapshotMissingCoreParamResultsIn400SolrException() {
whenCoreAdminOpHasParams(Maps.newHashMap()); whenCoreAdminOpHasParams(Maps.newHashMap());
try { Exception ex = expectThrows(Exception.class, () -> CoreAdminOperation.LISTSNAPSHOTS_OP.execute(callInfo));
CoreAdminOperation.LISTSNAPSHOTS_OP.execute(callInfo); assertSolrExceptionWithCode(ex, ErrorCode.BAD_REQUEST.code);
fail("Expected list-snapshot to fail when no 'commitName' param present");
} catch (Exception thrown) {
assertSolrExceptionWithCode(thrown, ErrorCode.BAD_REQUEST.code);
}
} }
private void whenUnexpectedErrorOccursDuringCoreAdminOp(Throwable cause) { private void whenUnexpectedErrorOccursDuringCoreAdminOp(Throwable cause) {

View File

@ -84,17 +84,14 @@ public class CoreMergeIndexesAdminHandlerTest extends SolrTestCaseJ4 {
try { try {
dirFactory.fail = true; dirFactory.fail = true;
ignoreException(WRAPPED_FAILING_MSG); ignoreException(WRAPPED_FAILING_MSG);
SolrException e = expectThrows(SolrException.class, () -> {
SolrQueryResponse resp = new SolrQueryResponse(); admin.handleRequestBody
admin.handleRequestBody (req(CoreAdminParams.ACTION,
(req(CoreAdminParams.ACTION, CoreAdminParams.CoreAdminAction.MERGEINDEXES.toString(),
CoreAdminParams.CoreAdminAction.MERGEINDEXES.toString(), CoreAdminParams.CORE, "collection1",
CoreAdminParams.CORE, "collection1", CoreAdminParams.INDEX_DIR, workDir.getAbsolutePath()),
CoreAdminParams.INDEX_DIR, workDir.getAbsolutePath()), new SolrQueryResponse());
resp); });
fail("exception expected");
} catch (SolrException e) {
// expected if error handling properly
assertEquals(FailingDirectoryFactory.FailingDirectoryFactoryException.class, e.getCause().getClass()); assertEquals(FailingDirectoryFactory.FailingDirectoryFactoryException.class, e.getCause().getClass());
} finally { } finally {
unIgnoreException(WRAPPED_FAILING_MSG); unIgnoreException(WRAPPED_FAILING_MSG);

View File

@ -49,22 +49,12 @@ public class InfoHandlerTest extends SolrTestCaseJ4 {
rsp = handleRequest(infoHandler, "logging"); rsp = handleRequest(infoHandler, "logging");
assertNotNull(rsp.getValues().get("watcher")); assertNotNull(rsp.getValues().get("watcher"));
try {
rsp = handleRequest(infoHandler, "info");
fail("Should have failed with not found");
} catch(SolrException e) {
assertEquals(404, e.code());
}
try {
rsp = handleRequest(infoHandler, "");
fail("Should have failed with not found");
} catch(SolrException e) {
assertEquals(404, e.code());
}
SolrException e = expectThrows(SolrException.class, () -> handleRequest(infoHandler, "info"));
assertEquals(404, e.code());
e = expectThrows(SolrException.class, () -> handleRequest(infoHandler, ""));
assertEquals(404, e.code());
} }
@Test @Test

View File

@ -16,6 +16,11 @@
*/ */
package org.apache.solr.handler.admin; package org.apache.solr.handler.admin;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.solr.SolrJettyTestBase; import org.apache.solr.SolrJettyTestBase;
import org.apache.solr.client.solrj.ResponseParser; import org.apache.solr.client.solrj.ResponseParser;
import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrClient;
@ -28,11 +33,6 @@ import org.apache.solr.core.SolrCore;
import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.response.SolrQueryResponse;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.concurrent.atomic.AtomicBoolean;
/** /**
* Extend SolrJettyTestBase because the SOLR-2535 bug only manifested itself when * Extend SolrJettyTestBase because the SOLR-2535 bug only manifested itself when
* the {@link org.apache.solr.servlet.SolrDispatchFilter} is used, which isn't for embedded Solr use. * the {@link org.apache.solr.servlet.SolrDispatchFilter} is used, which isn't for embedded Solr use.
@ -44,17 +44,13 @@ public class ShowFileRequestHandlerTest extends SolrJettyTestBase {
createAndStartJetty(legacyExampleCollection1SolrHome()); createAndStartJetty(legacyExampleCollection1SolrHome());
} }
public void test404ViaHttp() throws SolrServerException, IOException { public void test404ViaHttp() throws Exception {
SolrClient client = getSolrClient(); SolrClient client = getSolrClient();
QueryRequest request = new QueryRequest(params("file", QueryRequest request = new QueryRequest(params("file",
"does-not-exist-404.txt")); "does-not-exist-404.txt"));
request.setPath("/admin/file"); request.setPath("/admin/file");
try { SolrException e = expectThrows(SolrException.class, () -> request.process(client));
QueryResponse resp = request.process(client); assertEquals(404, e.code());
fail("didn't get 404 exception");
} catch (SolrException e) {
assertEquals(404, e.code());
}
} }
public void test404Locally() throws Exception { public void test404Locally() throws Exception {
@ -62,21 +58,17 @@ public class ShowFileRequestHandlerTest extends SolrJettyTestBase {
// we need to test that executing the handler directly does not // we need to test that executing the handler directly does not
// throw an exception, just sets the exception on the response. // throw an exception, just sets the exception on the response.
initCore("solrconfig.xml", "schema.xml"); initCore("solrconfig.xml", "schema.xml");
try {
// bypass TestHarness since it will throw any exception found in the
// response.
SolrCore core = h.getCore();
SolrQueryResponse rsp = new SolrQueryResponse();
core.execute(core.getRequestHandler("/admin/file"),
req("file", "does-not-exist-404.txt"), rsp);
assertNotNull("no exception in response", rsp.getException());
assertTrue("wrong type of exception: " + rsp.getException().getClass(),
rsp.getException() instanceof SolrException);
assertEquals(404, ((SolrException)rsp.getException()).code());
} catch (Exception e) { // bypass TestHarness since it will throw any exception found in the
assertNull("Should not have caught an exception", e); // response.
} SolrCore core = h.getCore();
SolrQueryResponse rsp = new SolrQueryResponse();
core.execute(core.getRequestHandler("/admin/file"),
req("file", "does-not-exist-404.txt"), rsp);
assertNotNull("no exception in response", rsp.getException());
assertTrue("wrong type of exception: " + rsp.getException().getClass(),
rsp.getException() instanceof SolrException);
assertEquals(404, ((SolrException)rsp.getException()).code());
} }
public void testDirList() throws SolrServerException, IOException { public void testDirList() throws SolrServerException, IOException {

View File

@ -71,13 +71,11 @@ public class TestCollectionAPIs extends SolrTestCaseJ4 {
assertEquals("X1", x[0]); assertEquals("X1", x[0]);
assertEquals("X2", x[1]); assertEquals("X2", x[1]);
assertEquals("Y", m.get("y")); assertEquals("Y", m.get("y"));
try {
CollectionsHandler.copy(params.required(), null, "z");
fail("Error expected");
} catch (SolrException e) {
assertEquals(e.code(), SolrException.ErrorCode.BAD_REQUEST.code);
} SolrException e = expectThrows(SolrException.class, () -> {
CollectionsHandler.copy(params.required(), null, "z");
});
assertEquals(e.code(), SolrException.ErrorCode.BAD_REQUEST.code);
} }
public void testCommands() throws Exception { public void testCommands() throws Exception {
@ -208,12 +206,9 @@ public class TestCollectionAPIs extends SolrTestCaseJ4 {
static void assertErrorContains(final ApiBag apiBag, final String path, final SolrRequest.METHOD method, static void assertErrorContains(final ApiBag apiBag, final String path, final SolrRequest.METHOD method,
final String payload, final CoreContainer cc, String expectedErrorMsg) throws Exception { final String payload, final CoreContainer cc, String expectedErrorMsg) throws Exception {
try { RuntimeException e = expectThrows(RuntimeException.class, () -> makeCall(apiBag, path, method, payload, cc));
makeCall(apiBag, path, method, payload, cc); assertTrue("Expected exception with error message '" + expectedErrorMsg + "' but got: " + e.getMessage(),
fail("Expected exception"); e.getMessage().contains(expectedErrorMsg));
} catch (RuntimeException e) {
assertTrue("Expected exception with error message '" + expectedErrorMsg + "' but got: " + e.getMessage(), e.getMessage().contains(expectedErrorMsg));
}
} }
public static Pair<SolrQueryRequest, SolrQueryResponse> makeCall(final ApiBag apiBag, String path, public static Pair<SolrQueryRequest, SolrQueryResponse> makeCall(final ApiBag apiBag, String path,

View File

@ -16,6 +16,17 @@
*/ */
package org.apache.solr.handler.component; package org.apache.solr.handler.component;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.solr.SolrJettyTestBase; import org.apache.solr.SolrJettyTestBase;
import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrClient;
@ -33,17 +44,6 @@ import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class DistributedDebugComponentTest extends SolrJettyTestBase { public class DistributedDebugComponentTest extends SolrJettyTestBase {
private static SolrClient collection1; private static SolrClient collection1;
@ -395,14 +395,11 @@ public class DistributedDebugComponentTest extends SolrJettyTestBase {
query.set("distrib", "true"); query.set("distrib", "true");
query.setFields("id", "text"); query.setFields("id", "text");
query.set("shards", shard1 + "," + shard2 + "," + badShard); query.set("shards", shard1 + "," + shard2 + "," + badShard);
try {
ignoreException("Server refused connection"); // verify that the request would fail if shards.tolerant=false
// verify that the request would fail if shards.tolerant=false ignoreException("Server refused connection");
collection1.query(query); expectThrows(SolrException.class, () -> collection1.query(query));
fail("Expecting exception");
} catch (SolrException e) {
//expected
}
query.set(ShardParams.SHARDS_TOLERANT, "true"); query.set(ShardParams.SHARDS_TOLERANT, "true");
QueryResponse response = collection1.query(query); QueryResponse response = collection1.query(query);
assertTrue((Boolean)response.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY)); assertTrue((Boolean)response.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));

View File

@ -16,8 +16,6 @@
*/ */
package org.apache.solr.handler.component; package org.apache.solr.handler.component;
import static org.hamcrest.CoreMatchers.is;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
@ -32,6 +30,8 @@ import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.ModifiableSolrParams;
import org.junit.Before; import org.junit.Before;
import static org.hamcrest.CoreMatchers.is;
public class DistributedFacetExistsSmallTest extends BaseDistributedSearchTestCase { public class DistributedFacetExistsSmallTest extends BaseDistributedSearchTestCase {
public static final String FLD = "t_s"; public static final String FLD = "t_s";
@ -150,8 +150,8 @@ public class DistributedFacetExistsSmallTest extends BaseDistributedSearchTestCa
} else { } else {
params.set("f."+FLD+".facet.mincount", ""+(2+random().nextInt(100)) ); params.set("f."+FLD+".facet.mincount", ""+(2+random().nextInt(100)) );
} }
try { SolrException e = expectThrows(SolrException.class, () -> {
if (random().nextBoolean()) { if (random().nextBoolean()) {
setDistributedParams(params); setDistributedParams(params);
queryServer(params); queryServer(params);
@ -159,13 +159,11 @@ public class DistributedFacetExistsSmallTest extends BaseDistributedSearchTestCa
params.set("distrib", "false"); params.set("distrib", "false");
controlClient.query(params); controlClient.query(params);
} }
fail(); });
} catch(SolrException e) { // check that distr and single index search fail the same assertEquals(e.code(), ErrorCode.BAD_REQUEST.code);
assertEquals(e.code(), ErrorCode.BAD_REQUEST.code); assertTrue(e.getMessage().contains("facet.exists"));
assertTrue(e.getMessage().contains("facet.exists")); assertTrue(e.getMessage().contains("facet.mincount"));
assertTrue(e.getMessage().contains("facet.mincount")); assertTrue(e.getMessage().contains(FLD));
assertTrue(e.getMessage().contains(FLD));
}
} }
private void checkBasicRequest() throws Exception { private void checkBasicRequest() throws Exception {

View File

@ -85,32 +85,28 @@ public class SpellCheckComponentTest extends SolrTestCaseJ4 {
,"/spellcheck/suggestions/[0]=='brwn'" ,"/spellcheck/suggestions/[0]=='brwn'"
,"/spellcheck/suggestions/[1]/numFound==1" ,"/spellcheck/suggestions/[1]/numFound==1"
); );
try {
assertJQ(req("qt",rh, SpellCheckComponent.COMPONENT_NAME, "true", SpellingParams.SPELLCHECK_BUILD, "true", "q","lowerfilt:(this OR brwn)", expectThrows(Exception.class, () -> {
SpellingParams.SPELLCHECK_COUNT,"5", SpellingParams.SPELLCHECK_EXTENDED_RESULTS,"false", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST, "6") assertJQ(req("qt",rh, SpellCheckComponent.COMPONENT_NAME, "true", SpellingParams.SPELLCHECK_BUILD, "true", "q","lowerfilt:(this OR brwn)",
,"/spellcheck/suggestions/[1]/numFound==1" SpellingParams.SPELLCHECK_COUNT,"5", SpellingParams.SPELLCHECK_EXTENDED_RESULTS,"false", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST, "6")
); ,"/spellcheck/suggestions/[1]/numFound==1"
fail("there should have been no suggestions (6<7)"); );
} catch(Exception e) { });
//correctly threw exception
}
assertJQ(req("qt",rh, SpellCheckComponent.COMPONENT_NAME, "true", SpellingParams.SPELLCHECK_BUILD, "true", "q","lowerfilt:(this OR brwn)", assertJQ(req("qt",rh, SpellCheckComponent.COMPONENT_NAME, "true", SpellingParams.SPELLCHECK_BUILD, "true", "q","lowerfilt:(this OR brwn)",
"fq", "id:[0 TO 9]", /*returns 10, less selective */ "fq", "lowerfilt:th*", /* returns 8, most selective */ "fq", "id:[0 TO 9]", /*returns 10, less selective */ "fq", "lowerfilt:th*", /* returns 8, most selective */
SpellingParams.SPELLCHECK_COUNT,"5", SpellingParams.SPELLCHECK_EXTENDED_RESULTS,"false", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST, ".90") SpellingParams.SPELLCHECK_COUNT,"5", SpellingParams.SPELLCHECK_EXTENDED_RESULTS,"false", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST, ".90")
,"/spellcheck/suggestions/[0]=='brwn'" ,"/spellcheck/suggestions/[0]=='brwn'"
,"/spellcheck/suggestions/[1]/numFound==1" ,"/spellcheck/suggestions/[1]/numFound==1"
); );
try {
expectThrows(Exception.class, () -> {
assertJQ(req("qt",rh, SpellCheckComponent.COMPONENT_NAME, "true", SpellingParams.SPELLCHECK_BUILD, "true", "q","lowerfilt:(this OR brwn)", assertJQ(req("qt",rh, SpellCheckComponent.COMPONENT_NAME, "true", SpellingParams.SPELLCHECK_BUILD, "true", "q","lowerfilt:(this OR brwn)",
"fq", "id:[0 TO 9]", /*returns 10, less selective */ "fq", "lowerfilt:th*", /* returns 8, most selective */ "fq", "id:[0 TO 9]", /*returns 10, less selective */ "fq", "lowerfilt:th*", /* returns 8, most selective */
SpellingParams.SPELLCHECK_COUNT,"5", SpellingParams.SPELLCHECK_EXTENDED_RESULTS,"false", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST, ".80") SpellingParams.SPELLCHECK_COUNT,"5", SpellingParams.SPELLCHECK_EXTENDED_RESULTS,"false", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST, ".80")
,"/spellcheck/suggestions/[1]/numFound==1" ,"/spellcheck/suggestions/[1]/numFound==1"
); );
fail("there should have been no suggestions ((.8 * 8)<7)"); });
} catch(Exception e) {
//correctly threw exception
}
assertJQ(req("qt",rh, SpellCheckComponent.COMPONENT_NAME, "true", SpellingParams.SPELLCHECK_BUILD, "true", "q","lowerfilt:(this OR brwn)", assertJQ(req("qt",rh, SpellCheckComponent.COMPONENT_NAME, "true", SpellingParams.SPELLCHECK_BUILD, "true", "q","lowerfilt:(this OR brwn)",
"fq", "id:[0 TO 9]", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST_FQ, "id:[0 TO 9]", "fq", "id:[0 TO 9]", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST_FQ, "id:[0 TO 9]",
@ -118,16 +114,14 @@ public class SpellCheckComponentTest extends SolrTestCaseJ4 {
,"/spellcheck/suggestions/[0]=='brwn'" ,"/spellcheck/suggestions/[0]=='brwn'"
,"/spellcheck/suggestions/[1]/numFound==1" ,"/spellcheck/suggestions/[1]/numFound==1"
); );
try {
expectThrows(Exception.class, () -> {
assertJQ(req("qt",rh, SpellCheckComponent.COMPONENT_NAME, "true", SpellingParams.SPELLCHECK_BUILD, "true", "q","lowerfilt:(this OR brwn)", assertJQ(req("qt",rh, SpellCheckComponent.COMPONENT_NAME, "true", SpellingParams.SPELLCHECK_BUILD, "true", "q","lowerfilt:(this OR brwn)",
"fq", "id:[0 TO 9]", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST_FQ, "lowerfilt:th*", "fq", "id:[0 TO 9]", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST_FQ, "lowerfilt:th*",
SpellingParams.SPELLCHECK_COUNT,"5", SpellingParams.SPELLCHECK_EXTENDED_RESULTS,"false", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST, ".64") SpellingParams.SPELLCHECK_COUNT,"5", SpellingParams.SPELLCHECK_EXTENDED_RESULTS,"false", SpellingParams.SPELLCHECK_MAX_RESULTS_FOR_SUGGEST, ".64")
,"/spellcheck/suggestions/[1]/numFound==1" ,"/spellcheck/suggestions/[1]/numFound==1"
); );
fail("there should have been no suggestions ((.64 * 10)<7)"); });
} catch(Exception e) {
//correctly threw exception
}
} }
@Test @Test

View File

@ -279,9 +279,6 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
); );
} }
public void doTestMVFieldStatisticsResult(String f) throws Exception { public void doTestMVFieldStatisticsResult(String f) throws Exception {
assertU(adoc("id", "1", f, "-10", f, "-100", "active_s", "true")); assertU(adoc("id", "1", f, "-10", f, "-100", "active_s", "true"));
assertU(adoc("id", "2", f, "-20", f, "200", "active_s", "true")); assertU(adoc("id", "2", f, "-20", f, "200", "active_s", "true"));
@ -1085,8 +1082,7 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
for (String param : new String[] { for (String param : new String[] {
"foo_i", "{!func}field(\"foo_i\")", "{!lucene}_val_:\"field(foo_i)\"" "foo_i", "{!func}field(\"foo_i\")", "{!lucene}_val_:\"field(foo_i)\""
}) { }) {
SolrQueryRequest req = req(common); try (SolrQueryRequest req = req(common)){
try {
ResponseBuilder rb = new ResponseBuilder(req, new SolrQueryResponse(), components); ResponseBuilder rb = new ResponseBuilder(req, new SolrQueryResponse(), components);
StatsField sf = new StatsField(rb, param); StatsField sf = new StatsField(rb, param);
@ -1096,8 +1092,6 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
assertEquals("field name of: " + param, assertEquals("field name of: " + param,
"foo_i", sf.getSchemaField().getName()); "foo_i", sf.getSchemaField().getName());
} finally {
req.close();
} }
} }
@ -1105,8 +1099,7 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
for (String param : new String[] { for (String param : new String[] {
"{!lucene}foo_t:cow", "{!func}query($nested)", "{!field f=foo_t}cow", "{!lucene}foo_t:cow", "{!func}query($nested)", "{!field f=foo_t}cow",
}) { }) {
SolrQueryRequest req = req(common); try (SolrQueryRequest req = req(common)) {
try {
ResponseBuilder rb = new ResponseBuilder(req, new SolrQueryResponse(), components); ResponseBuilder rb = new ResponseBuilder(req, new SolrQueryResponse(), components);
StatsField sf = new StatsField(rb, param); StatsField sf = new StatsField(rb, param);
@ -1119,8 +1112,6 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
assertEquals("query of :" + param, assertEquals("query of :" + param,
new TermQuery(new Term("foo_t","cow")), new TermQuery(new Term("foo_t","cow")),
qvs.getQuery()); qvs.getQuery());
} finally {
req.close();
} }
} }
} }
@ -1792,27 +1783,25 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
ignoreException("hllPreHashed"); ignoreException("hllPreHashed");
for (SchemaField field : new SchemaField[] { foo_s, foo_i }) { for (SchemaField field : new SchemaField[] { foo_s, foo_i }) {
// whitebox - field // whitebox - field
try { SolrException ex = expectThrows(SolrException.class, () -> {
HllOptions.parseHllOptions(params("cardinality","true", "hllPreHashed", "true"), field); HllOptions.parseHllOptions(params("cardinality","true", "hllPreHashed", "true"), field);
fail("hllPreHashed should have failed for " + field.getName()); });
} catch (SolrException e) { assertTrue("MSG: " + ex.getMessage(),
assertTrue("MSG: " + e.getMessage(), ex.getMessage().contains("hllPreHashed is only supported with Long"));
e.getMessage().contains("hllPreHashed is only supported with Long"));
}
// blackbox - field // blackbox - field
assertQEx("hllPreHashed " + field.getName(), "hllPreHashed is only supported with Long", assertQEx("hllPreHashed " + field.getName(), "hllPreHashed is only supported with Long",
req(params("stats.field","{!cardinality=true hllPreHashed=true}" + field.getName()), req(params("stats.field","{!cardinality=true hllPreHashed=true}" + field.getName()),
baseParams), baseParams),
ErrorCode.BAD_REQUEST); ErrorCode.BAD_REQUEST);
} }
// whitebox - function // whitebox - function
try { SolrException ex = expectThrows(SolrException.class, () -> {
HllOptions.parseHllOptions(params("cardinality","true", "hllPreHashed", "true"), null); HllOptions.parseHllOptions(params("cardinality","true", "hllPreHashed", "true"), null);
fail("hllPreHashed should have failed for function"); });
} catch (SolrException e) { assertTrue("MSG: " + ex.getMessage(),
assertTrue("MSG: " + e.getMessage(), ex.getMessage().contains("hllPreHashed is only supported with Long"));
e.getMessage().contains("hllPreHashed is only supported with Long"));
}
// blackbox - function // blackbox - function
assertQEx("hllPreHashed function", "hllPreHashed is only supported with Long", assertQEx("hllPreHashed function", "hllPreHashed is only supported with Long",
req(params("stats.field","{!func cardinality=true hllPreHashed=true}sum(foo_i,foo_l)"), req(params("stats.field","{!func cardinality=true hllPreHashed=true}sum(foo_i,foo_l)"),
@ -1823,13 +1812,10 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
ignoreException("accuracy"); ignoreException("accuracy");
for (String invalid : new String[] { "-1", "1.1", "100" }) { for (String invalid : new String[] { "-1", "1.1", "100" }) {
// whitebox // whitebox
try { ex = expectThrows(SolrException.class, () -> {
Object trash = HllOptions.parseHllOptions(params("cardinality",invalid), foo_s); HllOptions.parseHllOptions(params("cardinality",invalid), foo_s);
fail("Should have failed: " + invalid); });
} catch (SolrException e) { assertTrue("MSG: " + ex.getMessage(), ex.getMessage().contains("number between 0 and 1"));
assertTrue("MSG: " + e.getMessage(),
e.getMessage().contains("number between 0 and 1"));
}
// blackbox // blackbox
assertQEx("cardinality="+invalid, "number between 0 and 1", assertQEx("cardinality="+invalid, "number between 0 and 1",
req(params("stats.field","{!cardinality="+invalid+"}foo_s"), req(params("stats.field","{!cardinality="+invalid+"}foo_s"),
@ -1840,14 +1826,11 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
ignoreException("hllLog2m must be"); ignoreException("hllLog2m must be");
for (int invalid : new int[] { HLL.MINIMUM_LOG2M_PARAM-1, HLL.MAXIMUM_LOG2M_PARAM+11 }) { for (int invalid : new int[] { HLL.MINIMUM_LOG2M_PARAM-1, HLL.MAXIMUM_LOG2M_PARAM+11 }) {
// whitebox // whitebox
try { ex = expectThrows(SolrException.class, () -> {
Object trash = HllOptions.parseHllOptions(params("cardinality","true", HllOptions.parseHllOptions(params("cardinality","true", "hllLog2m", ""+invalid), foo_s);
"hllLog2m", ""+invalid), foo_s); });
fail("Should have failed: " + invalid); assertTrue("MSG: " + ex.getMessage(), ex.getMessage().contains("hllLog2m must be"));
} catch (SolrException e) {
assertTrue("MSG: " + e.getMessage(),
e.getMessage().contains("hllLog2m must be"));
}
// blackbox // blackbox
assertQEx("hllLog2m="+invalid, "hllLog2m must be", assertQEx("hllLog2m="+invalid, "hllLog2m must be",
req(params("stats.field","{!cardinality=true hllLog2m="+invalid+"}foo_s"), req(params("stats.field","{!cardinality=true hllLog2m="+invalid+"}foo_s"),
@ -1858,14 +1841,13 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
ignoreException("hllRegwidth must be"); ignoreException("hllRegwidth must be");
for (int invalid : new int[] { HLL.MINIMUM_REGWIDTH_PARAM-1, HLL.MAXIMUM_REGWIDTH_PARAM+1 }) { for (int invalid : new int[] { HLL.MINIMUM_REGWIDTH_PARAM-1, HLL.MAXIMUM_REGWIDTH_PARAM+1 }) {
// whitebox // whitebox
try { ex = expectThrows(SolrException.class, () -> {
Object trash = HllOptions.parseHllOptions(params("cardinality","true", HllOptions.parseHllOptions(params("cardinality","true",
"hllRegwidth", ""+invalid), foo_s); "hllRegwidth", ""+invalid), foo_s);
fail("Should have failed: " + invalid); });
} catch (SolrException e) { assertTrue("MSG: " + ex.getMessage(),
assertTrue("MSG: " + e.getMessage(), ex.getMessage().contains("hllRegwidth must be"));
e.getMessage().contains("hllRegwidth must be"));
}
// blackbox // blackbox
assertQEx("hllRegwidth="+invalid, "hllRegwidth must be", assertQEx("hllRegwidth="+invalid, "hllRegwidth must be",
req(params("stats.field","{!cardinality=true hllRegwidth="+invalid+"}foo_s"), req(params("stats.field","{!cardinality=true hllRegwidth="+invalid+"}foo_s"),
@ -1881,19 +1863,16 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
String percentiles = "10.0,99.9,1.0,2.0,20.0,30.0,40.0,50.0,60.0,70.0,80.0,98.0,99.0"; String percentiles = "10.0,99.9,1.0,2.0,20.0,30.0,40.0,50.0,60.0,70.0,80.0,98.0,99.0";
List <String> percentilesList = StrUtils.splitSmart(percentiles, ','); List <String> percentilesList = StrUtils.splitSmart(percentiles, ',');
// test empty case // test empty case
SolrQueryRequest query = req("q", "*:*", "stats", "true", try (SolrQueryRequest query = req("q", "*:*", "stats", "true", "stats.field",
"stats.field", "{!percentiles='" + percentiles + "'}stat_f"); "{!percentiles='" + percentiles + "'}stat_f")) {
try {
SolrQueryResponse rsp = h.queryAndResponse(null, query); SolrQueryResponse rsp = h.queryAndResponse(null, query);
NamedList<Double> pout = extractPercentils(rsp, "stat_f"); NamedList<Double> pout = extractPercentils(rsp, "stat_f");
for (int i = 0; i < percentilesList.size(); i++) { for (int i = 0; i < percentilesList.size(); i++) {
// ensure exact order, but all values should be null (empty result set) // ensure exact order, but all values should be null (empty result set)
assertEquals(percentilesList.get(i), pout.getName(i)); assertEquals(percentilesList.get(i), pout.getName(i));
assertEquals(null, pout.getVal(i)); assertNull(pout.getVal(i));
} }
} finally {
query.close();
} }
int id = 0; int id = 0;
@ -1907,9 +1886,8 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
assertU(commit()); assertU(commit());
query = req("q", "*:*", "stats", "true", try (SolrQueryRequest query = req("q", "*:*", "stats", "true",
"stats.field", "{!percentiles='" + percentiles + "'}stat_f"); "stats.field", "{!percentiles='" + percentiles + "'}stat_f")) {
try {
SolrQueryResponse rsp = h.queryAndResponse(null, query); SolrQueryResponse rsp = h.queryAndResponse(null, query);
NamedList<Double> pout = extractPercentils(rsp, "stat_f"); NamedList<Double> pout = extractPercentils(rsp, "stat_f");
for (int i = 0; i < percentilesList.size(); i++) { for (int i = 0; i < percentilesList.size(); i++) {
@ -1918,19 +1896,14 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
assertEquals(Double.parseDouble(p), pout.getVal(i), 1.0D); assertEquals(Double.parseDouble(p), pout.getVal(i), 1.0D);
} }
} finally {
query.close();
} }
// test request for no percentiles // test request for no percentiles
query = req("q", "*:*", "stats", "true", try (SolrQueryRequest query = req("q", "*:*", "stats", "true",
"stats.field", "{!percentiles=''}stat_f"); "stats.field", "{!percentiles=''}stat_f")) {
try {
SolrQueryResponse rsp = h.queryAndResponse(null, query); SolrQueryResponse rsp = h.queryAndResponse(null, query);
NamedList<Double> pout = extractPercentils(rsp, "stat_f"); NamedList<Double> pout = extractPercentils(rsp, "stat_f");
assertNull(pout); assertNull(pout);
} finally {
query.close();
} }
// non-numeric types don't support percentiles // non-numeric types don't support percentiles
@ -1939,16 +1912,12 @@ public class StatsComponentTest extends SolrTestCaseJ4 {
assertU(commit()); assertU(commit());
query = req("q", "*:*", "stats", "true", try (SolrQueryRequest query = req("q", "*:*", "stats", "true",
"stats.field", "{!percentiles='" + percentiles + "'}stat_dt", "stats.field", "{!percentiles='" + percentiles + "'}stat_dt",
"stats.field", "{!percentiles='" + percentiles + "'}stat_s"); "stats.field", "{!percentiles='" + percentiles + "'}stat_s")) {
try {
SolrQueryResponse rsp = h.queryAndResponse(null, query); SolrQueryResponse rsp = h.queryAndResponse(null, query);
assertNull(extractPercentils(rsp, "stat_dt")); assertNull(extractPercentils(rsp, "stat_dt"));
assertNull(extractPercentils(rsp, "stat_s")); assertNull(extractPercentils(rsp, "stat_s"));
} finally {
query.close();
} }
} }

View File

@ -78,21 +78,12 @@ public class SuggestComponentContextFilterQueryTest extends SolrTestCaseJ4 {
@Test @Test
public void testBuildThrowsIllegalArgumentExceptionWhenContextIsConfiguredButNotImplemented() throws Exception { public void testBuildThrowsIllegalArgumentExceptionWhenContextIsConfiguredButNotImplemented() throws Exception {
try { IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> {
assertQ( h.query(req("qt", rh, SuggesterParams.SUGGEST_BUILD, "true",
req("qt", rh, SuggesterParams.SUGGEST_DICT, "suggest_context_filtering_not_implemented",
SuggesterParams.SUGGEST_BUILD, "true", SuggesterParams.SUGGEST_Q, "examp"));
SuggesterParams.SUGGEST_DICT, "suggest_context_filtering_not_implemented", });
SuggesterParams.SUGGEST_Q, "examp") assertThat(ex.getMessage(), is("this suggester doesn't support contexts"));
,
""
);
fail("Expecting exception because ");
} catch (RuntimeException e) {
Throwable cause = e.getCause();
assertTrue(cause instanceof IllegalArgumentException);
assertThat(cause.getMessage(), is("this suggester doesn't support contexts"));
}
// When not building, no exception is thrown // When not building, no exception is thrown
assertQ(req("qt", rh, assertQ(req("qt", rh,
@ -210,7 +201,7 @@ public class SuggestComponentContextFilterQueryTest extends SolrTestCaseJ4 {
SuggesterParams.SUGGEST_Q, "examp"), SuggesterParams.SUGGEST_Q, "examp"),
"//lst[@name='suggest']/lst[@name='suggest_blended_infix_suggester_string']/lst[@name='examp']/int[@name='numFound'][.='0']"); "//lst[@name='suggest']/lst[@name='suggest_blended_infix_suggester_string']/lst[@name='examp']/int[@name='numFound'][.='0']");
assertQ(req("qt", rh, assertQ(req("qt", rh,
SuggesterParams.SUGGEST_BUILD, "true", SuggesterParams.SUGGEST_BUILD, "true",
SuggesterParams.SUGGEST_DICT, "suggest_blended_infix_suggester_string", SuggesterParams.SUGGEST_DICT, "suggest_blended_infix_suggester_string",
SuggesterParams.SUGGEST_CONTEXT_FILTER_QUERY, "ctx4", SuggesterParams.SUGGEST_CONTEXT_FILTER_QUERY, "ctx4",

View File

@ -16,12 +16,6 @@
*/ */
package org.apache.solr.handler.component; package org.apache.solr.handler.component;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
@ -30,6 +24,7 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.impl.LBSolrClient; import org.apache.solr.client.solrj.impl.LBSolrClient;
import org.apache.solr.client.solrj.impl.PreferenceRule; import org.apache.solr.client.solrj.impl.PreferenceRule;
@ -45,6 +40,12 @@ import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
/** /**
* Tests specifying a custom ShardHandlerFactory * Tests specifying a custom ShardHandlerFactory
*/ */
@ -262,14 +263,12 @@ public class TestHttpShardHandlerFactory extends SolrTestCaseJ4 {
public void testWhitelistHostCheckerDisabled() throws Exception { public void testWhitelistHostCheckerDisabled() throws Exception {
WhitelistHostChecker checker = new WhitelistHostChecker("http://cde:8983", false); WhitelistHostChecker checker = new WhitelistHostChecker("http://cde:8983", false);
checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList(new String[]{"abc-1.com:8983/solr"})); checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList(new String[]{"abc-1.com:8983/solr"}));
try { WhitelistHostChecker whitelistHostChecker = new WhitelistHostChecker("http://cde:8983", true);
checker = new WhitelistHostChecker("http://cde:8983", true); SolrException e = expectThrows(SolrException.class, () -> {
checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList(new String[]{"http://abc-1.com:8983/solr"})); whitelistHostChecker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList("http://abc-1.com:8983/solr"));
fail("Expecting exception"); });
} catch (SolrException se) { assertThat(e.code(), is(SolrException.ErrorCode.FORBIDDEN.code));
assertThat(se.code(), is(SolrException.ErrorCode.FORBIDDEN.code));
}
} }
@Test @Test
@ -283,67 +282,60 @@ public class TestHttpShardHandlerFactory extends SolrTestCaseJ4 {
@Test @Test
public void testWhitelistHostCheckerSingleHost() { public void testWhitelistHostCheckerSingleHost() {
WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983/solr", true); WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983/solr", true);
checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList(new String[]{"http://abc-1.com:8983/solr"})); checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList("http://abc-1.com:8983/solr"));
} }
@Test @Test
public void testWhitelistHostCheckerMultipleHost() { public void testWhitelistHostCheckerMultipleHost() {
WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true); WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true);
checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList(new String[]{"http://abc-1.com:8983/solr"})); checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList("http://abc-1.com:8983/solr"));
} }
@Test @Test
public void testWhitelistHostCheckerMultipleHost2() { public void testWhitelistHostCheckerMultipleHost2() {
WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true); WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true);
checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList(new String[]{"http://abc-1.com:8983/solr", "http://abc-2.com:8983/solr"})); checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList("http://abc-1.com:8983/solr", "http://abc-2.com:8983/solr"));
} }
@Test @Test
public void testWhitelistHostCheckerNoProtocolInParameter() { public void testWhitelistHostCheckerNoProtocolInParameter() {
WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true); WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true);
checker.checkWhitelist("abc-1.com:8983/solr", Arrays.asList(new String[]{"abc-1.com:8983/solr"})); checker.checkWhitelist("abc-1.com:8983/solr", Arrays.asList("abc-1.com:8983/solr"));
} }
@Test @Test
public void testWhitelistHostCheckerNonWhitelistedHost1() { public void testWhitelistHostCheckerNonWhitelistedHost1() {
WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true); WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true);
try { SolrException e = expectThrows(SolrException.class, () -> {
checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList(new String[]{"http://abc-4.com:8983/solr"})); checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList("http://abc-4.com:8983/solr"));
fail("Expected exception"); });
} catch (SolrException e) { assertThat(e.code(), is(SolrException.ErrorCode.FORBIDDEN.code));
assertThat(e.code(), is(SolrException.ErrorCode.FORBIDDEN.code)); assertThat(e.getMessage(), containsString("not on the shards whitelist"));
assertThat(e.getMessage(), containsString("not on the shards whitelist"));
}
} }
@Test @Test
public void testWhitelistHostCheckerNonWhitelistedHost2() { public void testWhitelistHostCheckerNonWhitelistedHost2() {
WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true); WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true);
try { SolrException e = expectThrows(SolrException.class, () -> {
checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList(new String[]{"http://abc-1.com:8983/solr", "http://abc-4.com:8983/solr"})); checker.checkWhitelist("http://abc-1.com:8983/solr", Arrays.asList("http://abc-1.com:8983/solr", "http://abc-4.com:8983/solr"));
fail("Expected exception"); });
} catch (SolrException e) { assertThat(e.code(), is(SolrException.ErrorCode.FORBIDDEN.code));
assertThat(e.code(), is(SolrException.ErrorCode.FORBIDDEN.code)); assertThat(e.getMessage(), containsString("not on the shards whitelist"));
assertThat(e.getMessage(), containsString("not on the shards whitelist"));
}
} }
@Test @Test
public void testWhitelistHostCheckerNonWhitelistedHostHttps() { public void testWhitelistHostCheckerNonWhitelistedHostHttps() {
WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true); WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true);
checker.checkWhitelist("https://abc-1.com:8983/solr", Arrays.asList(new String[]{"https://abc-1.com:8983/solr"})); checker.checkWhitelist("https://abc-1.com:8983/solr", Arrays.asList("https://abc-1.com:8983/solr"));
} }
@Test @Test
public void testWhitelistHostCheckerInvalidUrl() { public void testWhitelistHostCheckerInvalidUrl() {
WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true); WhitelistHostChecker checker = new WhitelistHostChecker("http://abc-1.com:8983, http://abc-2.com:8983, http://abc-3.com:8983", true);
try { SolrException e = expectThrows(SolrException.class, () -> checker.checkWhitelist("abc_1", Arrays.asList("abc_1")));
checker.checkWhitelist("abc_1", Arrays.asList(new String[]{"abc_1"})); assertThat(e.code(), is(SolrException.ErrorCode.BAD_REQUEST.code));
fail("Expected exception"); assertThat(e.getMessage(), containsString("Invalid URL syntax"));
} catch (SolrException e) {
assertThat(e.code(), is(SolrException.ErrorCode.BAD_REQUEST.code));
assertThat(e.getMessage(), containsString("Invalid URL syntax"));
}
} }
@Test @Test

View File

@ -96,14 +96,10 @@ public class HighlighterTest extends SolrTestCaseJ4 {
"id", "1")); "id", "1"));
assertU(commit()); assertU(commit());
try { IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
assertQ("Tried PostingsSolrHighlighter but failed due to offsets not in postings", h.query(req("q", "long", "hl.method", "postings", "df", field, "hl", "true"));
req("q", "long", "hl.method", "postings", "df", field, "hl", "true")); });
fail("Did not encounter exception for no offsets"); assertTrue("Should warn no offsets", e.getMessage().contains("indexed without offsets"));
} catch (Exception e) {
assertTrue("Cause should be illegal argument", e.getCause() instanceof IllegalArgumentException);
assertTrue("Should warn no offsets", e.getCause().getMessage().contains("indexed without offsets"));
}
// note: the default schema.xml has no offsets in postings to test the PostingsHighlighter. Leave that for another // note: the default schema.xml has no offsets in postings to test the PostingsHighlighter. Leave that for another
// test class. // test class.
} }

View File

@ -114,13 +114,8 @@ public class TestPostingsSolrHighlighter extends SolrTestCaseJ4 {
public void testMisconfiguredField() { public void testMisconfiguredField() {
ignoreException("was indexed without offsets"); ignoreException("was indexed without offsets");
try { expectThrows(Exception.class, () ->
assertQ("should fail, has no offsets", h.query(req("q", "text2:document", "sort", "id asc", "hl", "true", "hl.fl", "text2")));
req("q", "text2:document", "sort", "id asc", "hl", "true", "hl.fl", "text2"));
fail();
} catch (Exception expected) {
// expected
}
resetExceptionIgnores(); resetExceptionIgnores();
} }

View File

@ -69,17 +69,12 @@ public class TestUnifiedSolrHighlighter extends SolrTestCaseJ4 {
} }
public void testImpossibleOffsetSource() { public void testImpossibleOffsetSource() {
try { IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
assertQ("impossible offset source", h.query(req("q", "text2:document", "hl.offsetSource", "postings",
req("q", "text2:document", "hl.offsetSource", "postings", "hl.fl", "text2", "sort", "id asc", "hl", "true"), "hl.fl", "text2", "sort", "id asc", "hl", "true"));
"count(//lst[@name='highlighting']/*)=2", });
"//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='<em>document</em> one'", assertTrue("Should warn no offsets", e.getMessage().contains("indexed without offsets"));
"//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second <em>document</em>'");
fail("Did not encounter exception for no offsets");
} catch (Exception e) {
assertTrue("Cause should be illegal argument", e.getCause() instanceof IllegalArgumentException);
assertTrue("Should warn no offsets", e.getCause().getMessage().contains("indexed without offsets"));
}
} }
public void testMultipleSnippetsReturned() { public void testMultipleSnippetsReturned() {

View File

@ -38,12 +38,8 @@ public class WrapperMergePolicyFactoryTest extends SolrTestCaseJ4 {
public void testFailsIfNoClassSpecifiedForWrappedPolicy() { public void testFailsIfNoClassSpecifiedForWrappedPolicy() {
final MergePolicyFactoryArgs args = new MergePolicyFactoryArgs(); final MergePolicyFactoryArgs args = new MergePolicyFactoryArgs();
args.add(WrapperMergePolicyFactory.WRAPPED_PREFIX, "foo"); args.add(WrapperMergePolicyFactory.WRAPPED_PREFIX, "foo");
try { expectThrows(IllegalArgumentException.class,
new DefaultingWrapperMergePolicyFactory(resourceLoader, args, null).getMergePolicy(); () -> new DefaultingWrapperMergePolicyFactory(resourceLoader, args, null).getMergePolicy());
fail("Should have failed when no 'class' specified for wrapped merge policy");
} catch (final IllegalArgumentException e) {
// Good!
}
} }
public void testProperlyInitializesWrappedMergePolicy() { public void testProperlyInitializesWrappedMergePolicy() {

View File

@ -17,18 +17,13 @@
package org.apache.solr.internal.csv; package org.apache.solr.internal.csv;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.solr.SolrTestCaseJ4;
public class CharBufferTest extends TestCase { public class CharBufferTest extends TestCase {
public void testCreate() { public void testCreate() {
CharBuffer cb = new CharBuffer(); CharBuffer cb = new CharBuffer();
assertEquals(0, cb.length()); assertEquals(0, cb.length());
try { SolrTestCaseJ4.expectThrows(IllegalArgumentException.class, () -> new CharBuffer(0));
cb = new CharBuffer(0);
fail("Should not be possible");
} catch(IllegalArgumentException e) {
// expected
}
cb = new CharBuffer(128); cb = new CharBuffer(128);
assertEquals(0, cb.length()); assertEquals(0, cb.length());
} }

View File

@ -93,12 +93,7 @@ public class SolrMetricManagerTest extends SolrTestCaseJ4 {
// this should simply skip existing names // this should simply skip existing names
metricManager.registerAll(registryName, mr, true); metricManager.registerAll(registryName, mr, true);
// this should produce error // this should produce error
try { expectThrows(IllegalArgumentException.class, () -> metricManager.registerAll(registryName, mr, false));
metricManager.registerAll(registryName, mr, false);
fail("registerAll with duplicate metric names should fail");
} catch (IllegalArgumentException e) {
// expected
}
} }
@Test @Test

View File

@ -490,22 +490,20 @@ public class SimpleFacetsTest extends SolrTestCaseJ4 {
"*[count(//lst[@name='airport_s1']/int)=1]", "*[count(//lst[@name='airport_s1']/int)=1]",
"//lst[@name='airport_s1']/int[@name='ams'][.='2']" "//lst[@name='airport_s1']/int[@name='ams'][.='2']"
); );
try { SolrException e = expectThrows(SolrException.class, () -> {
h.query( h.query(
req( req(
"q", "*:*", "q", "*:*",
"fq", "id_i1:[2000 TO 2004]", "fq", "id_i1:[2000 TO 2004]",
"group.facet", "true", "group.facet", "true",
"facet", "true", "facet", "true",
"facet.field", "airport_s1", "facet.field", "airport_s1",
"facet.prefix", "a" "facet.prefix", "a"
) )
); );
fail("Exception should have been thrown"); });
} catch (SolrException e) { assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code());
}
} }
@Test @Test

View File

@ -690,13 +690,9 @@ public class TestIntervalFaceting extends SolrTestCaseJ4 {
private void assertBadInterval(String fieldName, String intervalStr, String errorMsg) { private void assertBadInterval(String fieldName, String intervalStr, String errorMsg) {
SchemaField f = h.getCore().getLatestSchema().getField(fieldName); SchemaField f = h.getCore().getLatestSchema().getField(fieldName);
try { SyntaxError e = expectThrows(SyntaxError.class, () -> new FacetInterval(f, intervalStr, new ModifiableSolrParams()));
new FacetInterval(f, intervalStr, new ModifiableSolrParams()); assertTrue("Unexpected error message for interval String: " + intervalStr + ": " +
fail("Expecting SyntaxError for interval String: " + intervalStr); e.getMessage(), e.getMessage().contains(errorMsg));
} catch (SyntaxError e) {
assertTrue("Unexpected error message for interval String: " + intervalStr + ": " +
e.getMessage(), e.getMessage().contains(errorMsg));
}
} }
private void assertInterval(String fieldName, String intervalStr, long[] included, long[] lowerThanStart, long[] graterThanEnd) throws SyntaxError { private void assertInterval(String fieldName, String intervalStr, long[] included, long[] lowerThanStart, long[] graterThanEnd) throws SyntaxError {

View File

@ -16,6 +16,16 @@
*/ */
package org.apache.solr.request; package org.apache.solr.request;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.LuceneTestCase;
import org.apache.solr.SolrJettyTestBase; import org.apache.solr.SolrJettyTestBase;
@ -33,16 +43,6 @@ import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/** /**
* See SOLR-2854. * See SOLR-2854.
*/ */
@ -112,12 +112,8 @@ public class TestRemoteStreaming extends SolrJettyTestBase {
SolrQuery query = new SolrQuery(); SolrQuery query = new SolrQuery();
query.setQuery( "*:*" );//for anything query.setQuery( "*:*" );//for anything
query.add("stream.url",makeDeleteAllUrl()); query.add("stream.url",makeDeleteAllUrl());
try { SolrException se = expectThrows(SolrException.class, () -> getSolrClient().query(query));
getSolrClient().query(query); assertSame(ErrorCode.BAD_REQUEST, ErrorCode.getErrorCode(se.code()));
fail();
} catch (SolrException se) {
assertSame(ErrorCode.BAD_REQUEST, ErrorCode.getErrorCode(se.code()));
}
} }
/** Compose a url that if you get it, it will delete all the data. */ /** Compose a url that if you get it, it will delete all the data. */

View File

@ -118,13 +118,9 @@ public class TestStreamBody extends RestTestBase {
public String getPath() { //don't let superclass substitute qt for the path public String getPath() { //don't let superclass substitute qt for the path
return "/update"; return "/update";
} }
}; };
try { SolrException se = expectThrows(SolrException.class, () -> queryRequest.process(getSolrClient()));
queryRequest.process(getSolrClient()); assertTrue(se.getMessage(), se.getMessage().contains("Stream Body is disabled"));
fail();
} catch (SolrException se) {
assertTrue(se.getMessage(), se.getMessage().contains("Stream Body is disabled"));
}
enableStreamBody(true); enableStreamBody(true);
queryRequest.process(getSolrClient()); queryRequest.process(getSolrClient());
} }

View File

@ -22,12 +22,9 @@ import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.CoreContainer; import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrCore; import org.apache.solr.core.SolrCore;
import org.apache.solr.request.LocalSolrQueryRequest; import org.apache.solr.request.LocalSolrQueryRequest;
@ -106,13 +103,9 @@ public class ChangedSchemaMergeTest extends SolrTestCaseJ4 {
SchemaSimilarityFactory broken = new SchemaSimilarityFactory(); SchemaSimilarityFactory broken = new SchemaSimilarityFactory();
broken.init(new ModifiableSolrParams()); broken.init(new ModifiableSolrParams());
// NO INFORM // NO INFORM
try { IllegalStateException e = expectThrows(IllegalStateException.class, broken::getSimilarity);
Similarity bogus = broken.getSimilarity(); assertTrue("GOT: " + e.getMessage(),
fail("SchemaSimilarityFactory should have thrown IllegalStateException b/c inform not used"); e.getMessage().contains("SolrCoreAware.inform"));
} catch (IllegalStateException expected) {
assertTrue("GOT: " + expected.getMessage(),
expected.getMessage().contains("SolrCoreAware.inform"));
}
} }
@Test @Test

View File

@ -42,56 +42,45 @@ public class CopyFieldTest extends SolrTestCaseJ4 {
@Test @Test
public void testCopyFieldSchemaFieldSchemaField() { public void testCopyFieldSchemaFieldSchemaField() {
try { IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
new CopyField(new SchemaField("source", new TextField()), null); new CopyField(new SchemaField("source", new TextField()), null);
fail("CopyField failed with null SchemaField argument."); });
} catch (IllegalArgumentException e) { assertTrue(e.getLocalizedMessage().contains("can't be NULL"));
assertTrue(e.getLocalizedMessage().contains("can't be NULL"));
} e = expectThrows(IllegalArgumentException.class, () -> {
try {
new CopyField(null, new SchemaField("destination", new TextField())); new CopyField(null, new SchemaField("destination", new TextField()));
fail("CopyField failed with null SchemaField argument."); });
} catch (IllegalArgumentException e) { assertTrue(e.getLocalizedMessage().contains("can't be NULL"));
assertTrue(e.getLocalizedMessage().contains("can't be NULL"));
} e = expectThrows(IllegalArgumentException.class, () -> {
try {
new CopyField(null, null); new CopyField(null, null);
fail("CopyField failed with null SchemaField argument."); });
} catch (IllegalArgumentException e) { assertTrue(e.getLocalizedMessage().contains("can't be NULL"));
assertTrue(e.getLocalizedMessage().contains("can't be NULL"));
}
} }
@Test @Test
public void testCopyFieldSchemaFieldSchemaFieldInt() { public void testCopyFieldSchemaFieldSchemaFieldInt() {
try { IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
new CopyField(null, new CopyField(null, new SchemaField("destination", new TextField()), 1000);
new SchemaField("destination", new TextField()), 1000); });
fail("CopyField failed with null SchemaField argument."); assertTrue(e.getLocalizedMessage().contains("can't be NULL"));
} catch (IllegalArgumentException e) {
assertTrue(e.getLocalizedMessage().contains("can't be NULL")); e = expectThrows(IllegalArgumentException.class, () -> {
} new CopyField(new SchemaField("source", new TextField()), null, 1000);
try { });
new CopyField(new SchemaField("source", new TextField()), null, assertTrue(e.getLocalizedMessage().contains("can't be NULL"));
1000);
fail("CopyField failed with null SchemaField argument."); e = expectThrows(IllegalArgumentException.class, () -> {
} catch (IllegalArgumentException e) {
assertTrue(e.getLocalizedMessage().contains("can't be NULL"));
}
try {
new CopyField(null, null, 1000); new CopyField(null, null, 1000);
fail("CopyField failed with null SchemaField argument."); });
} catch (IllegalArgumentException e) { assertTrue(e.getLocalizedMessage().contains("can't be NULL"));
assertTrue(e.getLocalizedMessage().contains("can't be NULL"));
} e = expectThrows(IllegalArgumentException.class, () -> {
try {
new CopyField(new SchemaField("source", new TextField()), new CopyField(new SchemaField("source", new TextField()),
new SchemaField("destination", new TextField()), -1000); new SchemaField("destination", new TextField()), -1000);
fail("CopyField failed with negative length argument."); });
} catch (IllegalArgumentException e) { assertTrue(e.getLocalizedMessage().contains("can't have a negative value"));
assertTrue(e.getLocalizedMessage().contains(
"can't have a negative value"));
}
new CopyField(new SchemaField("source", new TextField()), new CopyField(new SchemaField("source", new TextField()),
new SchemaField("destination", new TextField()), CopyField.UNLIMITED); new SchemaField("destination", new TextField()), CopyField.UNLIMITED);
} }

View File

@ -468,13 +468,7 @@ public class CurrencyFieldTypeTest extends SolrTestCaseJ4 {
assertEquals("3.14,GBP", new CurrencyValue(314, "GBP").strValue()); assertEquals("3.14,GBP", new CurrencyValue(314, "GBP").strValue());
CurrencyValue currencyValue = new CurrencyValue(314, "XYZ"); CurrencyValue currencyValue = new CurrencyValue(314, "XYZ");
try { expectThrows(SolrException.class, currencyValue::strValue);
String string = currencyValue.strValue();
fail("Expected SolrException");
} catch (SolrException exception) {
} catch (Throwable throwable) {
fail("Expected SolrException");
}
} }
@Test @Test

View File

@ -225,32 +225,27 @@ public class PreAnalyzedFieldTest extends SolrTestCaseJ4 {
"]}"; "]}";
@Test @Test
public void testParsers() { public void testParsers() throws Exception {
PreAnalyzedField paf = new PreAnalyzedField(); PreAnalyzedField paf = new PreAnalyzedField();
// use Simple format // use Simple format
HashMap<String,String> args = new HashMap<>(); HashMap<String,String> args = new HashMap<>();
args.put(PreAnalyzedField.PARSER_IMPL, SimplePreAnalyzedParser.class.getName()); args.put(PreAnalyzedField.PARSER_IMPL, SimplePreAnalyzedParser.class.getName());
paf.init(h.getCore().getLatestSchema(), args); paf.init(h.getCore().getLatestSchema(), args);
try { {
Field f = (Field)paf.fromString(field, valid[0]); Field f = (Field)paf.fromString(field, valid[0]);
} catch (Exception e) {
fail("Should pass: '" + valid[0] + "', exception: " + e);
} }
// use JSON format // use JSON format
args.put(PreAnalyzedField.PARSER_IMPL, JsonPreAnalyzedParser.class.getName()); args.put(PreAnalyzedField.PARSER_IMPL, JsonPreAnalyzedParser.class.getName());
paf.init(h.getCore().getLatestSchema(), args); paf.init(h.getCore().getLatestSchema(), args);
try { expectThrows(Exception.class, () -> paf.fromString(field, valid[0]));
Field f = (Field)paf.fromString(field, valid[0]);
fail("Should fail JSON parsing: '" + valid[0] + "'");
} catch (Exception e) {
}
byte[] deadbeef = new byte[]{(byte)0xd, (byte)0xe, (byte)0xa, (byte)0xd, (byte)0xb, (byte)0xe, (byte)0xe, (byte)0xf}; byte[] deadbeef = new byte[]{(byte)0xd, (byte)0xe, (byte)0xa, (byte)0xd, (byte)0xb, (byte)0xe, (byte)0xe, (byte)0xf};
PreAnalyzedParser parser = new JsonPreAnalyzedParser(); PreAnalyzedParser parser = new JsonPreAnalyzedParser();
try {
{
Field f = (Field)paf.fromString(field, jsonValid); Field f = (Field)paf.fromString(field, jsonValid);
assertEquals(jsonValid, parser.toFormattedString(f)); assertEquals(jsonValid, parser.toFormattedString(f));
} catch (Exception e) {
fail("Should pass: '" + jsonValid + "', exception: " + e);
} }
} }
} }

View File

@ -110,13 +110,8 @@ public class SpatialRPTFieldTypeTest extends AbstractBadConfigTestBase {
} }
public void testJunkValuesForDistanceUnits() throws Exception { public void testJunkValuesForDistanceUnits() throws Exception {
try { Exception ex = expectThrows(Exception.class, () -> setupRPTField("rose", "true"));
setupRPTField("rose", "true"); assertTrue(ex.getMessage().startsWith("Must specify distanceUnits as one of"));
fail("Expected exception for bad value of distanceUnits.");
} catch (Exception ex) {
if(!ex.getMessage().startsWith("Must specify distanceUnits as one of"))
throw ex;
}
} }
public void testMaxDistErrConversion() throws Exception { public void testMaxDistErrConversion() throws Exception {
@ -217,12 +212,7 @@ public class SpatialRPTFieldTypeTest extends AbstractBadConfigTestBase {
assertEquals(wkt, out); assertEquals(wkt, out);
//assert fails GeoJSON //assert fails GeoJSON
try { expectThrows(SolrException.class, () -> ftype.parseShape("{\"type\":\"Point\",\"coordinates\":[1,2]}"));
ftype.parseShape("{\"type\":\"Point\",\"coordinates\":[1,2]}");
fail("Should not parse GeoJSON if told format is WKT");
} catch (SolrException e) {// expected
System.out.println(e);
}
} }

View File

@ -15,6 +15,15 @@
* limitations under the License. * limitations under the License.
*/ */
package org.apache.solr.schema; package org.apache.solr.schema;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.UnaryOperator;
import org.apache.solr.SolrTestCaseJ4.SuppressSSL; import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient; import org.apache.solr.client.solrj.impl.CloudSolrClient;
@ -31,14 +40,6 @@ import org.restlet.ext.servlet.ServerServlet;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.UnaryOperator;
/** /**
* Tests a schemaless collection configuration with SolrCloud * Tests a schemaless collection configuration with SolrCloud
*/ */
@ -139,8 +140,6 @@ public class TestCloudSchemaless extends AbstractFullDistribZkTestBase {
// Now, let's ensure that writing the same field with two different types fails // Now, let's ensure that writing the same field with two different types fails
int failTrials = 50; int failTrials = 50;
for (int i = 0; i < failTrials; ++i) { for (int i = 0; i < failTrials; ++i) {
List<SolrInputDocument> docs = null;
SolrInputDocument intDoc = new SolrInputDocument(); SolrInputDocument intDoc = new SolrInputDocument();
intDoc.addField("id", Long.toHexString(Double.doubleToLongBits(random().nextDouble()))); intDoc.addField("id", Long.toHexString(Double.doubleToLongBits(random().nextDouble())));
intDoc.addField("longOrDateField" + i, "123"); intDoc.addField("longOrDateField" + i, "123");
@ -150,28 +149,20 @@ public class TestCloudSchemaless extends AbstractFullDistribZkTestBase {
dateDoc.addField("longOrDateField" + i, "1995-12-31T23:59:59Z"); dateDoc.addField("longOrDateField" + i, "1995-12-31T23:59:59Z");
// randomize the order of the docs // randomize the order of the docs
if (random().nextBoolean()) { List<SolrInputDocument> docs = random().nextBoolean()? Arrays.asList(intDoc, dateDoc): Arrays.asList(dateDoc, intDoc);
docs = Arrays.asList(intDoc, dateDoc);
} else {
docs = Arrays.asList(dateDoc, intDoc);
}
try { SolrException ex = expectThrows(SolrException.class, () -> {
randomClient.add(docs); randomClient.add(docs);
randomClient.commit(); randomClient.commit();
fail("Expected Bad Request Exception"); });
} catch (SolrException se) { assertEquals(ErrorCode.BAD_REQUEST, ErrorCode.getErrorCode(ex.code()));
assertEquals(ErrorCode.BAD_REQUEST, ErrorCode.getErrorCode(se.code()));
}
try { ex = expectThrows(SolrException.class, () -> {
CloudSolrClient cloudSolrClient = getCommonCloudSolrClient(); CloudSolrClient cloudSolrClient = getCommonCloudSolrClient();
cloudSolrClient.add(docs); cloudSolrClient.add(docs);
cloudSolrClient.commit(); cloudSolrClient.commit();
fail("Expected Bad Request Exception"); });
} catch (SolrException ex) { assertEquals(ErrorCode.BAD_REQUEST, ErrorCode.getErrorCode(ex.code()));
assertEquals(ErrorCode.BAD_REQUEST, ErrorCode.getErrorCode((ex).code()));
}
} }
} }
} }

View File

@ -201,30 +201,18 @@ public class BasicAuthIntegrationTest extends SolrCloudAuthTestCase {
CollectionAdminRequest.Reload reload = CollectionAdminRequest.reloadCollection(COLLECTION); CollectionAdminRequest.Reload reload = CollectionAdminRequest.reloadCollection(COLLECTION);
try (HttpSolrClient solrClient = getHttpSolrClient(baseUrl)) { try (HttpSolrClient solrClient = getHttpSolrClient(baseUrl)) {
try { expectThrows(HttpSolrClient.RemoteSolrException.class, () -> solrClient.request(reload));
rsp = solrClient.request(reload);
fail("must have failed");
} catch (HttpSolrClient.RemoteSolrException e) {
}
reload.setMethod(SolrRequest.METHOD.POST); reload.setMethod(SolrRequest.METHOD.POST);
try { expectThrows(HttpSolrClient.RemoteSolrException.class, () -> solrClient.request(reload));
rsp = solrClient.request(reload);
fail("must have failed");
} catch (HttpSolrClient.RemoteSolrException e) {
}
} }
cluster.getSolrClient().request(CollectionAdminRequest.reloadCollection(COLLECTION) cluster.getSolrClient().request(CollectionAdminRequest.reloadCollection(COLLECTION)
.setBasicAuthCredentials("harry", "HarryIsUberCool")); .setBasicAuthCredentials("harry", "HarryIsUberCool"));
try { expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
cluster.getSolrClient().request(CollectionAdminRequest.reloadCollection(COLLECTION) cluster.getSolrClient().request(CollectionAdminRequest.reloadCollection(COLLECTION)
.setBasicAuthCredentials("harry", "Cool12345")); .setBasicAuthCredentials("harry", "Cool12345"));
fail("This should not succeed"); });
} catch (HttpSolrClient.RemoteSolrException e) { assertAuthMetricsMinimums(14, 5, 8, 1, 0, 0);
assertAuthMetricsMinimums(14, 5, 8, 1, 0, 0);
}
executeCommand(baseUrl + authzPrefix, cl,"{set-permission : { name : update , role : admin}}", "harry", "HarryIsUberCool"); executeCommand(baseUrl + authzPrefix, cl,"{set-permission : { name : update , role : admin}}", "harry", "HarryIsUberCool");
@ -242,10 +230,9 @@ public class BasicAuthIntegrationTest extends SolrCloudAuthTestCase {
delQuery.setBasicAuthCredentials("harry","HarryIsUberCool"); delQuery.setBasicAuthCredentials("harry","HarryIsUberCool");
delQuery.process(aNewClient, COLLECTION);//this should succeed delQuery.process(aNewClient, COLLECTION);//this should succeed
try { try {
delQuery = new UpdateRequest().deleteByQuery("*:*"); HttpSolrClient.RemoteSolrException e = expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
delQuery.process(aNewClient, COLLECTION); new UpdateRequest().deleteByQuery("*:*").process(aNewClient, COLLECTION);
fail("This should not have succeeded without credentials"); });
} catch (HttpSolrClient.RemoteSolrException e) {
assertTrue(e.getMessage().contains("Unauthorized request")); assertTrue(e.getMessage().contains("Unauthorized request"));
} finally { } finally {
aNewClient.close(); aNewClient.close();
@ -377,9 +364,7 @@ public class BasicAuthIntegrationTest extends SolrCloudAuthTestCase {
ArrayList<Replica> l = new ArrayList<>(); ArrayList<Replica> l = new ArrayList<>();
for (Slice slice : coll.getSlices()) { for (Slice slice : coll.getSlices()) {
for (Replica replica : slice.getReplicas()) { l.addAll(slice.getReplicas());
l.add(replica);
}
} }
Collections.shuffle(l, random); Collections.shuffle(l, random);
return l.isEmpty() ? null : l.get(0); return l.isEmpty() ? null : l.get(0);

View File

@ -72,10 +72,7 @@ public class TestAuthorizationFramework extends AbstractFullDistribZkTestBase {
// This user is blacklisted in the mock. The request should return a 403. // This user is blacklisted in the mock. The request should return a 403.
params.add("uname", "user1"); params.add("uname", "user1");
try { expectThrows(Exception.class, () -> cloudClient.query(params));
cloudClient.query(params);
fail("This should have failed");
} catch (Exception e) {}
log.info("Ending test"); log.info("Ending test");
} finally { } finally {
MockAuthorizationPlugin.denyUsers.clear(); MockAuthorizationPlugin.denyUsers.clear();

View File

@ -43,8 +43,6 @@ import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import junit.framework.Assert;
public class TestDelegationWithHadoopAuth extends SolrCloudTestCase { public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {
protected static final int NUM_SERVERS = 2; protected static final int NUM_SERVERS = 2;
protected static final String USER_1 = "foo"; protected static final String USER_1 = "foo";
@ -381,23 +379,17 @@ public class TestDelegationWithHadoopAuth extends SolrCloudTestCase {
ss.close(); ss.close();
} }
ss = new HttpSolrClient.Builder(primarySolrClient.getBaseURL().toString()) try (HttpSolrClient client = new HttpSolrClient.Builder(primarySolrClient.getBaseURL())
.withKerberosDelegationToken(token) .withKerberosDelegationToken(token)
.withResponseParser(primarySolrClient.getParser()) .withResponseParser(primarySolrClient.getParser())
.build(); .build()) {
try {
// test with token via property // test with token via property
doSolrRequest(ss, request, HttpStatus.SC_OK); doSolrRequest(client, request, HttpStatus.SC_OK);
// test with param -- should throw an exception // test with param -- should throw an exception
ModifiableSolrParams tokenParam = new ModifiableSolrParams(); ModifiableSolrParams tokenParam = new ModifiableSolrParams();
tokenParam.set("delegation", "invalidToken"); tokenParam.set("delegation", "invalidToken");
try { expectThrows(IllegalArgumentException.class, () -> doSolrRequest(client, getAdminRequest(tokenParam), ErrorCode.FORBIDDEN.code));
doSolrRequest(ss, getAdminRequest(tokenParam), ErrorCode.FORBIDDEN.code);
Assert.fail("Expected exception");
} catch (IllegalArgumentException ex) {}
} finally {
ss.close();
} }
} }
} }

View File

@ -16,9 +16,6 @@
*/ */
package org.apache.solr.security.hadoop; package org.apache.solr.security.hadoop;
import static org.apache.solr.security.HttpParamDelegationTokenPlugin.USER_PARAM;
import static org.apache.solr.security.hadoop.ImpersonationUtil.*;
import java.net.InetAddress; import java.net.InetAddress;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.Files; import java.nio.file.Files;
@ -40,6 +37,11 @@ import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import static org.apache.solr.security.HttpParamDelegationTokenPlugin.USER_PARAM;
import static org.apache.solr.security.hadoop.ImpersonationUtil.getExpectedGroupExMsg;
import static org.apache.solr.security.hadoop.ImpersonationUtil.getExpectedHostExMsg;
import static org.apache.solr.security.hadoop.ImpersonationUtil.getProxyRequest;
public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase { public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {
protected static final int NUM_SERVERS = 2; protected static final int NUM_SERVERS = 2;
private static final boolean defaultAddRequestHeadersToContext = private static final boolean defaultAddRequestHeadersToContext =
@ -97,10 +99,8 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {
@Test @Test
public void testProxyNoConfigGroups() throws Exception { public void testProxyNoConfigGroups() throws Exception {
try (SolrClient solrClient = newSolrClient()) { try (SolrClient solrClient = newSolrClient()) {
solrClient.request(getProxyRequest("noGroups","bar")); HttpSolrClient.RemoteSolrException ex = expectThrows(HttpSolrClient.RemoteSolrException.class,
fail("Expected RemoteSolrException"); () -> solrClient.request(getProxyRequest("noGroups","bar")));
}
catch (HttpSolrClient.RemoteSolrException ex) {
assertTrue(ex.getLocalizedMessage(), ex.getMessage().contains(getExpectedGroupExMsg("noGroups", "bar"))); assertTrue(ex.getLocalizedMessage(), ex.getMessage().contains(getExpectedGroupExMsg("noGroups", "bar")));
} }
} }
@ -108,10 +108,8 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {
@Test @Test
public void testProxyWrongHost() throws Exception { public void testProxyWrongHost() throws Exception {
try (SolrClient solrClient = newSolrClient()) { try (SolrClient solrClient = newSolrClient()) {
solrClient.request(getProxyRequest("wrongHost","bar")); HttpSolrClient.RemoteSolrException ex = expectThrows(HttpSolrClient.RemoteSolrException.class,
fail("Expected RemoteSolrException"); () -> solrClient.request(getProxyRequest("wrongHost","bar")));
}
catch (HttpSolrClient.RemoteSolrException ex) {
assertTrue(ex.getMessage().contains(getExpectedHostExMsg("wrongHost"))); assertTrue(ex.getMessage().contains(getExpectedHostExMsg("wrongHost")));
} }
} }
@ -119,10 +117,8 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {
@Test @Test
public void testProxyNoConfigHosts() throws Exception { public void testProxyNoConfigHosts() throws Exception {
try (SolrClient solrClient = newSolrClient()) { try (SolrClient solrClient = newSolrClient()) {
solrClient.request(getProxyRequest("noHosts","bar")); HttpSolrClient.RemoteSolrException ex = expectThrows(HttpSolrClient.RemoteSolrException.class,
fail("Expected RemoteSolrException"); () -> solrClient.request(getProxyRequest("noHosts","bar")));
}
catch (HttpSolrClient.RemoteSolrException ex) {
assertTrue(ex.getMessage().contains(getExpectedHostExMsg("noHosts"))); assertTrue(ex.getMessage().contains(getExpectedHostExMsg("noHosts")));
} }
} }
@ -139,10 +135,8 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {
public void testProxyInvalidProxyUser() throws Exception { public void testProxyInvalidProxyUser() throws Exception {
try (SolrClient solrClient = newSolrClient()) { try (SolrClient solrClient = newSolrClient()) {
// wrong direction, should fail // wrong direction, should fail
solrClient.request(getProxyRequest("bar","anyHostAnyUser")); HttpSolrClient.RemoteSolrException ex = expectThrows(HttpSolrClient.RemoteSolrException.class,
fail("Expected RemoteSolrException"); () -> solrClient.request(getProxyRequest("bar","anyHostAnyUser")));
}
catch (HttpSolrClient.RemoteSolrException ex) {
assertTrue(ex.getMessage().contains(getExpectedGroupExMsg("bar", "anyHostAnyUser"))); assertTrue(ex.getMessage().contains(getExpectedGroupExMsg("bar", "anyHostAnyUser")));
} }
} }
@ -166,10 +160,8 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {
@Test @Test
public void testProxyInvalidGroup() throws Exception { public void testProxyInvalidGroup() throws Exception {
try (SolrClient solrClient = newSolrClient()) { try (SolrClient solrClient = newSolrClient()) {
solrClient.request(getProxyRequest("bogusGroup","bar")); HttpSolrClient.RemoteSolrException ex = expectThrows(HttpSolrClient.RemoteSolrException.class,
fail("Expected RemoteSolrException"); () -> solrClient.request(getProxyRequest("bogusGroup","bar")));
}
catch (HttpSolrClient.RemoteSolrException ex) {
assertTrue(ex.getMessage().contains(getExpectedGroupExMsg("bogusGroup", "bar"))); assertTrue(ex.getMessage().contains(getExpectedGroupExMsg("bogusGroup", "bar")));
} }
} }
@ -177,11 +169,7 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {
@Test @Test
public void testProxyNullProxyUser() throws Exception { public void testProxyNullProxyUser() throws Exception {
try (SolrClient solrClient = newSolrClient()) { try (SolrClient solrClient = newSolrClient()) {
solrClient.request(getProxyRequest("","bar")); expectThrows(HttpSolrClient.RemoteSolrException.class, () -> solrClient.request(getProxyRequest("","bar")));
fail("Expected RemoteSolrException");
}
catch (HttpSolrClient.RemoteSolrException ex) {
// this exception is specific to our implementation, don't check a specific message.
} }
} }
@ -199,15 +187,12 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {
// try a command to each node, one of them must be forwarded // try a command to each node, one of them must be forwarded
for (JettySolrRunner jetty : cluster.getJettySolrRunners()) { for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
HttpSolrClient client = try (HttpSolrClient client =
new HttpSolrClient.Builder(jetty.getBaseUrl().toString() + "/" + collectionName).build(); new HttpSolrClient.Builder(jetty.getBaseUrl().toString() + "/" + collectionName).build()) {
try {
ModifiableSolrParams params = new ModifiableSolrParams(); ModifiableSolrParams params = new ModifiableSolrParams();
params.set("q", "*:*"); params.set("q", "*:*");
params.set(USER_PARAM, "user"); params.set(USER_PARAM, "user");
client.query(params); client.query(params);
} finally {
client.close();
} }
} }
} }

View File

@ -23,9 +23,7 @@ import org.apache.solr.SolrTestCaseJ4;
import org.junit.BeforeClass; import org.junit.BeforeClass;
public class DirectSolrConnectionTest extends SolrTestCaseJ4 {
public class DirectSolrConnectionTest extends SolrTestCaseJ4
{
@BeforeClass @BeforeClass
@ -52,13 +50,8 @@ public class DirectSolrConnectionTest extends SolrTestCaseJ4
assertTrue( got.indexOf( "<str name=\"echoParams\">explicit</str>" ) > 5 ); assertTrue( got.indexOf( "<str name=\"echoParams\">explicit</str>" ) > 5 );
// It should throw an exception for unknown handler // It should throw an exception for unknown handler
try { expectThrows(Exception.class, () -> direct.request( "/path to nonexistang thingy!!", null ));
direct.request( "/path to nonexistang thingy!!", null );
fail( "should throw an exception" );
}
catch( Exception ex ){}
} }

View File

@ -16,6 +16,9 @@
*/ */
package org.apache.solr.servlet; package org.apache.solr.servlet;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
@ -31,10 +34,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Vector; import java.util.Vector;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.SolrTestCaseJ4;
@ -45,17 +44,20 @@ import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.ContentStream; import org.apache.solr.common.util.ContentStream;
import org.apache.solr.core.SolrCore; import org.apache.solr.core.SolrCore;
import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.servlet.SolrRequestParsers.MultipartRequestParser;
import org.apache.solr.servlet.SolrRequestParsers.FormDataRequestParser; import org.apache.solr.servlet.SolrRequestParsers.FormDataRequestParser;
import org.apache.solr.servlet.SolrRequestParsers.MultipartRequestParser;
import org.apache.solr.servlet.SolrRequestParsers.RawRequestParser; import org.apache.solr.servlet.SolrRequestParsers.RawRequestParser;
import org.apache.solr.servlet.SolrRequestParsers.StandardRequestParser; import org.apache.solr.servlet.SolrRequestParsers.StandardRequestParser;
import static org.mockito.Mockito.*;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class SolrRequestParserTest extends SolrTestCaseJ4 { public class SolrRequestParserTest extends SolrTestCaseJ4 {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@ -208,12 +210,7 @@ public class SolrRequestParserTest extends SolrTestCaseJ4 {
"=hallo" // missing key "=hallo" // missing key
}; };
for (String s : invalid) { for (String s : invalid) {
try { expectThrows(SolrException.class, () -> SolrRequestParsers.parseQueryString(s));
SolrRequestParsers.parseQueryString(s);
fail("Should throw SolrException");
} catch (SolrException se) {
// pass
}
} }
} }
@ -327,15 +324,12 @@ public class SolrRequestParserTest extends SolrTestCaseJ4 {
when(request.getMethod()).thenReturn("POST"); when(request.getMethod()).thenReturn("POST");
when(request.getInputStream()).thenReturn(new ByteServletInputStream(large.toString().getBytes(StandardCharsets.US_ASCII))); when(request.getInputStream()).thenReturn(new ByteServletInputStream(large.toString().getBytes(StandardCharsets.US_ASCII)));
FormDataRequestParser formdata = new FormDataRequestParser( limitKBytes ); FormDataRequestParser formdata = new FormDataRequestParser( limitKBytes );
try { SolrException e = expectThrows(SolrException.class, () -> {
formdata.parseParamsAndFillStreams(request, new ArrayList<ContentStream>()); formdata.parseParamsAndFillStreams(request, new ArrayList<>());
fail("should throw SolrException"); });
} catch (SolrException solre) { assertTrue(e.getMessage().contains("upload limit"));
assertTrue(solre.getMessage().contains("upload limit")); assertEquals(400, e.code());
assertEquals(400, solre.code());
}
verify(request).getInputStream(); verify(request).getInputStream();
} }
@ -363,14 +357,12 @@ public class SolrRequestParserTest extends SolrTestCaseJ4 {
} }
}); });
FormDataRequestParser formdata = new FormDataRequestParser( 2048 ); FormDataRequestParser formdata = new FormDataRequestParser( 2048 );
try { SolrException e = expectThrows(SolrException.class, () -> {
formdata.parseParamsAndFillStreams(request, new ArrayList<ContentStream>()); formdata.parseParamsAndFillStreams(request, new ArrayList<>());
fail("should throw SolrException"); });
} catch (SolrException solre) { assertTrue(e.getMessage().startsWith("Solr requires that request parameters"));
assertTrue(solre.getMessage().startsWith("Solr requires that request parameters")); assertEquals(500, e.code());
assertEquals(500, solre.code());
}
verify(request).getInputStream(); verify(request).getInputStream();
} }
@ -382,14 +374,12 @@ public class SolrRequestParserTest extends SolrTestCaseJ4 {
// we emulate Tomcat that throws IllegalStateException when parameters were parsed before: // we emulate Tomcat that throws IllegalStateException when parameters were parsed before:
when(request.getInputStream()).thenThrow(new IllegalStateException()); when(request.getInputStream()).thenThrow(new IllegalStateException());
FormDataRequestParser formdata = new FormDataRequestParser( 2048 ); FormDataRequestParser formdata = new FormDataRequestParser( 2048 );
try { SolrException e = expectThrows(SolrException.class, () -> {
formdata.parseParamsAndFillStreams(request, new ArrayList<ContentStream>()); formdata.parseParamsAndFillStreams(request, new ArrayList<>());
fail("should throw SolrException"); });
} catch (SolrException solre) { assertTrue(e.getMessage().startsWith("Solr requires that request parameters"));
assertTrue(solre.getMessage().startsWith("Solr requires that request parameters")); assertEquals(500, e.code());
assertEquals(500, solre.code());
}
verify(request).getInputStream(); verify(request).getInputStream();
} }
@ -432,10 +422,6 @@ public class SolrRequestParserTest extends SolrTestCaseJ4 {
} }
} }
@Test @Test
public void testAutoDetect() throws Exception { public void testAutoDetect() throws Exception {
String curl = "curl/7.30.0"; String curl = "curl/7.30.0";

View File

@ -60,12 +60,7 @@ public class ConjunctionSolrSpellCheckerTest extends SolrTestCase {
cssc.addChecker(checker1); cssc.addChecker(checker1);
cssc.addChecker(checker2); cssc.addChecker(checker2);
try { expectThrows(IllegalArgumentException.class, () -> cssc.addChecker(checker3));
cssc.addChecker(checker3);
fail("ConjunctionSolrSpellChecker should have thrown an exception about non-identical StringDistances.");
} catch (IllegalArgumentException iae) {
// correct behavior
}
} }
static class MockSolrSpellChecker extends SolrSpellChecker { static class MockSolrSpellChecker extends SolrSpellChecker {

View File

@ -154,11 +154,7 @@ public class HdfsDirectoryTest extends SolrTestCaseJ4 {
private void testEof(String name, Directory directory, long length) throws IOException { private void testEof(String name, Directory directory, long length) throws IOException {
IndexInput input = directory.openInput(name, new IOContext()); IndexInput input = directory.openInput(name, new IOContext());
input.seek(length); input.seek(length);
try { expectThrows(Exception.class, input::readByte);
input.readByte();
fail("should throw eof");
} catch (Exception e) {
}
} }
@Test @Test

View File

@ -906,12 +906,7 @@ public class AddBlockUpdateTest extends SolrTestCaseJ4 {
} }
private void assertFailedBlockU(final String msg) { private void assertFailedBlockU(final String msg) {
try { expectThrows(Exception.class, () -> assertBlockU(msg, "1"));
assertBlockU(msg, "1");
fail("expecting fail");
} catch (Exception e) {
// gotcha
}
} }
private void assertBlockU(final String msg, String expected) { private void assertBlockU(final String msg, String expected) {
@ -936,4 +931,3 @@ public class AddBlockUpdateTest extends SolrTestCaseJ4 {
} }
} }
} }

View File

@ -27,7 +27,6 @@ import org.junit.Test;
*/ */
public class AnalysisErrorHandlingTest extends SolrTestCaseJ4 { public class AnalysisErrorHandlingTest extends SolrTestCaseJ4 {
public String getCoreName() { return "basic"; } public String getCoreName() { return "basic"; }
@BeforeClass @BeforeClass
@ -35,16 +34,12 @@ public class AnalysisErrorHandlingTest extends SolrTestCaseJ4 {
initCore("solrconfig-basic.xml","solr/analysisconfs/analysis-err-schema.xml"); initCore("solrconfig-basic.xml","solr/analysisconfs/analysis-err-schema.xml");
} }
@Test @Test
public void testMultipleUpdatesPerAdd() { public void testMultipleUpdatesPerAdd() {
clearIndex(); clearIndex();
try { SolrException se = expectThrows(SolrException.class,
h.update("<add><doc><field name=\"id\">1</field><field name=\"text\">Alas Poor Yorik</field></doc></add>"); () -> h.update("<add><doc><field name=\"id\">1</field><field name=\"text\">Alas Poor Yorik</field></doc></add>")
fail("Failed to even throw the exception we are stewing over."); );
} catch (SolrException se) { assertTrue(se.getMessage().contains("Exception writing document id 1 to the index"));
assertTrue(se.getMessage().contains("Exception writing document id 1 to the index"));
}
} }
} }

View File

@ -60,25 +60,18 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {
} }
@Test @Test
public void testBuildDocument() throws Exception public void testBuildDocument() throws Exception {
{
SolrCore core = h.getCore(); SolrCore core = h.getCore();
// undefined field // undefined field
try { SolrInputDocument doc = new SolrInputDocument();
SolrInputDocument doc = new SolrInputDocument(); doc.setField( "unknown field", 12345 );
doc.setField( "unknown field", 12345 );
DocumentBuilder.toDocument( doc, core.getLatestSchema() ); SolrException ex = expectThrows(SolrException.class, () -> DocumentBuilder.toDocument( doc, core.getLatestSchema() ));
fail( "should throw an error" ); assertEquals("should be bad request", 400, ex.code());
}
catch( SolrException ex ) {
assertEquals( "should be bad request", 400, ex.code() );
}
} }
@Test @Test
public void testNullField() public void testNullField() {
{
SolrCore core = h.getCore(); SolrCore core = h.getCore();
// make sure a null value is not indexed // make sure a null value is not indexed
@ -89,34 +82,23 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {
} }
@Test @Test
public void testExceptions() public void testExceptions() {
{
SolrCore core = h.getCore(); SolrCore core = h.getCore();
// make sure a null value is not indexed // make sure a null value is not indexed
SolrInputDocument doc = new SolrInputDocument(); SolrInputDocument doc = new SolrInputDocument();
doc.addField( "id", "123" ); doc.addField( "id", "123" );
doc.addField( "unknown", "something" ); doc.addField( "unknown", "something" );
try { Exception ex = expectThrows(Exception.class, () -> DocumentBuilder.toDocument( doc, core.getLatestSchema() ));
DocumentBuilder.toDocument( doc, core.getLatestSchema() ); assertTrue( "should have document ID", ex.getMessage().indexOf( "doc=123" ) > 0 );
fail( "added an unknown field" );
}
catch( Exception ex ) {
assertTrue( "should have document ID", ex.getMessage().indexOf( "doc=123" ) > 0 );
}
doc.remove( "unknown" ); doc.remove( "unknown" );
doc.addField( "weight", "not a number" ); doc.addField( "weight", "not a number" );
try { ex = expectThrows(Exception.class, () -> DocumentBuilder.toDocument( doc, core.getLatestSchema()));
DocumentBuilder.toDocument( doc, core.getLatestSchema() ); assertTrue( "should have document ID", ex.getMessage().indexOf( "doc=123" ) > 0 );
fail( "invalid 'float' field value" ); assertTrue( "cause is number format", ex.getCause() instanceof NumberFormatException );
}
catch( Exception ex ) {
assertTrue( "should have document ID", ex.getMessage().indexOf( "doc=123" ) > 0 );
assertTrue( "cause is number format", ex.getCause() instanceof NumberFormatException );
}
// now make sure it is OK // now make sure it is OK
doc.setField( "weight", "1.34" ); doc.setField( "weight", "1.34" );
DocumentBuilder.toDocument( doc, core.getLatestSchema() ); DocumentBuilder.toDocument( doc, core.getLatestSchema() );

View File

@ -38,23 +38,13 @@ public class TestAtomicUpdateErrorCases extends SolrTestCaseJ4 {
addAndGetVersion(sdoc("id", "1", "val_i", "42"), null); addAndGetVersion(sdoc("id", "1", "val_i", "42"), null);
assertU(commit()); assertU(commit());
try { // updating docs should fail
ignoreException("updateLog"); ignoreException("updateLog");
SolrException ex = expectThrows(SolrException.class,
// updating docs should fail () -> addAndGetVersion(sdoc("id", "1", "val_i", map("inc",-666)), null));
addAndGetVersion(sdoc("id", "1", "val_i", map("inc",-666)), null); assertEquals(400, ex.code());
assertTrue(ex.getMessage().contains("unless <updateLog/> is configured"));
fail("didn't get error about needing updateLog"); resetExceptionIgnores();
} catch (SolrException ex) {
assertEquals(400, ex.code());
// if the message doesn't match our expectation, wrap & rethrow
if (ex.getMessage().indexOf("unless <updateLog/> is configured") < 0) {
throw new RuntimeException("exception message is not expected", ex);
}
} finally {
resetExceptionIgnores();
}
} finally { } finally {
System.clearProperty("enable.update.log"); System.clearProperty("enable.update.log");
deleteCore(); deleteCore();
@ -68,30 +58,20 @@ public class TestAtomicUpdateErrorCases extends SolrTestCaseJ4 {
assertNotNull("this test requires an update chain named 'nodistrib'", assertNotNull("this test requires an update chain named 'nodistrib'",
h.getCore().getUpdateProcessingChain("nodistrib")); h.getCore().getUpdateProcessingChain("nodistrib"));
// creating docs should work fine // creating docs should work fine
addAndGetVersion(sdoc("id", "1", "val_i", "42"), addAndGetVersion(sdoc("id", "1", "val_i", "42"),
params("update.chain","nodistrib")); params("update.chain","nodistrib"));
assertU(commit()); assertU(commit());
try { ignoreException("DistributedUpdateProcessorFactory");
ignoreException("DistributedUpdateProcessorFactory"); // updating docs should fail
SolrException ex = expectThrows(SolrException.class, () -> {
// updating docs should fail addAndGetVersion(sdoc("id", "1", "val_i", map("inc",-666)),
addAndGetVersion(sdoc("id", "1", "val_i", map("inc",-666)), params("update.chain","nodistrib"));
params("update.chain","nodistrib")); });
assertEquals(400, ex.code());
fail("didn't get error about needing DistributedUpdateProcessorFactory"); assertTrue(ex.getMessage().contains("DistributedUpdateProcessorFactory"));
} catch (SolrException ex) { resetExceptionIgnores();
assertEquals(400, ex.code());
// if the message doesn't match our expectation, wrap & rethrow
if (ex.getMessage().indexOf("DistributedUpdateProcessorFactory") < 0) {
throw new RuntimeException("exception message is not expected", ex);
}
} finally {
resetExceptionIgnores();
}
} finally { } finally {
deleteCore(); deleteCore();
} }

View File

@ -16,15 +16,15 @@
*/ */
package org.apache.solr.update; package org.apache.solr.update;
import java.io.IOException;
import java.util.concurrent.Callable;
import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputDocument;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.Callable;
public class TestUpdate extends SolrTestCaseJ4 { public class TestUpdate extends SolrTestCaseJ4 {
@BeforeClass @BeforeClass
public static void beforeClass() throws Exception { public static void beforeClass() throws Exception {
@ -82,21 +82,14 @@ public class TestUpdate extends SolrTestCaseJ4 {
long version2; long version2;
try { SolrException se = expectThrows(SolrException.class,
// try bad version added as a field in the doc () -> addAndGetVersion(sdoc("id","1", "val_is",map("add",-100), "_version_",2), null));
version2 = addAndGetVersion(sdoc("id","1", "val_is",map("add",-100), "_version_",2), null); assertEquals(409, se.code());
fail();
} catch (SolrException se) {
assertEquals(409, se.code());
}
try { // try bad version added as a request param
// try bad version added as a request param se = expectThrows(SolrException.class,
version2 = addAndGetVersion(sdoc("id","1", "val_is",map("add",-100)), params("_version_","2")); () -> addAndGetVersion(sdoc("id","1", "val_is",map("add",-100)), params("_version_","2")));
fail(); assertEquals(409, se.code());
} catch (SolrException se) {
assertEquals(409, se.code());
}
// try good version added as a field in the doc // try good version added as a field in the doc
version = addAndGetVersion(sdoc("id","1", "val_is",map("add",-100), "_version_",version), null); version = addAndGetVersion(sdoc("id","1", "val_is",map("add",-100), "_version_",version), null);
@ -130,15 +123,10 @@ public class TestUpdate extends SolrTestCaseJ4 {
version = deleteAndGetVersion("1", null); version = deleteAndGetVersion("1", null);
afterUpdate.call(); afterUpdate.call();
// test that updating a non-existing doc fails if we set _version_=1
try { se = expectThrows(SolrException.class,
// test that updating a non-existing doc fails if we set _version_=1 () -> addAndGetVersion(sdoc("id","1", "val_is",map("add",-101), "_version_","1"), null));
version2 = addAndGetVersion(sdoc("id","1", "val_is",map("add",-101), "_version_","1"), null); assertEquals(409, se.code());
fail();
} catch (SolrException se) {
assertEquals(409, se.code());
}
// test that by default we can update a non-existing doc // test that by default we can update a non-existing doc
version = addAndGetVersion(sdoc("id","1", "val_i",102, "val_is",map("add",-102)), null); version = addAndGetVersion(sdoc("id","1", "val_i",102, "val_is",map("add",-102)), null);
@ -208,20 +196,14 @@ public class TestUpdate extends SolrTestCaseJ4 {
); );
// test that updating a unique id results in failure. // test that updating a unique id results in failure.
try { ignoreException("Invalid update of id field");
ignoreException("Invalid update of id field"); se = expectThrows(SolrException.class,
version = addAndGetVersion(sdoc( () -> addAndGetVersion(
"id", map("set","1"), sdoc("id", map("set","1"), "val_is", map("inc","2000000000")), null)
"val_is", map("inc","2000000000") );
), resetExceptionIgnores();
null); assertEquals(400, se.code());
assertTrue(se.getMessage().contains("Invalid update of id field"));
fail();
} catch (SolrException se) {
resetExceptionIgnores();
assertEquals(400, se.code());
assertTrue(se.getMessage().indexOf("Invalid update of id field") >= 0);
}
afterUpdate.call(); afterUpdate.call();

View File

@ -43,20 +43,16 @@ public class IgnoreLargeDocumentProcessorFactoryTest extends SolrTestCase {
IgnoreLargeDocumentProcessorFactory factory = new IgnoreLargeDocumentProcessorFactory(); IgnoreLargeDocumentProcessorFactory factory = new IgnoreLargeDocumentProcessorFactory();
factory.init(args); factory.init(args);
try {
UpdateRequestProcessor processor = factory.getInstance(null, null, null); UpdateRequestProcessor processor = factory.getInstance(null, null, null);
processor.processAdd(getUpdate(1024)); expectThrows(SolrException.class, () -> processor.processAdd(getUpdate(1024)));
fail("Expected processor to ignore the update");
} catch (SolrException e) {
//expected
}
args = new NamedList(); args = new NamedList();
args.add(IgnoreLargeDocumentProcessorFactory.LIMIT_SIZE_PARAM, 2); args.add(IgnoreLargeDocumentProcessorFactory.LIMIT_SIZE_PARAM, 2);
factory = new IgnoreLargeDocumentProcessorFactory(); factory = new IgnoreLargeDocumentProcessorFactory();
factory.init(args); factory.init(args);
UpdateRequestProcessor processor = factory.getInstance(null, null, null); UpdateRequestProcessor requestProcessor = factory.getInstance(null, null, null);
processor.processAdd(getUpdate(1024)); requestProcessor.processAdd(getUpdate(1024));
} }

View File

@ -16,20 +16,18 @@
*/ */
package org.apache.solr.update.processor; package org.apache.solr.update.processor;
import org.apache.solr.common.params.ModifiableSolrParams; import javax.script.ScriptEngine;
import org.apache.solr.common.SolrException; import javax.script.ScriptEngineManager;
import java.util.ArrayList;
import java.util.List;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.core.SolrCore; import org.apache.solr.core.SolrCore;
import org.junit.Assume; import org.junit.Assume;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import java.util.ArrayList;
import java.util.List;
/** /**
* Tests {@link StatelessScriptUpdateProcessorFactory}. * Tests {@link StatelessScriptUpdateProcessorFactory}.
* *
@ -233,33 +231,22 @@ public class StatelessScriptUpdateProcessorFactoryTest extends UpdateProcessorTe
public void testPropogatedException() throws Exception { public void testPropogatedException() throws Exception {
final String chain = "error-on-add"; final String chain = "error-on-add";
try { SolrException e = expectThrows(SolrException.class, () ->
SolrInputDocument d = processAdd(chain, processAdd(chain, doc(f("id", "5"), f("name", " foo "),
doc(f("id", "5"), f("subject", "bar")))
f("name", " foo "), );
f("subject", "bar"))); assertTrue("Exception doesn't contain script error string: " + e.getMessage(),
} catch (SolrException e) { 0 < e.getMessage().indexOf("no-soup-fo-you"));
assertTrue("Exception doesn't contain script error string: " + e.getMessage(),
0 < e.getMessage().indexOf("no-soup-fo-you"));
return;
}
fail("Did not get exception from script");
} }
public void testMissingFunctions() throws Exception { public void testMissingFunctions() throws Exception {
final String chain = "missing-functions"; final String chain = "missing-functions";
try { SolrException e = expectThrows(SolrException.class, () ->
SolrInputDocument d = processAdd(chain, processAdd(chain, doc(f("id", "5"),
doc(f("id", "5"), f("name", " foo "), f("subject", "bar")))
f("name", " foo "), );
f("subject", "bar"))); assertTrue("Exception doesn't contain expected error: " + e.getMessage(),
} catch (SolrException e) { 0 < e.getMessage().indexOf("processAdd"));
assertTrue("Exception doesn't contain expected error: " + e.getMessage(),
0 < e.getMessage().indexOf("processAdd"));
return;
}
fail("Did not get exception from script");
} }
public void testJavaScriptCompatibility() throws Exception { public void testJavaScriptCompatibility() throws Exception {

View File

@ -16,17 +16,12 @@
*/ */
package org.apache.solr.update.processor; package org.apache.solr.update.processor;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItem;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import org.apache.lucene.util.TestUtil; import org.apache.lucene.util.TestUtil;
import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException;
@ -35,11 +30,16 @@ import org.apache.solr.common.util.ExecutorUtil;
import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.NamedList;
import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField; import org.apache.solr.schema.SchemaField;
import org.apache.solr.update.processor.DocBasedVersionConstraintsProcessorFactory;
import org.apache.solr.util.DefaultSolrThreadFactory; import org.apache.solr.util.DefaultSolrThreadFactory;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 { public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
@BeforeClass @BeforeClass
@ -223,23 +223,23 @@ public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
updateJ(jsonAdd(sdoc("id", "aaa", "name", "a1", "my_version_l", "1001")), updateJ(jsonAdd(sdoc("id", "aaa", "name", "a1", "my_version_l", "1001")),
params("update.chain","external-version-failhard")); params("update.chain","external-version-failhard"));
assertU(commit()); assertU(commit());
try {
SolrException ex = expectThrows(SolrException.class, () -> {
updateJ(jsonAdd(sdoc("id", "aaa", "name", "XX", "my_version_l", "42")), updateJ(jsonAdd(sdoc("id", "aaa", "name", "XX", "my_version_l", "42")),
params("update.chain","external-version-failhard")); params("update.chain","external-version-failhard"));
fail("no 409"); });
} catch (SolrException ex) { assertEquals(409, ex.code());
assertEquals(409, ex.code());
}
assertU(commit()); assertU(commit());
assertJQ(req("qt","/get", "id","aaa", "fl","name") assertJQ(req("qt","/get", "id","aaa", "fl","name")
, "=={'doc':{'name':'a1'}}"); , "=={'doc':{'name':'a1'}}");
try {
deleteAndGetVersion("aaa", params("del_version", "7", ex = expectThrows(SolrException.class, () -> {
"update.chain","external-version-failhard")); deleteAndGetVersion("aaa", params("del_version", "7",
fail("no 409"); "update.chain","external-version-failhard"));
} catch (SolrException ex) { });
assertEquals(409, ex.code()); assertEquals(409, ex.code());
}
assertJQ(req("qt","/get", "id","aaa", "fl","name") assertJQ(req("qt","/get", "id","aaa", "fl","name")
, "=={'doc':{'name':'a1'}}"); , "=={'doc':{'name':'a1'}}");
assertU(commit()); assertU(commit());
@ -247,13 +247,12 @@ public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
// fail low version delete against uncommitted doc from updateLog // fail low version delete against uncommitted doc from updateLog
updateJ(jsonAdd(sdoc("id", "aaa", "name", "a2", "my_version_l", "1002")), updateJ(jsonAdd(sdoc("id", "aaa", "name", "a2", "my_version_l", "1002")),
params("update.chain","external-version-failhard")); params("update.chain","external-version-failhard"));
try { ex = expectThrows(SolrException.class, () -> {
deleteAndGetVersion("aaa", params("del_version", "8", deleteAndGetVersion("aaa", params("del_version", "8",
"update.chain","external-version-failhard")); "update.chain","external-version-failhard"));
fail("no 409"); });
} catch (SolrException ex) { assertEquals(409, ex.code());
assertEquals(409, ex.code());
}
assertJQ(req("qt","/get", "id","aaa", "fl","name") assertJQ(req("qt","/get", "id","aaa", "fl","name")
, "=={'doc':{'name':'a2'}}"); , "=={'doc':{'name':'a2'}}");
assertU(commit()); assertU(commit());
@ -265,13 +264,12 @@ public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
// fail low version add against uncommitted "delete" from updateLog // fail low version add against uncommitted "delete" from updateLog
deleteAndGetVersion("aaa", params("del_version", "1010", deleteAndGetVersion("aaa", params("del_version", "1010",
"update.chain","external-version-failhard")); "update.chain","external-version-failhard"));
try { ex = expectThrows(SolrException.class, () -> {
updateJ(jsonAdd(sdoc("id", "aaa", "name", "XX", "my_version_l", "1005")), updateJ(jsonAdd(sdoc("id", "aaa", "name", "XX", "my_version_l", "1005")),
params("update.chain","external-version-failhard")); params("update.chain","external-version-failhard"));
fail("no 409"); });
} catch (SolrException ex) { assertEquals(409, ex.code());
assertEquals(409, ex.code());
}
assertJQ(req("qt","/get", "id","aaa", "fl","my_version_l") assertJQ(req("qt","/get", "id","aaa", "fl","my_version_l")
, "=={'doc':{'my_version_l':1010}}}"); , "=={'doc':{'my_version_l':1010}}}");
assertU(commit()); assertU(commit());
@ -282,13 +280,12 @@ public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
// fail low version add against committed "delete" // fail low version add against committed "delete"
// (delete was already done & committed above) // (delete was already done & committed above)
try { ex = expectThrows(SolrException.class, () -> {
updateJ(jsonAdd(sdoc("id", "aaa", "name", "XX", "my_version_l", "1009")), updateJ(jsonAdd(sdoc("id", "aaa", "name", "XX", "my_version_l", "1009")),
params("update.chain","external-version-failhard")); params("update.chain","external-version-failhard"));
fail("no 409"); });
} catch (SolrException ex) { assertEquals(409, ex.code());
assertEquals(409, ex.code());
}
assertJQ(req("qt","/get", "id","aaa", "fl","my_version_l") assertJQ(req("qt","/get", "id","aaa", "fl","my_version_l")
, "=={'doc':{'my_version_l':1010}}}"); , "=={'doc':{'my_version_l':1010}}}");
assertU(commit()); assertU(commit());
@ -304,28 +301,25 @@ public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
params("update.chain","external-version-failhard-multiple")); params("update.chain","external-version-failhard-multiple"));
assertU(commit()); assertU(commit());
// All variations of additional versions should fail other than my_version_l greater or my_version_f greater. // All variations of additional versions should fail other than my_version_l greater or my_version_f greater.
try { SolrException ex = expectThrows(SolrException.class, () -> {
updateJ(jsonAdd(sdoc("id", "aaa", "name", "X1", "my_version_l", "1000", "my_version_f", "1.0")), updateJ(jsonAdd(sdoc("id", "aaa", "name", "X1", "my_version_l", "1000", "my_version_f", "1.0")),
params("update.chain","external-version-failhard-multiple")); params("update.chain","external-version-failhard-multiple"));
fail("no 409"); });
} catch (SolrException ex) { assertEquals(409, ex.code());
assertEquals(409, ex.code());
} ex = expectThrows(SolrException.class, () -> {
try {
updateJ(jsonAdd(sdoc("id", "aaa", "name", "X2", "my_version_l", "1001", "my_version_f", "0.9")), updateJ(jsonAdd(sdoc("id", "aaa", "name", "X2", "my_version_l", "1001", "my_version_f", "0.9")),
params("update.chain","external-version-failhard-multiple")); params("update.chain","external-version-failhard-multiple"));
fail("no 409"); });
} catch (SolrException ex) { assertEquals(409, ex.code());
assertEquals(409, ex.code());
}
// Also fails on the exact same version // Also fails on the exact same version
try { ex = expectThrows(SolrException.class, () -> {
updateJ(jsonAdd(sdoc("id", "aaa", "name", "X3", "my_version_l", "1001", "my_version_f", "1.0")), updateJ(jsonAdd(sdoc("id", "aaa", "name", "X3", "my_version_l", "1001", "my_version_f", "1.0")),
params("update.chain","external-version-failhard-multiple")); params("update.chain","external-version-failhard-multiple"));
fail("no 409"); });
} catch (SolrException ex) { assertEquals(409, ex.code());
assertEquals(409, ex.code());
}
//Verify we are still unchanged //Verify we are still unchanged
assertU(commit()); assertU(commit());
assertJQ(req("q","+id:aaa +name:a1"), "/response/numFound==1"); assertJQ(req("q","+id:aaa +name:a1"), "/response/numFound==1");
@ -347,30 +341,28 @@ public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
updateJ(jsonAdd(sdoc("id", "aaa", "name", "a1", "my_version_l", "1001", "my_version_f", "1.0")), updateJ(jsonAdd(sdoc("id", "aaa", "name", "a1", "my_version_l", "1001", "my_version_f", "1.0")),
params("update.chain","external-version-failhard-multiple")); params("update.chain","external-version-failhard-multiple"));
assertU(commit()); assertU(commit());
try {
SolrException ex = expectThrows(SolrException.class, () -> {
deleteAndGetVersion("aaa", params("del_version", "1000", "del_version_2", "1.0", deleteAndGetVersion("aaa", params("del_version", "1000", "del_version_2", "1.0",
"update.chain","external-version-failhard-multiple")); "update.chain","external-version-failhard-multiple"));
fail("no 409"); });
} catch (SolrException ex) { assertEquals(409, ex.code());
assertEquals(409, ex.code());
} ex = expectThrows(SolrException.class, () -> {
try {
deleteAndGetVersion("aaa", params("del_version", "1001", "del_version_2", "0.9", deleteAndGetVersion("aaa", params("del_version", "1001", "del_version_2", "0.9",
"update.chain","external-version-failhard-multiple")); "update.chain","external-version-failhard-multiple"));
fail("no 409"); });
} catch (SolrException ex) { assertEquals(409, ex.code());
assertEquals(409, ex.code());
}
// And just verify if we pass version 1, we still error if version 2 isn't found. // And just verify if we pass version 1, we still error if version 2 isn't found.
try { ignoreException("Delete by ID must specify doc version param");
ignoreException("Delete by ID must specify doc version param"); ex = expectThrows(SolrException.class, () -> {
deleteAndGetVersion("aaa", params("del_version", "1001", deleteAndGetVersion("aaa", params("del_version", "1001",
"update.chain","external-version-failhard-multiple")); "update.chain","external-version-failhard-multiple"));
fail("no 400"); });
} catch (SolrException ex) { assertEquals(400, ex.code());
assertEquals(400, ex.code()); unIgnoreException("Delete by ID must specify doc version param");
unIgnoreException("Delete by ID must specify doc version param");
}
//Verify we are still unchanged //Verify we are still unchanged
assertU(commit()); assertU(commit());
assertJQ(req("q","+id:aaa +name:a1"), "/response/numFound==1"); assertJQ(req("q","+id:aaa +name:a1"), "/response/numFound==1");
@ -505,19 +497,18 @@ public class TestDocBasedVersionConstraints extends SolrTestCaseJ4 {
// Try updating both with a new version and using the enforced version chain, expect id=b to fail bc old // Try updating both with a new version and using the enforced version chain, expect id=b to fail bc old
// doc is missing the version field // doc is missing the version field
version = "3"; String newVersion = "3";
updateJ(json("[{\"id\": \"a\", \"name\": \"a1\", \"my_version_l\": " + version + "}]"), updateJ(json("[{\"id\": \"a\", \"name\": \"a1\", \"my_version_l\": " + newVersion + "}]"),
params("update.chain", "external-version-constraint")); params("update.chain", "external-version-constraint"));
try {
ignoreException("Doc exists in index, but has null versionField: my_version_l"); ignoreException("Doc exists in index, but has null versionField: my_version_l");
updateJ(json("[{\"id\": \"b\", \"name\": \"b1\", \"my_version_l\": " + version + "}]"), SolrException ex = expectThrows(SolrException.class, () -> {
params("update.chain", "external-version-constraint")); updateJ(json("[{\"id\": \"b\", \"name\": \"b1\", \"my_version_l\": " + newVersion + "}]"),
fail("Update to id=b should have failed because existing doc is missing version field"); params("update.chain", "external-version-constraint"));
} catch (final SolrException ex) { });
// expected assertEquals("Doc exists in index, but has null versionField: my_version_l", ex.getMessage());
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");
unIgnoreException("Doc exists in index, but has null versionField: my_version_l");
}
assertU(commit()); assertU(commit());
assertJQ(req("q","*:*"), "/response/numFound==2"); assertJQ(req("q","*:*"), "/response/numFound==2");
assertJQ(req("qt","/get", "id", "a", "fl", "id,my_version_l"), "=={'doc':{'id':'a', 'my_version_l':3}}"); // version changed to 3 assertJQ(req("qt","/get", "id", "a", "fl", "id,my_version_l"), "=={'doc':{'id':'a', 'my_version_l':3}}"); // version changed to 3

View File

@ -16,6 +16,7 @@
*/ */
package org.apache.solr.update.processor; package org.apache.solr.update.processor;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -26,8 +27,6 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import javax.xml.xpath.XPathExpressionException;
import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputDocument;
@ -136,81 +135,59 @@ public class TolerantUpdateProcessorTest extends UpdateProcessorTestBase {
@Test @Test
public void testInvalidAdds() throws IOException { public void testInvalidAdds() throws IOException {
SolrInputDocument invalidDoc = doc(field("text", "the quick brown fox")); //no id SolrInputDocument invalidDoc1 = doc(field("text", "the quick brown fox")); //no id
try { // This doc should fail without being tolerant
// This doc should fail without being tolerant Exception e = expectThrows(Exception.class, () -> add("not-tolerant", null, invalidDoc1));
add("not-tolerant", null, invalidDoc); assertTrue(e.getMessage().contains("Document is missing mandatory uniqueKey field"));
fail("Expecting exception");
} catch (Exception e) { assertAddsSucceedWithErrors("tolerant-chain-max-errors-10", Arrays.asList(new SolrInputDocument[]{invalidDoc1}), null, "(unknown)");
//expected
assertTrue(e.getMessage().contains("Document is missing mandatory uniqueKey field"));
}
assertAddsSucceedWithErrors("tolerant-chain-max-errors-10", Arrays.asList(new SolrInputDocument[]{invalidDoc}), null, "(unknown)");
//a valid doc //a valid doc
SolrInputDocument validDoc = doc(field("id", "1"), field("text", "the quick brown fox")); SolrInputDocument validDoc1 = doc(field("id", "1"), field("text", "the quick brown fox"));
try { // This batch should fail without being tolerant
// This batch should fail without being tolerant e = expectThrows(Exception.class, () -> add("not-tolerant", null,
add("not-tolerant", null, Arrays.asList(new SolrInputDocument[]{invalidDoc, validDoc})); Arrays.asList(new SolrInputDocument[]{invalidDoc1, validDoc1})));
fail("Expecting exception"); assertTrue(e.getMessage().contains("Document is missing mandatory uniqueKey field"));
} catch (Exception e) {
//expected
assertTrue(e.getMessage().contains("Document is missing mandatory uniqueKey field"));
}
assertU(commit()); assertU(commit());
assertQ(req("q","id:1") assertQ(req("q","id:1"),"//result[@numFound='0']");
,"//result[@numFound='0']");
assertAddsSucceedWithErrors("tolerant-chain-max-errors-10", Arrays.asList(new SolrInputDocument[]{invalidDoc, validDoc}), null, "(unknown)"); assertAddsSucceedWithErrors("tolerant-chain-max-errors-10", Arrays.asList(new SolrInputDocument[]{invalidDoc1, validDoc1}), null, "(unknown)");
assertU(commit()); assertU(commit());
// verify that the good document made it in. // verify that the good document made it in.
assertQ(req("q","id:1") assertQ(req("q","id:1"),"//result[@numFound='1']");
,"//result[@numFound='1']");
invalidDoc = doc(field("id", "2"), field("weight", "aaa"));
validDoc = doc(field("id", "3"), field("weight", "3"));
try {
// This batch should fail without being tolerant
add("not-tolerant", null, Arrays.asList(new SolrInputDocument[]{invalidDoc, validDoc})); //no id
fail("Expecting exception");
} catch (Exception e) {
//expected
assertTrue(e.getMessage().contains("Error adding field"));
}
SolrInputDocument invalidDoc2 = doc(field("id", "2"), field("weight", "aaa"));
SolrInputDocument validDoc2 = doc(field("id", "3"), field("weight", "3"));
// This batch should fail without being tolerant
e = expectThrows(Exception.class, () -> add("not-tolerant", null,
Arrays.asList(new SolrInputDocument[]{invalidDoc2, validDoc2})));
assertTrue(e.getMessage().contains("Error adding field"));
assertU(commit()); assertU(commit());
assertQ(req("q","id:3") assertQ(req("q","id:3"),"//result[@numFound='0']");
,"//result[@numFound='0']");
assertAddsSucceedWithErrors("tolerant-chain-max-errors-10", Arrays.asList(new SolrInputDocument[]{invalidDoc, validDoc}), null, "2"); assertAddsSucceedWithErrors("tolerant-chain-max-errors-10", Arrays.asList(new SolrInputDocument[]{invalidDoc2, validDoc2}), null, "2");
assertU(commit()); assertU(commit());
// The valid document was indexed // The valid document was indexed
assertQ(req("q","id:3") assertQ(req("q","id:3"),"//result[@numFound='1']");
,"//result[@numFound='1']");
// The invalid document was NOT indexed // The invalid document was NOT indexed
assertQ(req("q","id:2") assertQ(req("q","id:2"),"//result[@numFound='0']");
,"//result[@numFound='0']");
} }
@Test @Test
public void testMaxErrorsDefault() throws IOException { public void testMaxErrorsDefault() throws IOException {
try { // by default the TolerantUpdateProcessor accepts all errors, so this batch should succeed with 10 errors.
// by default the TolerantUpdateProcessor accepts all errors, so this batch should succeed with 10 errors. assertAddsSucceedWithErrors("tolerant-chain-max-errors-not-set", docs, null, badIds);
assertAddsSucceedWithErrors("tolerant-chain-max-errors-not-set", docs, null, badIds);
} catch(Exception e) {
fail("Shouldn't get an exception for this batch: " + e.getMessage());
}
assertU(commit()); assertU(commit());
assertQ(req("q","*:*") assertQ(req("q","*:*"),"//result[@numFound='10']");
,"//result[@numFound='10']");
} }
public void testMaxErrorsSucceed() throws IOException { public void testMaxErrorsSucceed() throws IOException {
@ -219,40 +196,31 @@ public class TolerantUpdateProcessorTest extends UpdateProcessorTestBase {
// still OK // still OK
assertAddsSucceedWithErrors("tolerant-chain-max-errors-not-set", docs, requestParams, badIds); assertAddsSucceedWithErrors("tolerant-chain-max-errors-not-set", docs, requestParams, badIds);
assertU(commit()); assertU(commit());
assertQ(req("q","*:*") assertQ(req("q","*:*"),"//result[@numFound='10']");
,"//result[@numFound='10']");
} }
@Test @Test
public void testMaxErrorsThrowsException() throws IOException { public void testMaxErrorsThrowsException() throws IOException {
ModifiableSolrParams requestParams = new ModifiableSolrParams(); ModifiableSolrParams requestParams = new ModifiableSolrParams();
requestParams.add("maxErrors", "5"); requestParams.add("maxErrors", "5");
try {
// should fail SolrException e = expectThrows(SolrException.class, () ->
assertAddsSucceedWithErrors("tolerant-chain-max-errors-not-set", docs, requestParams, badIds); assertAddsSucceedWithErrors("tolerant-chain-max-errors-not-set", docs, requestParams, badIds));
fail("Expecting exception"); assertTrue(e.getMessage(),
} catch (SolrException e) { e.getMessage().contains("ERROR: [doc=1] Error adding field 'weight'='b' msg=For input string: \"b\""));
assertTrue(e.getMessage(),
e.getMessage().contains("ERROR: [doc=1] Error adding field 'weight'='b' msg=For input string: \"b\""));
}
//the first good documents made it to the index //the first good documents made it to the index
assertU(commit()); assertU(commit());
assertQ(req("q","*:*") assertQ(req("q","*:*"),"//result[@numFound='6']");
,"//result[@numFound='6']");
} }
@Test @Test
public void testMaxErrorsInfinite() throws IOException { public void testMaxErrorsInfinite() throws IOException {
ModifiableSolrParams requestParams = new ModifiableSolrParams(); ModifiableSolrParams requestParams = new ModifiableSolrParams();
requestParams.add("maxErrors", "-1"); requestParams.add("maxErrors", "-1");
try { assertAddsSucceedWithErrors("tolerant-chain-max-errors-not-set", docs, null, badIds);
assertAddsSucceedWithErrors("tolerant-chain-max-errors-not-set", docs, null, badIds);
} catch(Exception e) {
fail("Shouldn't get an exception for this batch: " + e.getMessage());
}
assertU(commit()); assertU(commit());
assertQ(req("q","*:*") assertQ(req("q","*:*"),"//result[@numFound='10']");
,"//result[@numFound='10']");
} }
@Test @Test
@ -261,17 +229,14 @@ public class TolerantUpdateProcessorTest extends UpdateProcessorTestBase {
List<SolrInputDocument> smallBatch = docs.subList(0, 2); List<SolrInputDocument> smallBatch = docs.subList(0, 2);
ModifiableSolrParams requestParams = new ModifiableSolrParams(); ModifiableSolrParams requestParams = new ModifiableSolrParams();
requestParams.add("maxErrors", "0"); requestParams.add("maxErrors", "0");
try {
// should fail SolrException e = expectThrows(SolrException.class, () ->
assertAddsSucceedWithErrors("tolerant-chain-max-errors-10", smallBatch, requestParams, "1"); assertAddsSucceedWithErrors("tolerant-chain-max-errors-10", smallBatch, requestParams, "1"));
fail("Expecting exception"); assertTrue(e.getMessage().contains("ERROR: [doc=1] Error adding field 'weight'='b' msg=For input string: \"b\""));
} catch (SolrException e) {
assertTrue(e.getMessage().contains("ERROR: [doc=1] Error adding field 'weight'='b' msg=For input string: \"b\""));
}
//the first good documents made it to the index //the first good documents made it to the index
assertU(commit()); assertU(commit());
assertQ(req("q","*:*") assertQ(req("q","*:*"),"//result[@numFound='1']");
,"//result[@numFound='1']");
} }
@Test @Test

View File

@ -319,14 +319,9 @@ public class DateMathParserTest extends SolrTestCaseJ4 {
badCommands.put("?SECONDS", 0); badCommands.put("?SECONDS", 0);
for (String command : badCommands.keySet()) { for (String command : badCommands.keySet()) {
try { ParseException e = expectThrows(ParseException.class, () -> p.parseMath(command));
Date out = p.parseMath(command); assertEquals("Wrong pos for: " + command + " => " + e.getMessage(),
fail("Didn't generate SyntaxError for: " + command); badCommands.get(command).intValue(), e.getErrorOffset());
} catch (ParseException e) {
assertEquals("Wrong pos for: " + command + " => " + e.getMessage(),
badCommands.get(command).intValue(), e.getErrorOffset());
}
} }
} }

View File

@ -36,18 +36,10 @@ public class TestTestInjection extends SolrTestCase {
public void testBasics() { public void testBasics() {
TestInjection.failReplicaRequests = "true:100"; TestInjection.failReplicaRequests = "true:100";
try {
TestInjection.injectFailReplicaRequests();
fail("should fail 100%");
} catch (Throwable e) {
assertFalse("Should not fail based on bad syntax",
e.getMessage().toLowerCase(Locale.ENGLISH).contains("bad syntax"));
// good Exception e = expectThrows(Exception.class, TestInjection::injectFailReplicaRequests);
assertFalse("Should not fail based on bad syntax",
// assertTrue("Should fail with * based error: " + e.getClass().getName(), (e instanceof *)); e.getMessage().toLowerCase(Locale.ENGLISH).contains("bad syntax"));
}
TestInjection.failReplicaRequests = "true:00"; TestInjection.failReplicaRequests = "true:00";
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
@ -78,19 +70,13 @@ public class TestTestInjection extends SolrTestCase {
public void testBadSyntax(String syntax) { public void testBadSyntax(String syntax) {
TestInjection.failReplicaRequests = syntax; TestInjection.failReplicaRequests = syntax;
Exception e = expectThrows(Exception.class, TestInjection::injectFailReplicaRequests);
try { assertTrue(e.getMessage().toLowerCase(Locale.ENGLISH).contains("bad syntax"));
TestInjection.injectFailReplicaRequests();
fail("should fail 100%");
} catch (Exception e) {
assertTrue(e.getMessage().toLowerCase(Locale.ENGLISH).contains("bad syntax"));
// good
}
} }
public void testGoodSyntax(String syntax) { public void testGoodSyntax(String syntax) {
TestInjection.failReplicaRequests = syntax; TestInjection.failReplicaRequests = syntax;
try { try {
TestInjection.injectFailReplicaRequests(); TestInjection.injectFailReplicaRequests();
} catch (Exception e) { } catch (Exception e) {

View File

@ -34,28 +34,22 @@ public class BigEndianAscendingWordDeserializerTest extends SolrTestCase {
@Test @Test
public void constructorErrorTest() { public void constructorErrorTest() {
// word length too small // word length too small
try { IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
new BigEndianAscendingWordDeserializer(0/*wordLength, below minimum of 1*/, 0/*bytePadding, arbitrary*/, new byte[1]/*bytes, arbitrary, not used here*/); new BigEndianAscendingWordDeserializer(0/*wordLength, below minimum of 1*/, 0/*bytePadding, arbitrary*/, new byte[1]/*bytes, arbitrary, not used here*/);
fail("Should complain about too-short words."); });
} catch(final IllegalArgumentException e) { assertTrue(e.getMessage().contains("Word length must be"));
assertTrue(e.getMessage().contains("Word length must be"));
}
// word length too large // word length too large
try { e = expectThrows(IllegalArgumentException.class, () -> {
new BigEndianAscendingWordDeserializer(65/*wordLength, above maximum of 64*/, 0/*bytePadding, arbitrary*/, new byte[1]/*bytes, arbitrary, not used here*/); new BigEndianAscendingWordDeserializer(65/*wordLength, above maximum of 64*/, 0/*bytePadding, arbitrary*/, new byte[1]/*bytes, arbitrary, not used here*/);
fail("Should complain about too-long words."); });
} catch(final IllegalArgumentException e) { assertTrue(e.getMessage().contains("Word length must be"));
assertTrue(e.getMessage().contains("Word length must be"));
}
// byte padding negative // byte padding negative
try { e = expectThrows(IllegalArgumentException.class, () -> {
new BigEndianAscendingWordDeserializer(5/*wordLength, arbitrary*/, -1/*bytePadding, too small*/, new byte[1]/*bytes, arbitrary, not used here*/); new BigEndianAscendingWordDeserializer(5/*wordLength, arbitrary*/, -1/*bytePadding, too small*/, new byte[1]/*bytes, arbitrary, not used here*/);
fail("Should complain about negative byte padding."); });
} catch(final IllegalArgumentException e) { assertTrue(e.getMessage().contains("Byte padding must be"));
assertTrue(e.getMessage().contains("Byte padding must be"));
}
} }
/** /**

View File

@ -31,36 +31,28 @@ public class BigEndianAscendingWordSerializerTest extends SolrTestCase {
@Test @Test
public void constructorErrorTest() { public void constructorErrorTest() {
// word length too small // word length too small
try { IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
new BigEndianAscendingWordSerializer(0/*wordLength, below minimum of 1*/, 1/*wordCount, arbitrary*/, 0/*bytePadding, arbitrary*/); new BigEndianAscendingWordSerializer(0/*wordLength, below minimum of 1*/, 1/*wordCount, arbitrary*/, 0/*bytePadding, arbitrary*/);;
fail("Should complain about too-short words."); });
} catch(final IllegalArgumentException e) { assertTrue(e.getMessage().contains("Word length must be"));
assertTrue(e.getMessage().contains("Word length must be"));
}
// word length too large // word length too large
try { e = expectThrows(IllegalArgumentException.class, () -> {
new BigEndianAscendingWordSerializer(65/*wordLength, above max of 64*/, 1/*wordCount, arbitrary*/, 0/*bytePadding, arbitrary*/); new BigEndianAscendingWordSerializer(65/*wordLength, above max of 64*/, 1/*wordCount, arbitrary*/, 0/*bytePadding, arbitrary*/);
fail("Should complain about too-long words."); });
} catch(final IllegalArgumentException e) { assertTrue(e.getMessage().contains("Word length must be"));
assertTrue(e.getMessage().contains("Word length must be"));
}
// word count negative // word count negative
try { e = expectThrows(IllegalArgumentException.class, () -> {
new BigEndianAscendingWordSerializer(5/*wordLength, arbitrary*/, -1/*wordCount, too small*/, 0/*bytePadding, arbitrary*/); new BigEndianAscendingWordSerializer(5/*wordLength, arbitrary*/, -1/*wordCount, too small*/, 0/*bytePadding, arbitrary*/);
fail("Should complain about negative word count."); });
} catch(final IllegalArgumentException e) { assertTrue(e.getMessage().contains("Word count must be"));
assertTrue(e.getMessage().contains("Word count must be"));
}
// byte padding negative // byte padding negative
try { e = expectThrows(IllegalArgumentException.class, () -> {
new BigEndianAscendingWordSerializer(5/*wordLength, arbitrary*/, 1/*wordCount, arbitrary*/, -1/*bytePadding, too small*/); new BigEndianAscendingWordSerializer(5/*wordLength, arbitrary*/, 1/*wordCount, arbitrary*/, -1/*bytePadding, too small*/);
fail("Should complain about negative byte padding."); });
} catch(final IllegalArgumentException e) { assertTrue(e.getMessage().contains("Byte padding must be"));
assertTrue(e.getMessage().contains("Byte padding must be"));
}
} }
/** /**
@ -74,12 +66,8 @@ public class BigEndianAscendingWordSerializerTest extends SolrTestCase {
0/*bytePadding, arbitrary*/); 0/*bytePadding, arbitrary*/);
// getBytes without enough writeWord should throw // getBytes without enough writeWord should throw
try { RuntimeException e = expectThrows(RuntimeException.class, serializer::getBytes);
serializer.getBytes(); assertTrue(e.getMessage().contains("Not all words"));
fail("Should throw.");
} catch(final RuntimeException e) {
assertTrue(e.getMessage().contains("Not all words"));
}
} }
/** /**

View File

@ -17,10 +17,6 @@
package org.apache.solr.client.solrj; package org.apache.solr.client.solrj;
import static org.apache.solr.common.params.UpdateParams.ASSUME_CONTENT_TYPE;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.StringContains.containsString;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -38,6 +34,7 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import com.google.common.collect.Maps;
import org.apache.lucene.util.TestUtil; import org.apache.lucene.util.TestUtil;
import org.apache.solr.SolrTestCaseJ4.SuppressSSL; import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
@ -84,7 +81,9 @@ import org.noggit.JSONParser;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.google.common.collect.Maps; import static org.apache.solr.common.params.UpdateParams.ASSUME_CONTENT_TYPE;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.StringContains.containsString;
/** /**
* This should include tests against the example solr config * This should include tests against the example solr config
@ -482,50 +481,25 @@ abstract public class SolrExampleTests extends SolrExampleTestsBase
query.set(CommonParams.QT, "/analysis/field"); query.set(CommonParams.QT, "/analysis/field");
query.set(AnalysisParams.FIELD_TYPE, "pint"); query.set(AnalysisParams.FIELD_TYPE, "pint");
query.set(AnalysisParams.FIELD_VALUE, "ignore_exception"); query.set(AnalysisParams.FIELD_VALUE, "ignore_exception");
try { SolrException ex = expectThrows(SolrException.class, () -> client.query(query));
client.query( query ); assertEquals(400, ex.code());
Assert.fail("should have a number format exception"); assertThat(ex.getMessage(), containsString("Invalid Number: ignore_exception"));
}
catch(SolrException ex) { //the df=text here is a kluge for the test to supply a default field in case there is none in schema.xml
assertEquals(400, ex.code()); // alternatively, the resulting assertion could be modified to assert that no default field is specified.
assertThat(ex.getMessage(), containsString("Invalid Number: ignore_exception")); ex = expectThrows(SolrException.class, () -> client.deleteByQuery( "{!df=text} ??::?? ignore_exception" ));
} assertTrue(ex.getMessage().indexOf("??::?? ignore_exception")>0); // The reason should get passed through
catch(Throwable t) { assertEquals(400, ex.code());
t.printStackTrace();
Assert.fail("should have thrown a SolrException! not: "+t);
}
try {
//the df=text here is a kluge for the test to supply a default field in case there is none in schema.xml
// alternatively, the resulting assertion could be modified to assert that no default field is specified.
client.deleteByQuery( "{!df=text} ??::?? ignore_exception" ); // query syntax error
Assert.fail("should have a number format exception");
}
catch(SolrException ex) {
assertEquals(400, ex.code());
assertTrue(ex.getMessage().indexOf("??::?? ignore_exception")>0); // The reason should get passed through
}
catch(Throwable t) {
t.printStackTrace();
Assert.fail("should have thrown a SolrException! not: "+t);
}
SolrInputDocument doc = new SolrInputDocument(); SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", "DOCID"); doc.addField("id", "DOCID");
doc.addField("id", "DOCID2"); doc.addField("id", "DOCID2");
doc.addField("name", "hello"); doc.addField("name", "hello");
if (client instanceof HttpSolrClient) { if (client instanceof HttpSolrClient) {
try { ex = expectThrows(SolrException.class, () -> client.add(doc));
client.add(doc); assertEquals(400, ex.code());
fail("Should throw exception!"); assertTrue(ex.getMessage().indexOf("contains multiple values for uniqueKey") > 0);
} catch (SolrException ex) {
assertEquals(400, ex.code());
assertTrue(ex.getMessage().indexOf(
"contains multiple values for uniqueKey") > 0); // The reason should get passed through
} catch (Throwable t) {
Assert.fail("should have thrown a SolrException! not: " + t);
}
} else if (client instanceof ErrorTrackingConcurrentUpdateSolrClient) { } else if (client instanceof ErrorTrackingConcurrentUpdateSolrClient) {
//XXX concurrentupdatesolrserver reports errors differently //XXX concurrentupdatesolrserver reports errors differently
ErrorTrackingConcurrentUpdateSolrClient concurrentClient = (ErrorTrackingConcurrentUpdateSolrClient) client; ErrorTrackingConcurrentUpdateSolrClient concurrentClient = (ErrorTrackingConcurrentUpdateSolrClient) client;
@ -1199,47 +1173,35 @@ abstract public class SolrExampleTests extends SolrExampleTestsBase
SolrQuery query = new SolrQuery("*:*"); SolrQuery query = new SolrQuery("*:*");
query.addFacetPivotField("{!stats=s1}features,manu"); query.addFacetPivotField("{!stats=s1}features,manu");
query.addGetFieldStatistics("{!key=inStock_val tag=s1}inStock"); query.addGetFieldStatistics("{!key=inStock_val tag=s1}inStock");
try {
client.query(query); SolrException e = expectThrows(SolrException.class, () -> client.query(query));
fail("SolrException should be thrown on query"); assertEquals("Pivot facet on boolean is not currently supported, bad request returned", 400, e.code());
} catch (SolrException e) { assertTrue(e.getMessage().contains("is not currently supported"));
assertEquals("Pivot facet on boolean is not currently supported, bad request returned", 400, e.code()); assertTrue(e.getMessage().contains("boolean"));
assertTrue(e.getMessage().contains("is not currently supported"));
assertTrue(e.getMessage().contains("boolean"));
}
// asking for multiple stat tags -- see SOLR-6663 // asking for multiple stat tags -- see SOLR-6663
query = new SolrQuery("*:*"); SolrQuery query2 = new SolrQuery("*:*");
query.addFacetPivotField("{!stats=tag1,tag2}features,manu"); query2.addFacetPivotField("{!stats=tag1,tag2}features,manu");
query.addGetFieldStatistics("{!tag=tag1}price", "{!tag=tag2}popularity"); query2.addGetFieldStatistics("{!tag=tag1}price", "{!tag=tag2}popularity");
query.setFacetMinCount(0); query2.setFacetMinCount(0);
query.setRows(0); query2.setRows(0);
try {
client.query(query); e = expectThrows(SolrException.class, () -> client.query(query2));
fail("SolrException should be thrown on query"); assertEquals(400, e.code());
} catch (SolrException e) { assertTrue(e.getMessage().contains("stats"));
assertEquals(400, e.code()); assertTrue(e.getMessage().contains("comma"));
assertTrue(e.getMessage().contains("stats")); assertTrue(e.getMessage().contains("tag"));
assertTrue(e.getMessage().contains("comma"));
assertTrue(e.getMessage().contains("tag"));
}
// text field // text field
query = new SolrQuery("*:*"); SolrQuery query3 = new SolrQuery("*:*");
query.addFacetPivotField("{!stats=s1}features,manu"); query3.addFacetPivotField("{!stats=s1}features,manu");
query.addGetFieldStatistics("{!tag=s1}features"); query3.addGetFieldStatistics("{!tag=s1}features");
query.setFacetMinCount(0); query3.setFacetMinCount(0);
query.setRows(0); query3.setRows(0);
try { e = expectThrows(SolrException.class, () -> client.query(query3));
client.query(query); assertEquals("Pivot facet on string is not currently supported, bad request returned", 400, e.code());
fail("SolrException should be thrown on query"); assertTrue(e.getMessage().contains("is not currently supported"));
} catch (SolrException e) { assertTrue(e.getMessage().contains("text_general"));
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 @Test

View File

@ -898,13 +898,8 @@ public class TestPolicy extends SolrTestCaseJ4 {
} }
private static void expectError(String name, Object val, String msg) { private static void expectError(String name, Object val, String msg) {
try { Exception e = expectThrows(Exception.class, () -> Clause.validate(name, val, true));
Clause.validate(name, val, true); assertTrue("expected exception containing " + msg, e.getMessage().contains(msg));
fail("expected exception containing " + msg);
} catch (Exception e) {
assertTrue("expected exception containing " + msg, e.getMessage().contains(msg));
}
} }
public void testOperands() { public void testOperands() {

View File

@ -19,9 +19,9 @@ package org.apache.solr.client.solrj.embedded;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
@ -40,7 +40,6 @@ import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.NamedList;
import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
@ -62,17 +61,10 @@ public class SolrExampleJettyTest extends SolrExampleTests {
} }
@Test @Test
public void testBadSetup() public void testBadSetup() {
{ // setup the server...
try { String url = "http" + (isSSLMode() ? "s" : "") + "://127.0.0.1/?core=xxx";
// setup the server... expectThrows(Exception.class, () -> getHttpSolrClient(url));
String url = "http" + (isSSLMode() ? "s" : "") + "://127.0.0.1/?core=xxx";
HttpSolrClient client = getHttpSolrClient(url);
Assert.fail("HttpSolrServer should not allow a path with a parameter: " + client.getBaseURL());
}
catch( Exception ex ) {
// expected
}
} }
@Test @Test

View File

@ -16,10 +16,9 @@
*/ */
package org.apache.solr.client.solrj.embedded; package org.apache.solr.client.solrj.embedded;
import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule;
import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles;
import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule;
import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery;
@ -77,12 +76,7 @@ public class TestSolrProperties extends AbstractEmbeddedSolrServerTestCase {
SolrTestCaseJ4.ignoreException("unknown field"); SolrTestCaseJ4.ignoreException("unknown field");
// You can't add it to core1 // You can't add it to core1
try { expectThrows(Exception.class, () -> up.process(getSolrCore1()));
up.process(getSolrCore1());
fail("Can't add core0 field to core1!");
}
catch (Exception ex) {
}
// Add to core1 // Add to core1
doc.setField("id", "BBB"); doc.setField("id", "BBB");
@ -92,14 +86,8 @@ public class TestSolrProperties extends AbstractEmbeddedSolrServerTestCase {
up.process(getSolrCore1()); up.process(getSolrCore1());
// You can't add it to core1 // You can't add it to core1
try { SolrTestCaseJ4.ignoreException("core0");
SolrTestCaseJ4.ignoreException("core0"); expectThrows(Exception.class, () -> up.process(getSolrCore0()));
up.process(getSolrCore0());
fail("Can't add core1 field to core0!");
}
catch (Exception ex) {
}
SolrTestCaseJ4.resetExceptionIgnores(); SolrTestCaseJ4.resetExceptionIgnores();
// now Make sure AAA is in 0 and BBB in 1 // now Make sure AAA is in 0 and BBB in 1

View File

@ -207,12 +207,9 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
@Test @Test
public void testTimeout() throws Exception { public void testTimeout() throws Exception {
SolrQuery q = new SolrQuery("*:*"); SolrQuery q = new SolrQuery("*:*");
try(HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/slow/foo", DEFAULT_CONNECTION_TIMEOUT, 2000)) { try(HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/slow/foo", DEFAULT_CONNECTION_TIMEOUT, 2000)) {
client.query(q, METHOD.GET); SolrServerException e = expectThrows(SolrServerException.class, () -> client.query(q, METHOD.GET));
fail("No exception thrown.");
} catch (SolrServerException e) {
assertTrue(e.getMessage().contains("Timeout")); assertTrue(e.getMessage().contains("Timeout"));
} }
@ -230,13 +227,9 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/debug/foo")) { try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/debug/foo")) {
DebugServlet.setErrorCode(status); DebugServlet.setErrorCode(status);
try { SolrQuery q = new SolrQuery("foo");
SolrQuery q = new SolrQuery("foo"); SolrException e = expectThrows(SolrException.class, () -> client.query(q, METHOD.GET));
client.query(q, METHOD.GET); assertEquals("Unexpected exception status code", status, e.code());
fail("Didn't get excepted exception from oversided request");
} catch (SolrException e) {
assertEquals("Unexpected exception status code", status, e.code());
}
} finally { } finally {
DebugServlet.clear(); DebugServlet.clear();
} }
@ -248,9 +241,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/debug/foo")) { try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/debug/foo")) {
SolrQuery q = new SolrQuery("foo"); SolrQuery q = new SolrQuery("foo");
q.setParam("a", "\u1234"); q.setParam("a", "\u1234");
try { expectThrows(ParseException.class, () -> client.query(q, METHOD.GET));
client.query(q, METHOD.GET);
} catch (ParseException ignored) {}
//default method //default method
assertEquals("get", DebugServlet.lastMethod); assertEquals("get", DebugServlet.lastMethod);
@ -274,9 +265,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
//POST //POST
DebugServlet.clear(); DebugServlet.clear();
try { expectThrows(ParseException.class, () -> client.query(q, METHOD.POST));
client.query(q, METHOD.POST);
} catch (ParseException ignored) {}
assertEquals("post", DebugServlet.lastMethod); assertEquals("post", DebugServlet.lastMethod);
assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent")); assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent"));
@ -292,9 +281,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
//PUT //PUT
DebugServlet.clear(); DebugServlet.clear();
try { expectThrows(ParseException.class, () -> client.query(q, METHOD.PUT));
client.query(q, METHOD.PUT);
} catch (ParseException ignored) {}
assertEquals("put", DebugServlet.lastMethod); assertEquals("put", DebugServlet.lastMethod);
assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent")); assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent"));
@ -311,9 +298,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
//XML/GET //XML/GET
client.setParser(new XMLResponseParser()); client.setParser(new XMLResponseParser());
DebugServlet.clear(); DebugServlet.clear();
try { expectThrows(ParseException.class, () -> client.query(q, METHOD.GET));
client.query(q, METHOD.GET);
} catch (ParseException ignored) {}
assertEquals("get", DebugServlet.lastMethod); assertEquals("get", DebugServlet.lastMethod);
assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent")); assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent"));
@ -329,9 +314,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
//XML/POST //XML/POST
client.setParser(new XMLResponseParser()); client.setParser(new XMLResponseParser());
DebugServlet.clear(); DebugServlet.clear();
try { expectThrows(ParseException.class, () -> client.query(q, METHOD.POST));
client.query(q, METHOD.POST);
} catch (ParseException ignored) {}
assertEquals("post", DebugServlet.lastMethod); assertEquals("post", DebugServlet.lastMethod);
assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent")); assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent"));
@ -347,9 +330,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
client.setParser(new XMLResponseParser()); client.setParser(new XMLResponseParser());
DebugServlet.clear(); DebugServlet.clear();
try { expectThrows(ParseException.class, () -> client.query(q, METHOD.PUT));
client.query(q, METHOD.PUT);
} catch (ParseException ignored) {}
assertEquals("put", DebugServlet.lastMethod); assertEquals("put", DebugServlet.lastMethod);
assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent")); assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent"));
@ -370,9 +351,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
public void testDelete() throws Exception { public void testDelete() throws Exception {
DebugServlet.clear(); DebugServlet.clear();
try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/debug/foo")) { try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/debug/foo")) {
try { expectThrows(ParseException.class, () -> client.deleteById("id"));
client.deleteById("id");
} catch (ParseException ignored) {}
//default method //default method
assertEquals("post", DebugServlet.lastMethod); assertEquals("post", DebugServlet.lastMethod);
@ -391,9 +370,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
//XML //XML
client.setParser(new XMLResponseParser()); client.setParser(new XMLResponseParser());
try { expectThrows(ParseException.class, () -> client.deleteByQuery("*:*"));
client.deleteByQuery("*:*");
} catch (ParseException ignored) {}
assertEquals("post", DebugServlet.lastMethod); assertEquals("post", DebugServlet.lastMethod);
assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent")); assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent"));
@ -412,21 +389,10 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
DebugServlet.clear(); DebugServlet.clear();
try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/debug/foo")) { try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/debug/foo")) {
Collection<String> ids = Collections.singletonList("a"); Collection<String> ids = Collections.singletonList("a");
try { expectThrows(ParseException.class, () -> client.getById("a"));
client.getById("a"); expectThrows(ParseException.class, () -> client.getById(ids, null));
} catch (ParseException ignored) {} expectThrows(ParseException.class, () -> client.getById("foo", "a"));
expectThrows(ParseException.class, () -> client.getById("foo", ids, null));
try {
client.getById(ids, null);
} catch (ParseException ignored) {}
try {
client.getById("foo", "a");
} catch (ParseException ignored) {}
try {
client.getById("foo", ids, null);
} catch (ParseException ignored) {}
} }
} }
@ -437,9 +403,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
UpdateRequest req = new UpdateRequest(); UpdateRequest req = new UpdateRequest();
req.add(new SolrInputDocument()); req.add(new SolrInputDocument());
req.setParam("a", "\u1234"); req.setParam("a", "\u1234");
try { expectThrows(ParseException.class, () -> client.request(req));
client.request(req);
} catch (ParseException ignored) {}
//default method //default method
assertEquals("post", DebugServlet.lastMethod); assertEquals("post", DebugServlet.lastMethod);
@ -460,9 +424,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
//XML response and writer //XML response and writer
client.setParser(new XMLResponseParser()); client.setParser(new XMLResponseParser());
client.setRequestWriter(new RequestWriter()); client.setRequestWriter(new RequestWriter());
try { expectThrows(ParseException.class, () -> client.request(req));
client.request(req);
} catch (ParseException ignored) {}
assertEquals("post", DebugServlet.lastMethod); assertEquals("post", DebugServlet.lastMethod);
assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent")); assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent"));
@ -478,9 +440,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
client.setParser(new BinaryResponseParser()); client.setParser(new BinaryResponseParser());
client.setRequestWriter(new BinaryRequestWriter()); client.setRequestWriter(new BinaryRequestWriter());
DebugServlet.clear(); DebugServlet.clear();
try { expectThrows(ParseException.class, () -> client.request(req));
client.request(req);
} catch (ParseException ignored) {}
assertEquals("post", DebugServlet.lastMethod); assertEquals("post", DebugServlet.lastMethod);
assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent")); assertEquals("Solr[" + HttpSolrClient.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent"));
@ -501,40 +461,30 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
try (HttpSolrClient client = getHttpSolrClient(clientUrl)) { try (HttpSolrClient client = getHttpSolrClient(clientUrl)) {
SolrQuery q = new SolrQuery("*:*"); SolrQuery q = new SolrQuery("*:*");
// default = false // default = false
try { SolrServerException e = expectThrows(SolrServerException.class, () -> client.query(q));
client.query(q); assertTrue(e.getMessage().contains("redirect"));
fail("Should have thrown an exception.");
} catch (SolrServerException e) {
assertTrue(e.getMessage().contains("redirect"));
}
client.setFollowRedirects(true); client.setFollowRedirects(true);
client.query(q); client.query(q);
//And back again: //And back again:
client.setFollowRedirects(false); client.setFollowRedirects(false);
try { e = expectThrows(SolrServerException.class, () -> client.query(q));
client.query(q); assertTrue(e.getMessage().contains("redirect"));
fail("Should have thrown an exception.");
} catch (SolrServerException e) {
assertTrue(e.getMessage().contains("redirect"));
}
} }
} }
@Test @Test
public void testCompression() throws Exception { public void testCompression() throws Exception {
SolrQuery q = new SolrQuery("*:*"); final SolrQuery q = new SolrQuery("*:*");
final String clientUrl = jetty.getBaseUrl().toString() + "/debug/foo"; final String clientUrl = jetty.getBaseUrl().toString() + "/debug/foo";
try (HttpSolrClient client = getHttpSolrClient(clientUrl)) { try (HttpSolrClient client = getHttpSolrClient(clientUrl)) {
// verify request header gets set // verify request header gets set
DebugServlet.clear(); DebugServlet.clear();
try { expectThrows(ParseException.class, () -> client.query(q));
client.query(q); assertNull(DebugServlet.headers.toString(), DebugServlet.headers.get("Accept-Encoding"));
} catch (ParseException ignored) {}
assertNull(DebugServlet.headers.toString(), DebugServlet.headers.get("Accept-Encoding"));
} }
try (HttpSolrClient client = getHttpSolrClient(clientUrl, null, null, true)) { try (HttpSolrClient client = getHttpSolrClient(clientUrl, null, null, true)) {
@ -549,7 +499,6 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
client.query(q); client.query(q);
} catch (ParseException ignored) {} } catch (ParseException ignored) {}
} }
assertNull(DebugServlet.headers.get("Accept-Encoding")); assertNull(DebugServlet.headers.get("Accept-Encoding"));
// verify server compresses output // verify server compresses output
@ -579,8 +528,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
// verify compressed response can be handled // verify compressed response can be handled
try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/collection1")) { try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/collection1")) {
q = new SolrQuery("foo"); QueryResponse response = client.query(new SolrQuery("foo"));
QueryResponse response = client.query(q);
assertEquals(0, response.getStatus()); assertEquals(0, response.getStatus());
} }
} }
@ -685,9 +633,7 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
SolrQuery q = new SolrQuery("foo"); SolrQuery q = new SolrQuery("foo");
q.setParam("a", "\u1234"); q.setParam("a", "\u1234");
try { expectThrows(Exception.class, () -> server.query(q, random().nextBoolean()?METHOD.POST:METHOD.GET));
server.query(q, random().nextBoolean()?METHOD.POST:METHOD.GET);
} catch (Throwable t) {}
// Assert cookies from UseContextCallback // Assert cookies from UseContextCallback
assertNotNull(DebugServlet.cookies); assertNotNull(DebugServlet.cookies);
@ -759,48 +705,40 @@ public class BasicHttpSolrClientTest extends SolrJettyTestBase {
client.setQueryParams(setOf("serverOnly")); client.setQueryParams(setOf("serverOnly"));
UpdateRequest req = new UpdateRequest(); UpdateRequest req = new UpdateRequest();
setReqParamsOf(req, "serverOnly", "notServer"); setReqParamsOf(req, "serverOnly", "notServer");
try { expectThrows(ParseException.class, () -> client.request(req));
client.request(req);
} catch (ParseException ignored) {}
verifyServletState(client, req); verifyServletState(client, req);
// test without server query params // test without server query params
DebugServlet.clear(); DebugServlet.clear();
client.setQueryParams(setOf()); client.setQueryParams(setOf());
req = new UpdateRequest(); UpdateRequest req2 = new UpdateRequest();
req.setQueryParams(setOf("requestOnly")); req2.setQueryParams(setOf("requestOnly"));
setReqParamsOf(req, "requestOnly", "notRequest"); setReqParamsOf(req2, "requestOnly", "notRequest");
try { expectThrows(ParseException.class, () -> client.request(req2));
client.request(req); verifyServletState(client, req2);
} catch (ParseException ignored) {}
verifyServletState(client, req);
// test with both request and server query params // test with both request and server query params
DebugServlet.clear(); DebugServlet.clear();
req = new UpdateRequest(); UpdateRequest req3 = new UpdateRequest();
client.setQueryParams(setOf("serverOnly", "both")); client.setQueryParams(setOf("serverOnly", "both"));
req.setQueryParams(setOf("requestOnly", "both")); req3.setQueryParams(setOf("requestOnly", "both"));
setReqParamsOf(req, "serverOnly", "requestOnly", "both", "neither"); setReqParamsOf(req3, "serverOnly", "requestOnly", "both", "neither");
try { expectThrows(ParseException.class, () -> client.request(req3));
client.request(req); verifyServletState(client, req3);
} catch (ParseException ignored) {}
verifyServletState(client, req);
// test with both request and server query params with single stream // test with both request and server query params with single stream
DebugServlet.clear(); DebugServlet.clear();
req = new UpdateRequest(); UpdateRequest req4 = new UpdateRequest();
req.add(new SolrInputDocument()); req4.add(new SolrInputDocument());
client.setQueryParams(setOf("serverOnly", "both")); client.setQueryParams(setOf("serverOnly", "both"));
req.setQueryParams(setOf("requestOnly", "both")); req4.setQueryParams(setOf("requestOnly", "both"));
setReqParamsOf(req, "serverOnly", "requestOnly", "both", "neither"); setReqParamsOf(req4, "serverOnly", "requestOnly", "both", "neither");
try { expectThrows(ParseException.class, () -> client.request(req4));
client.request(req);
} catch (ParseException ignored) {}
// NOTE: single stream requests send all the params // NOTE: single stream requests send all the params
// as part of the query string. So add "neither" to the request // as part of the query string. So add "neither" to the request
// so it passes the verification step. // so it passes the verification step.
req.setQueryParams(setOf("requestOnly", "both", "neither")); req4.setQueryParams(setOf("requestOnly", "both", "neither"));
verifyServletState(client, req); verifyServletState(client, req4);
} }
} }

View File

@ -32,6 +32,9 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.lucene.util.LuceneTestCase.Slow; import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.lucene.util.TestUtil; import org.apache.lucene.util.TestUtil;
@ -75,10 +78,6 @@ import org.junit.rules.ExpectedException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/** /**
* This test would be faster if we simulated the zk state instead. * This test would be faster if we simulated the zk state instead.
@ -667,10 +666,8 @@ public class CloudSolrClientTest extends SolrCloudTestCase {
public void testShutdown() throws IOException { public void testShutdown() throws IOException {
try (CloudSolrClient client = getCloudSolrClient("[ff01::114]:33332")) { try (CloudSolrClient client = getCloudSolrClient("[ff01::114]:33332")) {
client.setZkConnectTimeout(100); client.setZkConnectTimeout(100);
client.connect(); SolrException ex = expectThrows(SolrException.class, client::connect);
fail("Expected exception"); assertTrue(ex.getCause() instanceof TimeoutException);
} catch (SolrException e) {
assertTrue(e.getCause() instanceof TimeoutException);
} }
} }
@ -679,14 +676,10 @@ public class CloudSolrClientTest extends SolrCloudTestCase {
@Test @Test
public void testWrongZkChrootTest() throws IOException { public void testWrongZkChrootTest() throws IOException {
exception.expect(SolrException.class);
exception.expectMessage("cluster not found/not ready");
try (CloudSolrClient client = getCloudSolrClient(cluster.getZkServer().getZkAddress() + "/xyz/foo")) { try (CloudSolrClient client = getCloudSolrClient(cluster.getZkServer().getZkAddress() + "/xyz/foo")) {
client.setZkClientTimeout(1000 * 60); client.setZkClientTimeout(1000 * 60);
client.connect(); SolrException ex = expectThrows(SolrException.class, client::connect);
fail("Expected exception"); assertTrue(ex.getMessage().contains("cluster not found/not ready"));
} }
} }
@ -765,16 +758,8 @@ public class CloudSolrClientTest extends SolrCloudTestCase {
public void testCollectionDoesntExist() throws Exception { public void testCollectionDoesntExist() throws Exception {
CloudSolrClient client = getRandomClient(); CloudSolrClient client = getRandomClient();
SolrInputDocument doc = new SolrInputDocument("id", "1", "title_s", "my doc"); SolrInputDocument doc = new SolrInputDocument("id", "1", "title_s", "my doc");
try { SolrException ex = expectThrows(SolrException.class, () -> client.add("boguscollectionname", doc));
client.add("boguscollectionname", doc); assertEquals("Collection not found: boguscollectionname", ex.getMessage());
fail();
} catch (SolrException ex) {
if (ex.getMessage().equals("Collection not found: boguscollectionname")) {
// pass
} else {
throw ex;
}
}
} }
public void testRetryUpdatesWhenClusterStateIsStale() throws Exception { public void testRetryUpdatesWhenClusterStateIsStale() throws Exception {

View File

@ -20,6 +20,7 @@ import org.apache.http.cookie.CookieAttributeHandler;
import org.apache.http.cookie.CookieOrigin; import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException; import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.solr.SolrTestCaseJ4;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -36,12 +37,7 @@ public class SolrPortAwareCookieSpecTest {
h.validate(cookie, origin); h.validate(cookie, origin);
cookie.setDomain("somehost:1234"); cookie.setDomain("somehost:1234");
try { SolrTestCaseJ4.expectThrows(MalformedCookieException.class, () -> h.validate(cookie, origin));
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
} }
@Test @Test
@ -51,12 +47,7 @@ public class SolrPortAwareCookieSpecTest {
final CookieAttributeHandler h = new SolrPortAwareCookieSpecFactory.PortAwareDomainHandler(); final CookieAttributeHandler h = new SolrPortAwareCookieSpecFactory.PortAwareDomainHandler();
cookie.setDomain("myhost"); cookie.setDomain("myhost");
try { SolrTestCaseJ4.expectThrows(IllegalArgumentException.class, () -> h.match(cookie, null));
h.match(cookie, null);
Assert.fail("IllegalArgumentException should have been thrown, since origin is null.");
} catch (final IllegalArgumentException ex) {
// expected
}
cookie.setDomain(null); cookie.setDomain(null);
Assert.assertFalse(h.match(cookie, origin)); Assert.assertFalse(h.match(cookie, origin));
@ -84,12 +75,7 @@ public class SolrPortAwareCookieSpecTest {
h.validate(cookie, origin); h.validate(cookie, origin);
cookie.setDomain("otherhost"); cookie.setDomain("otherhost");
try { SolrTestCaseJ4.expectThrows(MalformedCookieException.class, () -> h.validate(cookie, origin));
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
} }
@Test @Test
@ -102,19 +88,10 @@ public class SolrPortAwareCookieSpecTest {
h.validate(cookie, origin); h.validate(cookie, origin);
cookie.setDomain(".otherdomain.com"); cookie.setDomain(".otherdomain.com");
try { SolrTestCaseJ4.expectThrows(MalformedCookieException.class, () -> h.validate(cookie, origin));
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
cookie.setDomain("www.otherdomain.com"); cookie.setDomain("www.otherdomain.com");
try { SolrTestCaseJ4.expectThrows(MalformedCookieException.class, () -> h.validate(cookie, origin));
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
} }
@Test @Test
@ -127,12 +104,7 @@ public class SolrPortAwareCookieSpecTest {
h.validate(cookie, origin); h.validate(cookie, origin);
cookie.setDomain(".com"); cookie.setDomain(".com");
try { SolrTestCaseJ4.expectThrows(MalformedCookieException.class, () -> h.validate(cookie, origin));
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
} }
@Test @Test
@ -145,12 +117,7 @@ public class SolrPortAwareCookieSpecTest {
h.validate(cookie, origin); h.validate(cookie, origin);
cookie.setDomain(".b.c"); cookie.setDomain(".b.c");
try { SolrTestCaseJ4.expectThrows(MalformedCookieException.class, () -> h.validate(cookie, origin));
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
} }
@Test @Test
@ -179,18 +146,9 @@ public class SolrPortAwareCookieSpecTest {
@Test @Test
public void testDomainInvalidInput() throws Exception { public void testDomainInvalidInput() throws Exception {
final CookieAttributeHandler h = new SolrPortAwareCookieSpecFactory.PortAwareDomainHandler(); final CookieAttributeHandler h = new SolrPortAwareCookieSpecFactory.PortAwareDomainHandler();
try { SolrTestCaseJ4.expectThrows(IllegalArgumentException.class, () -> h.match(null, null));
h.match(null, null); SolrTestCaseJ4.expectThrows(IllegalArgumentException.class,
Assert.fail("IllegalArgumentException must have been thrown"); () -> h.match(new BasicClientCookie("name", "value"), null));
} catch (final IllegalArgumentException ex) {
// expected
}
try {
h.match(new BasicClientCookie("name", "value"), null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
} }
} }

View File

@ -40,13 +40,8 @@ public class TestCloudSolrClientConnections extends SolrTestCaseJ4 {
CloudSolrClient client = cluster.getSolrClient(); CloudSolrClient client = cluster.getSolrClient();
CollectionAdminRequest.List listReq = new CollectionAdminRequest.List(); CollectionAdminRequest.List listReq = new CollectionAdminRequest.List();
try { SolrException e = expectThrows(SolrException.class, () -> client.request(listReq));
client.request(listReq); assertTrue("Unexpected message: " + e.getMessage(), e.getMessage().contains("cluster not found/not ready"));
fail("Requests to a non-running cluster should throw a SolrException");
}
catch (SolrException e) {
assertTrue("Unexpected message: " + e.getMessage(), e.getMessage().contains("cluster not found/not ready"));
}
cluster.startJettySolrRunner(); cluster.startJettySolrRunner();
cluster.waitForAllNodes(30); cluster.waitForAllNodes(30);
@ -70,12 +65,10 @@ public class TestCloudSolrClientConnections extends SolrTestCaseJ4 {
MiniSolrCloudCluster cluster = new MiniSolrCloudCluster(0, createTempDir(), buildJettyConfig("/solr")); MiniSolrCloudCluster cluster = new MiniSolrCloudCluster(0, createTempDir(), buildJettyConfig("/solr"));
try { try {
CloudSolrClient client = cluster.getSolrClient(); CloudSolrClient client = cluster.getSolrClient();
try { SolrException e = expectThrows(SolrException.class, () -> {
((ZkClientClusterStateProvider)client.getClusterStateProvider()).uploadConfig(configPath, "testconfig"); ((ZkClientClusterStateProvider)client.getClusterStateProvider()).uploadConfig(configPath, "testconfig");
fail("Requests to a non-running cluster should throw a SolrException"); });
} catch (SolrException e) { assertTrue("Unexpected message: " + e.getMessage(), e.getMessage().contains("cluster not found/not ready"));
assertTrue("Unexpected message: " + e.getMessage(), e.getMessage().contains("cluster not found/not ready"));
}
cluster.startJettySolrRunner(); cluster.startJettySolrRunner();
cluster.waitForAllNodes(30); cluster.waitForAllNodes(30);

View File

@ -329,12 +329,7 @@ public class SchemaTest extends RestTestBase {
SchemaResponse.UpdateResponse deleteFieldResponse = deleteFieldRequest.process(getSolrClient()); SchemaResponse.UpdateResponse deleteFieldResponse = deleteFieldRequest.process(getSolrClient());
assertValidSchemaResponse(deleteFieldResponse); assertValidSchemaResponse(deleteFieldResponse);
try { expectThrows(SolrException.class, () -> fieldSchemaRequest.process(getSolrClient()));
fieldSchemaRequest.process(getSolrClient());
fail(String.format(Locale.ROOT, "after removal, the field %s shouldn't be anymore available over Schema API", fieldName));
} catch (SolrException e) {
//success
}
} }
@Test @Test
@ -454,13 +449,7 @@ public class SchemaTest extends RestTestBase {
SchemaResponse.UpdateResponse deleteDynamicFieldResponse = deleteFieldRequest.process(getSolrClient()); SchemaResponse.UpdateResponse deleteDynamicFieldResponse = deleteFieldRequest.process(getSolrClient());
assertValidSchemaResponse(deleteDynamicFieldResponse); assertValidSchemaResponse(deleteDynamicFieldResponse);
try { expectThrows(SolrException.class, () -> dynamicFieldSchemaRequest.process(getSolrClient()));
dynamicFieldSchemaRequest.process(getSolrClient());
fail(String.format(Locale.ROOT, "after removal, the dynamic field %s shouldn't be anymore available over Schema API",
dynamicFieldName));
} catch (SolrException e) {
//success
}
} }
@Test @Test

View File

@ -19,7 +19,6 @@ package org.apache.solr.client.solrj.request;
import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.response.ConfigSetAdminResponse; import org.apache.solr.client.solrj.response.ConfigSetAdminResponse;
import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
/** /**
@ -48,13 +47,9 @@ public class TestConfigSetAdminRequest extends SolrTestCaseJ4 {
} }
private void verifyException(ConfigSetAdminRequest request, String errorContains) { private void verifyException(ConfigSetAdminRequest request, String errorContains) {
try { Exception e = expectThrows(Exception.class, request::getParams);
request.getParams(); assertTrue("Expected exception message to contain: " + errorContains,
Assert.fail("Expected exception"); e.getMessage().contains(errorContains));
} catch (Exception e) {
assertTrue("Expected exception message to contain: " + errorContains,
e.getMessage().contains(errorContains));
}
} }
private static class MyConfigSetAdminRequest extends ConfigSetAdminRequest<MyConfigSetAdminRequest, ConfigSetAdminResponse> { private static class MyConfigSetAdminRequest extends ConfigSetAdminRequest<MyConfigSetAdminRequest, ConfigSetAdminResponse> {

View File

@ -43,7 +43,6 @@ import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.CoreContainer; import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrCore; import org.apache.solr.core.SolrCore;
import org.apache.solr.metrics.SolrCoreMetricManager; import org.apache.solr.metrics.SolrCoreMetricManager;
@ -163,43 +162,27 @@ public class TestCoreAdmin extends AbstractEmbeddedSolrServerTestCase {
params.set("name", collectionName); params.set("name", collectionName);
QueryRequest request = new QueryRequest(params); QueryRequest request = new QueryRequest(params);
request.setPath("/admin/cores"); request.setPath("/admin/cores");
boolean gotExp = false; expectThrows(SolrException.class, () -> getSolrAdmin().request(request));
NamedList<Object> resp = null;
try {
resp = getSolrAdmin().request(request);
} catch (SolrException e) {
gotExp = true;
}
assertTrue(gotExp);
} }
@Test @Test
public void testInvalidCoreNamesAreRejectedWhenCreatingCore() { public void testInvalidCoreNamesAreRejectedWhenCreatingCore() {
final Create createRequest = new Create(); final Create createRequest = new Create();
SolrException e = expectThrows(SolrException.class, () -> createRequest.setCoreName("invalid$core@name"));
try { final String exceptionMessage = e.getMessage();
createRequest.setCoreName("invalid$core@name"); assertTrue(exceptionMessage.contains("Invalid core"));
fail(); assertTrue(exceptionMessage.contains("invalid$core@name"));
} catch (SolrException e) { assertTrue(exceptionMessage.contains("must consist entirely of periods, underscores, hyphens, and alphanumerics"));
final String exceptionMessage = e.getMessage();
assertTrue(exceptionMessage.contains("Invalid core"));
assertTrue(exceptionMessage.contains("invalid$core@name"));
assertTrue(exceptionMessage.contains("must consist entirely of periods, underscores, hyphens, and alphanumerics"));
}
} }
@Test @Test
public void testInvalidCoreNamesAreRejectedWhenRenamingExistingCore() throws Exception { public void testInvalidCoreNamesAreRejectedWhenRenamingExistingCore() throws Exception {
try { SolrException e = expectThrows(SolrException.class,
CoreAdminRequest.renameCore("validExistingCoreName", "invalid$core@name", null); () -> CoreAdminRequest.renameCore("validExistingCoreName", "invalid$core@name", null));
fail(); final String exceptionMessage = e.getMessage();
} catch (SolrException e) { assertTrue(e.getMessage(), exceptionMessage.contains("Invalid core"));
final String exceptionMessage = e.getMessage(); assertTrue(exceptionMessage.contains("invalid$core@name"));
assertTrue(e.getMessage(), exceptionMessage.contains("Invalid core")); assertTrue(exceptionMessage.contains("must consist entirely of periods, underscores, hyphens, and alphanumerics"));
assertTrue(exceptionMessage.contains("invalid$core@name"));
assertTrue(exceptionMessage.contains("must consist entirely of periods, underscores, hyphens, and alphanumerics"));
}
} }
@Test @Test

View File

@ -68,12 +68,10 @@ public class TestDelegationTokenResponse extends SolrTestCase {
DelegationTokenResponse.Get getResponse = new DelegationTokenResponse.Get(); DelegationTokenResponse.Get getResponse = new DelegationTokenResponse.Get();
// not a map // not a map
try { expectThrows(SolrException.class, () -> {
delegationTokenResponse(getRequest, getResponse, ""); delegationTokenResponse(getRequest, getResponse, "");
getResponse.getDelegationToken(); getResponse.getDelegationToken();
fail("Expected SolrException"); });
} catch (SolrException se) {
}
// doesn't have Token outerMap // doesn't have Token outerMap
final String someToken = "someToken"; final String someToken = "someToken";
@ -81,12 +79,8 @@ public class TestDelegationTokenResponse extends SolrTestCase {
assertNull(getResponse.getDelegationToken()); assertNull(getResponse.getDelegationToken());
// Token is not a map // Token is not a map
try { delegationTokenResponse(getRequest, getResponse, getMapJson("Token", someToken));
delegationTokenResponse(getRequest, getResponse, getMapJson("Token", someToken)); expectThrows(SolrException.class, getResponse::getDelegationToken);
getResponse.getDelegationToken();
fail("Expected SolrException");
} catch (SolrException se) {
}
// doesn't have urlString // doesn't have urlString
delegationTokenResponse(getRequest, getResponse, getNestedMapJson("Token", "notUrlString", someToken)); delegationTokenResponse(getRequest, getResponse, getNestedMapJson("Token", "notUrlString", someToken));
@ -104,24 +98,18 @@ public class TestDelegationTokenResponse extends SolrTestCase {
DelegationTokenResponse.Renew renewResponse = new DelegationTokenResponse.Renew(); DelegationTokenResponse.Renew renewResponse = new DelegationTokenResponse.Renew();
// not a map // not a map
try { expectThrows(SolrException.class, () -> {
delegationTokenResponse(renewRequest, renewResponse, ""); delegationTokenResponse(renewRequest, renewResponse, "");
renewResponse.getExpirationTime(); renewResponse.getExpirationTime();
fail("Expected SolrException"); });
} catch (SolrException se) {
}
// doesn't have long // doesn't have long
delegationTokenResponse(renewRequest, renewResponse, getMapJson("notLong", "123")); delegationTokenResponse(renewRequest, renewResponse, getMapJson("notLong", "123"));
assertNull(renewResponse.getExpirationTime()); assertNull(renewResponse.getExpirationTime());
// long isn't valid // long isn't valid
try { delegationTokenResponse(renewRequest, renewResponse, getMapJson("long", "aaa"));
delegationTokenResponse(renewRequest, renewResponse, getMapJson("long", "aaa")); expectThrows(SolrException.class, renewResponse::getExpirationTime);
renewResponse.getExpirationTime();
fail("Expected SolrException");
} catch (SolrException se) {
}
// valid // valid
Long expirationTime = Long.MAX_VALUE; Long expirationTime = Long.MAX_VALUE;

View File

@ -53,30 +53,18 @@ public class TestToleratedUpdateError extends SolrTestCase {
@Test @Test
// commented out on: 24-Dec-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Sep-2018 // commented out on: 24-Dec-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Sep-2018
public void testParseMapErrorChecking() { public void testParseMapErrorChecking() {
SimpleOrderedMap<String> bogus = new SimpleOrderedMap<String>(); SimpleOrderedMap<String> bogus = new SimpleOrderedMap<>();
try { SolrException e = expectThrows(SolrException.class, () -> ToleratedUpdateError.parseMap(bogus));
ToleratedUpdateError.parseMap(bogus); assertTrue(e.toString(), e.getMessage().contains("Map does not represent a ToleratedUpdateError"));
fail("map should not be parsable");
} catch (SolrException e) {
assertTrue(e.toString(), e.getMessage().contains("Map does not represent a ToleratedUpdateError") );
}
bogus.add("id", "some id"); bogus.add("id", "some id");
bogus.add("message", "some message"); bogus.add("message", "some message");
try { e = expectThrows(SolrException.class, () -> ToleratedUpdateError.parseMap(bogus));
ToleratedUpdateError.parseMap(bogus); assertTrue(e.toString(), e.getMessage().contains("Map does not represent a ToleratedUpdateError"));
fail("map should still not be parsable");
} catch (SolrException e) {
assertTrue(e.toString(), e.getMessage().contains("Map does not represent a ToleratedUpdateError") );
}
bogus.add("type", "not a real type"); bogus.add("type", "not a real type");
try { e = expectThrows(SolrException.class, () -> ToleratedUpdateError.parseMap(bogus));
ToleratedUpdateError.parseMap(bogus); assertTrue(e.toString(), e.getMessage().contains("Invalid type"));
fail("invalid type should not be parsable");
} catch (SolrException e) {
assertTrue(e.toString(), e.getMessage().contains("Invalid type"));
}
} }
public void testParseMap() { public void testParseMap() {

View File

@ -76,19 +76,17 @@ public class JsonValidatorTest extends SolrTestCaseJ4 {
errs = validator.validateJson(Utils.fromJSONString("{name:x, age:'x21', adult:'true'}")); errs = validator.validateJson(Utils.fromJSONString("{name:x, age:'x21', adult:'true'}"));
assertEquals(1, errs.size()); assertEquals(1, errs.size());
try { Exception e = expectThrows(Exception.class, () -> {
validator = new JsonSchemaValidator("{" + new JsonSchemaValidator("{" +
" type:object," + " type:object," +
" properties: {" + " properties: {" +
" age : {type: int}," + " age : {type: int}," +
" adult : {type: Boolean}," + " adult : {type: Boolean}," +
" name: {type: string}}}"); " name: {type: string}}}");
fail("should have failed"); });
} catch (Exception e) { assertTrue(e.getMessage().contains("Unknown type"));
assertTrue(e.getMessage().contains("Unknown type"));
}
try { e = expectThrows(Exception.class, () -> {
new JsonSchemaValidator("{" + new JsonSchemaValidator("{" +
" type:object," + " type:object," +
" x : y," + " x : y," +
@ -96,21 +94,18 @@ public class JsonValidatorTest extends SolrTestCaseJ4 {
" age : {type: number}," + " age : {type: number}," +
" adult : {type: boolean}," + " adult : {type: boolean}," +
" name: {type: string}}}"); " name: {type: string}}}");
fail("should have failed"); });
} catch (Exception e) { assertTrue(e.getMessage().contains("Unknown key"));
assertTrue(e.getMessage().contains("Unknown key"));
} e = expectThrows(Exception.class, () -> {
try {
new JsonSchemaValidator("{" + new JsonSchemaValidator("{" +
" type:object," + " type:object," +
" propertes: {" + " propertes: {" +
" age : {type: number}," + " age : {type: number}," +
" adult : {type: boolean}," + " adult : {type: boolean}," +
" name: {type: string}}}"); " name: {type: string}}}");
fail("should have failed"); });
} catch (Exception e) { assertTrue(e.getMessage().contains("Unknown key : propertes"));
assertTrue(e.getMessage().contains("Unknown key : propertes"));
}
validator = new JsonSchemaValidator("{" + validator = new JsonSchemaValidator("{" +
" type:object," + " type:object," +

View File

@ -25,6 +25,7 @@ import org.apache.solr.common.SolrException;
import org.junit.Test; import org.junit.Test;
public class NamedListTest extends SolrTestCase { public class NamedListTest extends SolrTestCase {
public void testRemove() { public void testRemove() {
NamedList<String> nl = new NamedList<>(); NamedList<String> nl = new NamedList<>();
nl.add("key1", "value1"); nl.add("key1", "value1");
@ -87,14 +88,8 @@ public class NamedListTest extends SolrTestCase {
assertEquals("value1-3", values.get(2)); assertEquals("value1-3", values.get(2));
assertEquals(6, values.size()); assertEquals(6, values.size());
assertEquals(7, nl.size()); assertEquals(7, nl.size());
try {
values = (ArrayList<String>) nl.removeConfigArgs("key2"); expectThrows(SolrException.class, () -> nl.removeConfigArgs("key2"));
fail();
}
catch(SolrException e) {
// Expected exception.
assertTrue(true);
}
// nl should be unmodified when removeArgs throws an exception. // nl should be unmodified when removeArgs throws an exception.
assertEquals(7, nl.size()); assertEquals(7, nl.size());
} }

View File

@ -28,6 +28,7 @@ import static org.apache.solr.common.util.ValidatingJsonMap.ENUM_OF;
import static org.apache.solr.common.util.ValidatingJsonMap.NOT_NULL; import static org.apache.solr.common.util.ValidatingJsonMap.NOT_NULL;
public class TestValidatingJsonMap extends SolrTestCaseJ4 { public class TestValidatingJsonMap extends SolrTestCaseJ4 {
public void testBasic() throws Exception { public void testBasic() throws Exception {
ValidatingJsonMap m = ValidatingJsonMap.wrap( ValidatingJsonMap m = ValidatingJsonMap.wrap(
makeMap("a", Boolean.TRUE, makeMap("a", Boolean.TRUE,
@ -38,10 +39,8 @@ public class TestValidatingJsonMap extends SolrTestCaseJ4 {
assertEquals(Boolean.TRUE, m.getBool("a", Boolean.FALSE)); assertEquals(Boolean.TRUE, m.getBool("a", Boolean.FALSE));
assertEquals(Boolean.FALSE, m.getBool("b", Boolean.TRUE)); assertEquals(Boolean.FALSE, m.getBool("b", Boolean.TRUE));
assertEquals(Integer.valueOf(10), m.getInt("i",0)); assertEquals(Integer.valueOf(10), m.getInt("i",0));
try {
m.getList("l", ENUM_OF, ImmutableSet.of("X", "Z")); expectThrows(RuntimeException.class, () -> m.getList("l", ENUM_OF, ImmutableSet.of("X", "Z")));
fail("Must have failed with unexpected type");
} catch (RuntimeException e) { }
List l = m.getList("l", ENUM_OF, ImmutableSet.of("X", "Y", "Z")); List l = m.getList("l", ENUM_OF, ImmutableSet.of("X", "Y", "Z"));
assertEquals(2,l.size()); assertEquals(2,l.size());

View File

@ -82,16 +82,10 @@ public class MiniSolrCloudClusterTest extends SolrTestCase {
} }
}; };
try { Exception ex = expectThrows(Exception.class, cluster::shutdown);
cluster.shutdown(); assertEquals("Error shutting down MiniSolrCloudCluster", ex.getMessage());
fail("Expected an exception to be thrown on MiniSolrCloudCluster shutdown"); assertEquals("Expected one suppressed exception", 1, ex.getSuppressed().length);
} assertEquals("Fake IOException on shutdown!", ex.getSuppressed()[0].getMessage());
catch (Exception e) {
assertEquals("Error shutting down MiniSolrCloudCluster", e.getMessage());
assertEquals("Expected one suppressed exception", 1, e.getSuppressed().length);
assertEquals("Fake IOException on shutdown!", e.getSuppressed()[0].getMessage());
}
} }
@Test @Test