View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3;
18  
19  import static org.apache.commons.lang3.LangAssertions.assertIllegalArgumentException;
20  import static org.junit.jupiter.api.Assertions.assertArrayEquals;
21  import static org.junit.jupiter.api.Assertions.assertEquals;
22  import static org.junit.jupiter.api.Assertions.assertNotEquals;
23  import static org.junit.jupiter.api.Assertions.assertNotNull;
24  import static org.junit.jupiter.api.Assertions.assertTrue;
25  
26  import java.util.Random;
27  import java.util.stream.Stream;
28  
29  import org.junit.jupiter.api.Test;
30  import org.junit.jupiter.params.ParameterizedTest;
31  import org.junit.jupiter.params.provider.MethodSource;
32  import org.junit.jupiter.params.provider.ValueSource;
33  
34  /**
35   * Tests for {@link RandomUtils}
36   */
37  class RandomUtilsTest extends AbstractLangTest {
38  
39      /**
40       * For comparing doubles and floats
41       */
42      private static final double DELTA = 1e-5;
43  
44      /**
45       * Number of calls made by the exclusive upper bound tests.
46       */
47      private static final int EXCLUSIVE_BOUND_TRIALS = 1000;
48  
49      private static RandomUtils fixedRandom(final double value) {
50          final Random random = new Random(0) {
51              private static final long serialVersionUID = 1L;
52  
53              @Override
54              public double nextDouble() {
55                  return value;
56              }
57  
58              @Override
59              public float nextFloat() {
60                  return (float) value;
61              }
62          };
63          return new RandomUtils() {
64              @Override
65              Random random() {
66                  return random;
67              }
68          };
69      }
70  
71      static Stream<RandomUtils> randomProvider() {
72          return Stream.of(RandomUtils.secure(), RandomUtils.secureStrong(), RandomUtils.insecure());
73      }
74  
75      /**
76       * Tests next boolean
77       */
78      @Test
79      void testBoolean() {
80          final boolean result = RandomUtils.nextBoolean();
81          assertTrue(result || !result);
82      }
83  
84      @ParameterizedTest
85      @MethodSource("randomProvider")
86      void testBoolean(final RandomUtils ru) {
87          final boolean result = ru.randomBoolean();
88          assertTrue(result || !result);
89      }
90  
91      @Test
92      void testConstructor() {
93          assertNotNull(new RandomUtils());
94      }
95  
96      /**
97       * Tests extreme range.
98       */
99      @Test
100     void testExtremeRangeDouble() {
101         final double result = RandomUtils.nextDouble(0, Double.MAX_VALUE);
102         assertTrue(result >= 0 && result < Double.MAX_VALUE);
103     }
104 
105     @ParameterizedTest
106     @MethodSource("randomProvider")
107     void testExtremeRangeDouble(final RandomUtils ru) {
108         final double result = ru.randomDouble(0, Double.MAX_VALUE);
109         assertTrue(result >= 0 && result < Double.MAX_VALUE);
110     }
111 
112     /**
113      * Tests extreme range.
114      */
115     @Test
116     void testExtremeRangeFloat() {
117         final float result = RandomUtils.nextFloat(0, Float.MAX_VALUE);
118         assertTrue(result >= 0f && result < Float.MAX_VALUE);
119     }
120 
121     /**
122      * Tests extreme range.
123      */
124     @ParameterizedTest
125     @MethodSource("randomProvider")
126     void testExtremeRangeFloat(final RandomUtils ru) {
127         final float result = ru.randomFloat(0, Float.MAX_VALUE);
128         assertTrue(result >= 0f && result < Float.MAX_VALUE);
129     }
130 
131     /**
132      * Tests extreme range.
133      */
134     @Test
135     void testExtremeRangeInt() {
136         final int result = RandomUtils.nextInt(0, Integer.MAX_VALUE);
137         assertTrue(result >= 0);
138         assertTrue(result < Integer.MAX_VALUE);
139     }
140 
141     /**
142      * Tests extreme range.
143      */
144     @ParameterizedTest
145     @MethodSource("randomProvider")
146     void testExtremeRangeInt(final RandomUtils ru) {
147         final int result = ru.randomInt(0, Integer.MAX_VALUE);
148         assertTrue(result >= 0);
149         assertTrue(result < Integer.MAX_VALUE);
150     }
151 
152     /**
153      * Tests extreme range.
154      */
155     @Test
156     void testExtremeRangeLong() {
157         final long result = RandomUtils.nextLong(0, Long.MAX_VALUE);
158         assertTrue(result >= 0);
159         assertTrue(result < Long.MAX_VALUE);
160     }
161 
162     /**
163      * Tests extreme range.
164      */
165     @ParameterizedTest
166     @MethodSource("randomProvider")
167     void testExtremeRangeLong(final RandomUtils ru) {
168         final long result = ru.randomLong(0, Long.MAX_VALUE);
169         assertTrue(result >= 0);
170         assertTrue(result < Long.MAX_VALUE);
171     }
172 
173     /**
174      * Test a large value for long. A previous implementation using
175      * {@link RandomUtils#nextDouble(double, double)} could generate a value equal
176      * to the upper limit.
177      *
178      * <pre>
179      * return (long) nextDouble(startInclusive, endExclusive);
180      * </pre>
181      *
182      * <p>
183      * See LANG-1592.
184      * </p>
185      */
186     @Test
187     void testLargeValueRangeLong() {
188         final long startInclusive = 12900000000001L;
189         final long endExclusive = 12900000000016L;
190         // Note: The method using 'return (long) nextDouble(startInclusive, endExclusive)'
191         // takes thousands of calls to generate an error. This size loop fails most
192         // of the time with the previous method.
193         final int n = (int) (endExclusive - startInclusive) * 1000;
194         for (int i = 0; i < n; i++) {
195             assertNotEquals(endExclusive, RandomUtils.nextLong(startInclusive, endExclusive));
196         }
197     }
198 
199     /**
200      * Test a large value for long. A previous implementation using
201      * {@link RandomUtils#nextDouble(double, double)} could generate a value equal
202      * to the upper limit.
203      *
204      * <pre>
205      * return (long) nextDouble(startInclusive, endExclusive);
206      * </pre>
207      *
208      * <p>
209      * See LANG-1592.
210      * </p>
211      */
212     @ParameterizedTest
213     @MethodSource("randomProvider")
214     void testLargeValueRangeLong(final RandomUtils ru) {
215         final long startInclusive = 12900000000001L;
216         final long endExclusive = 12900000000016L;
217         // Note: The method using 'return (long) nextDouble(startInclusive, endExclusive)'
218         // takes thousands of calls to generate an error. This size loop fails most
219         // of the time with the previous method.
220         final int n = (int) (endExclusive - startInclusive) * 1000;
221         for (int i = 0; i < n; i++) {
222             assertNotEquals(endExclusive, ru.randomLong(startInclusive, endExclusive));
223         }
224     }
225 
226     /**
227      * Tests random byte array.
228      */
229     @Test
230     void testNextBytes() {
231         final byte[] result = RandomUtils.nextBytes(20);
232         assertEquals(20, result.length);
233     }
234 
235     /**
236      * Tests random byte array.
237      */
238     @ParameterizedTest
239     @MethodSource("randomProvider")
240     void testNextBytes(final RandomUtils ru) {
241         final byte[] result = ru.randomBytes(20);
242         assertEquals(20, result.length);
243     }
244 
245     @Test
246     void testNextBytesNegative() {
247         assertIllegalArgumentException(() -> RandomUtils.nextBytes(-1));
248     }
249 
250     @ParameterizedTest
251     @MethodSource("randomProvider")
252     void testNextBytesNegative(final RandomUtils ru) {
253         assertIllegalArgumentException(() -> ru.randomBytes(-1));
254     }
255 
256     /**
257      * Tests next double range.
258      */
259     @Test
260     void testNextDouble() {
261         final double result = RandomUtils.nextDouble(33d, 42d);
262         assertTrue(result >= 33d);
263         assertTrue(result < 42d);
264     }
265 
266     /**
267      * Tests next double range.
268      */
269     @ParameterizedTest
270     @MethodSource("randomProvider")
271     void testNextDouble(final RandomUtils ru) {
272         final double result = ru.randomDouble(33d, 42d);
273         assertTrue(result >= 33d);
274         assertTrue(result < 42d);
275     }
276 
277     /**
278      * Test a double range one ULP wide. A previous implementation could round the scaled value up to the
279      * exclusive upper limit about half of the time.
280      */
281     @Test
282     void testNextDoubleExclusiveUpperBound() {
283         final double startInclusive = 10d;
284         final double endExclusive = Math.nextUp(startInclusive);
285         for (int i = 0; i < EXCLUSIVE_BOUND_TRIALS; i++) {
286             assertEquals(startInclusive, RandomUtils.nextDouble(startInclusive, endExclusive));
287         }
288     }
289 
290     @Test
291     void testNextDoubleLowerGreaterUpper() {
292         assertIllegalArgumentException(() -> RandomUtils.nextDouble(2, 1));
293     }
294 
295     @ParameterizedTest
296     @MethodSource("randomProvider")
297     void testNextDoubleLowerGreaterUpper(final RandomUtils ru) {
298         assertIllegalArgumentException(() -> ru.randomDouble(2, 1));
299     }
300 
301     /**
302      * Test next double range with minimal range.
303      */
304     @Test
305     void testNextDoubleMinimalRange() {
306         assertEquals(42.1, RandomUtils.nextDouble(42.1, 42.1), DELTA);
307     }
308 
309     /**
310      * Test next double range with minimal range.
311      */
312     @ParameterizedTest
313     @MethodSource("randomProvider")
314     void testNextDoubleMinimalRange(final RandomUtils ru) {
315         assertEquals(42.1, ru.randomDouble(42.1, 42.1), DELTA);
316     }
317 
318     @Test
319     void testNextDoubleNegative() {
320         assertIllegalArgumentException(() -> RandomUtils.nextDouble(-1, 1));
321     }
322 
323     @ParameterizedTest
324     @MethodSource("randomProvider")
325     void testNextDoubleNegative(final RandomUtils ru) {
326         assertIllegalArgumentException(() -> ru.randomDouble(-1, 1));
327     }
328 
329     /**
330      * Tests next double range, random result.
331      */
332     @Test
333     void testNextDoubleRandomResult() {
334         final double result = RandomUtils.nextDouble();
335         assertTrue(result >= 0d);
336         assertTrue(result < Double.MAX_VALUE);
337     }
338 
339     /**
340      * Tests next double range, random result.
341      */
342     @ParameterizedTest
343     @MethodSource("randomProvider")
344     void testNextDoubleRandomResult(final RandomUtils ru) {
345         final double result = ru.randomDouble();
346         assertTrue(result >= 0d);
347         assertTrue(result < Double.MAX_VALUE);
348     }
349 
350     /**
351      * Tests next float range.
352      */
353     @Test
354     void testNextFloat() {
355         final float result = RandomUtils.nextFloat(33f, 42f);
356         assertTrue(result >= 33f);
357         assertTrue(result < 42f);
358     }
359 
360     /**
361      * Tests next float range.
362      */
363     @ParameterizedTest
364     @MethodSource("randomProvider")
365     void testNextFloat(final RandomUtils ru) {
366         final float result = ru.randomFloat(33f, 42f);
367         assertTrue(result >= 33f);
368         assertTrue(result < 42f);
369     }
370 
371     /**
372      * Test a float range one ULP wide. A previous implementation could round the scaled value up to the
373      * exclusive upper limit about half of the time.
374      */
375     @Test
376     void testNextFloatExclusiveUpperBound() {
377         final float startInclusive = 10f;
378         final float endExclusive = Math.nextUp(startInclusive);
379         for (int i = 0; i < EXCLUSIVE_BOUND_TRIALS; i++) {
380             assertEquals(startInclusive, RandomUtils.nextFloat(startInclusive, endExclusive));
381         }
382     }
383 
384     @Test
385     void testNextFloatLowerGreaterUpper() {
386         assertIllegalArgumentException(() -> RandomUtils.nextFloat(2, 1));
387     }
388 
389     @ParameterizedTest
390     @MethodSource("randomProvider")
391     void testNextFloatLowerGreaterUpper(final RandomUtils ru) {
392         assertIllegalArgumentException(() -> ru.randomFloat(2, 1));
393     }
394 
395     /**
396      * Test next float range with minimal range.
397      */
398     @Test
399     void testNextFloatMinimalRange() {
400         assertEquals(42.1f, RandomUtils.nextFloat(42.1f, 42.1f), DELTA);
401     }
402 
403     /**
404      * Test next float range with minimal range.
405      */
406     @ParameterizedTest
407     @MethodSource("randomProvider")
408     void testNextFloatMinimalRange(final RandomUtils ru) {
409         assertEquals(42.1f, ru.randomFloat(42.1f, 42.1f), DELTA);
410     }
411 
412     @Test
413     void testNextFloatNegative() {
414         assertIllegalArgumentException(() -> RandomUtils.nextFloat(-1, 1));
415     }
416 
417     @ParameterizedTest
418     @MethodSource("randomProvider")
419     void testNextFloatNegative(final RandomUtils ru) {
420         assertIllegalArgumentException(() -> ru.randomFloat(-1, 1));
421     }
422 
423     /**
424      * Tests next float range, random result.
425      */
426     @Test
427     void testNextFloatRandomResult() {
428         final float result = RandomUtils.nextFloat();
429         assertTrue(result >= 0f);
430         assertTrue(result < Float.MAX_VALUE);
431     }
432 
433     /**
434      * Tests next float range, random result.
435      */
436     @ParameterizedTest
437     @MethodSource("randomProvider")
438     void testNextFloatRandomResult(final RandomUtils ru) {
439         final float result = ru.randomFloat();
440         assertTrue(result >= 0f);
441         assertTrue(result < Float.MAX_VALUE);
442     }
443 
444     /**
445      * Tests next int range.
446      */
447     @Test
448     void testNextInt() {
449         final int result = RandomUtils.nextInt(33, 42);
450         assertTrue(result >= 33);
451         assertTrue(result < 42);
452     }
453 
454     /**
455      * Tests next int range.
456      */
457     @ParameterizedTest
458     @MethodSource("randomProvider")
459     void testNextInt(final RandomUtils ru) {
460         final int result = ru.randomInt(33, 42);
461         assertTrue(result >= 33);
462         assertTrue(result < 42);
463     }
464 
465     @Test
466     void testNextIntLowerGreaterUpper() {
467         assertIllegalArgumentException(() -> RandomUtils.nextInt(2, 1));
468     }
469 
470     @ParameterizedTest
471     @MethodSource("randomProvider")
472     void testNextIntLowerGreaterUpper(final RandomUtils ru) {
473         assertIllegalArgumentException(() -> ru.randomInt(2, 1));
474     }
475 
476     /**
477      * Test next int range with minimal range.
478      */
479     @Test
480     void testNextIntMinimalRange() {
481         assertEquals(42, RandomUtils.nextInt(42, 42));
482     }
483 
484     /**
485      * Test next int range with minimal range.
486      */
487     @ParameterizedTest
488     @MethodSource("randomProvider")
489     void testNextIntMinimalRange(final RandomUtils ru) {
490         assertEquals(42, ru.randomInt(42, 42));
491     }
492 
493     @Test
494     void testNextIntNegative() {
495         assertIllegalArgumentException(() -> RandomUtils.nextInt(-1, 1));
496     }
497 
498     @ParameterizedTest
499     @MethodSource("randomProvider")
500     void testNextIntNegative(final RandomUtils ru) {
501         assertIllegalArgumentException(() -> ru.randomInt(-1, 1));
502     }
503 
504     /**
505      * Tests next int range, random result.
506      */
507     @Test
508     void testNextIntRandomResult() {
509         final int randomResult = RandomUtils.nextInt();
510         assertTrue(randomResult > 0);
511         assertTrue(randomResult < Integer.MAX_VALUE);
512     }
513 
514     /**
515      * Tests next int range, random result.
516      */
517     @ParameterizedTest
518     @MethodSource("randomProvider")
519     void testNextIntRandomResult(final RandomUtils ru) {
520         final int randomResult = ru.randomInt();
521         assertTrue(randomResult > 0);
522         assertTrue(randomResult < Integer.MAX_VALUE);
523     }
524 
525     /**
526      * Tests next long range.
527      */
528     @Test
529     void testNextLong() {
530         final long result = RandomUtils.nextLong(33L, 42L);
531         assertTrue(result >= 33L);
532         assertTrue(result < 42L);
533     }
534 
535     /**
536      * Tests next long range.
537      */
538     @ParameterizedTest
539     @MethodSource("randomProvider")
540     void testNextLong(final RandomUtils ru) {
541         final long result = ru.randomLong(33L, 42L);
542         assertTrue(result >= 33L);
543         assertTrue(result < 42L);
544     }
545 
546     @Test
547     void testNextLongLowerGreaterUpper() {
548         assertIllegalArgumentException(() -> RandomUtils.nextLong(2, 1));
549     }
550 
551     @ParameterizedTest
552     @MethodSource("randomProvider")
553     void testNextLongLowerGreaterUpper(final RandomUtils ru) {
554         assertIllegalArgumentException(() -> ru.randomLong(2, 1));
555     }
556 
557     /**
558      * Test next long range with minimal range.
559      */
560     @Test
561     void testNextLongMinimalRange() {
562         assertEquals(42L, RandomUtils.nextLong(42L, 42L));
563     }
564 
565     /**
566      * Test next long range with minimal range.
567      */
568     @ParameterizedTest
569     @MethodSource("randomProvider")
570     void testNextLongMinimalRange(final RandomUtils ru) {
571         assertEquals(42L, ru.randomLong(42L, 42L));
572     }
573 
574     @Test
575     void testNextLongNegative() {
576         assertIllegalArgumentException(() -> RandomUtils.nextLong(-1, 1));
577     }
578 
579     @ParameterizedTest
580     @MethodSource("randomProvider")
581     void testNextLongNegative(final RandomUtils ru) {
582         assertIllegalArgumentException(() -> ru.randomLong(-1, 1));
583     }
584 
585     /**
586      * Tests next long range, random result.
587      */
588     @Test
589     void testNextLongRandomResult() {
590         final long result = RandomUtils.nextLong();
591         assertTrue(result >= 0L);
592         assertTrue(result < Long.MAX_VALUE);
593     }
594 
595     /**
596      * Tests next long range, random result.
597      */
598     @ParameterizedTest
599     @MethodSource("randomProvider")
600     void testNextLongRandomResult(final RandomUtils ru) {
601         final long result = ru.randomLong();
602         assertTrue(result >= 0L);
603         assertTrue(result < Long.MAX_VALUE);
604     }
605 
606     /**
607      * Test a double range one ULP wide. A previous implementation could round the scaled value up to the
608      * exclusive upper limit about half of the time.
609      */
610     @ParameterizedTest
611     @MethodSource("randomProvider")
612     void testRandomDoubleExclusiveUpperBound(final RandomUtils ru) {
613         final double startInclusive = 10d;
614         final double endExclusive = Math.nextUp(startInclusive);
615         for (int i = 0; i < EXCLUSIVE_BOUND_TRIALS; i++) {
616             assertEquals(startInclusive, ru.randomDouble(startInclusive, endExclusive));
617         }
618     }
619 
620     @ParameterizedTest
621     @ValueSource(doubles = {0, 0.5, 0.75, 0.9999999999999999})
622     void testRandomDoubleFixedBoundaries(final double value) {
623         final RandomUtils ru = fixedRandom(value);
624         assertEquals(10d, ru.randomDouble(10d, Math.nextUp(10d)));
625         assertEquals(0d, ru.randomDouble(0d, Double.MIN_VALUE));
626         assertEquals(Double.MIN_VALUE, ru.randomDouble(Double.MIN_VALUE, 2 * Double.MIN_VALUE));
627         assertEquals(Math.nextDown(Double.MAX_VALUE), ru.randomDouble(Math.nextDown(Double.MAX_VALUE), Double.MAX_VALUE));
628         assertEquals(value, ru.randomDouble(0d, 1d));
629         assertEquals(Double.MAX_VALUE, ru.randomDouble(10d, Double.POSITIVE_INFINITY));
630         assertEquals(Double.POSITIVE_INFINITY, ru.randomDouble(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY));
631     }
632 
633     /**
634      * Test a float range one ULP wide. A previous implementation could round the scaled value up to the
635      * exclusive upper limit about half of the time.
636      */
637     @ParameterizedTest
638     @MethodSource("randomProvider")
639     void testRandomFloatExclusiveUpperBound(final RandomUtils ru) {
640         final float startInclusive = 10f;
641         final float endExclusive = Math.nextUp(startInclusive);
642         for (int i = 0; i < EXCLUSIVE_BOUND_TRIALS; i++) {
643             assertEquals(startInclusive, ru.randomFloat(startInclusive, endExclusive));
644         }
645     }
646 
647     @ParameterizedTest
648     @ValueSource(doubles = {0, 0.5, 0.75, 0.9999999403953552})
649     void testRandomFloatFixedBoundaries(final double value) {
650         final RandomUtils ru = fixedRandom(value);
651         assertEquals(10f, ru.randomFloat(10f, Math.nextUp(10f)));
652         assertEquals(0f, ru.randomFloat(0f, Float.MIN_VALUE));
653         assertEquals(Float.MIN_VALUE, ru.randomFloat(Float.MIN_VALUE, 2 * Float.MIN_VALUE));
654         assertEquals(Math.nextDown(Float.MAX_VALUE), ru.randomFloat(Math.nextDown(Float.MAX_VALUE), Float.MAX_VALUE));
655         assertEquals((float) value, ru.randomFloat(0f, 1f));
656         assertEquals(Float.MAX_VALUE, ru.randomFloat(10f, Float.POSITIVE_INFINITY));
657         assertEquals(Float.POSITIVE_INFINITY, ru.randomFloat(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
658     }
659 
660     /**
661      * Tests a zero byte array length.
662      */
663     @Test
664     void testZeroLengthNextBytes() {
665         assertArrayEquals(new byte[0], RandomUtils.nextBytes(0));
666     }
667 
668     /**
669      * Tests a zero byte array length.
670      */
671     @ParameterizedTest
672     @MethodSource("randomProvider")
673     void testZeroLengthNextBytes(final RandomUtils ru) {
674         assertArrayEquals(new byte[0], ru.randomBytes(0));
675     }
676 }