Test that an iterator is the same after pickling, also when part-consumed
(self, protocol, it, stop=4, take=1, compare=None)
| 85 | class TestBasicOps(unittest.TestCase): |
| 86 | |
| 87 | def pickletest(self, protocol, it, stop=4, take=1, compare=None): |
| 88 | """Test that an iterator is the same after pickling, also when part-consumed""" |
| 89 | def expand(it, i=0): |
| 90 | # Recursively expand iterables, within sensible bounds |
| 91 | if i > 10: |
| 92 | raise RuntimeError("infinite recursion encountered") |
| 93 | if isinstance(it, str): |
| 94 | return it |
| 95 | try: |
| 96 | l = list(islice(it, stop)) |
| 97 | except TypeError: |
| 98 | return it # can't expand it |
| 99 | return [expand(e, i+1) for e in l] |
| 100 | |
| 101 | # Test the initial copy against the original |
| 102 | dump = pickle.dumps(it, protocol) |
| 103 | i2 = pickle.loads(dump) |
| 104 | self.assertEqual(type(it), type(i2)) |
| 105 | a, b = expand(it), expand(i2) |
| 106 | self.assertEqual(a, b) |
| 107 | if compare: |
| 108 | c = expand(compare) |
| 109 | self.assertEqual(a, c) |
| 110 | |
| 111 | # Take from the copy, and create another copy and compare them. |
| 112 | i3 = pickle.loads(dump) |
| 113 | took = 0 |
| 114 | try: |
| 115 | for i in range(take): |
| 116 | next(i3) |
| 117 | took += 1 |
| 118 | except StopIteration: |
| 119 | pass #in case there is less data than 'take' |
| 120 | dump = pickle.dumps(i3, protocol) |
| 121 | i4 = pickle.loads(dump) |
| 122 | a, b = expand(i3), expand(i4) |
| 123 | self.assertEqual(a, b) |
| 124 | if compare: |
| 125 | c = expand(compare[took:]) |
| 126 | self.assertEqual(a, c); |
| 127 | |
| 128 | def test_accumulate(self): |
| 129 | self.assertEqual(list(accumulate(range(10))), # one positional arg |
no test coverage detected