This is an automated email from the ASF dual-hosted git repository.
mdrob pushed a commit to branch branch_9x
in repository https://gitbox.apache.org/repos/asf/solr.git
The following commit(s) were added to refs/heads/branch_9x by this push:
new c9502d2 SOLR-15908 Document or fix error-prone patterns relating to
tests (#510)
c9502d2 is described below
commit c9502d25e7916354594d9bc046b753135083123d
Author: Mike Drob <[email protected]>
AuthorDate: Thu Jan 13 19:33:03 2022 -0600
SOLR-15908 Document or fix error-prone patterns relating to tests (#510)
(cherry picked from commit 3b6e918dc35e677f09c04678ba61052e93897126)
---
gradle/validation/error-prone.gradle | 35 +++++-----------
.../solr/gcs/ConcurrentDelegatingStorage.java | 2 +-
.../apache/solr/ltr/model/TestWrapperModel.java | 16 +++-----
.../apache/solr/cloud/CollectionsAPISolrJTest.java | 46 +++++++++-------------
.../solr/cloud/DistribJoinFromCollectionTest.java | 10 ++---
.../apache/solr/cloud/DocValuesNotIndexedTest.java | 8 ++--
.../api/collections/TestReplicaProperties.java | 37 +++++++----------
.../apache/solr/core/DirectoryFactoriesTest.java | 2 +-
.../solr/handler/TestStressIncrementalBackup.java | 1 +
.../solr/handler/TestStressThreadBackup.java | 1 +
.../solr/handler/export/TestExportWriter.java | 4 +-
.../apache/solr/handler/tagger/TaggerTestCase.java | 24 +++++------
.../solr/response/TestRetrieveFieldsOptimizer.java | 5 ++-
.../search/facet/SpatialHeatmapFacetsTest.java | 2 +-
.../solr/search/facet/TestJsonFacetErrors.java | 9 ++---
.../solr/store/blockcache/BlockDirectoryTest.java | 2 +-
.../apache/solr/store/hdfs/HdfsDirectoryTest.java | 2 +-
.../solr/update/TestExceedMaxTermLength.java | 27 ++++++-------
.../ClassificationUpdateProcessorFactoryTest.java | 30 +++++---------
...assificationUpdateProcessorIntegrationTest.java | 20 ++++------
.../org/apache/solr/util/DateMathParserTest.java | 1 +
.../solr/util/hll/IntegrationTestGenerator.java | 14 +++----
.../apache/solr/util/stats/MetricUtilsTest.java | 2 +-
solr/solr-ref-guide/build.gradle | 4 +-
.../apache/solr/guide}/BuildNavDataFiles.java | 2 +
.../apache/solr/guide}/CheckLinksAndAnchors.java | 10 +++--
.../solrj/io/stream/eval/AddEvaluatorTest.java | 2 +-
.../collections/AbstractIncrementalBackupTest.java | 6 +--
28 files changed, 136 insertions(+), 188 deletions(-)
diff --git a/gradle/validation/error-prone.gradle
b/gradle/validation/error-prone.gradle
index 706de1c..c6c412a 100644
--- a/gradle/validation/error-prone.gradle
+++ b/gradle/validation/error-prone.gradle
@@ -53,27 +53,15 @@ allprojects { prj ->
options.errorprone.errorproneArgs = [
'-Xep:InlineMeSuggester:OFF', // We don't use this annotation
- // test
- '-Xep:ExtendingJUnitAssert:OFF',
- '-Xep:UseCorrectAssertInTests:OFF',
- '-Xep:DefaultPackage:OFF',
- '-Xep:FloatingPointLiteralPrecision:OFF',
- '-Xep:CatchFail:OFF',
- '-Xep:TryFailThrowable:OFF',
- '-Xep:MathAbsoluteRandom:OFF',
- '-Xep:AssertionFailureIgnored:OFF',
- '-Xep:JUnit4TestNotRun:OFF',
- '-Xep:FallThrough:OFF',
- '-Xep:CatchAndPrintStackTrace:OFF',
- '-Xep:ToStringReturnsNull:OFF',
- '-Xep:ArrayAsKeyOfSetOrMap:OFF',
- '-Xep:StaticAssignmentInConstructor:OFF',
- '-Xep:SelfAssignment:OFF',
- '-Xep:InvalidPatternSyntax:OFF',
- '-Xep:MissingFail:OFF',
- '-Xep:ComparableType:OFF',
- '-Xep:InfiniteRecursion:OFF',
- '-Xep:MisusedDayOfYear:OFF',
+ // bug patterns related to our tests
+ '-Xep:ExtendingJUnitAssert:OFF', // we inherit from LuceneTestCase
which extends Assert
+ '-Xep:UseCorrectAssertInTests:OFF', // and this is a consequence
of the above
+ '-Xep:CatchFail:OFF', // our code is generally descriptive enough,
fix case by case if tests fail
+ '-Xep:JUnit4TestNotRun:OFF', // RandomizedRunner finds unannotated
test methods no problem
+ '-Xep:CatchAndPrintStackTrace:OFF', // TODO: there's a lot of
these but they should be easy to address
+ '-Xep:FloatingPointLiteralPrecision:OFF', // TODO: a lot of these
in our tests, likely unintentional
+ '-Xep:StaticAssignmentInConstructor:OFF', // we assign
SolrTestCaseJ4.configString in many tests, difficult to untangle
+ '-Xep:ComparableType:OFF', // SolrTestCaseJ4.Doc and Fld are messy
'-Xep:AlmostJavadoc:OFF',
'-Xep:AmbiguousMethodReference:OFF',
@@ -81,7 +69,7 @@ allprojects { prj ->
'-Xep:ArrayEquals:OFF',
'-Xep:ArrayHashCode:OFF',
'-Xep:ArrayToString:OFF',
- '-Xep:BadImport:OFF',
+ '-Xep:BadImport:OFF', // style preference that we don't want to
enforce
'-Xep:BadInstanceof:OFF',
'-Xep:BadShiftAmount:OFF',
'-Xep:ClassCanBeStatic:OFF',
@@ -102,7 +90,6 @@ allprojects { prj ->
'-Xep:IdentityHashMapUsage:OFF',
'-Xep:ImmutableEnumChecker:OFF',
'-Xep:InconsistentCapitalization:OFF',
- '-Xep:InconsistentHashCode:OFF',
'-Xep:InlineFormatString:OFF',
'-Xep:InputStreamSlowMultibyteRead:OFF',
'-Xep:IntLongMath:OFF',
@@ -112,7 +99,6 @@ allprojects { prj ->
'-Xep:JavaLangClash:OFF',
'-Xep:JavaUtilDate:OFF',
'-Xep:JdkObsolete:OFF',
- '-Xep:LockNotBeforeTry:OFF',
'-Xep:LogicalAssignment:OFF',
'-Xep:MissingOverride:OFF',
'-Xep:MissingSummary:OFF',
@@ -127,7 +113,6 @@ allprojects { prj ->
'-Xep:ObjectsHashCodePrimitive:OFF',
'-Xep:OperatorPrecedence:OFF',
'-Xep:ProtectedMembersInFinalClass:OFF',
- '-Xep:PublicConstructorForAbstractClass:OFF',
'-Xep:ReferenceEquality:OFF',
'-Xep:ReturnValueIgnored:OFF',
'-Xep:SameNameButDifferent:OFF',
diff --git
a/solr/contrib/gcs-repository/src/test/org/apache/solr/gcs/ConcurrentDelegatingStorage.java
b/solr/contrib/gcs-repository/src/test/org/apache/solr/gcs/ConcurrentDelegatingStorage.java
index 057dc2c..a1074f5 100644
---
a/solr/contrib/gcs-repository/src/test/org/apache/solr/gcs/ConcurrentDelegatingStorage.java
+++
b/solr/contrib/gcs-repository/src/test/org/apache/solr/gcs/ConcurrentDelegatingStorage.java
@@ -196,7 +196,7 @@ public class ConcurrentDelegatingStorage implements Storage
{
public synchronized Acl getAcl(String bucket, Acl.Entity entity) { return
delegate.getAcl(bucket, entity); }
@Override
- public synchronized boolean deleteAcl(String bucket, Acl.Entity entity,
BucketSourceOption... options) { return deleteAcl(bucket, entity, options); }
+ public synchronized boolean deleteAcl(String bucket, Acl.Entity entity,
BucketSourceOption... options) { return delegate.deleteAcl(bucket, entity,
options); }
@Override
public synchronized boolean deleteAcl(String bucket, Acl.Entity entity) {
return delegate.deleteAcl(bucket, entity); }
diff --git
a/solr/contrib/ltr/src/test/org/apache/solr/ltr/model/TestWrapperModel.java
b/solr/contrib/ltr/src/test/org/apache/solr/ltr/model/TestWrapperModel.java
index b31a6ba..af083e7 100644
--- a/solr/contrib/ltr/src/test/org/apache/solr/ltr/model/TestWrapperModel.java
+++ b/solr/contrib/ltr/src/test/org/apache/solr/ltr/model/TestWrapperModel.java
@@ -156,15 +156,11 @@ public class TestWrapperModel extends TestRerankBase {
"getFeatureStoreName", // wrapper and wrapped model feature store
should match, so need not override
"getParams" // the wrapper model's params are its own params i.e.
_not_ the params of the wrapped model
).contains(superClassMethod.getName())) {
- try {
- final Method subClassMethod = WrapperModel.class.getDeclaredMethod(
- superClassMethod.getName(),
- superClassMethod.getParameterTypes());
- fail(WrapperModel.class + " need not override\n'" + superClassMethod
+ "'"
- + " but it does override\n'" + subClassMethod + "'");
- } catch (NoSuchMethodException e) {
- // ok
- }
+ assertThrows("WrapperModel need not override '" +
superClassMethod.getName() + "'",
+ NoSuchMethodException.class, () -> {
+ WrapperModel.class.getDeclaredMethod(superClassMethod.getName(),
superClassMethod.getParameterTypes());
+ }
+ );
} else {
try {
final Method subClassMethod = WrapperModel.class.getDeclaredMethod(
@@ -174,7 +170,7 @@ public class TestWrapperModel extends TestRerankBase {
superClassMethod.getReturnType(),
subClassMethod.getReturnType());
} catch (NoSuchMethodException e) {
- fail(WrapperModel.class + " needs to override '" + superClassMethod
+ "'");
+ throw new AssertionError("WrapperModel needs to override '" +
superClassMethod + "'", e);
}
}
}
diff --git
a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPISolrJTest.java
b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPISolrJTest.java
index c7998e0..0653dc3 100644
--- a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPISolrJTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPISolrJTest.java
@@ -888,11 +888,9 @@ public class CollectionsAPISolrJTest extends
SolrCloudTestCase {
ZkStateReader zkStateReader = cluster.getSolrClient().getZkStateReader();
Aliases aliases;
if (!followAliases) {
- try {
- rename.process(cluster.getSolrClient());
- } catch (Exception e) {
- assertTrue(e.toString(), e.toString().contains("source collection
'col1' not found"));
- }
+ Exception e = assertThrows(Exception.class, () ->
+ rename.process(cluster.getSolrClient()));
+ assertTrue(e.toString(), e.toString().contains("source collection 'col1'
not found"));
} else {
rename.process(cluster.getSolrClient());
zkStateReader.aliasesManager.update();
@@ -920,30 +918,24 @@ public class CollectionsAPISolrJTest extends
SolrCloudTestCase {
assertEquals(compoundAliases.toString(), 1, compoundAliases.size());
assertTrue(compoundAliases.toString(),
compoundAliases.contains(collectionName2));
- try {
- rename = CollectionAdminRequest.renameCollection("catAlias", "bar");
- rename.setFollowAliases(followAliases);
- rename.process(cluster.getSolrClient());
- fail("category-based alias renaming should fail");
- } catch (Exception e) {
- if (followAliases) {
- assertTrue(e.toString(), e.toString().contains("is a routed alias"));
- } else {
- assertTrue(e.toString(), e.toString().contains("source collection
'catAlias' not found"));
- }
+ CollectionAdminRequest.Rename catRename =
CollectionAdminRequest.renameCollection("catAlias", "bar");
+ catRename.setFollowAliases(followAliases);
+ Exception e = assertThrows("category-based alias renaming should fail",
Exception.class,
+ () -> catRename.process(cluster.getSolrClient()));
+ if (followAliases) {
+ assertTrue(e.toString(), e.toString().contains("is a routed alias"));
+ } else {
+ assertTrue(e.toString(), e.toString().contains("source collection
'catAlias' not found"));
}
- try {
- rename = CollectionAdminRequest.renameCollection("col2", "foo");
- rename.setFollowAliases(followAliases);
- rename.process(cluster.getSolrClient());
- fail("should fail because 'foo' already exists");
- } catch (Exception e) {
- if (followAliases) {
- assertTrue(e.toString(), e.toString().contains("exists"));
- } else {
- assertTrue(e.toString(), e.toString().contains("source collection
'col2' not found"));
- }
+ CollectionAdminRequest.Rename rename2 =
CollectionAdminRequest.renameCollection("col2", "foo");
+ rename2.setFollowAliases(followAliases);
+ e = assertThrows("should fail because 'foo' already exists",
Exception.class,
+ () -> rename2.process(cluster.getSolrClient()));
+ if (followAliases) {
+ assertTrue(e.toString(), e.toString().contains("exists"));
+ } else {
+ assertTrue(e.toString(), e.toString().contains("source collection 'col2'
not found"));
}
}
diff --git
a/solr/core/src/test/org/apache/solr/cloud/DistribJoinFromCollectionTest.java
b/solr/core/src/test/org/apache/solr/cloud/DistribJoinFromCollectionTest.java
index 805e013..a823c2e 100644
---
a/solr/core/src/test/org/apache/solr/cloud/DistribJoinFromCollectionTest.java
+++
b/solr/core/src/test/org/apache/solr/cloud/DistribJoinFromCollectionTest.java
@@ -209,12 +209,10 @@ public class DistribJoinFromCollectionTest extends
SolrCloudTestCase{
final String joinQ = "{!join " + (anyScoreMode(isScoresTest))
+ "from=join_s fromIndex=" + wrongName + " to=join_s}match_s:c";
final QueryRequest qr = new QueryRequest(params("collection", toColl, "q",
joinQ, "fl", "id,get_s,score"));
- try {
- cluster.getSolrClient().request(qr);
- } catch (BaseHttpSolrClient.RemoteSolrException ex) {
- assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
- assertTrue(ex.getMessage().contains(wrongName));
- }
+ BaseHttpSolrClient.RemoteSolrException ex =
assertThrows(BaseHttpSolrClient.RemoteSolrException.class, () ->
+ cluster.getSolrClient().request(qr));
+ assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
+ assertTrue(ex.getMessage().contains(wrongName));
}
protected static String indexDoc(String collection, int id, String
joinField, String matchField, String getField) throws Exception {
diff --git
a/solr/core/src/test/org/apache/solr/cloud/DocValuesNotIndexedTest.java
b/solr/core/src/test/org/apache/solr/cloud/DocValuesNotIndexedTest.java
index 45ccbc9..3caf6db 100644
--- a/solr/core/src/test/org/apache/solr/cloud/DocValuesNotIndexedTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/DocValuesNotIndexedTest.java
@@ -494,15 +494,17 @@ class FieldProps {
// There's a vague chance that counts will roll over, so let's insure we
have some room to grow in a positive direction
void resetBase() {
if (name.startsWith("int")) {
- base = Math.abs(random().nextInt()) / 2;
+ base = (random().nextInt(Integer.MAX_VALUE)) / 2;
} else if (name.startsWith("long")) {
- base = Math.abs(random().nextLong()) / 2;
+ long lng = random().nextLong();
+ base = lng == Long.MIN_VALUE ? 0 : Math.abs(lng) / 2;
} else if (name.startsWith("float")) {
base = Math.abs(random().nextFloat()) / 2;
} else if (name.startsWith("double")) {
base = Math.abs(random().nextDouble()) / 2;
} else if (name.startsWith("date")) {
- base = Math.abs(random().nextLong()) / 2;
+ long lng = random().nextLong();
+ base = lng == Long.MIN_VALUE ? 0 : Math.abs(lng) / 2;
} else if (name.startsWith("bool")) {
base = true; // Must start with a known value since bools only have a
two values....
} else if (name.startsWith("string") || name.startsWith("sortable")) {
diff --git
a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestReplicaProperties.java
b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestReplicaProperties.java
index 060ad9c..4e906b8 100644
---
a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestReplicaProperties.java
+++
b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestReplicaProperties.java
@@ -89,14 +89,12 @@ public class TestReplicaProperties extends
ReplicaPropertiesBase {
try (CloudSolrClient client = createCloudClient(null)) {
client.connect();
- try {
+ SolrException se = assertThrows(SolrException.class, () ->
doPropertyAction(client,
"action",
CollectionParams.CollectionAction.BALANCESHARDUNIQUE.toString(),
- "property", "preferredLeader");
- } catch (SolrException se) {
- assertTrue("Should have seen missing required parameter 'collection'
error",
- se.getMessage().contains("Missing required parameter:
collection"));
- }
+ "property", "preferredLeader"));
+ assertTrue("Should have seen missing required parameter 'collection'
error",
+ se.getMessage().contains("Missing required parameter: collection"));
doPropertyAction(client,
"action",
CollectionParams.CollectionAction.BALANCESHARDUNIQUE.toString(),
@@ -112,18 +110,16 @@ public class TestReplicaProperties extends
ReplicaPropertiesBase {
"shardUnique", "true");
verifyUniqueAcrossCollection(client, COLLECTION_NAME,
"property.newunique");
- try {
+ se = assertThrows(SolrException.class, () ->
doPropertyAction(client,
"action",
CollectionParams.CollectionAction.BALANCESHARDUNIQUE.toString(),
"collection", COLLECTION_NAME,
"property", "whatever",
- "shardUnique", "false");
- fail("Should have thrown an exception here.");
- } catch (SolrException se) {
- assertTrue("Should have gotten a specific error message here",
- se.getMessage().contains("Balancing properties amongst replicas in
a slice requires that the " +
- "property be pre-defined as a unique property (e.g.
'preferredLeader') or that 'shardUnique' be set to 'true'"));
- }
+ "shardUnique", "false"));
+ assertTrue("Should have gotten a specific error message here",
+ se.getMessage().contains("Balancing properties amongst replicas in a
slice requires that the " +
+ "property be pre-defined as a unique property (e.g.
'preferredLeader') or that 'shardUnique' be set to 'true'"));
+
// Should be able to set non-unique-per-slice values in several places.
Map<String, Slice> slices =
client.getZkStateReader().getClusterState().getCollection(COLLECTION_NAME).getSlicesMap();
List<String> sliceList = new ArrayList<>(slices.keySet());
@@ -148,18 +144,15 @@ public class TestReplicaProperties extends
ReplicaPropertiesBase {
"property", "property.bogus1",
"property.value", "whatever");
- try {
+ se = assertThrows(SolrException.class, () ->
doPropertyAction(client,
"action",
CollectionParams.CollectionAction.BALANCESHARDUNIQUE.toString(),
"collection", COLLECTION_NAME,
"property", "bogus1",
- "shardUnique", "false");
- fail("Should have thrown parameter error here");
- } catch (SolrException se) {
- assertTrue("Should have caught specific exception ",
- se.getMessage().contains("Balancing properties amongst replicas in
a slice requires that the property be " +
- "pre-defined as a unique property (e.g. 'preferredLeader') or
that 'shardUnique' be set to 'true'"));
- }
+ "shardUnique", "false"));
+ assertTrue("Should have caught specific exception ",
+ se.getMessage().contains("Balancing properties amongst replicas in a
slice requires that the property be " +
+ "pre-defined as a unique property (e.g. 'preferredLeader') or
that 'shardUnique' be set to 'true'"));
// Should have no effect despite the "shardUnique" param being set.
diff --git
a/solr/core/src/test/org/apache/solr/core/DirectoryFactoriesTest.java
b/solr/core/src/test/org/apache/solr/core/DirectoryFactoriesTest.java
index 7d60a0d..b9853f1 100644
--- a/solr/core/src/test/org/apache/solr/core/DirectoryFactoriesTest.java
+++ b/solr/core/src/test/org/apache/solr/core/DirectoryFactoriesTest.java
@@ -95,7 +95,7 @@ public class DirectoryFactoriesTest extends SolrTestCaseJ4 {
assertTrue(path + " should still exist even after being released",
dirFac.exists(path));
} catch (AssertionError ae) {
- throw new AssertionError(clazz + ": " + ae.getMessage());
+ throw new AssertionError("Failed with " + clazz.getName(), ae);
} finally {
if (null != dirFac) {
dirFac.close();
diff --git
a/solr/core/src/test/org/apache/solr/handler/TestStressIncrementalBackup.java
b/solr/core/src/test/org/apache/solr/handler/TestStressIncrementalBackup.java
index 0e507a4..4c4bdf4 100644
---
a/solr/core/src/test/org/apache/solr/handler/TestStressIncrementalBackup.java
+++
b/solr/core/src/test/org/apache/solr/handler/TestStressIncrementalBackup.java
@@ -91,6 +91,7 @@ public class TestStressIncrementalBackup extends
SolrCloudTestCase {
System.clearProperty("solr.allowPaths");
}
+ @SuppressWarnings("AssertionFailureIgnored") // failure happens inside of
a thread
public void testCoreAdminHandler() throws Exception {
final int numBackupIters = 20; // don't use 'atLeast', we don't want
to blow up on nightly
diff --git
a/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.java
b/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.java
index 43b2436..93eb6cb 100644
--- a/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.java
+++ b/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.java
@@ -149,6 +149,7 @@ public class TestStressThreadBackup extends
SolrCloudTestCase {
}
+ @SuppressWarnings("AssertionFailureIgnored") // failure happens inside of a
thread
public void testSnapshotsAndBackupsDuringConcurrentCommitsAndOptimizes(final
BackupAPIImpl impl) throws Exception {
final int numBackupIters = 20; // don't use 'atLeast', we don't want to
blow up on nightly
diff --git
a/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
b/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
index db27ee1..152c2bb 100644
--- a/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
+++ b/solr/core/src/test/org/apache/solr/handler/export/TestExportWriter.java
@@ -684,13 +684,13 @@ public class TestExportWriter extends SolrTestCaseJ4 {
float_vals[5] = Float.MAX_VALUE;
float_vals[6] = Float.MIN_VALUE;
float_vals[7] = 1/3f; //0.33333334
- float_vals[8] = 0.33333333f;
+ float_vals[8] = 0.3333333f; //max digits before float loses precision
float_vals[9] = random().nextFloat();
for (int i = 0; i < numDocs; i++) {
int number = TestUtil.nextInt(random(), 0, 9);
assertU(adoc("id", String.valueOf(i),
- "floatdv", String.valueOf(number),
+ "floatdv", String.valueOf(float_vals[number]),
"intdv", String.valueOf(number),
"stringdv", String.valueOf(str_vals[number]),
"longdv", String.valueOf(number),
diff --git
a/solr/core/src/test/org/apache/solr/handler/tagger/TaggerTestCase.java
b/solr/core/src/test/org/apache/solr/handler/tagger/TaggerTestCase.java
index 25c7d86..c0d030a 100644
--- a/solr/core/src/test/org/apache/solr/handler/tagger/TaggerTestCase.java
+++ b/solr/core/src/test/org/apache/solr/handler/tagger/TaggerTestCase.java
@@ -188,21 +188,21 @@ public abstract class TaggerTestCase extends
SolrTestCaseJ4 {
/** Asserts the sorted arrays are equals, with a helpful error message when
not.*/
public void assertSortedArrayEquals(String message, Object[] expecteds,
Object[] actuals) {
- AssertionError error = null;
try {
assertArrayEquals(null, expecteds, actuals);
- } catch (AssertionError e) {
- error = e;
+ } catch (AssertionError error) {
+ TreeSet<Object> expectedRemaining = new
TreeSet<>(Arrays.asList(expecteds));
+ TreeSet<Object> actualsRemaining = new TreeSet<>(Arrays.asList(actuals));
+
+ expectedRemaining.removeAll(actualsRemaining); // expected - actual
+ if (!expectedRemaining.isEmpty()) {
+ message += ": didn't find expected " + expectedRemaining.first() + "
(of " + expectedRemaining.size() + ")";
+ } else {
+ Arrays.asList(expecteds).forEach(actualsRemaining::remove); // actual
- expected
+ message += ": didn't expect " + actualsRemaining.first() + " (of " +
actualsRemaining.size() + ")";
+ }
+ throw new AssertionError(message, error);
}
- if (error == null)
- return;
- TreeSet<Object> expectedRemaining = new
TreeSet<>(Arrays.asList(expecteds));
- expectedRemaining.removeAll(Arrays.asList(actuals));
- if (!expectedRemaining.isEmpty())
- fail(message+": didn't find expected "+expectedRemaining.first()+" (of
"+expectedRemaining.size()+"); "+ error);
- TreeSet<Object> actualsRemaining = new TreeSet<>(Arrays.asList(actuals));
- actualsRemaining.removeAll(Arrays.asList(expecteds));
- fail(message+": didn't expect "+actualsRemaining.first()+" (of
"+actualsRemaining.size()+"); "+ error);
}
class TestTag implements Comparable<TestTag> {
diff --git
a/solr/core/src/test/org/apache/solr/response/TestRetrieveFieldsOptimizer.java
b/solr/core/src/test/org/apache/solr/response/TestRetrieveFieldsOptimizer.java
index 07609d3..f63c76b 100644
---
a/solr/core/src/test/org/apache/solr/response/TestRetrieveFieldsOptimizer.java
+++
b/solr/core/src/test/org/apache/solr/response/TestRetrieveFieldsOptimizer.java
@@ -20,6 +20,7 @@ package org.apache.solr.response;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.time.Instant;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
@@ -527,7 +528,9 @@ class RetrieveField {
}
private String randDate() {
- return new Date(Math.abs(random().nextLong()) %
3_000_000_000_000L).toInstant().toString();
+ long lng = random().nextLong();
+ lng = (lng == Long.MIN_VALUE) ? 0 : Math.abs(lng) % 3_000_000_000_000L;
+ return Instant.ofEpochMilli(lng).toString();
}
List<String> getValsForField() {
diff --git
a/solr/core/src/test/org/apache/solr/search/facet/SpatialHeatmapFacetsTest.java
b/solr/core/src/test/org/apache/solr/search/facet/SpatialHeatmapFacetsTest.java
index 8192730..ab3f0e0 100644
---
a/solr/core/src/test/org/apache/solr/search/facet/SpatialHeatmapFacetsTest.java
+++
b/solr/core/src/test/org/apache/solr/search/facet/SpatialHeatmapFacetsTest.java
@@ -327,7 +327,7 @@ public class SpatialHeatmapFacetsTest extends
BaseDistributedSearchTestCase {
if (ri >= 0 && ri <= 3) {
counts[i] = ri; // 0 thru 3 will be made common
} else if (ri > 3) {
- counts[i] = Math.abs(random().nextInt());//lots of other possible
values up to max
+ counts[i] = random().nextInt(Integer.MAX_VALUE); //lots of other
possible values up to max
}
}
// Round-trip
diff --git
a/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetErrors.java
b/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetErrors.java
index 899ab33..f28a46e 100644
--- a/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetErrors.java
+++ b/solr/core/src/test/org/apache/solr/search/facet/TestJsonFacetErrors.java
@@ -93,15 +93,12 @@ public class TestJsonFacetErrors extends SolrTestCaseHS {
public void doTestErrors(Client client) throws Exception {
client.deleteByQuery("*:*", null);
- try {
+ SolrException e = assertThrows(SolrException.class, () ->
client.testJQ(params("ignore_exception", "true", "q", "*:*"
, "json.facet", "{f:{type:ignore_exception_aaa, field:bbbbbb}}"
)
- );
- } catch (SolrException e) {
- assertTrue( e.getMessage().contains("ignore_exception_aaa") );
- }
-
+ ));
+ assertTrue( e.getMessage().contains("ignore_exception_aaa") );
}
@Test
diff --git
a/solr/core/src/test/org/apache/solr/store/blockcache/BlockDirectoryTest.java
b/solr/core/src/test/org/apache/solr/store/blockcache/BlockDirectoryTest.java
index 28b1f21..d6ddea6 100644
---
a/solr/core/src/test/org/apache/solr/store/blockcache/BlockDirectoryTest.java
+++
b/solr/core/src/test/org/apache/solr/store/blockcache/BlockDirectoryTest.java
@@ -249,7 +249,7 @@ public class BlockDirectoryTest extends SolrTestCaseJ4 {
}
private String getName() {
- return Long.toString(Math.abs(random.nextLong()));
+ return Long.toUnsignedString(random.nextLong());
}
public static void rm(File file) {
diff --git
a/solr/core/src/test/org/apache/solr/store/hdfs/HdfsDirectoryTest.java
b/solr/core/src/test/org/apache/solr/store/hdfs/HdfsDirectoryTest.java
index a58c3ec..b1eb7c1 100644
--- a/solr/core/src/test/org/apache/solr/store/hdfs/HdfsDirectoryTest.java
+++ b/solr/core/src/test/org/apache/solr/store/hdfs/HdfsDirectoryTest.java
@@ -238,7 +238,7 @@ public class HdfsDirectoryTest extends SolrTestCaseJ4 {
}
private String getName() {
- return Long.toString(Math.abs(random.nextLong()));
+ return Long.toUnsignedString(random.nextLong());
}
public void testCantOverrideFiles() throws IOException {
diff --git
a/solr/core/src/test/org/apache/solr/update/TestExceedMaxTermLength.java
b/solr/core/src/test/org/apache/solr/update/TestExceedMaxTermLength.java
index 9bf502b..2bc3c25 100644
--- a/solr/core/src/test/org/apache/solr/update/TestExceedMaxTermLength.java
+++ b/solr/core/src/test/org/apache/solr/update/TestExceedMaxTermLength.java
@@ -72,23 +72,18 @@ public class TestExceedMaxTermLength extends SolrTestCaseJ4
{
assertFailedU(doc);
} else {
//Use JSON
- try {
- if(includeOkayFields) {
- String jsonStr = "[{'id':'1','%s':'%s', '%s': '%s'}]";
- jsonStr = String.format(Locale.ROOT, jsonStr, longFieldName,
longFieldValue,
- okayFieldName, okayFieldValue);
- updateJ(json(jsonStr), null);
- } else {
- String jsonStr = "[{'id':'1','%s':'%s'}]";
- jsonStr = String.format(Locale.ROOT, jsonStr, longFieldName,
longFieldValue);
- updateJ(json(jsonStr), null);
- }
- } catch (Exception e) {
- //expected
- String msg= e.getCause().getMessage();
- assertTrue(msg.contains("one immense term in field=\"cat\""));
+ final String jsonStr;
+ if(includeOkayFields) {
+ String format = "[{'id':'1','%s':'%s', '%s': '%s'}]";
+ jsonStr = String.format(Locale.ROOT, format, longFieldName,
longFieldValue,
+ okayFieldName, okayFieldValue);
+ } else {
+ String format = "[{'id':'1','%s':'%s'}]";
+ jsonStr = String.format(Locale.ROOT, format, longFieldName,
longFieldValue);
}
-
+ Exception e = assertThrows(Exception.class, () -> updateJ(json(jsonStr),
null));
+ assertNotNull(e.getCause());
+ assertTrue(e.getCause().getMessage().contains("one immense term in
field=\"cat\""));
}
assertU(commit());
diff --git
a/solr/core/src/test/org/apache/solr/update/processor/ClassificationUpdateProcessorFactoryTest.java
b/solr/core/src/test/org/apache/solr/update/processor/ClassificationUpdateProcessorFactoryTest.java
index 2929784..de429cf 100644
---
a/solr/core/src/test/org/apache/solr/update/processor/ClassificationUpdateProcessorFactoryTest.java
+++
b/solr/core/src/test/org/apache/solr/update/processor/ClassificationUpdateProcessorFactoryTest.java
@@ -64,21 +64,15 @@ public class ClassificationUpdateProcessorFactoryTest
extends SolrTestCaseJ4 {
@Test
public void init_emptyInputFields_shouldThrowExceptionWithDetailedMessage() {
args.removeAll("inputFields");
- try {
- cFactoryToTest.init(args);
- } catch (SolrException e) {
- assertEquals("Classification UpdateProcessor 'inputFields' can not be
null", e.getMessage());
- }
+ SolrException e = assertThrows(SolrException.class, () ->
cFactoryToTest.init(args));
+ assertEquals("Classification UpdateProcessor 'inputFields' can not be
null", e.getMessage());
}
@Test
public void init_emptyClassField_shouldThrowExceptionWithDetailedMessage() {
args.removeAll("classField");
- try {
- cFactoryToTest.init(args);
- } catch (SolrException e) {
- assertEquals("Classification UpdateProcessor 'classField' can not be
null", e.getMessage());
- }
+ SolrException e = assertThrows(SolrException.class, () ->
cFactoryToTest.init(args));
+ assertEquals("Classification UpdateProcessor 'classField' can not be
null", e.getMessage());
}
@Test
@@ -95,11 +89,8 @@ public class ClassificationUpdateProcessorFactoryTest
extends SolrTestCaseJ4 {
public void
init_unsupportedAlgorithm_shouldThrowExceptionWithDetailedMessage() {
args.removeAll("algorithm");
args.add("algorithm", "unsupported");
- try {
- cFactoryToTest.init(args);
- } catch (SolrException e) {
- assertEquals("Classification UpdateProcessor Algorithm: 'unsupported'
not supported", e.getMessage());
- }
+ SolrException e = assertThrows(SolrException.class, () ->
cFactoryToTest.init(args));
+ assertEquals("Classification UpdateProcessor Algorithm: 'unsupported' not
supported", e.getMessage());
}
@Test
@@ -110,13 +101,12 @@ public class ClassificationUpdateProcessorFactoryTest
extends SolrTestCaseJ4 {
SolrQueryRequest mockRequest = mock(SolrQueryRequest.class);
SolrQueryResponse mockResponse = mock(SolrQueryResponse.class);
args.add("knn.filterQuery", "not supported query");
- try {
- cFactoryToTest.init(args);
+ cFactoryToTest.init(args);
+ SolrException e = assertThrows(SolrException.class, () -> {
/* parsing failure happens because of the mocks, fine enough to check a
proper exception propagation */
cFactoryToTest.getInstance(mockRequest, mockResponse, mockProcessor);
- } catch (SolrException e) {
- assertEquals("Classification UpdateProcessor Training Filter Query: 'not
supported query' is not supported", e.getMessage());
- }
+ });
+ assertEquals("Classification UpdateProcessor Training Filter Query: 'not
supported query' is not supported", e.getMessage());
}
@Test
diff --git
a/solr/core/src/test/org/apache/solr/update/processor/ClassificationUpdateProcessorIntegrationTest.java
b/solr/core/src/test/org/apache/solr/update/processor/ClassificationUpdateProcessorIntegrationTest.java
index 3a80f8f..1d16681 100644
---
a/solr/core/src/test/org/apache/solr/update/processor/ClassificationUpdateProcessorIntegrationTest.java
+++
b/solr/core/src/test/org/apache/solr/update/processor/ClassificationUpdateProcessorIntegrationTest.java
@@ -86,19 +86,13 @@ public class ClassificationUpdateProcessorIntegrationTest
extends SolrTestCaseJ4
@Test
public void
classify_unsupportedFilterQueryConfiguration_shouldThrowExceptionWithDetailedMessage()
throws Exception {
indexTrainingSet();
- try {
- addDoc(adoc(ID, "21",
- TITLE, "word4 word4 word4",
- CONTENT, "word5 word5 ",
- AUTHOR, "Name1 Surname1"), BROKEN_CHAIN_FILTER_QUERY);
- addDoc(adoc(ID, "22",
- TITLE, "word1 word1",
- CONTENT, "word2 word2",
- AUTHOR, "Name Surname"), BROKEN_CHAIN_FILTER_QUERY);
- addDoc(commit());
- } catch (SolrException e) {
- assertEquals("Classification UpdateProcessor Training Filter Query: 'not
valid ( lucene query' is not supported", e.getMessage());
- }
+ SolrException e = assertThrows(SolrException.class, () -> addDoc(
+ adoc(ID, "21",
+ TITLE, "word4 word4 word4",
+ CONTENT, "word5 word5 ",
+ AUTHOR, "Name1 Surname1"), BROKEN_CHAIN_FILTER_QUERY));
+ assertEquals("Classification UpdateProcessor Training Filter Query: 'not
valid ( lucene query' is not supported", e.getMessage());
+ addDoc(commit());
}
/**
diff --git a/solr/core/src/test/org/apache/solr/util/DateMathParserTest.java
b/solr/core/src/test/org/apache/solr/util/DateMathParserTest.java
index d3ea248..bc9aba7 100644
--- a/solr/core/src/test/org/apache/solr/util/DateMathParserTest.java
+++ b/solr/core/src/test/org/apache/solr/util/DateMathParserTest.java
@@ -47,6 +47,7 @@ public class DateMathParserTest extends SolrTestCaseJ4 {
*/
private DateTimeFormatter parser;
+ @SuppressWarnings("MisusedDayOfYear") // use a bunch of pattern symbols for
more comprehensive testing
public DateMathParserTest() {
fmt = DateTimeFormatter.ofPattern("G yyyyy MM ww W D dd F E a HH hh mm ss
SSS z Z", Locale.ROOT)
.withZone(ZoneOffset.UTC);
diff --git
a/solr/core/src/test/org/apache/solr/util/hll/IntegrationTestGenerator.java
b/solr/core/src/test/org/apache/solr/util/hll/IntegrationTestGenerator.java
index 69757ce..cc2641c 100644
--- a/solr/core/src/test/org/apache/solr/util/hll/IntegrationTestGenerator.java
+++ b/solr/core/src/test/org/apache/solr/util/hll/IntegrationTestGenerator.java
@@ -223,8 +223,8 @@ public class IntegrationTestGenerator {
initLineAdd(output, hll, schemaVersion);
for(int i=0; i<SPARSE_THRESHOLD; i++) {
- final int registerIndex = Math.abs(random.nextInt()) %
REGISTER_COUNT;
- final int registerValue = ((Math.abs(random.nextInt()) %
REGISTER_MAX_VALUE) + 1);
+ final int registerIndex = random.nextInt(REGISTER_COUNT);
+ final int registerValue = random.nextInt(REGISTER_MAX_VALUE) + 1;
final long rawValue = constructHLLValue(LOG2M, registerIndex,
registerValue);
cumulativeAddLine(output, hll, rawValue, schemaVersion);
@@ -329,8 +329,8 @@ public class IntegrationTestGenerator {
// make a SPARSE set and populate with cardinality 1
final HLL sparseHLL = newHLL(HLLType.SPARSE);
- final int registerIndex = Math.abs(random.nextInt()) %
REGISTER_COUNT;
- final int registerValue = ((Math.abs(random.nextInt()) %
REGISTER_MAX_VALUE) + 1);
+ final int registerIndex = random.nextInt(REGISTER_COUNT);
+ final int registerValue = random.nextInt(REGISTER_MAX_VALUE) + 1;
final long rawValue = constructHLLValue(LOG2M, registerIndex,
registerValue);
sparseHLL.addRaw(rawValue);
@@ -400,8 +400,8 @@ public class IntegrationTestGenerator {
for(int i=0; i<SPARSE_THRESHOLD; i++) {
// make a SPARSE set and populate with cardinality 1
final HLL sparseHLL = newHLL(HLLType.SPARSE);
- final int registerIndex = Math.abs(random.nextInt()) %
REGISTER_COUNT;
- final int registerValue = ((Math.abs(random.nextInt()) %
REGISTER_MAX_VALUE) + 1);
+ final int registerIndex = random.nextInt(REGISTER_COUNT);
+ final int registerValue = random.nextInt(REGISTER_MAX_VALUE) + 1;
final long rawValue = constructHLLValue(LOG2M, registerIndex,
registerValue);
sparseHLL.addRaw(rawValue);
@@ -504,7 +504,7 @@ public class IntegrationTestGenerator {
* and {@link #SPARSE_THRESHOLD}) specified above.
*/
private static HLL newHLL(final HLLType type) {
- return newHLL(type);
+ return new HLL(LOG2M, REGWIDTH, EXPLICIT_THRESHOLD, SPARSE_THRESHOLD,
type);
}
/**
diff --git a/solr/core/src/test/org/apache/solr/util/stats/MetricUtilsTest.java
b/solr/core/src/test/org/apache/solr/util/stats/MetricUtilsTest.java
index 17358f2..6885499 100644
--- a/solr/core/src/test/org/apache/solr/util/stats/MetricUtilsTest.java
+++ b/solr/core/src/test/org/apache/solr/util/stats/MetricUtilsTest.java
@@ -46,7 +46,7 @@ public class MetricUtilsTest extends SolrTestCaseJ4 {
final Timer timer = new Timer();
final int iterations = random().nextInt(100);
for (int i = 0; i < iterations; ++i) {
- timer.update(Math.abs(random().nextInt()) + 1, TimeUnit.NANOSECONDS);
+ timer.update(random().nextInt(Integer.MAX_VALUE - 1) + 1,
TimeUnit.NANOSECONDS);
}
// obtain timer metrics
Map<String,Object> map = new HashMap<>();
diff --git a/solr/solr-ref-guide/build.gradle b/solr/solr-ref-guide/build.gradle
index 021ca45..abf8aa2 100644
--- a/solr/solr-ref-guide/build.gradle
+++ b/solr/solr-ref-guide/build.gradle
@@ -200,7 +200,7 @@ ext {
dependsOn "build${details.name}"
classpath = sourceSets.main.runtimeClasspath
- main = 'CheckLinksAndAnchors'
+ main = 'org.apache.solr.guide.CheckLinksAndAnchors'
workingDir = contentDir
// NOTE: even for the 'real' site, we check all relative links
@@ -285,7 +285,7 @@ abstract class PrepareSources extends DefaultTask {
.getPlugin(JavaPluginConvention.class)
.getSourceSets().getByName("main").getRuntimeClasspath() )
execSpec.setWorkingDir( intoDir )
- execSpec.setMain( 'BuildNavDataFiles' )
+ execSpec.setMain( 'org.apache.solr.guide.BuildNavDataFiles' )
execSpec.args([ intoDir, p.property('mainPage') ])
})
}
diff --git a/solr/solr-ref-guide/tools/BuildNavDataFiles.java
b/solr/solr-ref-guide/tools/org/apache/solr/guide/BuildNavDataFiles.java
similarity index 99%
rename from solr/solr-ref-guide/tools/BuildNavDataFiles.java
rename to solr/solr-ref-guide/tools/org/apache/solr/guide/BuildNavDataFiles.java
index 5b87bb8..9a4d3987 100644
--- a/solr/solr-ref-guide/tools/BuildNavDataFiles.java
+++ b/solr/solr-ref-guide/tools/org/apache/solr/guide/BuildNavDataFiles.java
@@ -15,6 +15,8 @@
* limitations under the License.
*/
+package org.apache.solr.guide;
+
import java.io.*;
import java.io.FilenameFilter;
import java.util.*;
diff --git a/solr/solr-ref-guide/tools/CheckLinksAndAnchors.java
b/solr/solr-ref-guide/tools/org/apache/solr/guide/CheckLinksAndAnchors.java
similarity index 96%
rename from solr/solr-ref-guide/tools/CheckLinksAndAnchors.java
rename to
solr/solr-ref-guide/tools/org/apache/solr/guide/CheckLinksAndAnchors.java
index d979b40..3d330d5 100644
--- a/solr/solr-ref-guide/tools/CheckLinksAndAnchors.java
+++ b/solr/solr-ref-guide/tools/org/apache/solr/guide/CheckLinksAndAnchors.java
@@ -15,6 +15,8 @@
* limitations under the License.
*/
+package org.apache.solr.guide;
+
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
@@ -38,7 +40,7 @@ import org.jsoup.select.Elements;
* Check various things regarding anchors, links & general doc structure
in the generated HTML site.
*
* <p>
- * Usage: <code>java CheckLinksAndAnchors some-html-dir-name/
[-check-all-relative-links] [-bare-bones]</code>
+ * Usage: <code>java org.apache.solr.guide.CheckLinksAndAnchors
some-html-dir-name/ [-check-all-relative-links] [-bare-bones]</code>
* </p>
* <p>
@@ -119,7 +121,7 @@ public class CheckLinksAndAnchors { // TODO: rename this
class now that it does
int problems = 0;
if (args.length < 1) {
- System.err.println("usage: CheckLinksAndAnchors <htmldir>
[-check-all-relative-links] [-bare-bones]");
+ System.err.println("usage: org.apache.solr.guide.CheckLinksAndAnchors
<htmldir> [-check-all-relative-links] [-bare-bones]");
System.exit(-1);
}
final File htmlDir = new File(args[0]);
@@ -133,14 +135,14 @@ public class CheckLinksAndAnchors { // TODO: rename this
class now that it does
final boolean checkAllRelativeLinks =
options.remove("-check-all-relative-links");
if (! options.isEmpty()) {
for (String brokenOpt : options) {
- System.err.println("CheckLinksAndAnchors: Unrecognized option: " +
brokenOpt);
+ System.err.println("org.apache.solr.guide.CheckLinksAndAnchors:
Unrecognized option: " + brokenOpt);
}
System.exit(-1);
}
final File[] pages = htmlDir.listFiles(new HtmlFileFilter());
if (0 == pages.length) {
- System.err.println("CheckLinksAndAnchors: No HTML Files found, wrong
htmlDir? forgot to built the site?");
+ System.err.println("org.apache.solr.guide.CheckLinksAndAnchors: No HTML
Files found, wrong htmlDir? forgot to built the site?");
System.exit(-1);
}
diff --git
a/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/eval/AddEvaluatorTest.java
b/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/eval/AddEvaluatorTest.java
index ca094d5..33825d0 100644
---
a/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/eval/AddEvaluatorTest.java
+++
b/solr/solrj/src/test/org/apache/solr/client/solrj/io/stream/eval/AddEvaluatorTest.java
@@ -241,7 +241,7 @@ public class AddEvaluatorTest extends SolrTestCase {
values.put("d", 4.123456789123456);
result = evaluator.evaluate(new Tuple(values));
Assert.assertTrue(result instanceof Double);
- Assert.assertEquals(14.623456789123456, result);
+ Assert.assertEquals(14.623456789123456, (Double) result, 0.000000001);
values.clear();
values.put("a", 123456789123456789L);
diff --git
a/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractIncrementalBackupTest.java
b/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractIncrementalBackupTest.java
index 09cf4cb..2c7b844 100644
---
a/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractIncrementalBackupTest.java
+++
b/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractIncrementalBackupTest.java
@@ -510,11 +510,7 @@ public abstract class AbstractIncrementalBackupTest
extends SolrCloudTestCase {
Arrays.sort(files1);
Arrays.sort(files2);
- try {
- assertArrayEquals(files1, files2);
- } catch (AssertionError e) {
- e.printStackTrace();
- }
+ assertArrayEquals(files1, files2);
for (int i = 0; i < files1.length; i++) {
URI file1Uri = repository.resolve(uri1, files1[i]);