View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.filter;
21  
22  import org.apache.hadoop.hbase.testclassification.SmallTests;
23  import org.apache.hadoop.hbase.util.Bytes;
24  import org.junit.Before;
25  import org.junit.Test;
26  import org.junit.experimental.categories.Category;
27  
28  import static org.junit.Assert.*;
29  
30  @Category(SmallTests.class)
31  public class TestRandomRowFilter {
32    protected RandomRowFilter quarterChanceFilter;
33  
34    @Before
35    public void setUp() throws Exception {
36      quarterChanceFilter = new RandomRowFilter(0.25f);
37    }
38  
39    /**
40     * Tests basics
41     * 
42     * @throws Exception
43     */
44    @Test
45    public void testBasics() throws Exception {
46      int included = 0;
47      int max = 1000000;
48      for (int i = 0; i < max; i++) {
49        if (!quarterChanceFilter.filterRowKey(Bytes.toBytes("row"), 0, Bytes
50            .toBytes("row").length)) {
51          included++;
52        }
53      }
54      // Now let's check if the filter included the right number of rows;
55      // since we're dealing with randomness, we must have a include an epsilon
56      // tolerance.
57      int epsilon = max / 100;
58      assertTrue("Roughly 25% should pass the filter", Math.abs(included - max
59          / 4) < epsilon);
60    }
61  
62    /**
63     * Tests serialization
64     * 
65     * @throws Exception
66     */
67    @Test
68    public void testSerialization() throws Exception {
69      RandomRowFilter newFilter = serializationTest(quarterChanceFilter);
70      // use epsilon float comparison
71      assertTrue("float should be equal", Math.abs(newFilter.getChance()
72          - quarterChanceFilter.getChance()) < 0.000001f);
73    }
74  
75    private RandomRowFilter serializationTest(RandomRowFilter filter)
76        throws Exception {
77      // Decompose filter to bytes.
78      byte[] buffer = filter.toByteArray();
79  
80      // Recompose filter.
81      RandomRowFilter newFilter = RandomRowFilter.parseFrom(buffer);
82  
83      return newFilter;
84    }
85  
86  }
87