Skip to content

Apache Lucene open-source search software

Random overhead improvements (#15327)

Dawid Weiss10cb3ee3aeb8
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/TestsAndRandomizationPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/TestsAndRandomizationPlugin.java
index aeef87536ad..1906f4ca20c 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/TestsAndRandomizationPlugin.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/TestsAndRandomizationPlugin.java
@@ -221,6 +221,15 @@ public class TestsAndRandomizationPlugin extends LuceneGradlePlugin {
buildOptions.addIntOption("tests.timeoutSuite", "Timeout (in millis) for an entire suite.");
optionsInheritedAsProperties.add("tests.timeoutSuite");
+ buildOptions.addIntOption(
+ "tests.random.maxcalls",
+ "Max number of calls to Randoms returned by LuceneTestCase.random()");
+ optionsInheritedAsProperties.add("tests.random.maxcalls");
+
+ buildOptions.addIntOption(
+ "tests.random.maxacquires", "Max number of per-test calls to LuceneTestCase.random()");
+ optionsInheritedAsProperties.add("tests.random.maxacquires");
+
Provider<Boolean> assertsOption =
buildOptions.addBooleanOption(
"tests.asserts",
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index e2410fb39df..ddacafe9bdc 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -63,8 +63,6 @@ Improvements
This avoids clashes with other ASM versions on classpath because it removes the dependency.
(Uwe Schindler)
-
-
* GITHUB#15002: Remove synchronized WeakHashMap from IndexReader. This was added to help prevent
SIGSEGV with the old unsafe "mmap hack", which has been replaced by MemorySegments.
(Uwe Schindler, Robert Muir)
@@ -106,7 +104,11 @@ Changes in Runtime Behavior
Build
---------------------
-* GITHUB#15325: Run the tests with assertions disabled ~25% of the time #15325 (Dawid Weiss)
+* GITHUB#15327: New low-level build options to detect abuse of LuceneTestCase.random():
+ tests.random.maxacquires and tests.random.maxcalls (Robert Muir, Dawid Weiss)
+
+* GITHUB#15325: Run the tests with assertions disabled ~25% of the time #15325
+ (Robert Muir, Dawid Weiss)
* GITHUB#14804: Detect and ban wildcard imports in Java (Robert Muir, Dawid Weiss)
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestRollingCharBuffer.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestRollingCharBuffer.java
index 9a9e74c8764..aa41b62a00b 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestRollingCharBuffer.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestRollingCharBuffer.java
@@ -28,7 +28,7 @@ public class TestRollingCharBuffer extends LuceneTestCase {
RollingCharBuffer buffer = new RollingCharBuffer();
- Random random = random();
+ Random random = nonAssertingRandom(random());
for (int iter = 0; iter < ITERS; iter++) {
final int stringLen = random.nextBoolean() ? random.nextInt(50) : random.nextInt(20000);
final String s;
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/compressing/AbstractTestCompressionMode.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/compressing/AbstractTestCompressionMode.java
index 2cca151e059..df639b3973f 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/compressing/AbstractTestCompressionMode.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/compressing/AbstractTestCompressionMode.java
@@ -39,6 +39,7 @@ public abstract class AbstractTestCompressionMode extends LuceneTestCase {
}
static byte[] randomArray(Random random, int length, int max) {
+ random = nonAssertingRandom(random);
final byte[] arr = new byte[length];
for (int i = 0; i < arr.length; ++i) {
arr[i] = (byte) RandomNumbers.randomIntBetween(random, 0, max);
@@ -83,7 +84,7 @@ public abstract class AbstractTestCompressionMode extends LuceneTestCase {
}
public void testDecompress() throws IOException {
- Random random = random();
+ Random random = nonAssertingRandom(random());
final int iterations = atLeast(random, 3);
for (int i = 0; i < iterations; ++i) {
final byte[] decompressed = randomArray(random);
@@ -99,7 +100,7 @@ public abstract class AbstractTestCompressionMode extends LuceneTestCase {
}
public void testPartialDecompress() throws IOException {
- Random random = random();
+ Random random = nonAssertingRandom(random());
final int iterations = atLeast(random, 3);
for (int i = 0; i < iterations; ++i) {
final byte[] decompressed = randomArray(random);
diff --git a/lucene/classification/src/test/org/apache/lucene/classification/utils/TestDataSplitter.java b/lucene/classification/src/test/org/apache/lucene/classification/utils/TestDataSplitter.java
index 5b8e02b8477..1e7f2447a8f 100644
--- a/lucene/classification/src/test/org/apache/lucene/classification/utils/TestDataSplitter.java
+++ b/lucene/classification/src/test/org/apache/lucene/classification/utils/TestDataSplitter.java
@@ -63,7 +63,7 @@ public class TestDataSplitter extends LuceneTestCase {
ft.setStoreTermVectorPositions(true);
Document doc;
- Random rnd = random();
+ Random rnd = nonAssertingRandom(random());
int numDocs = atLeast(100);
for (int i = 0; i < numDocs; i++) {
doc = new Document();
diff --git a/lucene/core/src/test/org/apache/lucene/analysis/standard/TestStandardAnalyzer.java b/lucene/core/src/test/org/apache/lucene/analysis/standard/TestStandardAnalyzer.java
index b51cdf86306..a9a7bd7145a 100644
--- a/lucene/core/src/test/org/apache/lucene/analysis/standard/TestStandardAnalyzer.java
+++ b/lucene/core/src/test/org/apache/lucene/analysis/standard/TestStandardAnalyzer.java
@@ -76,19 +76,20 @@ public class TestStandardAnalyzer extends BaseTokenStreamTestCase {
};
StringBuilder builder = new StringBuilder();
- int numChars = TestUtil.nextInt(random(), 100 * 1024, 1024 * 1024);
+ var rnd = nonAssertingRandom(random());
+ int numChars = TestUtil.nextInt(rnd, 100 * 1024, 1024 * 1024);
for (int i = 0; i < numChars; ) {
builder.append(
- WordBreak_ExtendNumLet_chars[random().nextInt(WordBreak_ExtendNumLet_chars.length)]);
+ WordBreak_ExtendNumLet_chars[rnd.nextInt(WordBreak_ExtendNumLet_chars.length)]);
++i;
- if (random().nextBoolean()) {
- int numFormatExtendChars = TestUtil.nextInt(random(), 1, 8);
+ if (rnd.nextBoolean()) {
+ int numFormatExtendChars = TestUtil.nextInt(rnd, 1, 8);
for (int j = 0; j < numFormatExtendChars; ++j) {
int codepoint;
- if (random().nextBoolean()) {
- codepoint = WordBreak_Format_chars[random().nextInt(WordBreak_Format_chars.length)];
+ if (rnd.nextBoolean()) {
+ codepoint = WordBreak_Format_chars[rnd.nextInt(WordBreak_Format_chars.length)];
} else {
- codepoint = WordBreak_Extend_chars[random().nextInt(WordBreak_Extend_chars.length)];
+ codepoint = WordBreak_Extend_chars[rnd.nextInt(WordBreak_Extend_chars.length)];
}
char[] chars = Character.toChars(codepoint);
builder.append(chars);
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene103/blocktree/TestTrie.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene103/blocktree/TestTrie.java
index f559262b160..f1bc495f656 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene103/blocktree/TestTrie.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene103/blocktree/TestTrie.java
@@ -194,9 +194,10 @@ public class TestTrie extends LuceneTestCase {
}
private static byte[] randomBytes() {
- byte[] bytes = new byte[random().nextInt(256) + 1];
+ var random = nonAssertingRandom(random());
+ byte[] bytes = new byte[random.nextInt(256) + 1];
for (int i = 1; i < bytes.length; i++) {
- bytes[i] = (byte) random().nextInt(1 << (i % 9));
+ bytes[i] = (byte) random.nextInt(1 << (i % 9));
}
return bytes;
}
diff --git a/lucene/core/src/test/org/apache/lucene/geo/TestGeoEncodingUtils.java b/lucene/core/src/test/org/apache/lucene/geo/TestGeoEncodingUtils.java
index d654e446475..5e32ac43501 100644
--- a/lucene/core/src/test/org/apache/lucene/geo/TestGeoEncodingUtils.java
+++ b/lucene/core/src/test/org/apache/lucene/geo/TestGeoEncodingUtils.java
@@ -27,6 +27,7 @@ import static org.apache.lucene.geo.GeoUtils.MAX_LON_INCL;
import static org.apache.lucene.geo.GeoUtils.MIN_LAT_INCL;
import static org.apache.lucene.geo.GeoUtils.MIN_LON_INCL;
+import com.carrotsearch.randomizedtesting.RandomizedTest;
import java.util.Random;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.lucene.tests.util.TestUtil;
@@ -42,8 +43,8 @@ public class TestGeoEncodingUtils extends LuceneTestCase {
*/
public void testLatitudeQuantization() throws Exception {
final double LATITUDE_DECODE = 180.0D / (0x1L << 32);
- Random random = random();
- for (int i = 0; i < 10000; i++) {
+ Random random = nonAssertingRandom(random());
+ for (int i = 0; i < RandomizedTest.randomIntBetween(1000, 10000); i++) {
int encoded = random.nextInt();
double min = MIN_LAT_INCL + (encoded - (long) Integer.MIN_VALUE) * LATITUDE_DECODE;
double decoded = decodeLatitude(encoded);
@@ -92,8 +93,8 @@ public class TestGeoEncodingUtils extends LuceneTestCase {
*/
public void testLongitudeQuantization() throws Exception {
final double LONGITUDE_DECODE = 360.0D / (0x1L << 32);
- Random random = random();
- for (int i = 0; i < 10000; i++) {
+ Random random = nonAssertingRandom(random());
+ for (int i = 0; i < RandomizedTest.randomIntBetween(1000, 10000); i++) {
int encoded = random.nextInt();
double min = MIN_LON_INCL + (encoded - (long) Integer.MIN_VALUE) * LONGITUDE_DECODE;
double decoded = decodeLongitude(encoded);
diff --git a/lucene/core/src/test/org/apache/lucene/geo/TestXYRectangle.java b/lucene/core/src/test/org/apache/lucene/geo/TestXYRectangle.java
index a70abdc7964..bd3a13201dc 100644
--- a/lucene/core/src/test/org/apache/lucene/geo/TestXYRectangle.java
+++ b/lucene/core/src/test/org/apache/lucene/geo/TestXYRectangle.java
@@ -139,17 +139,19 @@ public class TestXYRectangle extends LuceneTestCase {
/** make sure that if a point is inside a circle, it is inside of the bbox as well */
public void testRandomCircleToBBox() {
+ var random = nonAssertingRandom(random());
+
int iters = atLeast(100);
for (int iter = 0; iter < iters; iter++) {
- float centerX = ShapeTestUtil.nextFloat(random());
- float centerY = ShapeTestUtil.nextFloat(random());
+ float centerX = ShapeTestUtil.nextFloat(random);
+ float centerY = ShapeTestUtil.nextFloat(random);
final float radius;
- if (random().nextBoolean()) {
- radius = random().nextFloat() * TestUtil.nextInt(random(), 1, 100000);
+ if (random.nextBoolean()) {
+ radius = random.nextFloat() * TestUtil.nextInt(random, 1, 100000);
} else {
- radius = Math.abs(ShapeTestUtil.nextFloat(random()));
+ radius = Math.abs(ShapeTestUtil.nextFloat(random));
}
XYRectangle bbox = XYRectangle.fromPointDistance(centerX, centerY, radius);
@@ -159,16 +161,16 @@ public class TestXYRectangle extends LuceneTestCase {
for (int i = 0; i < numPointsToTry; i++) {
double x;
- if (random().nextBoolean()) {
- x = Math.min(Float.MAX_VALUE, centerX + radius + random().nextDouble());
+ if (random.nextBoolean()) {
+ x = Math.min(Float.MAX_VALUE, centerX + radius + random.nextDouble());
} else {
- x = Math.max(-Float.MAX_VALUE, centerX + radius - random().nextDouble());
+ x = Math.max(-Float.MAX_VALUE, centerX + radius - random.nextDouble());
}
double y;
- if (random().nextBoolean()) {
- y = Math.min(Float.MAX_VALUE, centerY + radius + random().nextDouble());
+ if (random.nextBoolean()) {
+ y = Math.min(Float.MAX_VALUE, centerY + radius + random.nextDouble());
} else {
- y = Math.max(-Float.MAX_VALUE, centerY + radius - random().nextDouble());
+ y = Math.max(-Float.MAX_VALUE, centerY + radius - random.nextDouble());
}
// cartesian says it's within the circle:
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestCollectorManager.java b/lucene/core/src/test/org/apache/lucene/search/TestCollectorManager.java
index 1e5826160f6..3ad804b876e 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestCollectorManager.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestCollectorManager.java
@@ -93,12 +93,14 @@ public class TestCollectorManager extends LuceneTestCase {
private static <C extends Collector> Object collectAll(
LeafReaderContext ctx, Collection<Integer> values, CollectorManager<C, ?> collectorManager)
throws IOException {
+ var rnd = nonAssertingRandom(random());
+
List<C> collectors = new ArrayList<>();
C collector = collectorManager.newCollector();
collectors.add(collector);
LeafCollector leafCollector = collector.getLeafCollector(ctx);
for (Integer v : values) {
- if (random().nextInt(10) == 1) {
+ if (rnd.nextInt(10) == 1) {
collector = collectorManager.newCollector();
collectors.add(collector);
leafCollector = collector.getLeafCollector(ctx);
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestConjunctionDISI.java b/lucene/core/src/test/org/apache/lucene/search/TestConjunctionDISI.java
index 69cfdc35350..3ade91fc60d 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestConjunctionDISI.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestConjunctionDISI.java
@@ -160,21 +160,21 @@ public class TestConjunctionDISI extends LuceneTestCase {
}
private static FixedBitSet randomSet(int maxDoc) {
- final int step = TestUtil.nextInt(random(), 1, 10);
+ var random = nonAssertingRandom(random());
+ final int step = TestUtil.nextInt(random, 1, 10);
FixedBitSet set = new FixedBitSet(maxDoc);
- for (int doc = random().nextInt(step);
- doc < maxDoc;
- doc += TestUtil.nextInt(random(), 1, step)) {
+ for (int doc = random.nextInt(step); doc < maxDoc; doc += TestUtil.nextInt(random, 1, step)) {
set.set(doc);
}
return set;
}
private static FixedBitSet clearRandomBits(FixedBitSet other) {
+ var random = nonAssertingRandom(random());
final FixedBitSet set = new FixedBitSet(other.length());
set.or(other);
for (int i = 0; i < set.length(); ++i) {
- if (random().nextBoolean()) {
+ if (random.nextBoolean()) {
set.clear(i);
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMultiCollectorManager.java b/lucene/core/src/test/org/apache/lucene/search/TestMultiCollectorManager.java
index d87515d0596..57fdf547e31 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestMultiCollectorManager.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestMultiCollectorManager.java
@@ -197,8 +197,9 @@ public class TestMultiCollectorManager extends LuceneTestCase {
C collector = collectorManager.newCollector();
collectors.add(collector);
LeafCollector leafCollector = collector.getLeafCollector(ctx);
+ Random random = nonAssertingRandom(random());
for (Integer v : values) {
- if (random().nextInt(10) == 1) {
+ if (random.nextInt(10) == 1) {
collector = collectorManager.newCollector();
collectors.add(collector);
leafCollector = collector.getLeafCollector(ctx);
diff --git a/lucene/core/src/test/org/apache/lucene/store/BaseDataOutputTestCase.java b/lucene/core/src/test/org/apache/lucene/store/BaseDataOutputTestCase.java
index d56a817e209..bb7483f32f1 100644
--- a/lucene/core/src/test/org/apache/lucene/store/BaseDataOutputTestCase.java
+++ b/lucene/core/src/test/org/apache/lucene/store/BaseDataOutputTestCase.java
@@ -58,6 +58,7 @@ public abstract class BaseDataOutputTestCase<T extends DataOutput> extends Lucen
protected static List<IOConsumer<DataInput>> addRandomData(
DataOutput dst, Random rnd, int maxAddCalls) throws IOException {
try {
+ rnd = LuceneTestCase.nonAssertingRandom(rnd);
List<IOConsumer<DataInput>> reply = new ArrayList<>();
for (int i = 0; i < maxAddCalls; i++) {
reply.add(RandomPicks.randomFrom(rnd, GENERATORS).apply(dst, rnd));
diff --git a/lucene/core/src/test/org/apache/lucene/store/TestByteBuffersDataInput.java b/lucene/core/src/test/org/apache/lucene/store/TestByteBuffersDataInput.java
index 0d4629e1c99..d29b9a19092 100644
--- a/lucene/core/src/test/org/apache/lucene/store/TestByteBuffersDataInput.java
+++ b/lucene/core/src/test/org/apache/lucene/store/TestByteBuffersDataInput.java
@@ -16,11 +16,11 @@
*/
package org.apache.lucene.store;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static com.carrotsearch.randomizedtesting.RandomizedTest.randomBoolean;
+import static com.carrotsearch.randomizedtesting.RandomizedTest.randomBytesOfLength;
+import static com.carrotsearch.randomizedtesting.RandomizedTest.randomIntBetween;
+import static com.carrotsearch.randomizedtesting.RandomizedTest.randomLongBetween;
-import com.carrotsearch.randomizedtesting.RandomizedTest;
-import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom;
import com.carrotsearch.randomizedtesting.annotations.Timeout;
import java.io.EOFException;
import java.io.IOException;
@@ -32,7 +32,7 @@ import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.IOConsumer;
import org.junit.Test;
-public final class TestByteBuffersDataInput extends RandomizedTest {
+public final class TestByteBuffersDataInput extends LuceneTestCase {
@Test
public void testSanity() throws IOException {
ByteBuffersDataOutput out = new ByteBuffersDataOutput();
@@ -69,10 +69,9 @@ public final class TestByteBuffersDataInput extends RandomizedTest {
public void testRandomReads() throws Exception {
ByteBuffersDataOutput dst = new ByteBuffersDataOutput();
- long seed = randomLong();
int max = LuceneTestCase.TEST_NIGHTLY ? 1_000_000 : 100_000;
List<IOConsumer<DataInput>> reply =
- TestByteBuffersDataOutput.addRandomData(dst, new Xoroshiro128PlusRandom(seed), max);
+ TestByteBuffersDataOutput.addRandomData(dst, nonAssertingRandom(random()), max);
ByteBuffersDataInput src = dst.toDataInput();
for (IOConsumer<DataInput> c : reply) {
@@ -94,10 +93,9 @@ public final class TestByteBuffersDataInput extends RandomizedTest {
byte[] prefix = new byte[randomIntBetween(0, 1024 * 8)];
dst.writeBytes(prefix);
- long seed = randomLong();
- int max = 10_000;
+ int max = atLeast(5000);
List<IOConsumer<DataInput>> reply =
- TestByteBuffersDataOutput.addRandomData(dst, new Xoroshiro128PlusRandom(seed), max);
+ TestByteBuffersDataOutput.addRandomData(dst, nonAssertingRandom(random()), max);
byte[] suffix = new byte[randomIntBetween(0, 1024 * 8)];
dst.writeBytes(suffix);
@@ -150,10 +148,9 @@ public final class TestByteBuffersDataInput extends RandomizedTest {
dst.writeBytes(prefix);
}
- long seed = randomLong();
int max = 1000;
List<IOConsumer<DataInput>> reply =
- TestByteBuffersDataOutput.addRandomData(dst, new Xoroshiro128PlusRandom(seed), max);
+ TestByteBuffersDataOutput.addRandomData(dst, random(), max);
ByteBuffersDataInput in = dst.toDataInput().slice(prefix.length, dst.size() - prefix.length);
diff --git a/lucene/core/src/test/org/apache/lucene/store/TestMMapDirectory.java b/lucene/core/src/test/org/apache/lucene/store/TestMMapDirectory.java
index f59adb31db2..33e12782334 100644
--- a/lucene/core/src/test/org/apache/lucene/store/TestMMapDirectory.java
+++ b/lucene/core/src/test/org/apache/lucene/store/TestMMapDirectory.java
@@ -55,7 +55,7 @@ public class TestMMapDirectory extends BaseDirectoryTestCase {
try (Directory dir = getDirectory(createTempDir("testAceWithThreads"))) {
try (IndexOutput out = dir.createOutput("test", IOContext.DEFAULT)) {
- final Random random = random();
+ final Random random = nonAssertingRandom(random());
for (int i = 0; i < nInts; i++) {
out.writeInt(random.nextInt());
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestMSBRadixSorter.java b/lucene/core/src/test/org/apache/lucene/util/TestMSBRadixSorter.java
index 304b9f6e510..98bb2639222 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestMSBRadixSorter.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestMSBRadixSorter.java
@@ -85,13 +85,14 @@ public class TestMSBRadixSorter extends LuceneTestCase {
}
private void testRandom(int commonPrefixLen, int maxLen) {
+ var random = nonAssertingRandom(random());
byte[] commonPrefix = new byte[commonPrefixLen];
- random().nextBytes(commonPrefix);
- final int len = random().nextInt(100000);
- BytesRef[] bytes = new BytesRef[len + random().nextInt(50)];
+ random.nextBytes(commonPrefix);
+ final int len = random.nextInt(100000);
+ BytesRef[] bytes = new BytesRef[len + random.nextInt(50)];
for (int i = 0; i < len; ++i) {
- byte[] b = new byte[commonPrefixLen + random().nextInt(maxLen)];
- random().nextBytes(b);
+ byte[] b = new byte[commonPrefixLen + random.nextInt(maxLen)];
+ random.nextBytes(b);
System.arraycopy(commonPrefix, 0, b, 0, commonPrefixLen);
bytes[i] = new BytesRef(b);
}
@@ -99,27 +100,19 @@ public class TestMSBRadixSorter extends LuceneTestCase {
}
public void testRandom() {
- for (int iter = 0; iter < 10; ++iter) {
- testRandom(0, 10);
- }
+ testRandom(0, 10);
}
public void testRandomWithLotsOfDuplicates() {
- for (int iter = 0; iter < 10; ++iter) {
- testRandom(0, 2);
- }
+ testRandom(0, 2);
}
public void testRandomWithSharedPrefix() {
- for (int iter = 0; iter < 10; ++iter) {
- testRandom(TestUtil.nextInt(random(), 1, 30), 10);
- }
+ testRandom(TestUtil.nextInt(random(), 1, 30), 10);
}
public void testRandomWithSharedPrefixAndLotsOfDuplicates() {
- for (int iter = 0; iter < 10; ++iter) {
- testRandom(TestUtil.nextInt(random(), 1, 30), 2);
- }
+ testRandom(TestUtil.nextInt(random(), 1, 30), 2);
}
public void testRandom2() {
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java b/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java
index da2b5019cd8..091834b0e38 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java
@@ -19,7 +19,6 @@ package org.apache.lucene.util;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
-import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom;
import com.carrotsearch.randomizedtesting.generators.RandomNumbers;
import java.util.ArrayList;
import java.util.Collections;
@@ -217,7 +216,7 @@ public class TestPriorityQueue extends LuceneTestCase {
var reference = new java.util.PriorityQueue<Integer>();
var pq = new IntegerQueue(size);
- Random localRandom = new Xoroshiro128PlusRandom(random().nextLong());
+ Random localRandom = nonAssertingRandom(random());
// Lucene's PriorityQueue.remove uses reference equality, not .equals to determine which
// elements
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestRadixSelector.java b/lucene/core/src/test/org/apache/lucene/util/TestRadixSelector.java
index ec1849dc3b5..9af08374945 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestRadixSelector.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestRadixSelector.java
@@ -22,6 +22,7 @@ import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.sameInstance;
import java.util.Arrays;
+import java.util.Random;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.lucene.tests.util.TestUtil;
@@ -34,13 +35,15 @@ public class TestRadixSelector extends LuceneTestCase {
}
private void doTestSelect() {
- final int from = random().nextInt(5);
- final int to = from + TestUtil.nextInt(random(), 1, 10000);
- final int maxLen = TestUtil.nextInt(random(), 1, 12);
- BytesRef[] arr = new BytesRef[from + to + random().nextInt(5)];
+ Random random = nonAssertingRandom(random());
+ final int from = random.nextInt(5);
+ final int to = from + TestUtil.nextInt(random, 1, 10000);
+ final int maxLen = TestUtil.nextInt(random, 1, 12);
+
+ BytesRef[] arr = new BytesRef[from + to + random.nextInt(5)];
for (int i = 0; i < arr.length; ++i) {
- byte[] bytes = new byte[TestUtil.nextInt(random(), 0, maxLen)];
- random().nextBytes(bytes);
+ byte[] bytes = new byte[TestUtil.nextInt(random, 0, maxLen)];
+ random.nextBytes(bytes);
arr[i] = new BytesRef(bytes);
}
doTest(arr, from, to, maxLen);
@@ -53,16 +56,18 @@ public class TestRadixSelector extends LuceneTestCase {
}
private void doTestSharedPrefixes() {
- final int from = random().nextInt(5);
- final int to = from + TestUtil.nextInt(random(), 1, 10000);
- final int maxLen = TestUtil.nextInt(random(), 1, 12);
- BytesRef[] arr = new BytesRef[from + to + random().nextInt(5)];
+ Random random = nonAssertingRandom(random());
+
+ final int from = random.nextInt(5);
+ final int to = from + TestUtil.nextInt(random, 1, 10000);
+ final int maxLen = TestUtil.nextInt(random, 1, 12);
+ BytesRef[] arr = new BytesRef[from + to + random.nextInt(5)];
for (int i = 0; i < arr.length; ++i) {
- byte[] bytes = new byte[TestUtil.nextInt(random(), 0, maxLen)];
- random().nextBytes(bytes);
+ byte[] bytes = new byte[TestUtil.nextInt(random, 0, maxLen)];
+ random.nextBytes(bytes);
arr[i] = new BytesRef(bytes);
}
- final int sharedPrefixLength = Math.min(arr[0].length, TestUtil.nextInt(random(), 1, maxLen));
+ final int sharedPrefixLength = Math.min(arr[0].length, TestUtil.nextInt(random, 1, maxLen));
for (int i = 1; i < arr.length; ++i) {
System.arraycopy(
arr[0].bytes,
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestStableMSBRadixSorter.java b/lucene/core/src/test/org/apache/lucene/util/TestStableMSBRadixSorter.java
index 4e7e0621727..66f94a3b969 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestStableMSBRadixSorter.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestStableMSBRadixSorter.java
@@ -110,13 +110,14 @@ public class TestStableMSBRadixSorter extends LuceneTestCase {
}
private void testRandom(int commonPrefixLen, int maxLen) {
+ var random = nonAssertingRandom(random());
byte[] commonPrefix = new byte[commonPrefixLen];
- random().nextBytes(commonPrefix);
- final int len = random().nextInt(100000);
- BytesRef[] bytes = new BytesRef[len + random().nextInt(50)];
+ random.nextBytes(commonPrefix);
+ final int len = random.nextInt(100000);
+ BytesRef[] bytes = new BytesRef[len + random.nextInt(50)];
for (int i = 0; i < len; ++i) {
- byte[] b = new byte[commonPrefixLen + random().nextInt(maxLen)];
- random().nextBytes(b);
+ byte[] b = new byte[commonPrefixLen + random.nextInt(maxLen)];
+ random.nextBytes(b);
System.arraycopy(commonPrefix, 0, b, 0, commonPrefixLen);
bytes[i] = new BytesRef(b);
}
@@ -124,27 +125,19 @@ public class TestStableMSBRadixSorter extends LuceneTestCase {
}
public void testRandom() {
- for (int iter = 0; iter < 10; ++iter) {
- testRandom(0, 10);
- }
+ testRandom(0, 10);
}
public void testRandomWithLotsOfDuplicates() {
- for (int iter = 0; iter < 10; ++iter) {
- testRandom(0, 2);
- }
+ testRandom(0, 2);
}
public void testRandomWithSharedPrefix() {
- for (int iter = 0; iter < 10; ++iter) {
- testRandom(TestUtil.nextInt(random(), 1, 30), 10);
- }
+ testRandom(TestUtil.nextInt(random(), 1, 30), 10);
}
public void testRandomWithSharedPrefixAndLotsOfDuplicates() {
- for (int iter = 0; iter < 10; ++iter) {
- testRandom(TestUtil.nextInt(random(), 1, 30), 2);
- }
+ testRandom(TestUtil.nextInt(random(), 1, 30), 2);
}
public void testRandom2() {
diff --git a/lucene/core/src/test/org/apache/lucene/util/automaton/TestCompiledAutomaton.java b/lucene/core/src/test/org/apache/lucene/util/automaton/TestCompiledAutomaton.java
index b4e23f6a2b9..5f336f76c61 100644
--- a/lucene/core/src/test/org/apache/lucene/util/automaton/TestCompiledAutomaton.java
+++ b/lucene/core/src/test/org/apache/lucene/util/automaton/TestCompiledAutomaton.java
@@ -105,7 +105,6 @@ public class TestCompiledAutomaton extends LuceneTestCase {
}
private String randomString() {
- // return _TestUtil.randomSimpleString(random);
return TestUtil.randomRealisticUnicodeString(random());
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/bkd/TestMutablePointTreeReaderUtils.java b/lucene/core/src/test/org/apache/lucene/util/bkd/TestMutablePointTreeReaderUtils.java
index 9dbe2ee210a..9343b510b9b 100644
--- a/lucene/core/src/test/org/apache/lucene/util/bkd/TestMutablePointTreeReaderUtils.java
+++ b/lucene/core/src/test/org/apache/lucene/util/bkd/TestMutablePointTreeReaderUtils.java
@@ -26,17 +26,12 @@ import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
public class TestMutablePointTreeReaderUtils extends LuceneTestCase {
-
public void testSort() {
- for (int iter = 0; iter < 10; ++iter) {
- doTestSort(false);
- }
+ doTestSort(false);
}
public void testSortWithIncrementalDocId() {
- for (int iter = 0; iter < 10; ++iter) {
- doTestSort(true);
- }
+ doTestSort(true);
}
private void doTestSort(boolean isDocIdIncremental) {
@@ -79,9 +74,7 @@ public class TestMutablePointTreeReaderUtils extends LuceneTestCase {
}
public void testSortByDim() {
- for (int iter = 0; iter < 5; ++iter) {
- doTestSortByDim();
- }
+ doTestSortByDim();
}
private void doTestSortByDim() {
@@ -132,9 +125,7 @@ public class TestMutablePointTreeReaderUtils extends LuceneTestCase {
}
public void testPartition() {
- for (int iter = 0; iter < 5; ++iter) {
- doTestPartition();
- }
+ doTestPartition();
}
private void doTestPartition() {
diff --git a/lucene/core/src/test/org/apache/lucene/util/compress/TestLowercaseAsciiCompression.java b/lucene/core/src/test/org/apache/lucene/util/compress/TestLowercaseAsciiCompression.java
index bfc9d59a522..be29ade703f 100644
--- a/lucene/core/src/test/org/apache/lucene/util/compress/TestLowercaseAsciiCompression.java
+++ b/lucene/core/src/test/org/apache/lucene/util/compress/TestLowercaseAsciiCompression.java
@@ -80,23 +80,25 @@ public class TestLowercaseAsciiCompression extends LuceneTestCase {
}
public void testRandomAscii() throws IOException {
- for (int iter = 0; iter < 1000; ++iter) {
- int len = random().nextInt(1000);
- byte[] bytes = new byte[len + random().nextInt(10)];
+ var random = nonAssertingRandom(random());
+ for (int iter = 0, max = atLeast(100); iter < max; ++iter) {
+ int len = random.nextInt(1000);
+ byte[] bytes = new byte[len + random.nextInt(10)];
for (int i = 0; i < bytes.length; ++i) {
- bytes[i] = (byte) TestUtil.nextInt(random(), ' ', '~');
+ bytes[i] = (byte) TestUtil.nextInt(random, ' ', '~');
}
doTestCompress(bytes, len);
}
}
public void testRandomCompressibleAscii() throws IOException {
- for (int iter = 0; iter < 1000; ++iter) {
- int len = TestUtil.nextInt(random(), 8, 1000);
- byte[] bytes = new byte[len + random().nextInt(10)];
+ var random = nonAssertingRandom(random());
+ for (int iter = 0, max = atLeast(100); iter < max; ++iter) {
+ int len = TestUtil.nextInt(random, 8, 1000);
+ byte[] bytes = new byte[len + random.nextInt(10)];
for (int i = 0; i < bytes.length; ++i) {
// only use always compressible bytes
- int b = random().nextInt(32);
+ int b = random.nextInt(32);
b = b | 0x20 | ((b & 0x20) << 1);
b -= 1;
bytes[i] = (byte) b;
@@ -106,20 +108,21 @@ public class TestLowercaseAsciiCompression extends LuceneTestCase {
}
public void testRandomCompressibleAsciiWithExceptions() throws IOException {
- for (int iter = 0; iter < 1000; ++iter) {
- int len = TestUtil.nextInt(random(), 8, 1000);
+ var random = nonAssertingRandom(random());
+ for (int iter = 0, max = atLeast(100); iter < max; ++iter) {
+ int len = TestUtil.nextInt(random, 8, 1000);
int exceptions = 0;
int maxExceptions = len >>> 5;
- byte[] bytes = new byte[len + random().nextInt(10)];
+ byte[] bytes = new byte[len + random.nextInt(10)];
for (int i = 0; i < bytes.length; ++i) {
- if (exceptions == maxExceptions || random().nextInt(100) != 0) {
- int b = random().nextInt(32);
+ if (exceptions == maxExceptions || random.nextInt(100) != 0) {
+ int b = random.nextInt(32);
b = b | 0x20 | ((b & 0x20) << 1);
b -= 1;
bytes[i] = (byte) b;
} else {
exceptions++;
- bytes[i] = (byte) random().nextInt(256);
+ bytes[i] = (byte) random.nextInt(256);
}
}
assertTrue(doTestCompress(bytes, len));
@@ -127,10 +130,11 @@ public class TestLowercaseAsciiCompression extends LuceneTestCase {
}
public void testRandom() throws IOException {
+ var random = nonAssertingRandom(random());
for (int iter = 0; iter < 1000; ++iter) {
- int len = random().nextInt(1000);
- byte[] bytes = new byte[len + random().nextInt(10)];
- random().nextBytes(bytes);
+ int len = random.nextInt(1000);
+ byte[] bytes = new byte[len + random.nextInt(10)];
+ random.nextBytes(bytes);
doTestCompress(bytes, len);
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/packed/TestDirectMonotonic.java b/lucene/core/src/test/org/apache/lucene/util/packed/TestDirectMonotonic.java
index a10af31835a..845b7ac8a44 100644
--- a/lucene/core/src/test/org/apache/lucene/util/packed/TestDirectMonotonic.java
+++ b/lucene/core/src/test/org/apache/lucene/util/packed/TestDirectMonotonic.java
@@ -204,7 +204,7 @@ public class TestDirectMonotonic extends LuceneTestCase {
}
private void doTestRandom(boolean merging) throws IOException {
- Random random = random();
+ Random random = nonAssertingRandom(random());
final int iters = atLeast(random, 3);
for (int iter = 0; iter < iters; ++iter) {
Directory dir = newDirectory();
diff --git a/lucene/core/src/test/org/apache/lucene/util/packed/TestPackedInts.java b/lucene/core/src/test/org/apache/lucene/util/packed/TestPackedInts.java
index bdb10f2e6ef..ecdb830c208 100644
--- a/lucene/core/src/test/org/apache/lucene/util/packed/TestPackedInts.java
+++ b/lucene/core/src/test/org/apache/lucene/util/packed/TestPackedInts.java
@@ -1225,20 +1225,21 @@ public class TestPackedInts extends LuceneTestCase {
}
public void testMonotonicBlockPackedReaderWriter() throws IOException {
+ var random = nonAssertingRandom(random());
+
final int iters = atLeast(2);
for (int iter = 0; iter < iters; ++iter) {
- final int blockSize = 1 << TestUtil.nextInt(random(), 6, 18);
- final int valueCount = random().nextInt(1 << 18);
+ final int blockSize = 1 << TestUtil.nextInt(random, 6, 18);
+ final int valueCount = random.nextInt(1 << 18);
final long[] values = new long[valueCount];
if (valueCount > 0) {
- values[0] =
- random().nextBoolean() ? random().nextInt(10) : random().nextInt(Integer.MAX_VALUE);
- int maxDelta = random().nextInt(64);
+ values[0] = random.nextBoolean() ? random.nextInt(10) : random.nextInt(Integer.MAX_VALUE);
+ int maxDelta = random.nextInt(64);
for (int i = 1; i < valueCount; ++i) {
- if (random().nextDouble() < 0.1d) {
- maxDelta = random().nextInt(64);
+ if (random.nextDouble() < 0.1d) {
+ maxDelta = random.nextInt(64);
}
- values[i] = Math.max(0, values[i - 1] + TestUtil.nextInt(random(), -16, maxDelta));
+ values[i] = Math.max(0, values[i - 1] + TestUtil.nextInt(random, -16, maxDelta));
}
}
diff --git a/lucene/sandbox/src/test/org/apache/lucene/sandbox/document/TestHalfFloatPoint.java b/lucene/sandbox/src/test/org/apache/lucene/sandbox/document/TestHalfFloatPoint.java
index 4182af1692f..95c13f98148 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/sandbox/document/TestHalfFloatPoint.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/sandbox/document/TestHalfFloatPoint.java
@@ -92,15 +92,14 @@ public class TestHalfFloatPoint extends LuceneTestCase {
values = ArrayUtil.copyOfSubArray(values, 0, o);
int iters = atLeast(1000000);
+ var rnd = nonAssertingRandom(random());
for (int iter = 0; iter < iters; ++iter) {
float f;
- if (random().nextBoolean()) {
- int floatBits = random().nextInt();
+ if (rnd.nextBoolean()) {
+ int floatBits = rnd.nextInt();
f = Float.intBitsToFloat(floatBits);
} else {
- f =
- (float)
- ((2 * random().nextFloat() - 1) * Math.pow(2, TestUtil.nextInt(random(), -16, 16)));
+ f = (float) ((2 * rnd.nextFloat() - 1) * Math.pow(2, TestUtil.nextInt(rnd, -16, 16)));
}
float rounded = HalfFloatPoint.shortBitsToHalfFloat(HalfFloatPoint.halfFloatToShortBits(f));
if (Float.isFinite(f) == false) {
diff --git a/lucene/spatial3d/src/test/org/apache/lucene/spatial3d/TestGeo3DPoint.java b/lucene/spatial3d/src/test/org/apache/lucene/spatial3d/TestGeo3DPoint.java
index eac5d2697de..ee07a08313f 100644
--- a/lucene/spatial3d/src/test/org/apache/lucene/spatial3d/TestGeo3DPoint.java
+++ b/lucene/spatial3d/src/test/org/apache/lucene/spatial3d/TestGeo3DPoint.java
@@ -1554,9 +1554,9 @@ public class TestGeo3DPoint extends LuceneTestCase {
* the double range and random doubles within the range too.
*/
public void testQuantization() throws Exception {
- Random random = random();
+ Random random = nonAssertingRandom(random());
PlanetModel planetModel = randomPlanetModel();
- for (int i = 0; i < 10000; i++) {
+ for (int i = 0; i < atLeast(5000); i++) {
int encoded = random.nextInt();
if (encoded <= planetModel.MIN_ENCODED_VALUE) {
continue;
diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/TestInputIterator.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/TestInputIterator.java
index 94ba3e3fdb8..5a75e022580 100644
--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/TestInputIterator.java
+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/TestInputIterator.java
@@ -41,8 +41,8 @@ public class TestInputIterator extends LuceneTestCase {
}
public void testTerms() throws Exception {
- Random random = random();
- int num = atLeast(10000);
+ Random random = nonAssertingRandom(random());
+ int num = atLeast(5000);
TreeMap<BytesRef, SimpleEntry<Long, BytesRef>> sorted = new TreeMap<>();
TreeMap<BytesRef, Long> sortedWithoutPayload = new TreeMap<>();
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseCompoundFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseCompoundFormatTestCase.java
index a592ace7f03..7e1792f5d55 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseCompoundFormatTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseCompoundFormatTestCase.java
@@ -682,8 +682,8 @@ public abstract class BaseCompoundFormatTestCase extends BaseIndexFileFormatTest
/** Creates a file of the specified size with random data. */
protected static void createRandomFile(Directory dir, String name, int size, byte[] segId)
throws IOException {
- Random rnd = random();
- try (IndexOutput os = dir.createOutput(name, newIOContext(random()))) {
+ Random rnd = nonAssertingRandom(random());
+ try (IndexOutput os = dir.createOutput(name, newIOContext(rnd))) {
CodecUtil.writeIndexHeader(os, "Foo", 0, segId, "suffix");
for (int i = 0; i < size; i++) {
byte b = (byte) rnd.nextInt(256);
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseStoredFieldsFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseStoredFieldsFormatTestCase.java
index 3f4d7d4ae69..dd09fd4dae6 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseStoredFieldsFormatTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseStoredFieldsFormatTestCase.java
@@ -97,7 +97,7 @@ public abstract class BaseStoredFieldsFormatTestCase extends BaseIndexFileFormat
public void testRandomStoredFields() throws IOException {
Directory dir = newDirectory();
- Random rand = random();
+ Random rand = nonAssertingRandom(random());
RandomIndexWriter w =
new RandomIndexWriter(
rand,
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/BaseBitSetTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/BaseBitSetTestCase.java
index 205d8861322..3cb22e51749 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/BaseBitSetTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/BaseBitSetTestCase.java
@@ -46,7 +46,7 @@ public abstract class BaseBitSetTestCase<T extends BitSet> extends LuceneTestCas
if (numBitsSet == numBits) {
set.set(0, numBits);
} else {
- Random random = random();
+ Random random = nonAssertingRandom(random());
for (int i = 0; i < numBitsSet; ++i) {
while (true) {
final int o = random.nextInt(numBits);
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/BaseDocIdSetTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/BaseDocIdSetTestCase.java
index 589eb03427f..e5c531c222c 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/BaseDocIdSetTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/BaseDocIdSetTestCase.java
@@ -63,7 +63,7 @@ public abstract class BaseDocIdSetTestCase<T extends DocIdSet> extends LuceneTes
/** Compare the content of the set against a {@link BitSet}. */
public void testAgainstBitSet() throws IOException {
- Random random = random();
+ Random random = nonAssertingRandom(random());
final int numBits = TestUtil.nextInt(random, 100, 1 << 20);
// test various random sets with various load factors
for (float percentSet : new float[] {0f, 0.0001f, random.nextFloat(), 0.9f, 1f}) {
@@ -181,7 +181,7 @@ public abstract class BaseDocIdSetTestCase<T extends DocIdSet> extends LuceneTes
}
public void testIntoBitSet() throws IOException {
- Random random = random();
+ Random random = nonAssertingRandom(random());
final int numBits = TestUtil.nextInt(random, 100, 1 << 20);
// test various random sets with various load factors
for (float percentSet : new float[] {0f, 0.0001f, random.nextFloat(), 0.9f, 1f}) {
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java
index 631a4fcebb6..00177cb2300 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java
@@ -30,6 +30,7 @@ import com.carrotsearch.randomizedtesting.MixWithSuiteName;
import com.carrotsearch.randomizedtesting.RandomizedContext;
import com.carrotsearch.randomizedtesting.RandomizedRunner;
import com.carrotsearch.randomizedtesting.RandomizedTest;
+import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom;
import com.carrotsearch.randomizedtesting.annotations.Listeners;
import com.carrotsearch.randomizedtesting.annotations.SeedDecorators;
import com.carrotsearch.randomizedtesting.annotations.TestGroup;
@@ -90,7 +91,9 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Supplier;
import java.util.regex.Pattern;
import junit.framework.AssertionFailedError;
import org.apache.lucene.analysis.Analyzer;
@@ -287,6 +290,21 @@ public abstract class LuceneTestCase extends Assert {
*/
public static final String SYSPROP_FAILFAST = "tests.failfast";
+ /**
+ * If specified, limits the number of method calls to each individual instance returned by {@link
+ * #random()}.
+ *
+ * @see #randomSupplier
+ */
+ public static final String SYSPROP_RANDOM_MAXCALLS = "tests.random.maxcalls";
+
+ /**
+ * If specified, limits the number of calls {@link #random()} itself.
+ *
+ * @see #randomSupplier
+ */
+ public static final String SYSPROP_RANDOM_MAXACQUIRES = "tests.random.maxacquires";
+
/** Annotation for tests that should only be run during nightly builds. */
@Documented
@Inherited
@@ -686,6 +704,37 @@ public abstract class LuceneTestCase extends Assert {
liveIWCFlushMode = flushMode;
}
+ private static final Supplier<Random> randomSupplier;
+
+ /** A counter of calls to {@link #random()} if {@link #SYSPROP_RANDOM_MAXACQUIRES} is defined. */
+ @SuppressWarnings("NonFinalStaticField")
+ private static AtomicLong randomCalls = new AtomicLong();
+
+ static {
+ int maxCalls = Integer.parseInt(System.getProperty(SYSPROP_RANDOM_MAXCALLS, "0"));
+ Supplier<Random> supplier = () -> RandomizedContext.current().getRandom();
+ if (maxCalls > 0) {
+ var finalizedSupplier = supplier;
+ supplier = () -> new MaxCallCountRandom(finalizedSupplier.get(), maxCalls);
+ }
+
+ int maxAquires = Integer.parseInt(System.getProperty(SYSPROP_RANDOM_MAXACQUIRES, "0"));
+ if (maxAquires > 0) {
+ var finalizedSupplier = supplier;
+ supplier =
+ () -> {
+ if (randomCalls.incrementAndGet() > maxAquires) {
+ throw new RuntimeException(
+ "Too many random() calls. Consider using LuceneTestCase.nonAssertingRandom for"
+ + " large loops or data generation.");
+ }
+ return finalizedSupplier.get();
+ };
+ }
+
+ randomSupplier = supplier;
+ }
+
// -----------------------------------------------------------------
// Suite and test case setup/ cleanup.
// -----------------------------------------------------------------
@@ -693,6 +742,7 @@ public abstract class LuceneTestCase extends Assert {
/** For subclasses to override. Overrides must call {@code super.setUp()}. */
@Before
public void setUp() throws Exception {
+ randomCalls.set(0);
parentChainCallRule.setupCalled = true;
}
@@ -738,17 +788,22 @@ public abstract class LuceneTestCase extends Assert {
* another test case.
*
* <p>There is an overhead connected with getting the {@link Random} for a particular context and
- * thread. It is better to cache the {@link Random} locally if tight loops with multiple
- * invocations are present or create a derivative local {@link Random} for millions of calls like
- * this:
- *
- * <pre>
- * Random random = new Random(random().nextLong());
- * // tight loop with many invocations.
- * </pre>
+ * thread. It is better to use a non-asserting {@link Random} instance locally if tight loops with
+ * multiple invocations are present. See {@link #nonAssertingRandom(Random)}.
*/
public static Random random() {
- return RandomizedContext.current().getRandom();
+ return randomSupplier.get();
+ }
+
+ /**
+ * Returns a Random instance based on the current state of another Random. The returned instance
+ * should be faster for thousands of consecutive calls because it doesn't assert that it isn't
+ * shared between threads or used within the correct {@link RandomizedContext}.
+ *
+ * <p>Use this method for local tight loops that generate a lot of random data.
+ */
+ public static Random nonAssertingRandom(Random rnd) {
+ return new Xoroshiro128PlusRandom(rnd.nextLong());
}
/**
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/MaxCallCountRandom.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/MaxCallCountRandom.java
new file mode 100644
index 00000000000..c37f31a6bcc
--- /dev/null
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/MaxCallCountRandom.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.lucene.tests.util;
+
+import java.util.Random;
+
+/**
+ * A {@link Random} subclass that counts calls to its methods and throws an exception if their
+ * number exceeds the provided thresholds.
+ *
+ * <p>This can be used to debug too many calls to a random returned by {@link
+ * LuceneTestCase#random()}.
+ */
+final class MaxCallCountRandom extends Random {
+ private final Random delegate;
+ // it doesn't have to be volatile (or thread-safe). just an approximation.
+ private long useCount;
+ private final long maxCalls;
+
+ public MaxCallCountRandom(Random delegate, long maxCalls) {
+ this.delegate = delegate;
+ this.maxCalls = maxCalls;
+ }
+
+ private void incrementUseCount() {
+ if (useCount++ > maxCalls) {
+ throw new RuntimeException("Random.* use count exceeded the limit.");
+ }
+ }
+
+ @Override
+ protected int next(int bits) {
+ throw new RuntimeException("Shouldn't be reachable.");
+ }
+
+ @Override
+ public boolean nextBoolean() {
+ incrementUseCount();
+ return delegate.nextBoolean();
+ }
+
+ @Override
+ public void nextBytes(byte[] bytes) {
+ incrementUseCount();
+ delegate.nextBytes(bytes);
+ }
+
+ @Override
+ public double nextDouble() {
+ incrementUseCount();
+ return delegate.nextDouble();
+ }
+
+ @Override
+ public float nextFloat() {
+ incrementUseCount();
+ return delegate.nextFloat();
+ }
+
+ @Override
+ public double nextGaussian() {
+ incrementUseCount();
+ return delegate.nextGaussian();
+ }
+
+ @Override
+ public int nextInt() {
+ incrementUseCount();
+ return delegate.nextInt();
+ }
+
+ @Override
+ public int nextInt(int n) {
+ incrementUseCount();
+ return delegate.nextInt(n);
+ }
+
+ @Override
+ public long nextLong() {
+ incrementUseCount();
+ return delegate.nextLong();
+ }
+}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.java
index 073da0d3a5b..07f8d096197 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.java
@@ -1695,6 +1695,8 @@ public final class TestUtil {
}
public static String randomSubString(Random random, int wordLength, boolean simple) {
+ random = LuceneTestCase.nonAssertingRandom(random);
+
if (wordLength == 0) {
return "";
}