ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/SplittableRandomTest.java
(Generate patch)

Comparing jsr166/src/test/tck/SplittableRandomTest.java (file contents):
Revision 1.2 by dl, Thu Jul 11 23:06:47 2013 UTC vs.
Revision 1.24 by jsr166, Fri Oct 13 16:14:40 2017 UTC

# Line 3 | Line 3
3   * Expert Group and released to the public domain, as explained at
4   * http://creativecommons.org/publicdomain/zero/1.0/
5   */
6 < import junit.framework.*;
7 < import java.util.*;
6 >
7 > import java.util.Arrays;
8 > import java.util.List;
9   import java.util.SplittableRandom;
10   import java.util.concurrent.atomic.AtomicInteger;
10 import java.util.concurrent.atomic.AtomicLong;
11   import java.util.concurrent.atomic.LongAdder;
12 + import java.lang.reflect.Method;
13 + import java.util.function.Predicate;
14 + import java.util.stream.Collectors;
15 +
16 + import junit.framework.Test;
17 + import junit.framework.TestSuite;
18  
19   public class SplittableRandomTest extends JSR166TestCase {
20  
21      public static void main(String[] args) {
22 <        junit.textui.TestRunner.run(suite());
22 >        main(suite(), args);
23      }
24      public static Test suite() {
25          return new TestSuite(SplittableRandomTest.class);
# Line 22 | Line 28 | public class SplittableRandomTest extend
28      /*
29       * Testing coverage notes:
30       *
31 <     * 1. Many of the test methods are adapted from ThreadLocalRandomTest
31 >     * 1. Many of the test methods are adapted from ThreadLocalRandomTest.
32       *
33 <     * 2. This set of tests do not check for random number generator
34 <     * quality. But we check for minimal API compliance by requiring
35 <     * that repeated calls to nextX methods, up to NCALLS tries,
36 <     * produce at least one different result. (In some possible
37 <     * universe, a "correct" implementation might fail, but the odds
38 <     * are vastly less than that of encountering a hardware failure
39 <     * while running the test.) For bounded nextX methods, we sample
40 <     * various intervals across multiples of primes. In other tests,
41 <     * we repeat under REPS different values.
33 >     * 2. These tests do not check for random number generator quality.
34 >     * But we check for minimal API compliance by requiring that
35 >     * repeated calls to nextX methods, up to NCALLS tries, produce at
36 >     * least two distinct results. (In some possible universe, a
37 >     * "correct" implementation might fail, but the odds are vastly
38 >     * less than that of encountering a hardware failure while running
39 >     * the test.) For bounded nextX methods, we sample various
40 >     * intervals across multiples of primes. In other tests, we repeat
41 >     * under REPS different values.
42       */
43  
44      // max numbers of calls to detect getting stuck on one value
45      static final int NCALLS = 10000;
46  
47      // max sampled int bound
48 <    static final int MAX_INT_BOUND = (1 << 28);
48 >    static final int MAX_INT_BOUND = (1 << 26);
49  
50 <    // Max sampled long bound
51 <    static final long MAX_LONG_BOUND = (1L << 42);
50 >    // max sampled long bound
51 >    static final long MAX_LONG_BOUND = (1L << 40);
52  
53      // Number of replications for other checks
54 <    static final int REPS = 20;
54 >    static final int REPS =
55 >        Integer.getInteger("SplittableRandomTest.reps", 4);
56  
57      /**
58 <     * Repeated calls to nextInt produce at least one different result
58 >     * Repeated calls to nextInt produce at least two distinct results
59       */
60      public void testNextInt() {
61          SplittableRandom sr = new SplittableRandom();
# Line 60 | Line 67 | public class SplittableRandomTest extend
67      }
68  
69      /**
70 <     * Repeated calls to nextLong produce at least one different result
70 >     * Repeated calls to nextLong produce at least two distinct results
71       */
72      public void testNextLong() {
73          SplittableRandom sr = new SplittableRandom();
# Line 72 | Line 79 | public class SplittableRandomTest extend
79      }
80  
81      /**
82 <     * Repeated calls to nextDouble produce at least one different result
82 >     * Repeated calls to nextDouble produce at least two distinct results
83       */
84      public void testNextDouble() {
85          SplittableRandom sr = new SplittableRandom();
86          double f = sr.nextDouble();
87 <        double i = 0;
87 >        int i = 0;
88          while (i < NCALLS && sr.nextDouble() == f)
89              ++i;
90          assertTrue(i < NCALLS);
# Line 88 | Line 95 | public class SplittableRandomTest extend
95       * same values for nextLong.
96       */
97      public void testSeedConstructor() {
98 <        for (long seed = 2; seed < MAX_LONG_BOUND; seed += 15485863)  {
98 >        for (long seed = 2; seed < MAX_LONG_BOUND; seed += 15485863) {
99              SplittableRandom sr1 = new SplittableRandom(seed);
100              SplittableRandom sr2 = new SplittableRandom(seed);
101 <            for (int i = 0; i < REPS; ++i)
101 >            for (int i = 0; i < REPS; ++i)
102                  assertEquals(sr1.nextLong(), sr2.nextLong());
103          }
104      }
# Line 127 | Line 134 | public class SplittableRandomTest extend
134      }
135  
136      /**
137 <     * nextInt(negative) throws IllegalArgumentException;
137 >     * nextInt(non-positive) throws IllegalArgumentException
138       */
139 <    public void testNextIntBoundedNeg() {
139 >    public void testNextIntBoundNonPositive() {
140          SplittableRandom sr = new SplittableRandom();
141 <        try {
142 <            int f = sr.nextInt(-17);
143 <            shouldThrow();
144 <        } catch (IllegalArgumentException success) {}
141 >        Runnable[] throwingActions = {
142 >            () -> sr.nextInt(-17),
143 >            () -> sr.nextInt(0),
144 >            () -> sr.nextInt(Integer.MIN_VALUE),
145 >        };
146 >        assertThrows(IllegalArgumentException.class, throwingActions);
147      }
148  
149      /**
150 <     * nextInt(least >= bound) throws IllegalArgumentException;
150 >     * nextInt(least >= bound) throws IllegalArgumentException
151       */
152      public void testNextIntBadBounds() {
153          SplittableRandom sr = new SplittableRandom();
154 <        try {
155 <            int f = sr.nextInt(17, 2);
156 <            shouldThrow();
157 <        } catch (IllegalArgumentException success) {}
154 >        Runnable[] throwingActions = {
155 >            () -> sr.nextInt(17, 2),
156 >            () -> sr.nextInt(-42, -42),
157 >            () -> sr.nextInt(Integer.MAX_VALUE, Integer.MIN_VALUE),
158 >        };
159 >        assertThrows(IllegalArgumentException.class, throwingActions);
160      }
161  
162      /**
163       * nextInt(bound) returns 0 <= value < bound;
164 <     * repeated calls produce at least one different result
164 >     * repeated calls produce at least two distinct results
165       */
166      public void testNextIntBounded() {
167          SplittableRandom sr = new SplittableRandom();
168 +        for (int i = 0; i < 2; i++) assertEquals(0, sr.nextInt(1));
169          // sample bound space across prime number increments
170          for (int bound = 2; bound < MAX_INT_BOUND; bound += 524959) {
171              int f = sr.nextInt(bound);
# Line 171 | Line 183 | public class SplittableRandomTest extend
183  
184      /**
185       * nextInt(least, bound) returns least <= value < bound;
186 <     * repeated calls produce at least one different result
186 >     * repeated calls produce at least two distinct results
187       */
188      public void testNextIntBounded2() {
189          SplittableRandom sr = new SplittableRandom();
# Line 192 | Line 204 | public class SplittableRandomTest extend
204      }
205  
206      /**
207 <     * nextLong(negative) throws IllegalArgumentException;
207 >     * nextLong(non-positive) throws IllegalArgumentException
208       */
209 <    public void testNextLongBoundedNeg() {
209 >    public void testNextLongBoundNonPositive() {
210          SplittableRandom sr = new SplittableRandom();
211 <        try {
212 <            long f = sr.nextLong(-17);
213 <            shouldThrow();
214 <        } catch (IllegalArgumentException success) {}
211 >        Runnable[] throwingActions = {
212 >            () -> sr.nextLong(-17L),
213 >            () -> sr.nextLong(0L),
214 >            () -> sr.nextLong(Long.MIN_VALUE),
215 >        };
216 >        assertThrows(IllegalArgumentException.class, throwingActions);
217      }
218  
219      /**
220 <     * nextLong(least >= bound) throws IllegalArgumentException;
220 >     * nextLong(least >= bound) throws IllegalArgumentException
221       */
222      public void testNextLongBadBounds() {
223          SplittableRandom sr = new SplittableRandom();
224 <        try {
225 <            long f = sr.nextLong(17, 2);
226 <            shouldThrow();
227 <        } catch (IllegalArgumentException success) {}
224 >        Runnable[] throwingActions = {
225 >            () -> sr.nextLong(17L, 2L),
226 >            () -> sr.nextLong(-42L, -42L),
227 >            () -> sr.nextLong(Long.MAX_VALUE, Long.MIN_VALUE),
228 >        };
229 >        assertThrows(IllegalArgumentException.class, throwingActions);
230      }
231  
232      /**
233       * nextLong(bound) returns 0 <= value < bound;
234 <     * repeated calls produce at least one different result
234 >     * repeated calls produce at least two distinct results
235       */
236      public void testNextLongBounded() {
237          SplittableRandom sr = new SplittableRandom();
238 +        for (int i = 0; i < 2; i++) assertEquals(0L, sr.nextLong(1L));
239          for (long bound = 2; bound < MAX_LONG_BOUND; bound += 15485863) {
240              long f = sr.nextLong(bound);
241              assertTrue(0 <= f && f < bound);
# Line 235 | Line 252 | public class SplittableRandomTest extend
252  
253      /**
254       * nextLong(least, bound) returns least <= value < bound;
255 <     * repeated calls produce at least one different result
255 >     * repeated calls produce at least two distinct results
256       */
257      public void testNextLongBounded2() {
258          SplittableRandom sr = new SplittableRandom();
# Line 256 | Line 273 | public class SplittableRandomTest extend
273      }
274  
275      /**
276 +     * nextDouble(non-positive) throws IllegalArgumentException
277 +     */
278 +    public void testNextDoubleBoundNonPositive() {
279 +        SplittableRandom sr = new SplittableRandom();
280 +        Runnable[] throwingActions = {
281 +            () -> sr.nextDouble(-17.0d),
282 +            () -> sr.nextDouble(0.0d),
283 +            () -> sr.nextDouble(-Double.MIN_VALUE),
284 +            () -> sr.nextDouble(Double.NEGATIVE_INFINITY),
285 +            () -> sr.nextDouble(Double.NaN),
286 +        };
287 +        assertThrows(IllegalArgumentException.class, throwingActions);
288 +    }
289 +
290 +    /**
291 +     * nextDouble(! (least < bound)) throws IllegalArgumentException
292 +     */
293 +    public void testNextDoubleBadBounds() {
294 +        SplittableRandom sr = new SplittableRandom();
295 +        Runnable[] throwingActions = {
296 +            () -> sr.nextDouble(17.0d, 2.0d),
297 +            () -> sr.nextDouble(-42.0d, -42.0d),
298 +            () -> sr.nextDouble(Double.MAX_VALUE, Double.MIN_VALUE),
299 +            () -> sr.nextDouble(Double.NaN, 0.0d),
300 +            () -> sr.nextDouble(0.0d, Double.NaN),
301 +        };
302 +        assertThrows(IllegalArgumentException.class, throwingActions);
303 +    }
304 +
305 +    // TODO: Test infinite bounds!
306 +    //() -> sr.nextDouble(Double.NEGATIVE_INFINITY, 0.0d),
307 +    //() -> sr.nextDouble(0.0d, Double.POSITIVE_INFINITY),
308 +
309 +    /**
310       * nextDouble(least, bound) returns least <= value < bound;
311 <     * repeated calls produce at least one different result
311 >     * repeated calls produce at least two distinct results
312       */
313      public void testNextDoubleBounded2() {
314          SplittableRandom sr = new SplittableRandom();
# Line 283 | Line 334 | public class SplittableRandomTest extend
334       */
335      public void testBadStreamSize() {
336          SplittableRandom r = new SplittableRandom();
337 <        try {
338 <            java.util.stream.IntStream x = r.ints(-1L);
339 <            shouldThrow();
340 <        } catch (IllegalArgumentException ok) {
341 <        }
342 <        try {
343 <            java.util.stream.LongStream x = r.longs(-1L);
344 <            shouldThrow();
345 <        } catch (IllegalArgumentException ok) {
295 <        }
296 <        try {
297 <            java.util.stream.DoubleStream x = r.doubles(-1L);
298 <            shouldThrow();
299 <        } catch (IllegalArgumentException ok) {
300 <        }
337 >        Runnable[] throwingActions = {
338 >            () -> { java.util.stream.IntStream x = r.ints(-1L); },
339 >            () -> { java.util.stream.IntStream x = r.ints(-1L, 2, 3); },
340 >            () -> { java.util.stream.LongStream x = r.longs(-1L); },
341 >            () -> { java.util.stream.LongStream x = r.longs(-1L, -1L, 1L); },
342 >            () -> { java.util.stream.DoubleStream x = r.doubles(-1L); },
343 >            () -> { java.util.stream.DoubleStream x = r.doubles(-1L, .5, .6); },
344 >        };
345 >        assertThrows(IllegalArgumentException.class, throwingActions);
346      }
347  
348      /**
# Line 306 | Line 351 | public class SplittableRandomTest extend
351       */
352      public void testBadStreamBounds() {
353          SplittableRandom r = new SplittableRandom();
354 <        try {
355 <            java.util.stream.IntStream x = r.ints(2, 1);
356 <            shouldThrow();
357 <        } catch (IllegalArgumentException ok) {
358 <        }
359 <        try {
360 <            java.util.stream.LongStream x = r.longs(1, -2);
361 <            shouldThrow();
362 <        } catch (IllegalArgumentException ok) {
318 <        }
319 <        try {
320 <            java.util.stream.DoubleStream x = r.doubles(0, 0);
321 <            shouldThrow();
322 <        } catch (IllegalArgumentException ok) {
323 <        }
354 >        Runnable[] throwingActions = {
355 >            () -> { java.util.stream.IntStream x = r.ints(2, 1); },
356 >            () -> { java.util.stream.IntStream x = r.ints(10, 42, 42); },
357 >            () -> { java.util.stream.LongStream x = r.longs(-1L, -1L); },
358 >            () -> { java.util.stream.LongStream x = r.longs(10, 1L, -2L); },
359 >            () -> { java.util.stream.DoubleStream x = r.doubles(0.0, 0.0); },
360 >            () -> { java.util.stream.DoubleStream x = r.doubles(10, .5, .4); },
361 >        };
362 >        assertThrows(IllegalArgumentException.class, throwingActions);
363      }
364  
365      /**
# Line 332 | Line 371 | public class SplittableRandomTest extend
371          long size = 0;
372          for (int reps = 0; reps < REPS; ++reps) {
373              counter.reset();
374 <            r.ints(size).parallel().forEach(x -> {counter.increment();});
375 <            assertEquals(counter.sum(), size);
374 >            r.ints(size).parallel().forEach(x -> counter.increment());
375 >            assertEquals(size, counter.sum());
376              size += 524959;
377          }
378      }
# Line 347 | Line 386 | public class SplittableRandomTest extend
386          long size = 0;
387          for (int reps = 0; reps < REPS; ++reps) {
388              counter.reset();
389 <            r.longs(size).parallel().forEach(x -> {counter.increment();});
390 <            assertEquals(counter.sum(), size);
389 >            r.longs(size).parallel().forEach(x -> counter.increment());
390 >            assertEquals(size, counter.sum());
391              size += 524959;
392          }
393      }
# Line 362 | Line 401 | public class SplittableRandomTest extend
401          long size = 0;
402          for (int reps = 0; reps < REPS; ++reps) {
403              counter.reset();
404 <            r.doubles(size).parallel().forEach(x -> {counter.increment();});
405 <            assertEquals(counter.sum(), size);
404 >            r.doubles(size).parallel().forEach(x -> counter.increment());
405 >            assertEquals(size, counter.sum());
406              size += 524959;
407          }
408      }
409  
371
410      /**
411       * Each of a parallel sized stream of bounded ints is within bounds
412       */
# Line 379 | Line 417 | public class SplittableRandomTest extend
417          for (int least = -15485867; least < MAX_INT_BOUND; least += 524959) {
418              for (int bound = least + 2; bound > least && bound < MAX_INT_BOUND; bound += 67867967) {
419                  final int lo = least, hi = bound;
420 <                r.ints(size, lo, hi).parallel().
421 <                    forEach(x -> {if (x < lo || x >= hi)
422 <                                fails.getAndIncrement(); });
420 >                r.ints(size, lo, hi).parallel().forEach(
421 >                    x -> {
422 >                        if (x < lo || x >= hi)
423 >                            fails.getAndIncrement(); });
424              }
425          }
426 <        assertEquals(fails.get(), 0);
426 >        assertEquals(0, fails.get());
427      }
428  
429      /**
# Line 397 | Line 436 | public class SplittableRandomTest extend
436          for (long least = -86028121; least < MAX_LONG_BOUND; least += 1982451653L) {
437              for (long bound = least + 2; bound > least && bound < MAX_LONG_BOUND; bound += Math.abs(bound * 7919)) {
438                  final long lo = least, hi = bound;
439 <                r.longs(size, lo, hi).parallel().
440 <                    forEach(x -> {if (x < lo || x >= hi)
441 <                                fails.getAndIncrement(); });
439 >                r.longs(size, lo, hi).parallel().forEach(
440 >                    x -> {
441 >                        if (x < lo || x >= hi)
442 >                            fails.getAndIncrement(); });
443              }
444          }
445 <        assertEquals(fails.get(), 0);
445 >        assertEquals(0, fails.get());
446      }
447  
448      /**
# Line 415 | Line 455 | public class SplittableRandomTest extend
455          for (double least = 0.00011; least < 1.0e20; least *= 9) {
456              for (double bound = least * 1.0011; bound < 1.0e20; bound *= 17) {
457                  final double lo = least, hi = bound;
458 <                r.doubles(size, lo, hi).parallel().
459 <                    forEach(x -> {if (x < lo || x >= hi)
460 <                                fails.getAndIncrement(); });
458 >                r.doubles(size, lo, hi).parallel().forEach(
459 >                    x -> {
460 >                        if (x < lo || x >= hi)
461 >                            fails.getAndIncrement(); });
462              }
463          }
464 <        assertEquals(fails.get(), 0);
464 >        assertEquals(0, fails.get());
465      }
466  
467      /**
# Line 430 | Line 471 | public class SplittableRandomTest extend
471          LongAdder counter = new LongAdder();
472          SplittableRandom r = new SplittableRandom();
473          long size = 100;
474 <        r.ints().limit(size).parallel().forEach(x -> {counter.increment();});
475 <        assertEquals(counter.sum(), size);
474 >        r.ints().limit(size).parallel().forEach(x -> counter.increment());
475 >        assertEquals(size, counter.sum());
476      }
477  
478      /**
# Line 441 | Line 482 | public class SplittableRandomTest extend
482          LongAdder counter = new LongAdder();
483          SplittableRandom r = new SplittableRandom();
484          long size = 100;
485 <        r.longs().limit(size).parallel().forEach(x -> {counter.increment();});
486 <        assertEquals(counter.sum(), size);
485 >        r.longs().limit(size).parallel().forEach(x -> counter.increment());
486 >        assertEquals(size, counter.sum());
487      }
488  
448
489      /**
490       * A parallel unsized stream of doubles generates at least 100 values
491       */
# Line 453 | Line 493 | public class SplittableRandomTest extend
493          LongAdder counter = new LongAdder();
494          SplittableRandom r = new SplittableRandom();
495          long size = 100;
496 <        r.doubles().limit(size).parallel().forEach(x -> {counter.increment();});
497 <        assertEquals(counter.sum(), size);
496 >        r.doubles().limit(size).parallel().forEach(x -> counter.increment());
497 >        assertEquals(size, counter.sum());
498      }
499  
500      /**
# Line 464 | Line 504 | public class SplittableRandomTest extend
504          LongAdder counter = new LongAdder();
505          SplittableRandom r = new SplittableRandom();
506          long size = 100;
507 <        r.ints().limit(size).forEach(x -> {counter.increment();});
508 <        assertEquals(counter.sum(), size);
507 >        r.ints().limit(size).forEach(x -> counter.increment());
508 >        assertEquals(size, counter.sum());
509      }
510  
511      /**
# Line 475 | Line 515 | public class SplittableRandomTest extend
515          LongAdder counter = new LongAdder();
516          SplittableRandom r = new SplittableRandom();
517          long size = 100;
518 <        r.longs().limit(size).forEach(x -> {counter.increment();});
519 <        assertEquals(counter.sum(), size);
518 >        r.longs().limit(size).forEach(x -> counter.increment());
519 >        assertEquals(size, counter.sum());
520      }
521  
482
522      /**
523       * A sequential unsized stream of doubles generates at least 100 values
524       */
# Line 487 | Line 526 | public class SplittableRandomTest extend
526          LongAdder counter = new LongAdder();
527          SplittableRandom r = new SplittableRandom();
528          long size = 100;
529 <        r.doubles().limit(size).forEach(x -> {counter.increment();});
530 <        assertEquals(counter.sum(), size);
529 >        r.doubles().limit(size).forEach(x -> counter.increment());
530 >        assertEquals(size, counter.sum());
531 >    }
532 >
533 >    /**
534 >     * SplittableRandom should implement most of Random's public methods
535 >     */
536 >    public void testShouldImplementMostRandomMethods() throws Throwable {
537 >        Predicate<Method> wasForgotten = method -> {
538 >            String name = method.getName();
539 >            // some methods deliberately not implemented
540 >            if (name.equals("setSeed")) return false;
541 >            if (name.equals("nextFloat")) return false;
542 >            if (name.equals("nextGaussian")) return false;
543 >            try {
544 >                SplittableRandom.class.getMethod(
545 >                    method.getName(), method.getParameterTypes());
546 >            } catch (ReflectiveOperationException ex) {
547 >                return true;
548 >            }
549 >            return false;
550 >        };
551 >        List<Method> forgotten =
552 >            Arrays.stream(java.util.Random.class.getMethods())
553 >            .filter(wasForgotten)
554 >            .collect(Collectors.toList());
555 >        if (!forgotten.isEmpty())
556 >            throw new AssertionError("Please implement: " + forgotten);
557 >    }
558 >
559 >    /**
560 >     * Repeated calls to nextBytes produce at least values of different signs for every byte
561 >     */
562 >    public void testNextBytes() {
563 >        SplittableRandom sr = new SplittableRandom();
564 >        int n = sr.nextInt(1, 20);
565 >        byte[] bytes = new byte[n];
566 >        outer:
567 >        for (int i = 0; i < n; i++) {
568 >            for (int tries = NCALLS; tries-->0; ) {
569 >                byte before = bytes[i];
570 >                sr.nextBytes(bytes);
571 >                byte after = bytes[i];
572 >                if (after * before < 0)
573 >                    continue outer;
574 >            }
575 >            fail("not enough variation in random bytes");
576 >        }
577      }
578  
579 +    /**
580 +     * Filling an empty array with random bytes succeeds without effect.
581 +     */
582 +    public void testNextBytes_emptyArray() {
583 +        new SplittableRandom().nextBytes(new byte[0]);
584 +    }
585 +
586 +    public void testNextBytes_nullArray() {
587 +        try {
588 +            new SplittableRandom().nextBytes(null);
589 +            shouldThrow();
590 +        } catch (NullPointerException success) {}
591 +    }
592  
593   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines