LUCENE-8938: use expectThrows() to verify the ex thrown in tests

This commit is contained in:
Munendra S N 2019-07-29 22:21:18 +05:30
parent 1d303cee7f
commit 70a8deb0ab
24 changed files with 241 additions and 519 deletions

View File

@ -175,12 +175,7 @@ public class TestSynonymGraphFilter extends BaseTokenStreamTestCase {
String testFile = "a => 1";
Analyzer analyzer = new MockAnalyzer(random(), MockTokenizer.SIMPLE, false);
SolrSynonymParser parser = new SolrSynonymParser(true, true, analyzer);
try {
parser.parse(new StringReader(testFile));
fail("didn't get expected exception");
} catch (ParseException expected) {
// expected exc
}
expectThrows(ParseException.class, () -> parser.parse(new StringReader(testFile)));
analyzer.close();
}
@ -191,12 +186,7 @@ public class TestSynonymGraphFilter extends BaseTokenStreamTestCase {
String testFile = "a => b => c";
Analyzer analyzer = new MockAnalyzer(random());
SolrSynonymParser parser = new SolrSynonymParser(true, true, analyzer);
try {
parser.parse(new StringReader(testFile));
fail("didn't get expected exception");
} catch (ParseException expected) {
// expected exc
}
expectThrows(ParseException.class, () -> parser.parse(new StringReader(testFile)));
analyzer.close();
}
@ -561,13 +551,10 @@ public class TestSynonymGraphFilter extends BaseTokenStreamTestCase {
public void testZeroSyns() throws Exception {
Tokenizer tokenizer = new MockTokenizer();
tokenizer.setReader(new StringReader("aa bb"));
try {
new SynonymGraphFilter(tokenizer, new SynonymMap.Builder(true).build(), true);
fail("did not hit expected exception");
} catch (IllegalArgumentException iae) {
// expected
assertEquals("fst must be non-null", iae.getMessage());
}
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () ->
new SynonymGraphFilter(tokenizer, new SynonymMap.Builder(true).build(), true));
assertEquals("fst must be non-null", ex.getMessage());
}
public void testOutputHangsOffEnd() throws Exception {

View File

@ -140,90 +140,50 @@ public class TestCharArrayMap extends LuceneTestCase {
assertTrue(map.containsKey("bar"));
assertEquals(2, map.get("bar").intValue());
map = CharArrayMap.unmodifiableMap(map);
assertEquals("Map size changed due to unmodifiableMap call" , size, map.size());
CharArrayMap<Integer> unmodifiableMap = CharArrayMap.unmodifiableMap(map);
assertEquals("Map size changed due to unmodifiableMap call" , size, unmodifiableMap.size());
String NOT_IN_MAP = "SirGallahad";
assertFalse("Test String already exists in map", map.containsKey(NOT_IN_MAP));
assertNull("Test String already exists in map", map.get(NOT_IN_MAP));
assertFalse("Test String already exists in map", unmodifiableMap.containsKey(NOT_IN_MAP));
assertNull("Test String already exists in map", unmodifiableMap.get(NOT_IN_MAP));
try{
map.put(NOT_IN_MAP.toCharArray(), 3);
fail("Modified unmodifiable map");
}catch (UnsupportedOperationException e) {
// expected
assertFalse("Test String has been added to unmodifiable map", map.containsKey(NOT_IN_MAP));
assertNull("Test String has been added to unmodifiable map", map.get(NOT_IN_MAP));
assertEquals("Size of unmodifiable map has changed", size, map.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put(NOT_IN_MAP.toCharArray(), 3));
assertFalse("Test String has been added to unmodifiable map", unmodifiableMap.containsKey(NOT_IN_MAP));
assertNull("Test String has been added to unmodifiable map", unmodifiableMap.get(NOT_IN_MAP));
assertEquals("Size of unmodifiable map has changed", size, unmodifiableMap.size());
try{
map.put(NOT_IN_MAP, 3);
fail("Modified unmodifiable map");
}catch (UnsupportedOperationException e) {
// expected
assertFalse("Test String has been added to unmodifiable map", map.containsKey(NOT_IN_MAP));
assertNull("Test String has been added to unmodifiable map", map.get(NOT_IN_MAP));
assertEquals("Size of unmodifiable map has changed", size, map.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put(NOT_IN_MAP, 3));
assertFalse("Test String has been added to unmodifiable map", unmodifiableMap.containsKey(NOT_IN_MAP));
assertNull("Test String has been added to unmodifiable map", unmodifiableMap.get(NOT_IN_MAP));
assertEquals("Size of unmodifiable map has changed", size, unmodifiableMap.size());
try{
map.put(new StringBuilder(NOT_IN_MAP), 3);
fail("Modified unmodifiable map");
}catch (UnsupportedOperationException e) {
// expected
assertFalse("Test String has been added to unmodifiable map", map.containsKey(NOT_IN_MAP));
assertNull("Test String has been added to unmodifiable map", map.get(NOT_IN_MAP));
assertEquals("Size of unmodifiable map has changed", size, map.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put(new StringBuilder(NOT_IN_MAP), 3));
assertFalse("Test String has been added to unmodifiable map", unmodifiableMap.containsKey(NOT_IN_MAP));
assertNull("Test String has been added to unmodifiable map", unmodifiableMap.get(NOT_IN_MAP));
assertEquals("Size of unmodifiable map has changed", size, unmodifiableMap.size());
try{
map.clear();
fail("Modified unmodifiable map");
}catch (UnsupportedOperationException e) {
// expected
assertEquals("Size of unmodifiable map has changed", size, map.size());
}
expectThrows(UnsupportedOperationException.class, unmodifiableMap::clear);
assertEquals("Size of unmodifiable map has changed", size, unmodifiableMap.size());
try{
map.entrySet().clear();
fail("Modified unmodifiable map");
}catch (UnsupportedOperationException e) {
// expected
assertEquals("Size of unmodifiable map has changed", size, map.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableMap.entrySet().clear());
assertEquals("Size of unmodifiable map has changed", size, unmodifiableMap.size());
try{
map.keySet().clear();
fail("Modified unmodifiable map");
}catch (UnsupportedOperationException e) {
// expected
assertEquals("Size of unmodifiable map has changed", size, map.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableMap.keySet().clear());
assertEquals("Size of unmodifiable map has changed", size, unmodifiableMap.size());
try{
map.put((Object) NOT_IN_MAP, 3);
fail("Modified unmodifiable map");
}catch (UnsupportedOperationException e) {
// expected
assertFalse("Test String has been added to unmodifiable map", map.containsKey(NOT_IN_MAP));
assertNull("Test String has been added to unmodifiable map", map.get(NOT_IN_MAP));
assertEquals("Size of unmodifiable map has changed", size, map.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put((Object) NOT_IN_MAP, 3));
assertFalse("Test String has been added to unmodifiable map", unmodifiableMap.containsKey(NOT_IN_MAP));
assertNull("Test String has been added to unmodifiable map", unmodifiableMap.get(NOT_IN_MAP));
assertEquals("Size of unmodifiable map has changed", size, unmodifiableMap.size());
try{
map.putAll(Collections.singletonMap(NOT_IN_MAP, 3));
fail("Modified unmodifiable map");
}catch (UnsupportedOperationException e) {
// expected
assertFalse("Test String has been added to unmodifiable map", map.containsKey(NOT_IN_MAP));
assertNull("Test String has been added to unmodifiable map", map.get(NOT_IN_MAP));
assertEquals("Size of unmodifiable map has changed", size, map.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableMap.putAll(Collections.singletonMap(NOT_IN_MAP, 3)));
assertFalse("Test String has been added to unmodifiable map", unmodifiableMap.containsKey(NOT_IN_MAP));
assertNull("Test String has been added to unmodifiable map", unmodifiableMap.get(NOT_IN_MAP));
assertEquals("Size of unmodifiable map has changed", size, unmodifiableMap.size());
assertTrue(map.containsKey("foo"));
assertEquals(1, map.get("foo").intValue());
assertTrue(map.containsKey("bar"));
assertEquals(2, map.get("bar").intValue());
assertTrue(unmodifiableMap.containsKey("foo"));
assertEquals(1, unmodifiableMap.get("foo").intValue());
assertTrue(unmodifiableMap.containsKey("bar"));
assertEquals(2, unmodifiableMap.get("bar").intValue());
}
public void testToString() {

View File

@ -90,87 +90,49 @@ public class TestCharArraySet extends LuceneTestCase {
// TODO: break this up into simpler test methods, vs "telling a story"
public void testModifyOnUnmodifiable(){
CharArraySet set=new CharArraySet(10, true);
CharArraySet set = new CharArraySet(10, true);
set.addAll(Arrays.asList(TEST_STOP_WORDS));
final int size = set.size();
set = CharArraySet.unmodifiableSet(set);
assertEquals("Set size changed due to unmodifiableSet call" , size, set.size());
CharArraySet unmodifiableSet = CharArraySet.unmodifiableSet(set);
assertEquals("Set size changed due to unmodifiableSet call" , size, unmodifiableSet.size());
String NOT_IN_SET = "SirGallahad";
assertFalse("Test String already exists in set", set.contains(NOT_IN_SET));
assertFalse("Test String already exists in set", unmodifiableSet.contains(NOT_IN_SET));
try{
set.add(NOT_IN_SET.toCharArray());
fail("Modified unmodifiable set");
}catch (UnsupportedOperationException e) {
// expected
assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET));
assertEquals("Size of unmodifiable set has changed", size, set.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableSet.add(NOT_IN_SET.toCharArray()));
assertFalse("Test String has been added to unmodifiable set", unmodifiableSet.contains(NOT_IN_SET));
assertEquals("Size of unmodifiable set has changed", size, unmodifiableSet.size());
try{
set.add(NOT_IN_SET);
fail("Modified unmodifiable set");
}catch (UnsupportedOperationException e) {
// expected
assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET));
assertEquals("Size of unmodifiable set has changed", size, set.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableSet.add(NOT_IN_SET));
assertFalse("Test String has been added to unmodifiable set", unmodifiableSet.contains(NOT_IN_SET));
assertEquals("Size of unmodifiable set has changed", size, unmodifiableSet.size());
try{
set.add(new StringBuilder(NOT_IN_SET));
fail("Modified unmodifiable set");
}catch (UnsupportedOperationException e) {
// expected
assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET));
assertEquals("Size of unmodifiable set has changed", size, set.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableSet.add(new StringBuilder(NOT_IN_SET)));
assertFalse("Test String has been added to unmodifiable set", unmodifiableSet.contains(NOT_IN_SET));
assertEquals("Size of unmodifiable set has changed", size, unmodifiableSet.size());
try{
set.clear();
fail("Modified unmodifiable set");
}catch (UnsupportedOperationException e) {
// expected
assertFalse("Changed unmodifiable set", set.contains(NOT_IN_SET));
assertEquals("Size of unmodifiable set has changed", size, set.size());
}
try{
set.add((Object) NOT_IN_SET);
fail("Modified unmodifiable set");
}catch (UnsupportedOperationException e) {
// expected
assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET));
assertEquals("Size of unmodifiable set has changed", size, set.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableSet.clear());
assertFalse("Changed unmodifiable set", unmodifiableSet.contains(NOT_IN_SET));
assertEquals("Size of unmodifiable set has changed", size, unmodifiableSet.size());
expectThrows(UnsupportedOperationException.class, () -> unmodifiableSet.add((Object) NOT_IN_SET));
assertFalse("Test String has been added to unmodifiable set", unmodifiableSet.contains(NOT_IN_SET));
assertEquals("Size of unmodifiable set has changed", size, unmodifiableSet.size());
// This test was changed in 3.1, as a contains() call on the given Collection using the "correct" iterator's
// current key (now a char[]) on a Set<String> would not hit any element of the CAS and therefor never call
// remove() on the iterator
try{
set.removeAll(new CharArraySet(Arrays.asList(TEST_STOP_WORDS), true));
fail("Modified unmodifiable set");
}catch (UnsupportedOperationException e) {
// expected
assertEquals("Size of unmodifiable set has changed", size, set.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableSet.removeAll(new CharArraySet(Arrays.asList(TEST_STOP_WORDS), true)));
assertEquals("Size of unmodifiable set has changed", size, unmodifiableSet.size());
try{
set.retainAll(new CharArraySet(Arrays.asList(NOT_IN_SET), true));
fail("Modified unmodifiable set");
}catch (UnsupportedOperationException e) {
// expected
assertEquals("Size of unmodifiable set has changed", size, set.size());
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableSet.retainAll(new CharArraySet(Arrays.asList(NOT_IN_SET), true)));
assertEquals("Size of unmodifiable set has changed", size, unmodifiableSet.size());
try{
set.addAll(Arrays.asList(NOT_IN_SET));
fail("Modified unmodifiable set");
}catch (UnsupportedOperationException e) {
// expected
assertFalse("Test String has been added to unmodifiable set", set.contains(NOT_IN_SET));
}
expectThrows(UnsupportedOperationException.class, () -> unmodifiableSet.addAll(Arrays.asList(NOT_IN_SET)));
assertFalse("Test String has been added to unmodifiable set", unmodifiableSet.contains(NOT_IN_SET));
for (int i = 0; i < TEST_STOP_WORDS.length; i++) {
assertTrue(set.contains(TEST_STOP_WORDS[i]));
assertTrue(unmodifiableSet.contains(TEST_STOP_WORDS[i]));
}
}

View File

@ -127,21 +127,15 @@ public class TestAllFilesCheckIndexHeader extends LuceneTestCase {
dirCopy.sync(Collections.singleton(name));
}
try {
// NOTE: we .close so that if the test fails (truncation not detected) we don't also get all these confusing errors about open files:
DirectoryReader.open(dirCopy).close();
fail("wrong bytes not detected after randomizing first " + wrongBytes + " bytes out of " + victimLength + " for file " + victim);
} catch (CorruptIndexException | EOFException | IndexFormatTooOldException e) {
// expected
}
expectThrowsAnyOf(Arrays.asList(CorruptIndexException.class, EOFException.class, IndexFormatTooOldException.class),
() -> DirectoryReader.open(dirCopy).close()
);
// CheckIndex should also fail:
try {
TestUtil.checkIndex(dirCopy, true, true, null);
fail("wrong bytes not detected after randomizing first " + wrongBytes + " bytes out of " + victimLength + " for file " + victim);
} catch (CorruptIndexException | EOFException | IndexFormatTooOldException e) {
// expected
}
expectThrowsAnyOf(Arrays.asList(CorruptIndexException.class, EOFException.class, IndexFormatTooOldException.class),
() -> DirectoryReader.open(dirCopy).close()
);
}
}
}

View File

@ -19,6 +19,7 @@ package org.apache.lucene.index;
import java.io.EOFException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import org.apache.lucene.analysis.MockAnalyzer;
@ -104,21 +105,15 @@ public class TestAllFilesDetectTruncation extends LuceneTestCase {
dirCopy.sync(Collections.singleton(name));
}
try {
// NOTE: we .close so that if the test fails (truncation not detected) we don't also get all these confusing errors about open files:
DirectoryReader.open(dirCopy).close();
fail("truncation not detected after removing " + lostBytes + " bytes out of " + victimLength + " for file " + victim);
} catch (CorruptIndexException | EOFException e) {
// expected
}
expectThrowsAnyOf(Arrays.asList(CorruptIndexException.class, EOFException.class),
() -> DirectoryReader.open(dirCopy).close()
);
// CheckIndex should also fail:
try {
TestUtil.checkIndex(dirCopy, true, true, null);
fail("truncation not detected after removing " + lostBytes + " bytes out of " + victimLength + " for file " + victim);
} catch (CorruptIndexException | EOFException e) {
// expected
}
expectThrowsAnyOf(Arrays.asList(CorruptIndexException.class, EOFException.class),
() -> TestUtil.checkIndex(dirCopy, true, true, null)
);
}
}
}

View File

@ -21,6 +21,7 @@ import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
@ -475,22 +476,16 @@ public class TestDirectoryReader extends LuceneTestCase {
if (dir instanceof BaseDirectoryWrapper) {
((BaseDirectoryWrapper)dir).setCheckIndexOnClose(false); // we will hit NoSuchFileException in MDW since we nuked it!
}
try {
DirectoryReader.open(dir);
fail("expected FileNotFoundException/NoSuchFileException");
} catch (FileNotFoundException | NoSuchFileException e) {
// expected
}
expectThrowsAnyOf(Arrays.asList(FileNotFoundException.class, NoSuchFileException.class),
() -> DirectoryReader.open(dir)
);
IOUtils.rm(dirFile);
// Make sure we still get a CorruptIndexException (not NPE):
try {
DirectoryReader.open(dir);
fail("expected FileNotFoundException/NoSuchFileException");
} catch (FileNotFoundException | NoSuchFileException e) {
// expected
}
expectThrowsAnyOf(Arrays.asList(FileNotFoundException.class, NoSuchFileException.class),
() -> DirectoryReader.open(dir)
);
dir.close();
}

View File

@ -372,12 +372,7 @@ public class TestIndexableField extends LuceneTestCase {
public void testNotIndexedTermVectors() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir);
try {
w.addDocument(Collections.<IndexableField>singletonList(new CustomField()));
fail("didn't hit exception");
} catch (IllegalArgumentException iae) {
// expected
}
expectThrows(IllegalArgumentException.class, () -> w.addDocument(Collections.singletonList(new CustomField())));
w.close();
dir.close();
}

