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    *      http://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.rng.sampling;
18  
19  import java.util.ArrayList;
20  import java.util.Arrays;
21  import java.util.Collections;
22  import java.util.List;
23  import org.apache.commons.rng.UniformRandomProvider;
24  import org.junit.jupiter.api.Assertions;
25  import org.junit.jupiter.api.Test;
26  
27  /**
28   * Tests for {@link CollectionSampler}.
29   */
30  class CollectionSamplerTest {
31  
32      @Test
33      void testSampleTrivial() {
34          final ArrayList<String> list = new ArrayList<>();
35          list.add("Apache");
36          list.add("Commons");
37          list.add("RNG");
38  
39          final CollectionSampler<String> sampler =
40              new CollectionSampler<>(RandomAssert.createRNG(), list);
41          final String word = sampler.sample();
42          for (final String w : list) {
43              if (word.equals(w)) {
44                  return;
45              }
46          }
47          Assertions.fail(word + " not in list");
48      }
49  
50      @Test
51      void testSamplePrecondition() {
52          final UniformRandomProvider rng = RandomAssert.seededRNG();
53          // Must fail for empty collection.
54          final List<String> empty = Collections.emptyList();
55          Assertions.assertThrows(IllegalArgumentException.class,
56              () -> new CollectionSampler<>(rng, empty));
57      }
58  
59      /**
60       * Test the SharedStateSampler implementation.
61       */
62      @Test
63      void testSharedStateSampler() {
64          final UniformRandomProvider rng1 = RandomAssert.seededRNG();
65          final UniformRandomProvider rng2 = RandomAssert.seededRNG();
66          final List<String> list = Arrays.asList("Apache", "Commons", "RNG");
67          final CollectionSampler<String> sampler1 =
68              new CollectionSampler<>(rng1, list);
69          final CollectionSampler<String> sampler2 = sampler1.withUniformRandomProvider(rng2);
70          RandomAssert.assertProduceSameSequence(sampler1, sampler2);
71      }
72  }