1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.rng.core.source32;
18
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.ObjectInputStream;
22 import java.io.ObjectOutputStream;
23 import java.io.Serializable;
24 import java.util.Random;
25
26 import org.apache.commons.rng.RandomProviderState;
27 import org.apache.commons.rng.core.RandomProviderDefaultState;
28 import org.apache.commons.rng.core.util.NumberFactory;
29 import org.junit.Assert;
30 import org.junit.Test;
31
32 public class JDKRandomTest {
33
34
35
36
37
38 static class SerializableTestObject implements Serializable {
39 private static final long serialVersionUID = 1L;
40
41 private int state0;
42 private double state1;
43 private long state2;
44 private boolean stte3;
45
46
47
48
49
50
51
52
53 private void readObject(ObjectInputStream input)
54 throws IOException,
55 ClassNotFoundException {
56 Assert.fail("This should not be run during the test");
57 }
58 }
59
60 @Test
61 public void testReferenceCode() {
62 final long refSeed = -1357111213L;
63 final JDKRandom rng = new JDKRandom(refSeed);
64 final Random jdk = new Random(refSeed);
65
66
67
68 final int numRepeats = 1000;
69 for (int r = 0; r < numRepeats; r++) {
70 Assert.assertEquals(r + " nextInt", jdk.nextInt(), rng.nextInt());
71 }
72 }
73
74
75
76
77
78 @Test
79 public void testRestoreToNewInstance() {
80 final long seed = 8796746234L;
81 final JDKRandom rng1 = new JDKRandom(seed);
82 final JDKRandom rng2 = new JDKRandom(seed + 1);
83
84
85 final int numRepeats = 10;
86 for (int r = 0; r < numRepeats; r++) {
87 Assert.assertNotEquals(r + " nextInt", rng1.nextInt(), rng2.nextInt());
88 }
89
90 final RandomProviderState state = rng1.saveState();
91
92
93
94 rng2.restoreState(state);
95
96
97 for (int r = 0; r < numRepeats; r++) {
98 Assert.assertEquals(r + " nextInt", rng1.nextInt(), rng2.nextInt());
99 }
100 }
101
102
103
104
105
106
107
108 @Test(expected = IllegalStateException.class)
109 public void testRestoreWithInvalidClass() throws IOException {
110
111 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
112 final ObjectOutputStream oos = new ObjectOutputStream(bos);
113 oos.writeObject(new SerializableTestObject());
114 oos.close();
115
116
117
118 final byte[] state = bos.toByteArray();
119 final int stateSize = state.length;
120 final byte[] sizeAndState = new byte[4 + stateSize];
121 System.arraycopy(NumberFactory.makeByteArray(stateSize), 0, sizeAndState, 0, 4);
122 System.arraycopy(state, 0, sizeAndState, 4, stateSize);
123
124 final RandomProviderDefaultState dummyState = new RandomProviderDefaultState(sizeAndState);
125
126 final JDKRandom rng = new JDKRandom(13L);
127
128 rng.restoreState(dummyState);
129 }
130 }