1 /* 2 * Copyright (C) 2018 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 #ifndef LIBTEXTCLASSIFIER_UTILS_TESTING_TEST_DATA_GENERATOR_H_ 18 #define LIBTEXTCLASSIFIER_UTILS_TESTING_TEST_DATA_GENERATOR_H_ 19 20 #include <algorithm> 21 #include <iostream> 22 #include <limits> 23 #include <random> 24 #include <string> 25 #include <type_traits> 26 27 #include "utils/strings/stringpiece.h" 28 29 // Generates test data randomly. 30 class TestDataGenerator { 31 public: TestDataGenerator()32 explicit TestDataGenerator() : random_engine_(0) {} 33 34 template <typename T, 35 typename std::enable_if_t<std::is_integral<T>::value>* = nullptr> generate()36 T generate() { 37 typedef typename std::conditional<sizeof(T) >= sizeof(int16_t), T, 38 std::int16_t>::type rand_type; 39 std::uniform_int_distribution<rand_type> dist( 40 std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); 41 return static_cast<T>(dist(random_engine_)); 42 } 43 44 template <> generate()45 bool generate() { 46 std::bernoulli_distribution dist(0.5); 47 return dist(random_engine_); 48 } 49 50 template <> generate()51 char generate() { 52 std::uniform_int_distribution<int> dist(0, 25); 53 return dist(random_engine_) + 'a'; 54 } 55 56 template <typename T, typename std::enable_if_t< 57 std::is_floating_point<T>::value>* = nullptr> generate()58 T generate() { 59 std::uniform_real_distribution<T> dist; 60 return dist(random_engine_); 61 } 62 63 template <typename T, typename std::enable_if_t< 64 std::is_same<std::string, T>::value>* = nullptr> generate()65 T generate() { 66 std::uniform_int_distribution<> dist(1, 10); 67 return std::string(dist(random_engine_), '*'); 68 } 69 70 private: 71 std::default_random_engine random_engine_; 72 }; 73 74 #endif // LIBTEXTCLASSIFIER_UTILS_TESTING_TEST_DATA_GENERATOR_H_ 75