Get rid of deprecated assertThat() usages (#12982)

This commit is contained in:
sabi0 2024-01-10 16:31:29 +01:00 committed by GitHub
parent 872702d828
commit d7a14257ce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 227 additions and 264 deletions

View File

@ -17,13 +17,13 @@
package org.apache.lucene.geo;
import static org.apache.lucene.tests.geo.GeoTestUtil.nextBoxNotCrossingDateline;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import java.text.ParseException;
import java.util.List;
import org.apache.lucene.tests.geo.GeoTestUtil;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.hamcrest.MatcherAssert;
/** Test case for the Polygon {@link Tessellator} class */
public class TestTessellator extends LuceneTestCase {
@ -828,7 +828,7 @@ public class TestTessellator extends LuceneTestCase {
public void testComplexPolygon50() throws Exception {
String geoJson = GeoTestUtil.readShape("lucene-10563-1.geojson.gz");
Polygon[] polygons = Polygon.fromGeoJSON(geoJson);
assertThat("Only one polygon", polygons.length, equalTo(1));
assertEquals("Only one polygon", 1, polygons.length);
Polygon polygon = polygons[0];
List<Tessellator.Triangle> tessellation = Tessellator.tessellate(polygon, true);
// calculate the area of big polygons have numerical error
@ -841,20 +841,19 @@ public class TestTessellator extends LuceneTestCase {
public void testComplexPolygon50_WithMonitor() throws Exception {
String geoJson = GeoTestUtil.readShape("lucene-10563-1.geojson.gz");
Polygon[] polygons = Polygon.fromGeoJSON(geoJson);
assertThat("Only one polygon", polygons.length, equalTo(1));
assertEquals("Only one polygon", 1, polygons.length);
Polygon polygon = polygons[0];
TestCountingMonitor monitor = new TestCountingMonitor();
Tessellator.tessellate(polygon, true, monitor);
assertThat("Expected many monitor calls", monitor.count, greaterThan(390));
assertThat("Expected specific number of splits", monitor.splitsStarted, equalTo(3));
assertThat(
"Expected splits to start and end", monitor.splitsStarted, equalTo(monitor.splitsEnded));
MatcherAssert.assertThat("Expected many monitor calls", monitor.count, greaterThan(390));
assertEquals("Expected specific number of splits", 3, monitor.splitsStarted);
assertEquals("Expected splits to start and end", monitor.splitsEnded, monitor.splitsStarted);
}
public void testComplexPolygon51() throws Exception {
String geoJson = GeoTestUtil.readShape("lucene-10563-2.geojson.gz");
Polygon[] polygons = Polygon.fromGeoJSON(geoJson);
assertThat("Only one polygon", polygons.length, equalTo(1));
assertEquals("Only one polygon", 1, polygons.length);
Polygon polygon = polygons[0];
boolean checkSelfIntersections = random().nextBoolean();
IllegalArgumentException ex =
@ -874,7 +873,7 @@ public class TestTessellator extends LuceneTestCase {
public void testComplexPolygon52() throws Exception {
String geoJson = GeoTestUtil.readShape("lucene-10563-3.geojson.gz");
Polygon[] polygons = Polygon.fromGeoJSON(geoJson);
assertThat("Only one polygon", polygons.length, equalTo(1));
assertEquals("Only one polygon", 1, polygons.length);
Polygon polygon = polygons[0];
boolean checkSelfIntersections = random().nextBoolean();
IllegalArgumentException ex =
@ -1056,7 +1055,7 @@ public class TestTessellator extends LuceneTestCase {
}
}
}
if (p.getHoles() != null && p.getHoles().length > 0) {
if (p.getHoles() != null) {
for (Polygon hole : p.getHoles()) {
if (isEdgeFromPolygon(hole, aLon, aLat, bLon, bLat)) {
return true;

View File

@ -16,9 +16,6 @@
*/
package org.apache.lucene.index;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.sameInstance;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
@ -142,7 +139,7 @@ public class TestFieldInfos extends LuceneTestCase {
assertEquals("testValue2", fi.getAttribute("testKey1"));
break;
default:
assertFalse("Unknown field", true);
fail("Unknown field");
}
}
reader.close();
@ -188,7 +185,7 @@ public class TestFieldInfos extends LuceneTestCase {
FieldInfo fi1 = fis.fieldInfo("f1");
assertEquals("attdoc1", fi1.getAttribute("att1"));
assertEquals("attdoc1", fi1.getAttribute("att2"));
assertEquals(null, fi1.getAttribute("att3"));
assertNull(fi1.getAttribute("att3"));
// test that attributes for f2 are introduced by d2
FieldInfo fi2 = fis.fieldInfo("f2");
@ -205,9 +202,8 @@ public class TestFieldInfos extends LuceneTestCase {
IndexReader reader = DirectoryReader.open(writer);
FieldInfos actual = FieldInfos.getMergedFieldInfos(reader);
FieldInfos expected = FieldInfos.EMPTY;
assertThat(actual, sameInstance(expected));
assertSame(FieldInfos.EMPTY, actual);
reader.close();
writer.close();
@ -234,8 +230,8 @@ public class TestFieldInfos extends LuceneTestCase {
FieldInfos actual = FieldInfos.getMergedFieldInfos(reader);
FieldInfos expected = reader.leaves().get(0).reader().getFieldInfos();
assertThat(reader.leaves().size(), equalTo(1));
assertThat(actual, sameInstance(expected));
assertEquals(1, reader.leaves().size());
assertSame(expected, actual);
reader.close();
writer.close();

View File

@ -18,7 +18,7 @@
package org.apache.lucene.index;
import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
import static org.hamcrest.core.StringContains.containsString;
import static org.hamcrest.Matchers.containsString;
import java.io.IOException;
import java.util.ArrayList;
@ -88,6 +88,7 @@ import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.NumericUtils;
import org.hamcrest.MatcherAssert;
public class TestIndexSorting extends LuceneTestCase {
static class AssertingNeedsIndexSortCodec extends FilterCodec {
@ -657,7 +658,7 @@ public class TestIndexSorting extends LuceneTestCase {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
SortField sortField = new SortField("foo", SortField.Type.LONG, reverse);
sortField.setMissingValue(Long.valueOf(Long.MIN_VALUE));
sortField.setMissingValue(Long.MIN_VALUE);
Sort indexSort = new Sort(sortField);
iwc.setIndexSort(indexSort);
IndexWriter w = new IndexWriter(dir, iwc);
@ -704,7 +705,7 @@ public class TestIndexSorting extends LuceneTestCase {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
SortField sortField = new SortedNumericSortField("foo", SortField.Type.LONG, reverse);
sortField.setMissingValue(Long.valueOf(Long.MIN_VALUE));
sortField.setMissingValue(Long.MIN_VALUE);
Sort indexSort = new Sort(sortField);
iwc.setIndexSort(indexSort);
IndexWriter w = new IndexWriter(dir, iwc);
@ -760,7 +761,7 @@ public class TestIndexSorting extends LuceneTestCase {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
SortField sortField = new SortField("foo", SortField.Type.LONG, reverse);
sortField.setMissingValue(Long.valueOf(Long.MAX_VALUE));
sortField.setMissingValue(Long.MAX_VALUE);
Sort indexSort = new Sort(sortField);
iwc.setIndexSort(indexSort);
IndexWriter w = new IndexWriter(dir, iwc);
@ -808,7 +809,7 @@ public class TestIndexSorting extends LuceneTestCase {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
SortField sortField = new SortedNumericSortField("foo", SortField.Type.LONG, reverse);
sortField.setMissingValue(Long.valueOf(Long.MAX_VALUE));
sortField.setMissingValue(Long.MAX_VALUE);
Sort indexSort = new Sort(sortField);
iwc.setIndexSort(indexSort);
IndexWriter w = new IndexWriter(dir, iwc);
@ -948,7 +949,7 @@ public class TestIndexSorting extends LuceneTestCase {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
SortField sortField = new SortField("foo", SortField.Type.INT, reverse);
sortField.setMissingValue(Integer.valueOf(Integer.MIN_VALUE));
sortField.setMissingValue(Integer.MIN_VALUE);
Sort indexSort = new Sort(sortField);
iwc.setIndexSort(indexSort);
IndexWriter w = new IndexWriter(dir, iwc);
@ -994,7 +995,7 @@ public class TestIndexSorting extends LuceneTestCase {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
SortField sortField = new SortedNumericSortField("foo", SortField.Type.INT, reverse);
sortField.setMissingValue(Integer.valueOf(Integer.MIN_VALUE));
sortField.setMissingValue(Integer.MIN_VALUE);
Sort indexSort = new Sort(sortField);
iwc.setIndexSort(indexSort);
IndexWriter w = new IndexWriter(dir, iwc);
@ -1050,7 +1051,7 @@ public class TestIndexSorting extends LuceneTestCase {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
SortField sortField = new SortField("foo", SortField.Type.INT, reverse);
sortField.setMissingValue(Integer.valueOf(Integer.MAX_VALUE));
sortField.setMissingValue(Integer.MAX_VALUE);
Sort indexSort = new Sort(sortField);
iwc.setIndexSort(indexSort);
IndexWriter w = new IndexWriter(dir, iwc);
@ -1098,7 +1099,7 @@ public class TestIndexSorting extends LuceneTestCase {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
SortField sortField = new SortedNumericSortField("foo", SortField.Type.INT, reverse);
sortField.setMissingValue(Integer.valueOf(Integer.MAX_VALUE));
sortField.setMissingValue(Integer.MAX_VALUE);
Sort indexSort = new Sort(sortField);
iwc.setIndexSort(indexSort);
IndexWriter w = new IndexWriter(dir, iwc);
@ -2103,13 +2104,13 @@ public class TestIndexSorting extends LuceneTestCase {
w2.close();
IllegalArgumentException expected =
expectThrows(IllegalArgumentException.class, () -> w.addIndexes(dir2));
assertThat(expected.getMessage(), containsString("cannot change index sort"));
MatcherAssert.assertThat(expected.getMessage(), containsString("cannot change index sort"));
CodecReader[] codecReaders = new CodecReader[reader.leaves().size()];
for (int i = 0; i < codecReaders.length; ++i) {
codecReaders[i] = (CodecReader) reader.leaves().get(i).reader();
}
expected = expectThrows(IllegalArgumentException.class, () -> w.addIndexes(codecReaders));
assertThat(expected.getMessage(), containsString("cannot change index sort"));
MatcherAssert.assertThat(expected.getMessage(), containsString("cannot change index sort"));
reader.close();
dir2.close();
@ -2207,11 +2208,7 @@ public class TestIndexSorting extends LuceneTestCase {
public void testBadSort() throws Exception {
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
IllegalArgumentException expected =
expectThrows(
IllegalArgumentException.class,
() -> {
iwc.setIndexSort(Sort.RELEVANCE);
});
expectThrows(IllegalArgumentException.class, () -> iwc.setIndexSort(Sort.RELEVANCE));
assertEquals("Cannot sort index with sort field <score>", expected.getMessage());
}
@ -2230,14 +2227,11 @@ public class TestIndexSorting extends LuceneTestCase {
final IndexWriterConfig iwc2 = new IndexWriterConfig(new MockAnalyzer(random()));
iwc2.setIndexSort(new Sort(new SortField("bar", SortField.Type.LONG)));
IllegalArgumentException e =
expectThrows(
IllegalArgumentException.class,
() -> {
new IndexWriter(dir, iwc2);
});
expectThrows(IllegalArgumentException.class, () -> new IndexWriter(dir, iwc2));
String message = e.getMessage();
assertTrue(message.contains("cannot change previous indexSort=<long: \"foo\">"));
assertTrue(message.contains("to new indexSort=<long: \"bar\">"));
MatcherAssert.assertThat(
message, containsString("cannot change previous indexSort=<long: \"foo\">"));
MatcherAssert.assertThat(message, containsString("to new indexSort=<long: \"bar\">"));
dir.close();
}
@ -2355,7 +2349,7 @@ public class TestIndexSorting extends LuceneTestCase {
// Must use the same seed for both RandomIndexWriters so they behave identically
long seed = random().nextLong();
// We add document alread in ID order for the first writer:
// We add document already in ID order for the first writer:
Directory dir1 = newFSDirectory(createTempDir());
Random random1 = new Random(seed);
@ -2826,7 +2820,7 @@ public class TestIndexSorting extends LuceneTestCase {
doc.add(dvs.get(j));
IllegalArgumentException exc =
expectThrows(IllegalArgumentException.class, () -> w.addDocument(doc));
assertThat(exc.getMessage(), containsString("expected field [field] to be "));
MatcherAssert.assertThat(exc.getMessage(), containsString("expected field [field] to be "));
doc.clear();
doc.add(dvs.get(i));
w.addDocument(doc);

View File

@ -16,7 +16,7 @@
*/
package org.apache.lucene.search;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.instanceOf;
import com.carrotsearch.randomizedtesting.generators.RandomNumbers;
import java.io.IOException;
@ -36,6 +36,7 @@ import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.store.Directory;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.hamcrest.MatcherAssert;
public class TestCollectorManager extends LuceneTestCase {
@ -62,7 +63,7 @@ public class TestCollectorManager extends LuceneTestCase {
// Test only wrapping one of the collector managers:
Object result = collectAll(ctx, expected, cm);
assertThat(result, instanceOf(List.class));
MatcherAssert.assertThat(result, instanceOf(List.class));
IntStream intResults = ((List<Integer>) result).stream().mapToInt(i -> i);
assertArrayEquals(
IntStream.concat(expectedEven, expectedOdd).sorted().toArray(),

View File

@ -18,7 +18,6 @@ package org.apache.lucene.search;
import static org.apache.lucene.search.BooleanClause.Occur;
import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
import static org.hamcrest.CoreMatchers.equalTo;
import java.io.IOException;
import java.util.List;
@ -63,32 +62,32 @@ public class TestConstantScoreScorer extends LuceneTestCase {
// "foo bar" match
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(2));
assertThat(scorer.score(), equalTo(1f));
assertEquals(2, doc);
assertEquals(1f, scorer.score(), 0);
// should not reset iterator
scorer.setMinCompetitiveScore(2f);
assertThat(scorer.docID(), equalTo(doc));
assertThat(scorer.iterator().docID(), equalTo(doc));
assertThat(scorer.score(), equalTo(1f));
assertEquals(doc, scorer.docID());
assertEquals(doc, scorer.iterator().docID());
assertEquals(1f, scorer.score(), 0);
// "bar foo" match
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(3));
assertThat(scorer.score(), equalTo(1f));
assertEquals(3, doc);
assertEquals(1f, scorer.score(), 0);
// "foo not bar" match
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(4));
assertThat(scorer.score(), equalTo(1f));
assertEquals(4, doc);
assertEquals(1f, scorer.score(), 0);
// "foo bar foo" match
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(5));
assertThat(scorer.score(), equalTo(1f));
assertEquals(5, doc);
assertEquals(1f, scorer.score(), 0);
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(NO_MORE_DOCS));
assertEquals(NO_MORE_DOCS, doc);
}
}
@ -99,16 +98,16 @@ public class TestConstantScoreScorer extends LuceneTestCase {
// "foo bar" match
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(2));
assertThat(scorer.score(), equalTo(1f));
assertEquals(2, doc);
assertEquals(1f, scorer.score(), 0);
scorer.setMinCompetitiveScore(2f);
assertThat(scorer.docID(), equalTo(doc));
assertThat(scorer.iterator().docID(), equalTo(doc));
assertThat(scorer.score(), equalTo(1f));
assertEquals(doc, scorer.docID());
assertEquals(doc, scorer.iterator().docID());
assertEquals(1f, scorer.score(), 0);
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(NO_MORE_DOCS));
assertEquals(NO_MORE_DOCS, doc);
}
}
@ -127,24 +126,24 @@ public class TestConstantScoreScorer extends LuceneTestCase {
// "foo bar" match
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(2));
assertThat(scorer.score(), equalTo(1f));
assertEquals(2, doc);
assertEquals(1f, scorer.score(), 0);
// should not reset iterator
scorer.setMinCompetitiveScore(2f);
assertThat(scorer.docID(), equalTo(doc));
assertThat(scorer.iterator().docID(), equalTo(doc));
assertThat(scorer.score(), equalTo(1f));
assertEquals(doc, scorer.docID());
assertEquals(doc, scorer.iterator().docID());
assertEquals(1f, scorer.score(), 0);
// "foo not bar" will match the approximation but not the two phase iterator
// "foo bar foo" match
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(5));
assertThat(scorer.score(), equalTo(1f));
assertEquals(5, doc);
assertEquals(1f, scorer.score(), 0);
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(NO_MORE_DOCS));
assertEquals(NO_MORE_DOCS, doc);
}
}
@ -156,16 +155,16 @@ public class TestConstantScoreScorer extends LuceneTestCase {
// "foo bar" match
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(2));
assertThat(scorer.score(), equalTo(1f));
assertEquals(2, doc);
assertEquals(1f, scorer.score(), 0);
scorer.setMinCompetitiveScore(2f);
assertThat(scorer.docID(), equalTo(doc));
assertThat(scorer.iterator().docID(), equalTo(doc));
assertThat(scorer.score(), equalTo(1f));
assertEquals(doc, scorer.docID());
assertEquals(doc, scorer.iterator().docID());
assertEquals(1f, scorer.score(), 0);
doc = scorer.iterator().nextDoc();
assertThat(doc, equalTo(NO_MORE_DOCS));
assertEquals(NO_MORE_DOCS, doc);
}
}
@ -200,7 +199,7 @@ public class TestConstantScoreScorer extends LuceneTestCase {
Weight weight = searcher.createWeight(new ConstantScoreQuery(query), scoreMode, 1);
List<LeafReaderContext> leaves = searcher.getIndexReader().leaves();
assertThat(leaves.size(), equalTo(1));
assertEquals(1, leaves.size());
LeafReaderContext context = leaves.get(0);
Scorer scorer = weight.scorer(context);

View File

@ -16,7 +16,7 @@
*/
package org.apache.lucene.search;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.instanceOf;
import java.io.IOException;
import java.util.Random;
@ -36,6 +36,7 @@ import org.apache.lucene.tests.search.DummyTotalHitCountCollector;
import org.apache.lucene.tests.search.QueryUtils;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.lucene.tests.util.TestUtil;
import org.hamcrest.MatcherAssert;
@LuceneTestCase.SuppressCodecs(value = "SimpleText")
public class TestIndexSortSortedNumericDocValuesRangeQuery extends LuceneTestCase {
@ -359,7 +360,8 @@ public class TestIndexSortSortedNumericDocValuesRangeQuery extends LuceneTestCas
Query rewrittenQuery = query.rewrite(newSearcher(reader));
assertNotEquals(query, rewrittenQuery);
assertThat(rewrittenQuery, instanceOf(IndexSortSortedNumericDocValuesRangeQuery.class));
MatcherAssert.assertThat(
rewrittenQuery, instanceOf(IndexSortSortedNumericDocValuesRangeQuery.class));
IndexSortSortedNumericDocValuesRangeQuery rangeQuery =
(IndexSortSortedNumericDocValuesRangeQuery) rewrittenQuery;

View File

@ -17,8 +17,6 @@
package org.apache.lucene.search;
import static org.hamcrest.CoreMatchers.equalTo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@ -75,7 +73,7 @@ public class TestQueryVisitor extends LuceneTestCase {
new Term("field1", "tm3"), new Term("field1", "term4"),
new Term("field1", "term5"), new Term("field2", "term10")));
query.visit(QueryVisitor.termCollector(terms));
assertThat(terms, equalTo(expected));
assertEquals(expected, terms);
}
public void extractAllTerms() {
@ -103,7 +101,7 @@ public class TestQueryVisitor extends LuceneTestCase {
new Term("field1", "term8"),
new Term("field2", "term10")));
query.visit(visitor);
assertThat(terms, equalTo(expected));
assertEquals(expected, terms);
}
public void extractTermsFromField() {
@ -121,7 +119,7 @@ public class TestQueryVisitor extends LuceneTestCase {
actual.addAll(Arrays.asList(terms));
}
});
assertThat(actual, equalTo(expected));
assertEquals(expected, actual);
}
static class BoostedTermExtractor extends QueryVisitor {
@ -160,7 +158,7 @@ public class TestQueryVisitor extends LuceneTestCase {
expected.put(new Term("field1", "term4"), 3f);
expected.put(new Term("field1", "term5"), 3f);
expected.put(new Term("field2", "term10"), 6f);
assertThat(termsToBoosts, equalTo(expected));
assertEquals(expected, termsToBoosts);
}
public void testLeafQueryTypeCounts() {
@ -343,13 +341,13 @@ public class TestQueryVisitor extends LuceneTestCase {
extractor.collectTerms(minimumTermSet);
Set<Term> expected1 = new HashSet<>(Collections.singletonList(new Term("field1", "t1")));
assertThat(minimumTermSet, equalTo(expected1));
assertEquals(expected1, minimumTermSet);
assertTrue(extractor.nextTermSet());
Set<Term> expected2 =
new HashSet<>(Arrays.asList(new Term("field1", "tm2"), new Term("field1", "tm3")));
minimumTermSet.clear();
extractor.collectTerms(minimumTermSet);
assertThat(minimumTermSet, equalTo(expected2));
assertEquals(expected2, minimumTermSet);
BooleanQuery bq =
new BooleanQuery.Builder()
@ -368,11 +366,10 @@ public class TestQueryVisitor extends LuceneTestCase {
Set<Term> expected3 = new HashSet<>(Arrays.asList(new Term("f", "1"), new Term("f", "3333")));
minimumTermSet.clear();
ex2.collectTerms(minimumTermSet);
assertThat(minimumTermSet, equalTo(expected3));
assertEquals(expected3, minimumTermSet);
ex2.getWeight(); // force sort order
assertThat(
ex2.toString(),
equalTo(
"AND(AND(OR(AND(TERM(f:3333),TERM(f:44444)),AND(TERM(f:1),TERM(f:61),AND(TERM(f:211))))))"));
assertEquals(
"AND(AND(OR(AND(TERM(f:3333),TERM(f:44444)),AND(TERM(f:1),TERM(f:61),AND(TERM(f:211))))))",
ex2.toString());
}
}

View File

@ -17,7 +17,6 @@
package org.apache.lucene.search.uhighlight;
import static org.apache.lucene.search.uhighlight.TestWholeBreakIterator.assertSameBreaks;
import static org.hamcrest.CoreMatchers.equalTo;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import java.text.BreakIterator;
@ -29,7 +28,7 @@ public class TestCustomSeparatorBreakIterator extends LuceneTestCase {
private static final Character[] SEPARATORS = new Character[] {' ', '\u0000', 8233};
public void testBreakOnCustomSeparator() throws Exception {
Character separator = randomSeparator();
char separator = randomSeparator();
BreakIterator bi = new CustomSeparatorBreakIterator(separator);
String source =
"this"
@ -42,40 +41,38 @@ public class TestCustomSeparatorBreakIterator extends LuceneTestCase {
+ separator
+ "sentence";
bi.setText(source);
assertThat(bi.current(), equalTo(0));
assertThat(bi.first(), equalTo(0));
assertThat(source.substring(bi.current(), bi.next()), equalTo("this" + separator));
assertThat(source.substring(bi.current(), bi.next()), equalTo("is" + separator));
assertThat(source.substring(bi.current(), bi.next()), equalTo("the" + separator));
assertThat(source.substring(bi.current(), bi.next()), equalTo("first" + separator));
assertThat(source.substring(bi.current(), bi.next()), equalTo("sentence"));
assertThat(bi.next(), equalTo(BreakIterator.DONE));
assertEquals(0, bi.current());
assertEquals(0, bi.first());
assertEquals("this" + separator, source.substring(bi.current(), bi.next()));
assertEquals("is" + separator, source.substring(bi.current(), bi.next()));
assertEquals("the" + separator, source.substring(bi.current(), bi.next()));
assertEquals("first" + separator, source.substring(bi.current(), bi.next()));
assertEquals("sentence", source.substring(bi.current(), bi.next()));
assertEquals(BreakIterator.DONE, bi.next());
assertThat(bi.last(), equalTo(source.length()));
assertEquals(source.length(), bi.last());
int current = bi.current();
assertThat(source.substring(bi.previous(), current), equalTo("sentence"));
assertEquals("sentence", source.substring(bi.previous(), current));
current = bi.current();
assertThat(source.substring(bi.previous(), current), equalTo("first" + separator));
assertEquals("first" + separator, source.substring(bi.previous(), current));
current = bi.current();
assertThat(source.substring(bi.previous(), current), equalTo("the" + separator));
assertEquals("the" + separator, source.substring(bi.previous(), current));
current = bi.current();
assertThat(source.substring(bi.previous(), current), equalTo("is" + separator));
assertEquals("is" + separator, source.substring(bi.previous(), current));
current = bi.current();
assertThat(source.substring(bi.previous(), current), equalTo("this" + separator));
assertThat(bi.previous(), equalTo(BreakIterator.DONE));
assertThat(bi.current(), equalTo(0));
assertEquals("this" + separator, source.substring(bi.previous(), current));
assertEquals(BreakIterator.DONE, bi.previous());
assertEquals(0, bi.current());
assertThat(
source.substring(0, bi.following(9)),
equalTo("this" + separator + "is" + separator + "the" + separator));
assertEquals(
"this" + separator + "is" + separator + "the" + separator,
source.substring(0, bi.following(9)));
assertThat(
source.substring(0, bi.preceding(9)), equalTo("this" + separator + "is" + separator));
assertEquals("this" + separator + "is" + separator, source.substring(0, bi.preceding(9)));
assertThat(bi.first(), equalTo(0));
assertThat(
source.substring(0, bi.next(3)),
equalTo("this" + separator + "is" + separator + "the" + separator));
assertEquals(0, bi.first());
assertEquals(
"this" + separator + "is" + separator + "the" + separator, source.substring(0, bi.next(3)));
}
public void testSingleSentences() throws Exception {

View File

@ -16,8 +16,6 @@
*/
package org.apache.lucene.index.memory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.core.StringContains.containsString;
import java.io.IOException;
@ -86,6 +84,7 @@ import org.apache.lucene.tests.analysis.MockPayloadAnalyzer;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.lucene.tests.util.TestUtil;
import org.apache.lucene.util.BytesRef;
import org.hamcrest.MatcherAssert;
import org.junit.Before;
import org.junit.Test;
@ -105,38 +104,30 @@ public class TestMemoryIndex extends LuceneTestCase {
MemoryIndex mi = new MemoryIndex();
mi.addField("f1", "some text", analyzer);
assertThat(mi.search(new MatchAllDocsQuery()), not(is(0.0f)));
assertThat(mi.search(new TermQuery(new Term("f1", "some"))), not(is(0.0f)));
assertNotEquals(0.0f, mi.search(new MatchAllDocsQuery()));
assertNotEquals(0.0f, mi.search(new TermQuery(new Term("f1", "some"))));
// check we can add a new field after searching
mi.addField("f2", "some more text", analyzer);
assertThat(mi.search(new TermQuery(new Term("f2", "some"))), not(is(0.0f)));
assertNotEquals(0.0f, mi.search(new TermQuery(new Term("f2", "some"))));
// freeze!
mi.freeze();
RuntimeException expected =
expectThrows(
RuntimeException.class,
() -> {
mi.addField("f3", "and yet more", analyzer);
});
assertThat(expected.getMessage(), containsString("frozen"));
expectThrows(RuntimeException.class, () -> mi.addField("f3", "and yet more", analyzer));
MatcherAssert.assertThat(expected.getMessage(), containsString("frozen"));
expected =
expectThrows(
RuntimeException.class,
() -> {
mi.setSimilarity(new BM25Similarity(1, 1));
});
assertThat(expected.getMessage(), containsString("frozen"));
expectThrows(RuntimeException.class, () -> mi.setSimilarity(new BM25Similarity(1, 1)));
MatcherAssert.assertThat(expected.getMessage(), containsString("frozen"));
assertThat(mi.search(new TermQuery(new Term("f1", "some"))), not(is(0.0f)));
assertNotEquals(0.0f, mi.search(new TermQuery(new Term("f1", "some"))));
mi.reset();
mi.addField("f1", "wibble", analyzer);
assertThat(mi.search(new TermQuery(new Term("f1", "some"))), is(0.0f));
assertThat(mi.search(new TermQuery(new Term("f1", "wibble"))), not(is(0.0f)));
assertEquals(0.0f, mi.search(new TermQuery(new Term("f1", "some"))), 0);
assertNotEquals(0.0f, mi.search(new TermQuery(new Term("f1", "wibble"))));
// check we can set the Similarity again
mi.setSimilarity(new ClassicSimilarity());
@ -256,14 +247,14 @@ public class TestMemoryIndex extends LuceneTestCase {
MemoryIndex mi = MemoryIndex.fromDocument(doc, analyzer);
assertThat(mi.search(new TermQuery(new Term("field1", "text"))), not(0.0f));
assertThat(mi.search(new TermQuery(new Term("field2", "text"))), is(0.0f));
assertThat(mi.search(new TermQuery(new Term("field2", "untokenized text"))), not(0.0f));
assertNotEquals(0.0f, mi.search(new TermQuery(new Term("field1", "text"))));
assertEquals(0.0f, mi.search(new TermQuery(new Term("field2", "text"))), 0);
assertNotEquals(0.0f, mi.search(new TermQuery(new Term("field2", "untokenized text"))));
assertThat(mi.search(new TermQuery(new Term("field1", "some more text"))), is(0.0f));
assertThat(mi.search(new PhraseQuery("field1", "some", "more", "text")), not(0.0f));
assertThat(mi.search(new PhraseQuery("field1", "some", "text")), not(0.0f));
assertThat(mi.search(new PhraseQuery("field1", "text", "some")), is(0.0f));
assertEquals(0.0f, mi.search(new TermQuery(new Term("field1", "some more text"))), 0);
assertNotEquals(0.0f, mi.search(new PhraseQuery("field1", "some", "more", "text")));
assertNotEquals(0.0f, mi.search(new PhraseQuery("field1", "some", "text")));
assertEquals(0.0f, mi.search(new PhraseQuery("field1", "text", "some")), 0);
}
public void testDocValues() throws Exception {

View File

@ -16,8 +16,6 @@
*/
package org.apache.lucene.index.memory;
import static org.hamcrest.CoreMatchers.equalTo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
@ -77,7 +75,7 @@ import org.apache.lucene.util.IOUtils;
* the same results for queries on some randomish indexes.
*/
public class TestMemoryIndexAgainstDirectory extends BaseTokenStreamTestCase {
private Set<String> queries = new HashSet<>();
private final Set<String> queries = new HashSet<>();
@Override
public void setUp() throws Exception {
@ -92,7 +90,7 @@ public class TestMemoryIndexAgainstDirectory extends BaseTokenStreamTestCase {
InputStream stream = getClass().getResourceAsStream(resource);
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
String line = null;
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.length() > 0 && !line.startsWith("#") && !line.startsWith("//")) {
@ -477,7 +475,7 @@ public class TestMemoryIndexAgainstDirectory extends BaseTokenStreamTestCase {
doc.add(new SortedSetDocValuesField("sorted_set", randomTerm));
}
if (random().nextBoolean()) {
// randomily just add a normal string field
// randomly just add a normal string field
doc.add(new StringField("sorted_set", randomTerm, Field.Store.NO));
}
}
@ -648,7 +646,7 @@ public class TestMemoryIndexAgainstDirectory extends BaseTokenStreamTestCase {
writer.addDocument(doc);
writer.close();
for (IndexableField field : doc) {
memory.addField(field.name(), ((Field) field).stringValue(), mockAnalyzer);
memory.addField(field.name(), field.stringValue(), mockAnalyzer);
}
DirectoryReader competitor = DirectoryReader.open(dir);
LeafReader memIndexReader = (LeafReader) memory.createSearcher().getIndexReader();
@ -722,39 +720,39 @@ public class TestMemoryIndexAgainstDirectory extends BaseTokenStreamTestCase {
while (termEnum.next() != null) {
assertNotNull(memTermEnum.next());
assertThat(termEnum.totalTermFreq(), equalTo(memTermEnum.totalTermFreq()));
assertEquals(memTermEnum.totalTermFreq(), termEnum.totalTermFreq());
PostingsEnum docsPosEnum = termEnum.postings(null, PostingsEnum.POSITIONS);
PostingsEnum memDocsPosEnum = memTermEnum.postings(null, PostingsEnum.POSITIONS);
String currentTerm = termEnum.term().utf8ToString();
assertThat(
assertEquals(
"Token mismatch for field: " + field_name,
currentTerm,
equalTo(memTermEnum.term().utf8ToString()));
memTermEnum.term().utf8ToString(),
currentTerm);
docsPosEnum.nextDoc();
memDocsPosEnum.nextDoc();
int freq = docsPosEnum.freq();
assertThat(freq, equalTo(memDocsPosEnum.freq()));
assertEquals(memDocsPosEnum.freq(), freq);
for (int i = 0; i < freq; i++) {
String failDesc = " (field:" + field_name + " term:" + currentTerm + ")";
int memPos = memDocsPosEnum.nextPosition();
int pos = docsPosEnum.nextPosition();
assertThat("Position test failed" + failDesc, memPos, equalTo(pos));
assertThat(
assertEquals("Position test failed" + failDesc, pos, memPos);
assertEquals(
"Start offset test failed" + failDesc,
memDocsPosEnum.startOffset(),
equalTo(docsPosEnum.startOffset()));
assertThat(
docsPosEnum.startOffset(),
memDocsPosEnum.startOffset());
assertEquals(
"End offset test failed" + failDesc,
memDocsPosEnum.endOffset(),
equalTo(docsPosEnum.endOffset()));
assertThat(
docsPosEnum.endOffset(),
memDocsPosEnum.endOffset());
assertEquals(
"Missing payload test failed" + failDesc,
docsPosEnum.getPayload(),
equalTo(docsPosEnum.getPayload()));
memDocsPosEnum.getPayload());
}
}
assertNull("Still some tokens not processed", memTermEnum.next());

View File

@ -17,13 +17,14 @@
package org.apache.lucene.monitor;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.containsString;
import java.io.IOException;
import java.util.Collections;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.hamcrest.MatcherAssert;
public abstract class FieldFilterPresearcherComponentTestBase extends PresearcherTestBase {
@ -71,7 +72,7 @@ public abstract class FieldFilterPresearcherComponentTestBase extends Presearche
expectThrows(
IllegalArgumentException.class,
() -> monitor.match(new Document[] {doc1, doc2}, QueryMatch.SIMPLE_MATCHER));
assertThat(e.getMessage(), containsString("language:"));
MatcherAssert.assertThat(e.getMessage(), containsString("language:"));
}
}

View File

@ -17,8 +17,6 @@
package org.apache.lucene.monitor;
import static org.hamcrest.core.Is.is;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
@ -51,24 +49,24 @@ public class TestCachePurging extends MonitorTestBase {
};
monitor.addQueryIndexUpdateListener(listener);
monitor.register(queries);
assertThat(monitor.getQueryCount(), is(3));
assertThat(monitor.getDisjunctCount(), is(4));
assertThat(monitor.getQueryCacheStats().cachedQueries, is(4));
assertEquals(3, monitor.getQueryCount());
assertEquals(4, monitor.getDisjunctCount());
assertEquals(4, monitor.getQueryCacheStats().cachedQueries);
Document doc = new Document();
doc.add(newTextField("field", "test1 test2 test3", Field.Store.NO));
assertThat(monitor.match(doc, QueryMatch.SIMPLE_MATCHER).getMatchCount(), is(3));
assertEquals(3, monitor.match(doc, QueryMatch.SIMPLE_MATCHER).getMatchCount());
monitor.deleteById("1");
assertThat(monitor.getQueryCount(), is(2));
assertThat(monitor.getQueryCacheStats().cachedQueries, is(4));
assertThat(monitor.match(doc, QueryMatch.SIMPLE_MATCHER).getMatchCount(), is(2));
assertEquals(2, monitor.getQueryCount());
assertEquals(4, monitor.getQueryCacheStats().cachedQueries);
assertEquals(2, monitor.match(doc, QueryMatch.SIMPLE_MATCHER).getMatchCount());
monitor.purgeCache();
assertThat(monitor.getQueryCacheStats().cachedQueries, is(2));
assertEquals(2, monitor.getQueryCacheStats().cachedQueries);
MatchingQueries<QueryMatch> result = monitor.match(doc, QueryMatch.SIMPLE_MATCHER);
assertThat(result.getMatchCount(), is(2));
assertEquals(2, result.getMatchCount());
assertTrue(purgeCount.get() > 0);
}
}

View File

@ -17,13 +17,14 @@
package org.apache.lucene.monitor;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.containsString;
import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
public class TestDocumentBatch extends LuceneTestCase {
@ -40,7 +41,8 @@ public class TestDocumentBatch extends LuceneTestCase {
Document doc = new Document();
try (DocumentBatch batchDoc = DocumentBatch.of(ANALYZER, doc);
DocumentBatch batchArr = DocumentBatch.of(ANALYZER, new Document[] {doc})) {
assertThat(batchDoc.getClass().getName(), containsString("SingletonDocumentBatch"));
MatcherAssert.assertThat(
batchDoc.getClass().getName(), containsString("SingletonDocumentBatch"));
assertEquals(batchDoc.getClass(), batchArr.getClass());
}
}
@ -53,7 +55,7 @@ public class TestDocumentBatch extends LuceneTestCase {
DocumentBatch batch3 = DocumentBatch.of(ANALYZER, doc, doc, doc)) {
assertNotEquals(batch1.getClass(), batch2.getClass());
assertEquals(batch2.getClass(), batch3.getClass());
assertThat(batch3.getClass().getName(), containsString("MultiDocumentBatch"));
MatcherAssert.assertThat(batch3.getClass().getName(), containsString("MultiDocumentBatch"));
}
}
}

View File

@ -17,11 +17,12 @@
package org.apache.lucene.monitor;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.containsString;
import java.io.IOException;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.hamcrest.MatcherAssert;
public class TestPresearcherMatchCollector extends MonitorTestBase {
@ -46,8 +47,8 @@ public class TestPresearcherMatchCollector extends MonitorTestBase {
assertNotNull(matches.match("2", 0));
String pm = matches.match("2", 0).presearcherMatches;
assertThat(pm, containsString("field:(foo test)"));
assertThat(pm, containsString("f2:(quuz)"));
MatcherAssert.assertThat(pm, containsString("field:(foo test)"));
MatcherAssert.assertThat(pm, containsString("f2:(quuz)"));
assertNotNull(matches.match("3", 0));
assertEquals(" field:foo", matches.match("3", 0).presearcherMatches);

View File

@ -17,8 +17,6 @@
package org.apache.lucene.queries.spans;
import static org.hamcrest.CoreMatchers.equalTo;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@ -86,6 +84,6 @@ public class TestSpanQueryVisitor extends LuceneTestCase {
new Term("field1", "term5"), new Term("field1", "term6"),
new Term("field1", "term7"), new Term("field2", "term10")));
query.visit(QueryVisitor.termCollector(terms));
assertThat(terms, equalTo(expected));
assertEquals(expected, terms);
}
}

View File

@ -16,6 +16,9 @@
*/
package org.apache.lucene.search.spell;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
@ -34,6 +37,7 @@ import org.apache.lucene.tests.util.English;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.lucene.tests.util.TestUtil;
import org.apache.lucene.util.IOUtils;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
public class TestWordBreakSpellChecker extends LuceneTestCase {
@ -49,7 +53,7 @@ public class TestWordBreakSpellChecker extends LuceneTestCase {
for (int i = 900; i < 1112; i++) {
Document doc = new Document();
String num = English.intToEnglish(i).replaceAll("[-]", " ").replaceAll("[,]", "");
String num = English.intToEnglish(i).replace("-", " ").replace(",", "");
doc.add(newTextField("numbers", num, Field.Store.NO));
writer.addDocument(doc);
}
@ -105,10 +109,10 @@ public class TestWordBreakSpellChecker extends LuceneTestCase {
BreakSuggestionSortMethod.NUM_CHANGES_THEN_MAX_FREQUENCY);
// sanity check that our suggester isn't completely broken
assertThat(sw.length, org.hamcrest.Matchers.greaterThan(0));
MatcherAssert.assertThat(sw.length, greaterThan(0));
// if maxEvaluations is respected, we can't possibly have more suggestions then that.
assertThat(sw.length, org.hamcrest.Matchers.lessThan(maxEvals));
// if maxEvaluations is respected, we can't possibly have more suggestions than that
MatcherAssert.assertThat(sw.length, lessThan(maxEvals));
}
}
@ -338,7 +342,6 @@ public class TestWordBreakSpellChecker extends LuceneTestCase {
public void testRandom() throws Exception {
int numDocs = TestUtil.nextInt(random(), (10 * RANDOM_MULTIPLIER), (100 * RANDOM_MULTIPLIER));
IndexReader ir = null;
Directory dir = newDirectory();
Analyzer analyzer = new MockAnalyzer(random(), MockTokenizer.WHITESPACE, false);
@ -372,7 +375,7 @@ public class TestWordBreakSpellChecker extends LuceneTestCase {
writer.commit();
writer.close();
ir = DirectoryReader.open(dir);
IndexReader ir = DirectoryReader.open(dir);
WordBreakSpellChecker wbsp = new WordBreakSpellChecker();
wbsp.setMaxChanges(1);
wbsp.setMinBreakWordLength(1);

View File

@ -20,7 +20,6 @@ import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
import static org.apache.lucene.search.suggest.document.TestSuggestField.Entry;
import static org.apache.lucene.search.suggest.document.TestSuggestField.assertSuggestions;
import static org.apache.lucene.search.suggest.document.TestSuggestField.iwcWithSuggestField;
import static org.hamcrest.core.IsEqual.equalTo;
import java.io.IOException;
import java.util.Objects;
@ -195,8 +194,8 @@ public class TestPrefixCompletionQuery extends LuceneTestCase {
// the search should be admissible for a single segment
TopSuggestDocs suggest = indexSearcher.suggest(query, num, false);
assertTrue(suggest.totalHits.value >= 1);
assertThat(suggest.scoreLookupDocs()[0].key.toString(), equalTo("abc_" + topScore));
assertThat(suggest.scoreLookupDocs()[0].score, equalTo((float) topScore));
assertEquals("abc_" + topScore, suggest.scoreLookupDocs()[0].key.toString());
assertEquals((float) topScore, suggest.scoreLookupDocs()[0].score, 0);
filter = new NumericRangeBitsProducer("filter_int_fld", 0, 0);
query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"), filter);

View File

@ -17,14 +17,14 @@
package org.apache.lucene.search.suggest.document;
import static org.apache.lucene.tests.analysis.BaseTokenStreamTestCase.assertTokenStreamContents;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.startsWith;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@ -67,6 +67,7 @@ import org.apache.lucene.tests.util.TestUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRefBuilder;
import org.hamcrest.MatcherAssert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -89,22 +90,16 @@ public class TestSuggestField extends LuceneTestCase {
public void testEmptySuggestion() throws Exception {
IllegalArgumentException expected =
expectThrows(
IllegalArgumentException.class,
() -> {
new SuggestField("suggest_field", "", 3);
});
assertTrue(expected.getMessage().contains("value"));
IllegalArgumentException.class, () -> new SuggestField("suggest_field", "", 3));
MatcherAssert.assertThat(expected.getMessage(), containsString("value"));
}
@Test
public void testNegativeWeight() throws Exception {
IllegalArgumentException expected =
expectThrows(
IllegalArgumentException.class,
() -> {
new SuggestField("suggest_field", "sugg", -1);
});
assertTrue(expected.getMessage().contains("weight"));
IllegalArgumentException.class, () -> new SuggestField("suggest_field", "sugg", -1));
MatcherAssert.assertThat(expected.getMessage(), containsString("weight"));
}
@Test
@ -115,28 +110,22 @@ public class TestSuggestField extends LuceneTestCase {
IllegalArgumentException expected =
expectThrows(
IllegalArgumentException.class,
() -> {
new SuggestField("name", charsRefBuilder.toString(), 1);
});
assertTrue(expected.getMessage().contains("[0x1f]"));
() -> new SuggestField("name", charsRefBuilder.toString(), 1));
MatcherAssert.assertThat(expected.getMessage(), containsString("[0x1f]"));
charsRefBuilder.setCharAt(2, (char) CompletionAnalyzer.HOLE_CHARACTER);
expected =
expectThrows(
IllegalArgumentException.class,
() -> {
new SuggestField("name", charsRefBuilder.toString(), 1);
});
assertTrue(expected.getMessage().contains("[0x1e]"));
() -> new SuggestField("name", charsRefBuilder.toString(), 1));
MatcherAssert.assertThat(expected.getMessage(), containsString("[0x1e]"));
charsRefBuilder.setCharAt(2, (char) NRTSuggesterBuilder.END_BYTE);
expected =
expectThrows(
IllegalArgumentException.class,
() -> {
new SuggestField("name", charsRefBuilder.toString(), 1);
});
assertTrue(expected.getMessage().contains("[0x0]"));
() -> new SuggestField("name", charsRefBuilder.toString(), 1));
MatcherAssert.assertThat(expected.getMessage(), containsString("[0x0]"));
}
@Test
@ -149,7 +138,7 @@ public class TestSuggestField extends LuceneTestCase {
PrefixCompletionQuery query =
new PrefixCompletionQuery(analyzer, new Term("suggest_field", "ab"));
TopSuggestDocs lookupDocs = suggestIndexSearcher.suggest(query, 3, false);
assertThat(lookupDocs.totalHits.value, equalTo(0L));
assertEquals(0L, lookupDocs.totalHits.value);
reader.close();
iw.close();
}
@ -382,13 +371,12 @@ public class TestSuggestField extends LuceneTestCase {
expected.add(doc);
}
}
Collections.sort(
expected,
expected.sort(
(a, b) -> {
// sort by higher score:
int cmp = Float.compare(b.value, a.value);
if (cmp == 0) {
// tie break by completion key
// tie-break by completion key
cmp = Lookup.CHARSEQUENCE_COMPARATOR.compare(a.output, b.output);
if (cmp == 0) {
// prefer smaller doc id, in case of a tie
@ -522,7 +510,7 @@ public class TestSuggestField extends LuceneTestCase {
PrefixCompletionQuery query =
new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"), filter);
TopSuggestDocs suggest = indexSearcher.suggest(query, num, false);
assertThat(suggest.totalHits.value, equalTo(0L));
assertEquals(0L, suggest.totalHits.value);
reader.close();
iw.close();
}
@ -551,7 +539,7 @@ public class TestSuggestField extends LuceneTestCase {
PrefixCompletionQuery query =
new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"));
TopSuggestDocs suggest = indexSearcher.suggest(query, num, false);
assertThat(suggest.totalHits.value, equalTo(0L));
assertEquals(0L, suggest.totalHits.value);
reader.close();
iw.close();
@ -621,8 +609,7 @@ public class TestSuggestField extends LuceneTestCase {
// check that the doc ids are consistent
for (int i = 0; i < suggestDocs1.scoreDocs.length; i++) {
ScoreDoc suggestScoreDoc = suggestDocs1.scoreDocs[i];
assertThat(suggestScoreDoc.doc, equalTo(suggestDocs2.scoreDocs[i].doc));
assertEquals(suggestDocs1.scoreDocs[i].doc, suggestDocs2.scoreDocs[i].doc);
}
reader.close();
@ -685,7 +672,7 @@ public class TestSuggestField extends LuceneTestCase {
PrefixCompletionQuery query =
new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"));
TopSuggestDocs suggest =
indexSearcher.suggest(query, (entries.size() == 0) ? 1 : entries.size(), false);
indexSearcher.suggest(query, entries.isEmpty() ? 1 : entries.size(), false);
assertSuggestions(suggest, entries.toArray(new Entry[entries.size()]));
reader.close();
@ -719,7 +706,7 @@ public class TestSuggestField extends LuceneTestCase {
StoredFields storedFields = reader.storedFields();
for (SuggestScoreDoc suggestScoreDoc : suggest.scoreLookupDocs()) {
String key = suggestScoreDoc.key.toString();
assertTrue(key.startsWith("abc_"));
MatcherAssert.assertThat(key, startsWith("abc_"));
String substring = key.substring(4);
int fieldValue = Integer.parseInt(substring);
Document doc = storedFields.document(suggestScoreDoc.doc);
@ -741,8 +728,7 @@ public class TestSuggestField extends LuceneTestCase {
Map<String, Integer> mappings = new HashMap<>();
for (int i = 0; i < num; i++) {
Document document = new Document();
String suggest =
prefixes[i % 3] + TestUtil.randomSimpleString(random(), 10) + "_" + String.valueOf(i);
String suggest = prefixes[i % 3] + TestUtil.randomSimpleString(random(), 10) + "_" + i;
int weight = random().nextInt(Integer.MAX_VALUE);
document.add(new SuggestField("suggest_field", suggest, weight));
mappings.put(suggest, weight);
@ -766,12 +752,12 @@ public class TestSuggestField extends LuceneTestCase {
assertTrue(topScore >= scoreDoc.score);
}
topScore = scoreDoc.score;
assertThat((float) mappings.get(scoreDoc.key.toString()), equalTo(scoreDoc.score));
assertEquals(scoreDoc.score, (float) mappings.get(scoreDoc.key.toString()), 0);
assertNotNull(mappings.remove(scoreDoc.key.toString()));
}
}
assertThat(mappings.size(), equalTo(0));
assertEquals(0, mappings.size());
reader.close();
iw.close();
}
@ -939,11 +925,11 @@ public class TestSuggestField extends LuceneTestCase {
+ toString(expected[i])
+ " but actual: "
+ toString(lookupDoc);
assertThat(msg, lookupDoc.key.toString(), equalTo(expected[i].output));
assertThat(msg, lookupDoc.score, equalTo(expected[i].value));
assertThat(msg, lookupDoc.context, equalTo(expected[i].context));
assertEquals(msg, expected[i].output, lookupDoc.key.toString());
assertEquals(msg, expected[i].value, lookupDoc.score, 0);
assertEquals(msg, expected[i].context, lookupDoc.context);
}
assertThat(suggestScoreDocs.length, equalTo(expected.length));
assertEquals(expected.length, suggestScoreDocs.length);
}
private static String toString(Entry expected) {
@ -963,9 +949,9 @@ public class TestSuggestField extends LuceneTestCase {
iwc.setMergePolicy(newLogMergePolicy());
Codec filterCodec =
new FilterCodec(TestUtil.getDefaultCodec().getName(), TestUtil.getDefaultCodec()) {
CompletionPostingsFormat.FSTLoadMode fstLoadMode =
final CompletionPostingsFormat.FSTLoadMode fstLoadMode =
RandomPicks.randomFrom(random(), CompletionPostingsFormat.FSTLoadMode.values());
PostingsFormat postingsFormat = new Completion99PostingsFormat(fstLoadMode);
final PostingsFormat postingsFormat = new Completion99PostingsFormat(fstLoadMode);
@Override
public PostingsFormat postingsFormat() {
@ -986,8 +972,8 @@ public class TestSuggestField extends LuceneTestCase {
}
public static final class PayloadAttrToTypeAttrFilter extends TokenFilter {
private PayloadAttribute payload = addAttribute(PayloadAttribute.class);
private TypeAttribute type = addAttribute(TypeAttribute.class);
private final PayloadAttribute payload = addAttribute(PayloadAttribute.class);
private final TypeAttribute type = addAttribute(TypeAttribute.class);
protected PayloadAttrToTypeAttrFilter(TokenStream input) {
super(input);

View File

@ -16,10 +16,11 @@
*/
package org.apache.lucene.tests.util;
import org.hamcrest.Matchers;
import static org.hamcrest.Matchers.*;
import org.hamcrest.MatcherAssert;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
@ -89,7 +90,7 @@ public class TestReproduceMessage extends WithNestedTests {
case ERROR:
throw new RuntimeException(pt.toString());
case FAILURE:
Assert.assertTrue(pt.toString(), false);
fail(pt.toString());
throw new RuntimeException("unreachable");
}
}
@ -108,49 +109,49 @@ public class TestReproduceMessage extends WithNestedTests {
public void testAssumeBeforeClass() throws Exception {
type = SoreType.ASSUMPTION;
where = SorePoint.BEFORE_CLASS;
Assert.assertTrue(runAndReturnSyserr().isEmpty());
MatcherAssert.assertThat(runAndReturnSyserr(), is(emptyString()));
}
@Test
public void testAssumeInitializer() throws Exception {
type = SoreType.ASSUMPTION;
where = SorePoint.INITIALIZER;
Assert.assertTrue(runAndReturnSyserr().isEmpty());
MatcherAssert.assertThat(runAndReturnSyserr(), is(emptyString()));
}
@Test
public void testAssumeRule() throws Exception {
type = SoreType.ASSUMPTION;
where = SorePoint.RULE;
Assert.assertEquals("", runAndReturnSyserr());
MatcherAssert.assertThat(runAndReturnSyserr(), is(emptyString()));
}
@Test
public void testAssumeBefore() throws Exception {
type = SoreType.ASSUMPTION;
where = SorePoint.BEFORE;
Assert.assertTrue(runAndReturnSyserr().isEmpty());
MatcherAssert.assertThat(runAndReturnSyserr(), is(emptyString()));
}
@Test
public void testAssumeTest() throws Exception {
type = SoreType.ASSUMPTION;
where = SorePoint.TEST;
Assert.assertTrue(runAndReturnSyserr().isEmpty());
MatcherAssert.assertThat(runAndReturnSyserr(), is(emptyString()));
}
@Test
public void testAssumeAfter() throws Exception {
type = SoreType.ASSUMPTION;
where = SorePoint.AFTER;
Assert.assertTrue(runAndReturnSyserr().isEmpty());
MatcherAssert.assertThat(runAndReturnSyserr(), is(emptyString()));
}
@Test
public void testAssumeAfterClass() throws Exception {
type = SoreType.ASSUMPTION;
where = SorePoint.AFTER_CLASS;
Assert.assertTrue(runAndReturnSyserr().isEmpty());
MatcherAssert.assertThat(runAndReturnSyserr(), is(emptyString()));
}
/*
@ -161,19 +162,19 @@ public class TestReproduceMessage extends WithNestedTests {
public void testFailureBeforeClass() throws Exception {
type = SoreType.FAILURE;
where = SorePoint.BEFORE_CLASS;
Assert.assertTrue(runAndReturnSyserr().contains("NOTE: reproduce with:"));
MatcherAssert.assertThat(runAndReturnSyserr(), containsString("NOTE: reproduce with:"));
}
@Test
public void testFailureInitializer() throws Exception {
type = SoreType.FAILURE;
where = SorePoint.INITIALIZER;
Assert.assertTrue(runAndReturnSyserr().contains("NOTE: reproduce with:"));
MatcherAssert.assertThat(runAndReturnSyserr(), containsString("NOTE: reproduce with:"));
}
static void checkTestName(String syserr, String expectedName) {
Assert.assertTrue(syserr.contains("NOTE: reproduce with:"));
Assert.assertThat(syserr, Matchers.containsString(" --tests " + expectedName));
MatcherAssert.assertThat(syserr, containsString("NOTE: reproduce with:"));
MatcherAssert.assertThat(syserr, containsString(" --tests " + expectedName));
}
@Test
@ -208,7 +209,7 @@ public class TestReproduceMessage extends WithNestedTests {
public void testFailureAfterClass() throws Exception {
type = SoreType.FAILURE;
where = SorePoint.AFTER_CLASS;
Assert.assertTrue(runAndReturnSyserr().contains("NOTE: reproduce with:"));
MatcherAssert.assertThat(runAndReturnSyserr(), containsString("NOTE: reproduce with:"));
}
/*
@ -219,14 +220,14 @@ public class TestReproduceMessage extends WithNestedTests {
public void testErrorBeforeClass() throws Exception {
type = SoreType.ERROR;
where = SorePoint.BEFORE_CLASS;
Assert.assertTrue(runAndReturnSyserr().contains("NOTE: reproduce with:"));
MatcherAssert.assertThat(runAndReturnSyserr(), containsString("NOTE: reproduce with:"));
}
@Test
public void testErrorInitializer() throws Exception {
type = SoreType.ERROR;
where = SorePoint.INITIALIZER;
Assert.assertTrue(runAndReturnSyserr().contains("NOTE: reproduce with:"));
MatcherAssert.assertThat(runAndReturnSyserr(), containsString("NOTE: reproduce with:"));
}
@Test
@ -261,7 +262,7 @@ public class TestReproduceMessage extends WithNestedTests {
public void testErrorAfterClass() throws Exception {
type = SoreType.ERROR;
where = SorePoint.AFTER_CLASS;
Assert.assertTrue(runAndReturnSyserr().contains("NOTE: reproduce with:"));
MatcherAssert.assertThat(runAndReturnSyserr(), containsString("NOTE: reproduce with:"));
}
private String runAndReturnSyserr() {