|
| 1 | +import unittest |
| 2 | +import sys |
| 3 | + |
| 4 | +from data_juicer.utils.common_utils import ( |
| 5 | + stats_to_number, dict_to_hash, nested_access, is_string_list, |
| 6 | + avg_split_string_list_under_limit, is_float |
| 7 | +) |
| 8 | + |
| 9 | +from data_juicer.utils.unittest_utils import DataJuicerTestCaseBase |
| 10 | + |
| 11 | +class CommonUtilsTest(DataJuicerTestCaseBase): |
| 12 | + |
| 13 | + def test_stats_to_number(self): |
| 14 | + self.assertEqual(stats_to_number('1.0'), 1.0) |
| 15 | + self.assertEqual(stats_to_number([1.0, 2.0, 3.0]), 2.0) |
| 16 | + |
| 17 | + self.assertEqual(stats_to_number([]), -sys.maxsize) |
| 18 | + self.assertEqual(stats_to_number(None), -sys.maxsize) |
| 19 | + self.assertEqual(stats_to_number([], reverse=False), sys.maxsize) |
| 20 | + self.assertEqual(stats_to_number(None, reverse=False), sys.maxsize) |
| 21 | + |
| 22 | + def test_dict_to_hash(self): |
| 23 | + self.assertEqual(len(dict_to_hash({'a': 1, 'b': 2})), 64) |
| 24 | + self.assertEqual(len(dict_to_hash({'a': 1, 'b': 2}, hash_length=32)), 32) |
| 25 | + |
| 26 | + def test_nested_access(self): |
| 27 | + self.assertEqual(nested_access({'a': {'b': 1}}, 'a.b'), 1) |
| 28 | + self.assertEqual(nested_access({'a': [{'b': 1}]}, 'a.0.b', digit_allowed=True), 1) |
| 29 | + self.assertEqual(nested_access({'a': [{'b': 1}]}, 'a.0.b', digit_allowed=False), None) |
| 30 | + |
| 31 | + def test_is_string_list(self): |
| 32 | + self.assertTrue(is_string_list(['a', 'b', 'c'])) |
| 33 | + self.assertFalse(is_string_list([1, 2, 3])) |
| 34 | + self.assertFalse(is_string_list(['a', 2, 'c'])) |
| 35 | + |
| 36 | + def test_is_float(self): |
| 37 | + self.assertTrue(is_float('1.0')) |
| 38 | + self.assertTrue(is_float(1.0)) |
| 39 | + self.assertTrue(is_float('1e-4')) |
| 40 | + self.assertFalse(is_float('a')) |
| 41 | + |
| 42 | + def test_avg_split_string_list_under_limit(self): |
| 43 | + test_data = [ |
| 44 | + (['a', 'b', 'c'], [1, 2, 3], None, [['a', 'b', 'c']]), |
| 45 | + (['a', 'b', 'c'], [1, 2, 3], 3, [['a', 'b'], ['c']]), |
| 46 | + (['a', 'b', 'c'], [1, 2, 3], 2, [['a'], ['b'], ['c']]), |
| 47 | + (['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 1, 1], 3, [['a', 'b'], ['c'], ['d', 'e']]), |
| 48 | + (['a', 'b', 'c'], [1, 2], 3, [['a', 'b', 'c']]), |
| 49 | + (['a', 'b', 'c'], [1, 2, 3], 100, [['a', 'b', 'c']]), |
| 50 | + ] |
| 51 | + |
| 52 | + for str_list, token_nums, max_token_num, expected_result in test_data: |
| 53 | + self.assertEqual(avg_split_string_list_under_limit(str_list, token_nums, max_token_num), expected_result) |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == '__main__': |
| 57 | + unittest.main() |
0 commit comments