Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# This file is part of utils. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# Use of this source code is governed by a 3-clause BSD-style 

10# license that can be found in the LICENSE file. 

11# 

12 

13import unittest 

14import itertools 

15 

16from lsst.utils.iteration import isplit, ensure_iterable, chunk_iterable 

17 

18 

19class IterationTestCase(unittest.TestCase): 

20 """Tests for `iterable` helper. 

21 """ 

22 

23 def testIterable(self): 

24 test_data = ( 

25 # Boolean indicates to test that we know it's 

26 # meant to be returned unchanged. 

27 (0, False), 

28 ("hello", False), 

29 ({1: 2, 3: 4}, False), 

30 ([0, 1, 2], True), 

31 (["hello", "world"], True), 

32 ({"a", "b", "c"}, True), 

33 ) 

34 

35 for data, is_iterable in test_data: 

36 iterator = ensure_iterable(data) 

37 if not is_iterable: 

38 # Turn into a list so we can check against the 

39 # expected result. 

40 data = [data] 

41 for original, from_iterable in itertools.zip_longest(data, iterator): 

42 self.assertEqual(original, from_iterable) 

43 

44 def testChunking(self): 

45 """Chunk iterables.""" 

46 simple = list(range(101)) 

47 out = [] 

48 n_chunks = 0 

49 for chunk in chunk_iterable(simple, chunk_size=10): 

50 out.extend(chunk) 

51 n_chunks += 1 

52 self.assertEqual(out, simple) 

53 self.assertEqual(n_chunks, 11) 

54 

55 test_dict = {k: 1 for k in range(101)} 

56 n_chunks = 0 

57 for chunk in chunk_iterable(test_dict, chunk_size=45): 

58 # Subtract 1 for each key in chunk 

59 for k in chunk: 

60 test_dict[k] -= 1 

61 n_chunks += 1 

62 # Should have matched every key 

63 self.assertEqual(sum(test_dict.values()), 0) 

64 self.assertEqual(n_chunks, 3) 

65 

66 def testIsplit(self): 

67 # Test compatibility with str.split 

68 seps = ("\n", " ", "d") 

69 input_str = "ab\ncd ef\n" 

70 

71 for sep in seps: 

72 for input in (input_str, input_str.encode()): 

73 test_sep = sep.encode() if isinstance(input, bytes) else sep 

74 isp = list(isplit(input, sep=test_sep)) 

75 ssp = input.split(test_sep) 

76 self.assertEqual(isp, ssp) 

77 

78 

79if __name__ == "__main__": 79 ↛ 80line 79 didn't jump to line 80, because the condition on line 79 was never true

80 unittest.main()