'Test that an iterator is the same after pickling, also when part-consumed'

def pickletest(self, it, stop=4, take=1, compare=None):

    def expand(it, i=0):
        if (i > 10):
            raise RuntimeError('infinite    recursion    encountered')
        if isinstance(it, str):
            return it
        try:
            l = list(islice(it, stop))
        except TypeError:
            return it
        return [expand(e, (i + 1)) for e in l]
    dump = pickle.dumps(it)
    i2 = pickle.loads(dump)
    self.assertEqual(type(it), type(i2))
    (a, b) = (expand(it), expand(i2))
    self.assertEqual(a, b)
    if compare:
        c = expand(compare)
        self.assertEqual(a, c)
    i3 = pickle.loads(dump)
    took = 0
    try:
        for i in range(take):
            next(i3)
            took += 1
    except StopIteration:
        pass
    dump = pickle.dumps(i3)
    i4 = pickle.loads(dump)
    (a, b) = (expand(i3), expand(i4))
    self.assertEqual(a, b)
    if compare:
        c = expand(compare[took:])
        self.assertEqual(a, c)