View File

@ -38,6 +38,7 @@ import org.apache.lucene.util.TestUtil;
*/
@SuppressFileSystems("ExtrasFS")
public class TestSwappedIndexFiles extends LuceneTestCase {
public void test() throws Exception {
Directory dir1 = newDirectory();
Directory dir2 = newDirectory();
@ -107,21 +108,15 @@ public class TestSwappedIndexFiles extends LuceneTestCase {
dirCopy.sync(Collections.singleton(name));
}
try {
// NOTE: we .close so that if the test fails (truncation not detected) we don't also get all these confusing errors about open files:
DirectoryReader.open(dirCopy).close();
fail("wrong file " + victim + " not detected");
} catch (CorruptIndexException | EOFException | IndexFormatTooOldException e) {
// expected
}
expectThrowsAnyOf(Arrays.asList(CorruptIndexException.class, EOFException.class, IndexFormatTooOldException.class),
() -> DirectoryReader.open(dirCopy).close()
);
// CheckIndex should also fail:
try {
TestUtil.checkIndex(dirCopy, true, true, null);
fail("wrong file " + victim + " not detected");
} catch (CorruptIndexException | EOFException | IndexFormatTooOldException e) {
// expected
}
expectThrowsAnyOf(Arrays.asList(CorruptIndexException.class, EOFException.class, IndexFormatTooOldException.class),
() -> TestUtil.checkIndex(dirCopy, true, true, null)
);
}
}
}

