1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "dictionary/utils/bloom_filter.h"
18 
19 #include <gtest/gtest.h>
20 
21 #include <algorithm>
22 #include <cstdlib>
23 #include <functional>
24 #include <random>
25 #include <unordered_set>
26 #include <vector>
27 
28 namespace latinime {
29 namespace {
30 
TEST(BloomFilterTest,TestFilter)31 TEST(BloomFilterTest, TestFilter) {
32     static const int TEST_RANDOM_DATA_MAX = 65536;
33     static const int ELEMENT_COUNT = 1000;
34     std::vector<int> elements;
35 
36     // Initialize data set with random integers.
37     {
38         // Use the uniform integer distribution [0, TEST_RANDOM_DATA_MAX].
39         std::uniform_int_distribution<int> distribution(0, TEST_RANDOM_DATA_MAX);
40         auto randomNumberGenerator = std::bind(distribution, std::mt19937());
41         for (int i = 0; i < ELEMENT_COUNT; ++i) {
42             elements.push_back(randomNumberGenerator());
43         }
44     }
45 
46     // Make sure BloomFilter contains nothing by default.
47     BloomFilter bloomFilter;
48     for (const int elem : elements) {
49         ASSERT_FALSE(bloomFilter.isInFilter(elem));
50     }
51 
52     // Copy some of the test vector into bloom filter.
53     std::unordered_set<int> elementsThatHaveBeenSetInFilter;
54     {
55         // Use the uniform integer distribution [0, 1].
56         std::uniform_int_distribution<int> distribution(0, 1);
57         auto randomBitGenerator = std::bind(distribution, std::mt19937());
58         for (const int elem : elements) {
59             if (randomBitGenerator() == 0) {
60                 bloomFilter.setInFilter(elem);
61                 elementsThatHaveBeenSetInFilter.insert(elem);
62             }
63         }
64     }
65 
66     for (const int elem : elements) {
67         const bool existsInFilter = bloomFilter.isInFilter(elem);
68         const bool hasBeenSetInFilter =
69                 elementsThatHaveBeenSetInFilter.find(elem) != elementsThatHaveBeenSetInFilter.end();
70         if (hasBeenSetInFilter) {
71             EXPECT_TRUE(existsInFilter) << "elem: " << elem;
72         }
73         if (!existsInFilter) {
74             EXPECT_FALSE(hasBeenSetInFilter) << "elem: " << elem;
75         }
76     }
77 }
78 
79 }  // namespace
80 }  // namespace latinime
81