SOLR-12555: Use `expectThrows` for expected exceptions

This commit replaces the `try { doX(); fail(); }` pattern with the
`expectThrows` test helper, which was created for this purpose.

This commit makes these changes in the core package:
`o.a.solr.core`.
This commit is contained in:
Jason Gerlowski 2018-12-01 14:33:49 -05:00
parent e5281ef3d5
commit 6e4c9b3b58
9 changed files with 141 additions and 217 deletions

View File

@ -63,15 +63,16 @@ public class PluginInfoTest extends DOMUtilTestBase {
@Test
public void testNameRequired() throws Exception {
Node nodeWithNoName = getNode("<plugin></plugin>", "plugin");
SolrTestCaseJ4.ignoreException("missing mandatory attribute");
try {
PluginInfo pi = new PluginInfo(nodeWithNoName, "Node with No name", true, false);
fail("Exception should have been thrown");
} catch (RuntimeException e) {
assertTrue(e.getMessage().contains("missing mandatory attribute"));
SolrTestCaseJ4.ignoreException("missing mandatory attribute");
RuntimeException thrown = expectThrows(RuntimeException.class, () -> {
PluginInfo pi = new PluginInfo(nodeWithNoName, "Node with No name", true, false);
});
assertTrue(thrown.getMessage().contains("missing mandatory attribute"));
} finally {
SolrTestCaseJ4.resetExceptionIgnores();
}
Node nodeWithAName = getNode("<plugin name=\"myName\" />", "plugin");
PluginInfo pi2 = new PluginInfo(nodeWithAName, "Node with a Name", true, false);
assertTrue(pi2.name.equals("myName"));
@ -80,16 +81,16 @@ public class PluginInfoTest extends DOMUtilTestBase {
@Test
public void testClassRequired() throws Exception {
Node nodeWithNoClass = getNode("<plugin></plugin>", "plugin");
SolrTestCaseJ4.ignoreException("missing mandatory attribute");
try {
@SuppressWarnings("unused")
PluginInfo pi = new PluginInfo(nodeWithNoClass, "Node with No Class", false, true);
fail("Exception should have been thrown");
} catch (RuntimeException e) {
assertTrue(e.getMessage().contains("missing mandatory attribute"));
SolrTestCaseJ4.ignoreException("missing mandatory attribute");
RuntimeException thrown = expectThrows(RuntimeException.class, () -> {
PluginInfo pi = new PluginInfo(nodeWithNoClass, "Node with No Class", false, true);
});
assertTrue(thrown.getMessage().contains("missing mandatory attribute"));
} finally {
SolrTestCaseJ4.resetExceptionIgnores();
}
Node nodeWithAClass = getNode("<plugin class=\"myName\" />", "plugin");
PluginInfo pi2 = new PluginInfo(nodeWithAClass, "Node with a Class", false, true);
assertTrue(pi2.className.equals("myName"));

View File

@ -29,7 +29,6 @@ import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import junit.framework.Assert;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.KeywordTokenizerFactory;
import org.apache.lucene.analysis.ngram.NGramFilterFactory;
@ -59,6 +58,7 @@ public class ResourceLoaderTest extends SolrTestCaseJ4 {
Files.write(temp.resolve("dummy.txt"), new byte[]{});
Path instanceDir = temp.resolve("instance");
Files.createDirectories(instanceDir.resolve("conf"));
try (SolrResourceLoader loader = new SolrResourceLoader(instanceDir)) {
loader.openResource("../../dummy.txt").close();
fail();
@ -70,11 +70,11 @@ public class ResourceLoaderTest extends SolrTestCaseJ4 {
public void testAwareCompatibility() throws Exception {
Class<?> clazz = ResourceLoaderAware.class;
final Class<?> clazz1 = ResourceLoaderAware.class;
// Check ResourceLoaderAware valid objects
//noinspection unchecked
assertAwareCompatibility(clazz, new NGramFilterFactory(map("minGramSize", "1", "maxGramSize", "2")));
assertAwareCompatibility(clazz, new KeywordTokenizerFactory(new HashMap<>()));
assertAwareCompatibility(clazz1, new NGramFilterFactory(map("minGramSize", "1", "maxGramSize", "2")));
assertAwareCompatibility(clazz1, new KeywordTokenizerFactory(new HashMap<>()));
// Make sure it throws an error for invalid objects
Object[] invalid = new Object[] {
@ -84,19 +84,15 @@ public class ResourceLoaderTest extends SolrTestCaseJ4 {
new JSONResponseWriter()
};
for( Object obj : invalid ) {
try {
assertAwareCompatibility(clazz, obj);
Assert.fail( "Should be invalid class: "+obj + " FOR " + clazz );
}
catch( SolrException ex ) { } // OK
expectThrows(SolrException.class, () -> assertAwareCompatibility(clazz1, obj));
}
clazz = SolrCoreAware.class;
final Class<?> clazz2 = SolrCoreAware.class;
// Check ResourceLoaderAware valid objects
assertAwareCompatibility(clazz, new LukeRequestHandler());
assertAwareCompatibility(clazz, new FacetComponent());
assertAwareCompatibility(clazz, new JSONResponseWriter());
assertAwareCompatibility(clazz2, new LukeRequestHandler());
assertAwareCompatibility(clazz2, new FacetComponent());
assertAwareCompatibility(clazz2, new JSONResponseWriter());
// Make sure it throws an error for invalid objects
//noinspection unchecked
@ -106,13 +102,8 @@ public class ResourceLoaderTest extends SolrTestCaseJ4 {
new KeywordTokenizerFactory(new HashMap<>())
};
for( Object obj : invalid ) {
try {
assertAwareCompatibility(clazz, obj);
Assert.fail( "Should be invalid class: "+obj + " FOR " + clazz );
}
catch( SolrException ex ) { } // OK
expectThrows(SolrException.class, () -> assertAwareCompatibility(clazz2, obj));
}
}
public void testBOMMarkers() throws Exception {
@ -145,15 +136,11 @@ public class ResourceLoaderTest extends SolrTestCaseJ4 {
public void testWrongEncoding() throws Exception {
String wrongEncoding = "stopwordsWrongEncoding.txt";
SolrResourceLoader loader = new SolrResourceLoader(TEST_PATH().resolve("collection1"));
// ensure we get our exception
try {
loader.getLines(wrongEncoding);
fail();
} catch (SolrException expected) {
assertTrue(expected.getCause() instanceof CharacterCodingException);
try(SolrResourceLoader loader = new SolrResourceLoader(TEST_PATH().resolve("collection1"))) {
// ensure we get our exception
SolrException thrown = expectThrows(SolrException.class, () -> loader.getLines(wrongEncoding));
assertTrue(thrown.getCause() instanceof CharacterCodingException);
}
loader.close();
}
public void testClassLoaderLibs() throws Exception {

View File

@ -159,39 +159,32 @@ public class TestCodecSupport extends SolrTestCaseJ4 {
}
public void testBadCompressionMode() throws Exception {
try {
SolrException thrown = expectThrows(SolrException.class, () -> {
doTestCompressionMode("something_that_doesnt_exist", "something_that_doesnt_exist");
fail("Expecting exception");
} catch (SolrException e) {
assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, e.code());
assertTrue("Unexpected Exception message: " + e.getMessage(),
e.getMessage().contains("Unable to reload core"));
}
});
assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, thrown.code());
assertTrue("Unexpected Exception message: " + thrown.getMessage(),
thrown.getMessage().contains("Unable to reload core"));
SchemaCodecFactory factory = new SchemaCodecFactory();
NamedList<String> nl = new NamedList<>();
final SchemaCodecFactory factory1 = new SchemaCodecFactory();
final NamedList<String> nl = new NamedList<>();
nl.add(SchemaCodecFactory.COMPRESSION_MODE, "something_that_doesnt_exist");
try {
factory.init(nl);
fail("Expecting exception");
} catch (SolrException e) {
assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, e.code());
assertTrue("Unexpected Exception message: " + e.getMessage(),
e.getMessage().contains("Invalid compressionMode: 'something_that_doesnt_exist'"));
}
factory = new SchemaCodecFactory();
nl = new NamedList<>();
nl.add(SchemaCodecFactory.COMPRESSION_MODE, "");
try {
factory.init(nl);
fail("Expecting exception");
} catch (SolrException e) {
assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, e.code());
assertTrue("Unexpected Exception message: " + e.getMessage(),
e.getMessage().contains("Invalid compressionMode: ''"));
}
thrown = expectThrows(SolrException.class, () -> {
factory1.init(nl);
});
assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, thrown.code());
assertTrue("Unexpected Exception message: " + thrown.getMessage(),
thrown.getMessage().contains("Invalid compressionMode: 'something_that_doesnt_exist'"));
final SchemaCodecFactory factory2 = new SchemaCodecFactory();
final NamedList<String> nl2 = new NamedList<>();
nl2.add(SchemaCodecFactory.COMPRESSION_MODE, "");
thrown = expectThrows(SolrException.class, () -> {
factory2.init(nl2);
});
assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, thrown.code());
assertTrue("Unexpected Exception message: " + thrown.getMessage(),
thrown.getMessage().contains("Invalid compressionMode: ''"));
}
public void testCompressionModeDefault() throws IOException {

View File

@ -196,18 +196,15 @@ public class TestConfig extends SolrTestCaseJ4 {
Assert.assertEquals(-1, SolrConfig.convertHeapOptionStyleConfigStringToBytes(""));
// Invalid values
try {
RuntimeException thrown = expectThrows(RuntimeException.class, () -> {
SolrConfig.convertHeapOptionStyleConfigStringToBytes("3jbk32k"); // valid suffix but non-numeric prefix
Assert.fail();
} catch (RuntimeException e) {
Assert.assertTrue(e.getMessage().contains("Invalid"));
}
try {
});
assertTrue(thrown.getMessage().contains("Invalid"));
thrown = expectThrows(RuntimeException.class, () -> {
SolrConfig.convertHeapOptionStyleConfigStringToBytes("300x"); // valid prefix but invalid suffix
Assert.fail();
} catch (RuntimeException e) {
Assert.assertTrue(e.getMessage().contains("Invalid"));
}
});
assertTrue(thrown.getMessage().contains("Invalid"));
}
@Test

View File

@ -46,22 +46,18 @@ public class TestConfigSetProperties extends SolrTestCaseJ4 {
@Test
public void testEmptyConfigSetProperties() throws Exception {
try {
SolrException thrown = expectThrows(SolrException.class, () -> {
createConfigSetProps("");
fail("Excepted SolrException");
} catch (SolrException ex) {
assertEquals(ErrorCode.SERVER_ERROR.code, ex.code());
}
});
assertEquals(ErrorCode.SERVER_ERROR.code, thrown.code());
}
@Test
public void testConfigSetPropertiesNotMap() throws Exception {
try {
SolrException thrown = expectThrows(SolrException.class, () -> {
createConfigSetProps(JSONUtil.toJSON(new String[] {"test"}));
fail("Expected SolrException");
} catch (SolrException ex) {
assertEquals(ErrorCode.SERVER_ERROR.code, ex.code());
}
});
assertEquals(ErrorCode.SERVER_ERROR.code, thrown.code());
}
@Test

View File

@ -88,19 +88,16 @@ public class TestConfigSets extends SolrTestCaseJ4 {
@Test
public void testNonExistentConfigSetThrowsException() {
CoreContainer container = null;
final CoreContainer container = setupContainer(getFile("solr/configsets").getAbsolutePath());
try {
container = setupContainer(getFile("solr/configsets").getAbsolutePath());
Path testDirectory = container.getResourceLoader().getInstancePath();
container.create("core1", ImmutableMap.of("configSet", "nonexistent"));
fail("Expected core creation to fail");
}
catch (Exception e) {
Throwable wrappedException = getWrappedException(e);
Exception thrown = expectThrows(Exception.class, "Expected core creation to fail", () -> {
container.create("core1", ImmutableMap.of("configSet", "nonexistent"));
});
Throwable wrappedException = getWrappedException(thrown);
assertThat(wrappedException.getMessage(), containsString("nonexistent"));
}
finally {
} finally {
if (container != null)
container.shutdown();
}

View File

@ -166,26 +166,17 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
assertEquals("There should not be cores", 0, cores.getCores().size());
// try and remove a core that does not exist
try {
SolrException thrown = expectThrows(SolrException.class, () -> {
cores.unload("non_existent_core");
fail("Should have thrown an exception when unloading a non-existent core");
}
catch (SolrException e) {
assertThat(e.getMessage(), containsString("Cannot unload non-existent core [non_existent_core]"));
}
});
assertThat(thrown.getMessage(), containsString("Cannot unload non-existent core [non_existent_core]"));
// try and remove a null core
try {
thrown = expectThrows(SolrException.class, () -> {
cores.unload(null);
fail("Should have thrown an exception when unloading a null core");
}
catch (Exception e) {
if (!(e instanceof SolrException)) {
fail("Should not have thrown SolrException but got " + e);
}
assertThat(e.getMessage(), containsString("Cannot unload non-existent core [null]"));
}
});
assertThat(thrown.getMessage(), containsString("Cannot unload non-existent core [null]"));
} finally {
cores.shutdown();
}
@ -411,16 +402,13 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// -----
// try to add a collection with a configset that doesn't exist
try {
ignoreException(Pattern.quote("bogus_path"));
ignoreException(Pattern.quote("bogus_path"));
SolrException thrown = expectThrows(SolrException.class, () -> {
cc.create("bogus", ImmutableMap.of("configSet", "bogus_path"));
fail("bogus inst dir failed to trigger exception from create");
} catch (SolrException e) {
Throwable cause = Throwables.getRootCause(e);
assertTrue("init exception doesn't mention bogus dir: " + cause.getMessage(),
0 < cause.getMessage().indexOf("bogus_path"));
}
});
Throwable rootCause = Throwables.getRootCause(thrown);
assertTrue("init exception doesn't mention bogus dir: " + rootCause.getMessage(),
0 < rootCause.getMessage().indexOf("bogus_path"));
// check that we have the cores we expect
cores = cc.getLoadedCoreNames();
@ -439,16 +427,13 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// check that we get null accessing a non-existent core
assertNull(cc.getCore("does_not_exist"));
// check that we get a 500 accessing the core with an init failure
try {
thrown = expectThrows(SolrException.class, () -> {
SolrCore c = cc.getCore("bogus");
fail("Failed to get Exception on accessing core with init failure");
} catch (SolrException ex) {
assertEquals(500, ex.code());
String cause = Throwables.getRootCause(ex).getMessage();
assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
0 < cause.indexOf("bogus_path"));
}
});
assertEquals(500, thrown.code());
String cause = Throwables.getRootCause(thrown).getMessage();
assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
0 < cause.indexOf("bogus_path"));
cc.shutdown();
}
@ -494,16 +479,12 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// check that we get null accessing a non-existent core
assertNull(cc.getCore("does_not_exist"));
// check that we get a 500 accessing the core with an init failure
try {
SolrException thrown = expectThrows(SolrException.class, () -> {
SolrCore c = cc.getCore("col_bad");
fail("Failed to get Exception on accessing core with init failure");
} catch (SolrException ex) {
assertEquals(500, ex.code());
// double wrapped
String cause = ex.getCause().getCause().getMessage();
assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
0 < cause.indexOf("DummyMergePolicy"));
}
});
assertEquals(500, thrown.code());
String cause = thrown.getCause().getCause().getMessage();
assertTrue("getCore() ex cause doesn't mention init fail: " + cause, 0 < cause.indexOf("DummyMergePolicy"));
// -----
// "fix" the bad collection
@ -528,15 +509,12 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// -----
// try to add a collection with a path that doesn't exist
try {
ignoreException(Pattern.quote("bogus_path"));
ignoreException(Pattern.quote("bogus_path"));
thrown = expectThrows(SolrException.class, () -> {
cc.create("bogus", ImmutableMap.of("configSet", "bogus_path"));
fail("bogus inst dir failed to trigger exception from create");
} catch (SolrException e) {
assertTrue("init exception doesn't mention bogus dir: " + e.getCause().getCause().getMessage(),
0 < e.getCause().getCause().getMessage().indexOf("bogus_path"));
}
});
assertTrue("init exception doesn't mention bogus dir: " + thrown.getCause().getCause().getMessage(),
0 < thrown.getCause().getCause().getMessage().indexOf("bogus_path"));
// check that we have the cores we expect
cores = cc.getLoadedCoreNames();
@ -557,16 +535,13 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
// check that we get null accessing a non-existent core
assertNull(cc.getCore("does_not_exist"));
// check that we get a 500 accessing the core with an init failure
try {
thrown = expectThrows(SolrException.class, () -> {
SolrCore c = cc.getCore("bogus");
fail("Failed to get Exception on accessing core with init failure");
} catch (SolrException ex) {
assertEquals(500, ex.code());
// double wrapped
String cause = ex.getCause().getMessage();
assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
0 < cause.indexOf("bogus_path"));
}
});
assertEquals(500, thrown.code());
cause = thrown.getCause().getMessage();
assertTrue("getCore() ex cause doesn't mention init fail: " + cause,
0 < cause.indexOf("bogus_path"));
// -----
// break col_bad's config and try to RELOAD to add failure
@ -578,19 +553,16 @@ public class TestCoreContainer extends SolrTestCaseJ4 {
"This is giberish, not valid XML <",
IOUtils.UTF_8);
try {
ignoreException(Pattern.quote("SAX"));
cc.reload("col_bad");
fail("corrupt solrconfig.xml failed to trigger exception from reload");
} catch (SolrException e) {
Throwable rootException = getWrappedException(e);
assertTrue("We're supposed to have a wrapped SAXParserException here, but we don't",
rootException instanceof SAXParseException);
SAXParseException se = (SAXParseException) rootException;
assertTrue("reload exception doesn't refer to slrconfig.xml " + se.getSystemId(),
0 < se.getSystemId().indexOf("solrconfig.xml"));
}
ignoreException(Pattern.quote("SAX"));
thrown = expectThrows(SolrException.class,
"corrupt solrconfig.xml failed to trigger exception from reload",
() -> { cc.reload("col_bad"); });
Throwable rootException = getWrappedException(thrown);
assertTrue("We're supposed to have a wrapped SAXParserException here, but we don't",
rootException instanceof SAXParseException);
SAXParseException se = (SAXParseException) rootException;
assertTrue("reload exception doesn't refer to slrconfig.xml " + se.getSystemId(),
0 < se.getSystemId().indexOf("solrconfig.xml"));
assertEquals("Failed core reload should not have changed start time",
col_bad_old_start, getCoreStartTime(cc, "col_bad"));

View File

@ -228,12 +228,8 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {
CoreContainer cc = init();
try {
try {
cc.getCore("corep1");
fail("Should have thrown exception");
} catch (SolrCoreInitializationException scie) {
assertTrue(scie.getMessage().contains("init failure"));
}
Exception thrown = expectThrows(SolrCoreInitializationException.class, () -> cc.getCore("corep1"));
assertTrue(thrown.getMessage().contains("init failure"));
try (SolrCore sc = cc.getCore("corep2")) {
assertNotNull("Core corep2 should be loaded", sc);
}
@ -249,17 +245,15 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {
corePropFile = Paths.get(solrHomeDirectory.toString(), "corep4", "core.properties");
assertFalse("Should not be a properties file yet for corep4", Files.exists(corePropFile));
try {
thrown = expectThrows(SolrException.class, () -> {
cc.create("corep4", ImmutableMap.of(
CoreDescriptor.CORE_NAME, "corep4",
CoreDescriptor.CORE_SCHEMA, "not-there.xml",
CoreDescriptor.CORE_CONFIG, "solrconfig-minimal.xml",
CoreDescriptor.CORE_TRANSIENT, "false",
CoreDescriptor.CORE_LOADONSTARTUP, "true"));
fail("Should have thrown exception getting core ");
} catch (SolrException se) {
assertTrue(se.getMessage().contains("Can't find resource"));
}
});
assertTrue(thrown.getMessage().contains("Can't find resource"));
assertFalse("Failed corep4 should not have left a core.properties file around", Files.exists(corePropFile));
// Finally, just for yucks, let's determine that a this create path also leaves a prop file.
@ -344,23 +338,18 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {
// name, isLazy, loadOnStartup
addCoreWithProps("core1", makeCoreProperties("core1", false, true));
addCoreWithProps("core2", makeCoreProperties("core2", false, false, "name=core1"));
CoreContainer cc = null;
try {
cc = init();
fail("Should have thrown exception in testDuplicateNames");
} catch (SolrException se) {
String message = se.getMessage();
assertTrue("Wrong exception thrown on duplicate core names",
message.indexOf("Found multiple cores with the name [core1]") != -1);
assertTrue(File.separator + "core1 should have been mentioned in the message: " + message,
message.indexOf(File.separator + "core1") != -1);
assertTrue(File.separator + "core2 should have been mentioned in the message:" + message,
message.indexOf(File.separator + "core2") != -1);
} finally {
if (cc != null) {
cc.shutdown();
}
}
SolrException thrown = expectThrows(SolrException.class, () -> {
CoreContainer cc = null;
try { cc = init(); }
finally { if (cc != null) cc.shutdown(); }
});
final String message = thrown.getMessage();
assertTrue("Wrong exception thrown on duplicate core names",
message.indexOf("Found multiple cores with the name [core1]") != -1);
assertTrue(File.separator + "core1 should have been mentioned in the message: " + message,
message.indexOf(File.separator + "core1") != -1);
assertTrue(File.separator + "core2 should have been mentioned in the message:" + message,
message.indexOf(File.separator + "core2") != -1);
}
@ -533,17 +522,12 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {
assumeTrue("Cannot make " + homeDir + " non-readable. Test aborted.", homeDir.setReadable(false, false));
assumeFalse("Appears we are a super user, skip test", homeDir.canRead());
CoreContainer cc = null;
try {
cc = init();
fail("Should have thrown an exception here");
} catch (Exception ex) {
assertThat(ex.getMessage(), containsString("Error reading core root directory"));
} finally {
if (cc != null) {
cc.shutdown();
}
}
Exception thrown = expectThrows(Exception.class, () -> {
CoreContainer cc = null;
try { cc = init(); }
finally { if (cc != null) cc.shutdown(); }
});
assertThat(thrown.getMessage(), containsString("Error reading core root directory"));
// So things can be cleaned up by the framework!
homeDir.setReadable(true, false);

View File

@ -309,7 +309,7 @@ public class TestLazyCores extends SolrTestCaseJ4 {
}
private void tryCreateFail(CoreAdminHandler admin, String name, String dataDir, String... errs) throws Exception {
try {
SolrException thrown = expectThrows(SolrException.class, () -> {
SolrQueryResponse resp = new SolrQueryResponse();
SolrQueryRequest request = req(CoreAdminParams.ACTION,
@ -320,14 +320,11 @@ public class TestLazyCores extends SolrTestCaseJ4 {
"config", "solrconfig.xml");
admin.handleRequestBody(request, resp);
fail("Should have thrown an error");
} catch (SolrException se) {
//SolrException cause = (SolrException)se.getCause();
assertEquals("Exception code should be 500", 500, se.code());
for (String err : errs) {
assertTrue("Should have seen an exception containing the an error",
se.getMessage().contains(err));
}
});
assertEquals("Exception code should be 500", 500, thrown.code());
for (String err : errs) {
assertTrue("Should have seen an exception containing the an error",
thrown.getMessage().contains(err));
}
}
@Test