test_sequences_and_iterators.py revision 12391:ceeca8b41e4b
1import pytest
2from pybind11_tests import sequences_and_iterators as m
3from pybind11_tests import ConstructorStats
4
5
6def isclose(a, b, rel_tol=1e-05, abs_tol=0.0):
7    """Like math.isclose() from Python 3.5"""
8    return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
9
10
11def allclose(a_list, b_list, rel_tol=1e-05, abs_tol=0.0):
12    return all(isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol) for a, b in zip(a_list, b_list))
13
14
15def test_generalized_iterators():
16    assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero()) == [(1, 2), (3, 4)]
17    assert list(m.IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero()) == [(1, 2)]
18    assert list(m.IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero()) == []
19
20    assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero_keys()) == [1, 3]
21    assert list(m.IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero_keys()) == [1]
22    assert list(m.IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero_keys()) == []
23
24    # __next__ must continue to raise StopIteration
25    it = m.IntPairs([(0, 0)]).nonzero()
26    for _ in range(3):
27        with pytest.raises(StopIteration):
28            next(it)
29
30    it = m.IntPairs([(0, 0)]).nonzero_keys()
31    for _ in range(3):
32        with pytest.raises(StopIteration):
33            next(it)
34
35
36def test_sequence():
37    cstats = ConstructorStats.get(m.Sequence)
38
39    s = m.Sequence(5)
40    assert cstats.values() == ['of size', '5']
41
42    assert "Sequence" in repr(s)
43    assert len(s) == 5
44    assert s[0] == 0 and s[3] == 0
45    assert 12.34 not in s
46    s[0], s[3] = 12.34, 56.78
47    assert 12.34 in s
48    assert isclose(s[0], 12.34) and isclose(s[3], 56.78)
49
50    rev = reversed(s)
51    assert cstats.values() == ['of size', '5']
52
53    rev2 = s[::-1]
54    assert cstats.values() == ['of size', '5']
55
56    it = iter(m.Sequence(0))
57    for _ in range(3):  # __next__ must continue to raise StopIteration
58        with pytest.raises(StopIteration):
59            next(it)
60    assert cstats.values() == ['of size', '0']
61
62    expected = [0, 56.78, 0, 0, 12.34]
63    assert allclose(rev, expected)
64    assert allclose(rev2, expected)
65    assert rev == rev2
66
67    rev[0::2] = m.Sequence([2.0, 2.0, 2.0])
68    assert cstats.values() == ['of size', '3', 'from std::vector']
69
70    assert allclose(rev, [2, 56.78, 2, 0, 2])
71
72    assert cstats.alive() == 4
73    del it
74    assert cstats.alive() == 3
75    del s
76    assert cstats.alive() == 2
77    del rev
78    assert cstats.alive() == 1
79    del rev2
80    assert cstats.alive() == 0
81
82    assert cstats.values() == []
83    assert cstats.default_constructions == 0
84    assert cstats.copy_constructions == 0
85    assert cstats.move_constructions >= 1
86    assert cstats.copy_assignments == 0
87    assert cstats.move_assignments == 0
88
89
90def test_map_iterator():
91    sm = m.StringMap({'hi': 'bye', 'black': 'white'})
92    assert sm['hi'] == 'bye'
93    assert len(sm) == 2
94    assert sm['black'] == 'white'
95
96    with pytest.raises(KeyError):
97        assert sm['orange']
98    sm['orange'] = 'banana'
99    assert sm['orange'] == 'banana'
100
101    expected = {'hi': 'bye', 'black': 'white', 'orange': 'banana'}
102    for k in sm:
103        assert sm[k] == expected[k]
104    for k, v in sm.items():
105        assert v == expected[k]
106
107    it = iter(m.StringMap({}))
108    for _ in range(3):  # __next__ must continue to raise StopIteration
109        with pytest.raises(StopIteration):
110            next(it)
111
112
113def test_python_iterator_in_cpp():
114    t = (1, 2, 3)
115    assert m.object_to_list(t) == [1, 2, 3]
116    assert m.object_to_list(iter(t)) == [1, 2, 3]
117    assert m.iterator_to_list(iter(t)) == [1, 2, 3]
118
119    with pytest.raises(TypeError) as excinfo:
120        m.object_to_list(1)
121    assert "object is not iterable" in str(excinfo.value)
122
123    with pytest.raises(TypeError) as excinfo:
124        m.iterator_to_list(1)
125    assert "incompatible function arguments" in str(excinfo.value)
126
127    def bad_next_call():
128        raise RuntimeError("py::iterator::advance() should propagate errors")
129
130    with pytest.raises(RuntimeError) as excinfo:
131        m.iterator_to_list(iter(bad_next_call, None))
132    assert str(excinfo.value) == "py::iterator::advance() should propagate errors"
133
134    l = [1, None, 0, None]
135    assert m.count_none(l) == 2
136    assert m.find_none(l) is True
137    assert m.count_nonzeros({"a": 0, "b": 1, "c": 2}) == 2
138
139    r = range(5)
140    assert all(m.tuple_iterator(tuple(r)))
141    assert all(m.list_iterator(list(r)))
142    assert all(m.sequence_iterator(r))
143
144
145def test_iterator_passthrough():
146    """#181: iterator passthrough did not compile"""
147    from pybind11_tests.sequences_and_iterators import iterator_passthrough
148
149    assert list(iterator_passthrough(iter([3, 5, 7, 9, 11, 13, 15]))) == [3, 5, 7, 9, 11, 13, 15]
150
151
152def test_iterator_rvp():
153    """#388: Can't make iterators via make_iterator() with different r/v policies """
154    import pybind11_tests.sequences_and_iterators as m
155
156    assert list(m.make_iterator_1()) == [1, 2, 3]
157    assert list(m.make_iterator_2()) == [1, 2, 3]
158    assert not isinstance(m.make_iterator_1(), type(m.make_iterator_2()))
159