View File

@ -35,12 +35,9 @@ public final class TestRateLimiter extends LuceneTestCase {
Thread t = new Thread() {
@Override
public void run() {
try {
expectThrows(ThreadInterruptedException.class, () -> {
new SimpleRateLimiter(1).pause((long) (1.5*Integer.MAX_VALUE*1024*1024/1000));
fail("should have been interrupted");
} catch (ThreadInterruptedException tie) {
// expected
}
});
}
};
t.start();

View File

@ -47,10 +47,7 @@ public class TestCheckJoinIndex extends LuceneTestCase {
w.close();
BitSetProducer parentsFilter = new QueryBitSetProducer(new MatchNoDocsQuery());
try {
CheckJoinIndex.check(reader, parentsFilter);
fail("Invalid index");
} catch (IllegalStateException e) {
// expected
expectThrows(IllegalStateException.class, () -> CheckJoinIndex.check(reader, parentsFilter));
} finally {
reader.close();
dir.close();
@ -88,10 +85,7 @@ public class TestCheckJoinIndex extends LuceneTestCase {
w.close();
BitSetProducer parentsFilter = new QueryBitSetProducer(new TermQuery(new Term("parent", "true")));
try {
CheckJoinIndex.check(reader, parentsFilter);
fail("Invalid index");
} catch (IllegalStateException e) {
// expected
expectThrows(IllegalStateException.class, () -> CheckJoinIndex.check(reader, parentsFilter));
} finally {
reader.close();
dir.close();
@ -128,10 +122,7 @@ public class TestCheckJoinIndex extends LuceneTestCase {
BitSetProducer parentsFilter = new QueryBitSetProducer(new TermQuery(new Term("parent", "true")));
try {
CheckJoinIndex.check(reader, parentsFilter);
fail("Invalid index");
} catch (IllegalStateException e) {
// expected
expectThrows(IllegalStateException.class, () -> CheckJoinIndex.check(reader, parentsFilter));
} finally {
reader.close();
dir.close();

View File

@ -169,18 +169,8 @@ public class TestQueryParser extends QueryParserTestBase {
// doesn't work for some reason.
@SuppressWarnings("rawtype")
public void testProtectedCtors() throws Exception {
try {
QueryParser.class.getConstructor(CharStream.class);
fail("please switch public QueryParser(CharStream) to be protected");
} catch (NoSuchMethodException nsme) {
// expected
}
try {
QueryParser.class.getConstructor(QueryParserTokenManager.class);
fail("please switch public QueryParser(QueryParserTokenManager) to be protected");
} catch (NoSuchMethodException nsme) {
// expected
}
expectThrows(NoSuchMethodException.class, () -> QueryParser.class.getConstructor(CharStream.class));
expectThrows(NoSuchMethodException.class, () -> QueryParser.class.getConstructor(QueryParserTokenManager.class));
}
public void testFuzzySlopeExtendability() throws ParseException {

View File

@ -24,7 +24,15 @@ import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.lucene.analysis.*;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.LowerCaseFilter;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.analysis.MockSynonymFilter;
import org.apache.lucene.analysis.MockTokenFilter;
import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.document.DateTools;
@ -34,17 +42,27 @@ import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
//import org.apache.lucene.queryparser.classic.CharStream;
//import org.apache.lucene.queryparser.classic.ParseException;
//import org.apache.lucene.queryparser.classic.QueryParser;
//import org.apache.lucene.queryparser.classic.QueryParserBase;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.queryparser.classic.QueryParserBase;
//import org.apache.lucene.queryparser.classic.QueryParserTokenManager;
import org.apache.lucene.queryparser.classic.TestQueryParser;
import org.apache.lucene.queryparser.flexible.standard.CommonQueryParserConfiguration;
import org.apache.lucene.search.*;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.MatchNoDocsQuery;
import org.apache.lucene.search.MultiTermQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.RegexpQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.automaton.Automata;
@ -484,23 +502,16 @@ public abstract class QueryParserTestBase extends LuceneTestCase {
// Range queries:
assertWildcardQueryEquals("[A TO C]", "[a TO c]");
// Test suffix queries: first disallow
try {
Exception ex = expectThrows(Exception.class, () -> {
assertWildcardQueryEquals("*Term", "*term", false);
} catch(Exception pe) {
// expected exception
if(!isQueryParserException(pe)){
fail();
}
}
try {
});
assertTrue(isQueryParserException(ex));
ex = expectThrows(Exception.class, () -> {
assertWildcardQueryEquals("?Term", "?term");
fail();
} catch(Exception pe) {
// expected exception
if(!isQueryParserException(pe)){
fail();
}
}
});
assertTrue(isQueryParserException(ex));
// Test suffix queries: then allow
assertWildcardQueryEquals("*Term", "*term", true);
assertWildcardQueryEquals("?Term", "?term", true);

View File

@ -19,6 +19,7 @@ package org.apache.lucene.replicator;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
@ -141,12 +142,9 @@ public class LocalReplicatorTest extends ReplicatorTestCase {
public void testObtainMissingFile() throws IOException {
replicator.publish(createRevision(1));
SessionToken res = replicator.checkForUpdate(null);
try {
expectThrowsAnyOf(Arrays.asList(FileNotFoundException.class, NoSuchFileException.class), () -> {
replicator.obtainFile(res.id, res.sourceFiles.keySet().iterator().next(), "madeUpFile");
fail("should have failed obtaining an unrecognized file");
} catch (FileNotFoundException | NoSuchFileException e) {
// expected
}
});
}
@Test

View File

@ -137,13 +137,8 @@ public class HttpReplicatorTest extends ReplicatorTestCase {
try {
publishRevision(5);
try {
replicationServlet.setRespondWithError(true);
client.updateNow();
fail("expected exception");
} catch (Throwable t) {
// expected
}
expectThrows(Exception.class, client::updateNow);
replicationServlet.setRespondWithError(false);
client.updateNow(); // now it should work

View File

@ -747,12 +747,7 @@ public class TestTermAutomatonQuery extends LuceneTestCase {
TermAutomatonQuery q = new TermAutomatonQuery("field");
int initState = q.createState();
q.setAccept(initState, true);
try {
q.finish();
fail("did not hit exc");
} catch (IllegalStateException ise) {
// expected
}
expectThrows(IllegalStateException.class, q::finish);
}
public void testRewriteNoMatch() throws Exception {

View File

@ -1212,14 +1212,11 @@ public class AnalyzingSuggesterTest extends LuceneTestCase {
Directory tempDir = getDirectory();
AnalyzingSuggester suggester = new AnalyzingSuggester(tempDir, "suggest", a);
String bigString = TestUtil.randomSimpleString(random(), 30000, 30000);
try {
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> {
suggester.build(new InputArrayIterator(new Input[] {
new Input(bigString, 7)}));
fail("did not hit expected exception");
} catch (IllegalArgumentException iae) {
// expected
assertTrue(iae.getMessage().contains("input automaton is too large"));
}
});
assertTrue(ex.getMessage().contains("input automaton is too large"));
IOUtils.close(a, tempDir);
}

View File

@ -60,19 +60,10 @@ public class TestCompressingTermVectorsFormat extends BaseTermVectorsFormatTestC
assertNotNull(terms);
TermsEnum termsEnum = terms.iterator();
assertEquals(SeekStatus.FOUND, termsEnum.seekCeil(new BytesRef("this")));
try {
termsEnum.ord();
fail();
} catch (UnsupportedOperationException expected) {
// expected exception
}
try {
termsEnum.seekExact(0);
fail();
} catch (UnsupportedOperationException expected) {
// expected exception
}
expectThrows(UnsupportedOperationException.class, termsEnum::ord);
expectThrows(UnsupportedOperationException.class, () -> termsEnum.seekExact(0));
ir.close();
iw.close();
dir.close();

View File

@ -54,12 +54,9 @@ public class TestHandleLimitFS extends MockFileSystemTestCase {
}
// now exceed
try {
Files.newOutputStream(Files.createTempFile(dir, null, null));
fail("didn't hit exception");
} catch (IOException e) {
IOException e = expectThrows(IOException.class, () ->
Files.newOutputStream(Files.createTempFile(dir, null, null)));
assertTrue(e.getMessage().contains("Too many open files"));
}
IOUtils.close(toClose);
}

View File

@ -53,37 +53,17 @@ public class TestHandleTrackingFS extends MockFileSystemTestCase {
OutputStream file = Files.newOutputStream(dir.resolve("somefile"));
file.write(5);
try {
file.close();
fail("expected IOException");
} catch (IOException ex) {
// expected
}
expectThrows(IOException.class, file::close);
SeekableByteChannel channel = Files.newByteChannel(dir.resolve("somefile"));
try {
channel.close();
fail("expected IOException");
} catch (IOException ex) {
// expected
}
expectThrows(IOException.class, channel::close);
InputStream stream = Files.newInputStream(dir.resolve("somefile"));
try {
stream.close();
fail("expected IOException");
} catch (IOException ex) {
// expected
}
expectThrows(IOException.class, stream::close);
fs.close();
DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir);
try {
dirStream.close();
fail("expected IOException");
} catch (IOException ex) {
// expected
}
expectThrows(IOException.class, dirStream::close);
}
@ -102,34 +82,14 @@ public class TestHandleTrackingFS extends MockFileSystemTestCase {
}.getFileSystem(URI.create("file:///"));
Path dir = new FilterPath(path, fs);
try {
OutputStream file = Files.newOutputStream(dir.resolve("somefile"));
fail("expected IOException");
} catch (IOException ex) {
// expected
}
expectThrows(IOException.class, () -> Files.newOutputStream(dir.resolve("somefile")));
try {
SeekableByteChannel channel = Files.newByteChannel(dir.resolve("somefile"));
fail("expected IOException");
} catch (IOException ex) {
// expected
}
expectThrows(IOException.class, () -> Files.newByteChannel(dir.resolve("somefile")));
try {
InputStream stream = Files.newInputStream(dir.resolve("somefile"));
fail("expected IOException");
} catch (IOException ex) {
// expected
}
expectThrows(IOException.class, () -> Files.newInputStream(dir.resolve("somefile")));
fs.close();
try {
DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir);
fail("expected IOException");
} catch (IOException ex) {
// expected
}
expectThrows(IOException.class, () -> Files.newDirectoryStream(dir));
fs.close();
}
}

View File

@ -44,12 +44,9 @@ public class TestLeakFS extends MockFileSystemTestCase {
file.write(5);
file.close();
InputStream leak = Files.newInputStream(dir.resolve("stillopen"));
try {
dir.getFileSystem().close();
fail("should have gotten exception");
} catch (Exception e) {
Exception e = expectThrows(Exception.class, () -> dir.getFileSystem().close());
assertTrue(e.getMessage().contains("file handle leaks"));
}
leak.close();
}
@ -58,12 +55,8 @@ public class TestLeakFS extends MockFileSystemTestCase {
Path dir = wrap(createTempDir());
OutputStream leak = Files.newOutputStream(dir.resolve("leaky"));
try {
dir.getFileSystem().close();
fail("should have gotten exception");
} catch (Exception e) {
Exception e = expectThrows(Exception.class, () -> dir.getFileSystem().close());
assertTrue(e.getMessage().contains("file handle leaks"));
}
leak.close();
}
@ -75,12 +68,9 @@ public class TestLeakFS extends MockFileSystemTestCase {
file.write(5);
file.close();
FileChannel leak = FileChannel.open(dir.resolve("stillopen"));
try {
dir.getFileSystem().close();
fail("should have gotten exception");
} catch (Exception e) {
Exception e = expectThrows(Exception.class, () -> dir.getFileSystem().close());
assertTrue(e.getMessage().contains("file handle leaks"));
}
leak.close();
}
@ -92,12 +82,8 @@ public class TestLeakFS extends MockFileSystemTestCase {
file.write(5);
file.close();
AsynchronousFileChannel leak = AsynchronousFileChannel.open(dir.resolve("stillopen"));
try {
dir.getFileSystem().close();
fail("should have gotten exception");
} catch (Exception e) {
Exception e = expectThrows(Exception.class, () -> dir.getFileSystem().close());
assertTrue(e.getMessage().contains("file handle leaks"));
}
leak.close();
}
@ -109,12 +95,9 @@ public class TestLeakFS extends MockFileSystemTestCase {
file.write(5);
file.close();
SeekableByteChannel leak = Files.newByteChannel(dir.resolve("stillopen"));
try {
dir.getFileSystem().close();
fail("should have gotten exception");
} catch (Exception e) {
Exception e = expectThrows(Exception.class, () -> dir.getFileSystem().close());
assertTrue(e.getMessage().contains("file handle leaks"));
}
leak.close();
}
}

View File

@ -82,10 +82,7 @@ public class TestVerboseFS extends MockFileSystemTestCase {
Files.createDirectory(dir.resolve("subdir"));
assertTrue(stream.sawMessage());
try {
Files.createDirectory(dir.resolve("subdir"));
fail("didn't get expected exception");
} catch (IOException expected) {}
expectThrows(IOException.class, () -> Files.createDirectory(dir.resolve("subdir")));
}
/** Test delete */
@ -96,10 +93,7 @@ public class TestVerboseFS extends MockFileSystemTestCase {
Files.delete(dir.resolve("foobar"));
assertTrue(stream.sawMessage());
try {
Files.delete(dir.resolve("foobar"));
fail("didn't get expected exception");
} catch (IOException expected) {}
expectThrows(IOException.class, () -> Files.delete(dir.resolve("foobar")));
}
/** Test deleteIfExists */
@ -122,10 +116,7 @@ public class TestVerboseFS extends MockFileSystemTestCase {
Files.copy(dir.resolve("foobar"), dir.resolve("baz"));
assertTrue(stream.sawMessage());
try {
Files.copy(dir.resolve("nonexistent"), dir.resolve("something"));
fail("didn't get expected exception");
} catch (IOException expected) {}
expectThrows(IOException.class, () -> Files.copy(dir.resolve("nonexistent"), dir.resolve("something")));
}
/** Test move */
@ -136,10 +127,7 @@ public class TestVerboseFS extends MockFileSystemTestCase {
Files.move(dir.resolve("foobar"), dir.resolve("baz"));
assertTrue(stream.sawMessage());
try {
Files.move(dir.resolve("nonexistent"), dir.resolve("something"));
fail("didn't get expected exception");
} catch (IOException expected) {}
expectThrows(IOException.class, () -> Files.move(dir.resolve("nonexistent"), dir.resolve("something")));
}
/** Test newOutputStream */
@ -150,10 +138,7 @@ public class TestVerboseFS extends MockFileSystemTestCase {
assertTrue(stream.sawMessage());
file.close();
try {
Files.newOutputStream(dir.resolve("output"), StandardOpenOption.CREATE_NEW);
fail("didn't get expected exception");
} catch (IOException expected) {}
expectThrows(IOException.class, () -> Files.newOutputStream(dir.resolve("output"), StandardOpenOption.CREATE_NEW));
}
/** Test FileChannel.open */
@ -164,10 +149,8 @@ public class TestVerboseFS extends MockFileSystemTestCase {
assertTrue(stream.sawMessage());
channel.close();
try {
FileChannel.open(dir.resolve("foobar"), StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE);
fail("didn't get expected exception");
} catch (IOException expected) {}
expectThrows(IOException.class, () -> FileChannel.open(dir.resolve("foobar"),
StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE));
}
/** Test AsynchronousFileChannel.open */
@ -178,10 +161,8 @@ public class TestVerboseFS extends MockFileSystemTestCase {
assertTrue(stream.sawMessage());
channel.close();
try {
AsynchronousFileChannel.open(dir.resolve("foobar"), StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE);
fail("didn't get expected exception");
} catch (IOException expected) {}
expectThrows(IOException.class, () -> AsynchronousFileChannel.open(dir.resolve("foobar"),
StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE));
}
/** Test newByteChannel */
@ -192,32 +173,15 @@ public class TestVerboseFS extends MockFileSystemTestCase {
assertTrue(stream.sawMessage());
channel.close();
try {
Files.newByteChannel(dir.resolve("foobar"), StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE);
fail("didn't get expected exception");
} catch (IOException expected) {}
expectThrows(IOException.class, () -> Files.newByteChannel(dir.resolve("foobar"),
StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE));
}
/** Test that verbose does not corrumpt file not found exceptions */
public void testVerboseFSNoSuchFileException() throws IOException {
/** Test that verbose does not corrupt file not found exceptions */
public void testVerboseFSNoSuchFileException() {
Path dir = wrap(createTempDir());
try {
AsynchronousFileChannel.open(dir.resolve("doesNotExist.rip"));
fail("did not hit exception");
} catch (NoSuchFileException nsfe) {
// expected
}
try {
FileChannel.open(dir.resolve("doesNotExist.rip"));
fail("did not hit exception");
} catch (NoSuchFileException nsfe) {
// expected
}
try {
Files.newByteChannel(dir.resolve("stillopen"));
fail("did not hit exception");
} catch (NoSuchFileException nsfe) {
// expected
}
expectThrows(NoSuchFileException.class, () -> AsynchronousFileChannel.open(dir.resolve("doesNotExist.rip")));
expectThrows(NoSuchFileException.class, () -> FileChannel.open(dir.resolve("doesNotExist.rip")));
expectThrows(NoSuchFileException.class, () -> Files.newByteChannel(dir.resolve("stillopen")));
}
}

View File

@ -55,12 +55,9 @@ public class TestWindowsFS extends MockFileSystemTestCase {
file.write(5);
file.close();
InputStream is = Files.newInputStream(dir.resolve("stillopen"));
try {
Files.delete(dir.resolve("stillopen"));
fail("should have gotten exception");
} catch (IOException e) {
IOException e = expectThrows(IOException.class, () -> Files.delete(dir.resolve("stillopen")));
assertTrue(e.getMessage().contains("access denied"));
}
is.close();
}
@ -72,12 +69,9 @@ public class TestWindowsFS extends MockFileSystemTestCase {
file.write(5);
file.close();
InputStream is = Files.newInputStream(dir.resolve("stillopen"));
try {
Files.deleteIfExists(dir.resolve("stillopen"));
fail("should have gotten exception");
} catch (IOException e) {
IOException e = expectThrows(IOException.class, () -> Files.deleteIfExists(dir.resolve("stillopen")));
assertTrue(e.getMessage().contains("access denied"));
}
is.close();
}
@ -90,12 +84,10 @@ public class TestWindowsFS extends MockFileSystemTestCase {
file.write(5);
file.close();
InputStream is = Files.newInputStream(dir.resolve("stillopen"));
try {
Files.move(dir.resolve("stillopen"), dir.resolve("target"), StandardCopyOption.ATOMIC_MOVE);
fail("should have gotten exception");
} catch (IOException e) {
IOException e = expectThrows(IOException.class, () ->
Files.move(dir.resolve("stillopen"), dir.resolve("target"), StandardCopyOption.ATOMIC_MOVE));
assertTrue(e.getMessage().contains("access denied"));
}
is.close();
}

View File

@ -56,14 +56,10 @@ public class TestMockDirectoryWrapper extends BaseDirectoryTestCase {
// close() to ensure the written bytes are not buffered and counted
// against the directory size
out.close();
out = dir.createOutput("bar", IOContext.DEFAULT);
try {
out.writeBytes(bytes, bytes.length);
fail("should have failed on disk full");
} catch (IOException e) {
// expected
}
out.close();
IndexOutput out2 = dir.createOutput("bar", IOContext.DEFAULT);
expectThrows(IOException.class, () -> out2.writeBytes(bytes, bytes.length));
out2.close();
dir.close();
// test copyBytes
@ -74,14 +70,10 @@ public class TestMockDirectoryWrapper extends BaseDirectoryTestCase {
// close() to ensure the written bytes are not buffered and counted
// against the directory size
out.close();
out = dir.createOutput("bar", IOContext.DEFAULT);
try {
out.copyBytes(new ByteArrayDataInput(bytes), bytes.length);
fail("should have failed on disk full");
} catch (IOException e) {
// expected
}
out.close();
IndexOutput out3 = dir.createOutput("bar", IOContext.DEFAULT);
expectThrows(IOException.class, () -> out3.copyBytes(new ByteArrayDataInput(bytes), bytes.length));
out3.close();
dir.close();
}

View File

@ -28,30 +28,16 @@ public class TestRunWithRestrictedPermissions extends LuceneTestCase {
}
public void testNormallyAllowedStuff() throws Exception {
try {
runWithRestrictedPermissions(this::doSomeForbiddenStuff);
fail("this should not pass!");
} catch (SecurityException se) {
// pass
}
expectThrows(SecurityException.class, () -> runWithRestrictedPermissions(this::doSomeForbiddenStuff));
}
public void testCompletelyForbidden1() throws Exception {
try {
runWithRestrictedPermissions(this::doSomeCompletelyForbiddenStuff);
fail("this should not pass!");
} catch (SecurityException se) {
// pass
}
expectThrows(SecurityException.class, () -> runWithRestrictedPermissions(this::doSomeCompletelyForbiddenStuff));
}
public void testCompletelyForbidden2() throws Exception {
try {
runWithRestrictedPermissions(this::doSomeCompletelyForbiddenStuff, new AllPermission());
fail("this should not pass (not even with AllPermission)");
} catch (SecurityException se) {
// pass
}
expectThrows(SecurityException.class, () ->
runWithRestrictedPermissions(this::doSomeCompletelyForbiddenStuff, new AllPermission()));
}
private Void doSomeForbiddenStuff() throws IOException {