test_sequences_and_iterators.py revision 11986:c12e4625ab56
1import pytest
2
3
4def isclose(a, b, rel_tol=1e-05, abs_tol=0.0):
5    """Like math.isclose() from Python 3.5"""
6    return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
7
8
9def allclose(a_list, b_list, rel_tol=1e-05, abs_tol=0.0):
10    return all(isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol) for a, b in zip(a_list, b_list))
11
12
13def test_generalized_iterators():
14    from pybind11_tests import IntPairs
15
16    assert list(IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero()) == [(1, 2), (3, 4)]
17    assert list(IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero()) == [(1, 2)]
18    assert list(IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero()) == []
19
20    assert list(IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero_keys()) == [1, 3]
21    assert list(IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero_keys()) == [1]
22    assert list(IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero_keys()) == []
23
24
25def test_sequence():
26    from pybind11_tests import Sequence, ConstructorStats
27
28    cstats = ConstructorStats.get(Sequence)
29
30    s = Sequence(5)
31    assert cstats.values() == ['of size', '5']
32
33    assert "Sequence" in repr(s)
34    assert len(s) == 5
35    assert s[0] == 0 and s[3] == 0
36    assert 12.34 not in s
37    s[0], s[3] = 12.34, 56.78
38    assert 12.34 in s
39    assert isclose(s[0], 12.34) and isclose(s[3], 56.78)
40
41    rev = reversed(s)
42    assert cstats.values() == ['of size', '5']
43
44    rev2 = s[::-1]
45    assert cstats.values() == ['of size', '5']
46
47    expected = [0, 56.78, 0, 0, 12.34]
48    assert allclose(rev, expected)
49    assert allclose(rev2, expected)
50    assert rev == rev2
51
52    rev[0::2] = Sequence([2.0, 2.0, 2.0])
53    assert cstats.values() == ['of size', '3', 'from std::vector']
54
55    assert allclose(rev, [2, 56.78, 2, 0, 2])
56
57    assert cstats.alive() == 3
58    del s
59    assert cstats.alive() == 2
60    del rev
61    assert cstats.alive() == 1
62    del rev2
63    assert cstats.alive() == 0
64
65    assert cstats.values() == []
66    assert cstats.default_constructions == 0
67    assert cstats.copy_constructions == 0
68    assert cstats.move_constructions >= 1
69    assert cstats.copy_assignments == 0
70    assert cstats.move_assignments == 0
71
72
73def test_map_iterator():
74    from pybind11_tests import StringMap
75
76    m = StringMap({'hi': 'bye', 'black': 'white'})
77    assert m['hi'] == 'bye'
78    assert len(m) == 2
79    assert m['black'] == 'white'
80
81    with pytest.raises(KeyError):
82        assert m['orange']
83    m['orange'] = 'banana'
84    assert m['orange'] == 'banana'
85
86    expected = {'hi': 'bye', 'black': 'white', 'orange': 'banana'}
87    for k in m:
88        assert m[k] == expected[k]
89    for k, v in m.items():
90        assert v == expected[k]
91