001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.filter;
019
020import static org.junit.jupiter.api.Assertions.assertTrue;
021
022import org.apache.hadoop.hbase.KeyValueUtil;
023import org.apache.hadoop.hbase.testclassification.FilterTests;
024import org.apache.hadoop.hbase.testclassification.SmallTests;
025import org.apache.hadoop.hbase.util.Bytes;
026import org.junit.jupiter.api.BeforeEach;
027import org.junit.jupiter.api.Tag;
028import org.junit.jupiter.api.Test;
029
030@Tag(FilterTests.TAG)
031@Tag(SmallTests.TAG)
032public class TestRandomRowFilter {
033
034  protected RandomRowFilter quarterChanceFilter;
035
036  @BeforeEach
037  public void setUp() throws Exception {
038    quarterChanceFilter = new RandomRowFilter(0.25f);
039  }
040
041  /**
042   * Tests basics
043   */
044  @Test
045  public void testBasics() throws Exception {
046    int included = 0;
047    int max = 1000000;
048    for (int i = 0; i < max; i++) {
049      if (!quarterChanceFilter.filterRowKey(KeyValueUtil.createFirstOnRow(Bytes.toBytes("row")))) {
050        included++;
051      }
052    }
053    // Now let's check if the filter included the right number of rows;
054    // since we're dealing with randomness, we must have a include an epsilon
055    // tolerance.
056    int epsilon = max / 100;
057    assertTrue(Math.abs(included - max / 4) < epsilon, "Roughly 25% should pass filter");
058  }
059
060  /**
061   * Tests serialization
062   */
063  @Test
064  public void testSerialization() throws Exception {
065    RandomRowFilter newFilter = serializationTest(quarterChanceFilter);
066    // use epsilon float comparison
067    assertTrue(Math.abs(newFilter.getChance() - quarterChanceFilter.getChance()) < 0.000001f,
068      "float should be equal");
069  }
070
071  private RandomRowFilter serializationTest(RandomRowFilter filter) throws Exception {
072    // Decompose filter to bytes.
073    byte[] buffer = filter.toByteArray();
074
075    // Recompose filter.
076    RandomRowFilter newFilter = RandomRowFilter.parseFrom(buffer);
077
078    return newFilter;
079  }
080
081}