test_sequences_and_iterators.py
Go to the documentation of this file.
1 import pytest
2 from pytest import approx
3 
4 from pybind11_tests import ConstructorStats
5 from pybind11_tests import sequences_and_iterators as m
6 
7 
9  assert m.make_forward_slice_size_t() == slice(0, -1, 1)
10  assert m.make_reversed_slice_object() == slice(None, None, -1)
11 
12 
13 @pytest.mark.skipif(not m.has_optional, reason="no <optional>")
15  assert m.make_reversed_slice_size_t_optional() == slice(None, None, -1)
16  assert m.make_reversed_slice_size_t_optional_verbose() == slice(None, None, -1)
17 
18 
20  assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero()) == [(1, 2), (3, 4)]
21  assert list(m.IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero()) == [(1, 2)]
22  assert list(m.IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero()) == []
23 
24  assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero_keys()) == [1, 3]
25  assert list(m.IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero_keys()) == [1]
26  assert list(m.IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero_keys()) == []
27 
28  assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero_values()) == [2, 4]
29  assert list(m.IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero_values()) == [2]
30  assert list(m.IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero_values()) == []
31 
32  # __next__ must continue to raise StopIteration
33  it = m.IntPairs([(0, 0)]).nonzero()
34  for _ in range(3):
35  with pytest.raises(StopIteration):
36  next(it)
37 
38  it = m.IntPairs([(0, 0)]).nonzero_keys()
39  for _ in range(3):
40  with pytest.raises(StopIteration):
41  next(it)
42 
43 
45  pairs = m.IntPairs([(1, 2), (3, 4), (0, 5)])
46  assert list(pairs.nonref()) == [(1, 2), (3, 4), (0, 5)]
47  assert list(pairs.nonref_keys()) == [1, 3, 0]
48  assert list(pairs.nonref_values()) == [2, 4, 5]
49 
50 
52  assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).simple_iterator()) == [
53  (1, 2),
54  (3, 4),
55  (0, 5),
56  ]
57  assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).simple_keys()) == [1, 3, 0]
58  assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).simple_values()) == [2, 4, 5]
59 
60 
62  """Test that iterators reference rather than copy their referents."""
63  vec = m.VectorNonCopyableInt()
64  vec.append(3)
65  vec.append(5)
66  assert [int(x) for x in vec] == [3, 5]
67  # Increment everything to make sure the referents can be mutated
68  for x in vec:
69  x.set(int(x) + 1)
70  assert [int(x) for x in vec] == [4, 6]
71 
72  vec = m.VectorNonCopyableIntPair()
73  vec.append([3, 4])
74  vec.append([5, 7])
75  assert [int(x) for x in vec.keys()] == [3, 5]
76  assert [int(x) for x in vec.values()] == [4, 7]
77  for x in vec.keys():
78  x.set(int(x) + 1)
79  for x in vec.values():
80  x.set(int(x) + 10)
81  assert [int(x) for x in vec.keys()] == [4, 6]
82  assert [int(x) for x in vec.values()] == [14, 17]
83 
84 
86  sliceable = m.Sliceable(100)
87  assert sliceable[::] == (0, 100, 1)
88  assert sliceable[10::] == (10, 100, 1)
89  assert sliceable[:10:] == (0, 10, 1)
90  assert sliceable[::10] == (0, 100, 10)
91  assert sliceable[-10::] == (90, 100, 1)
92  assert sliceable[:-10:] == (0, 90, 1)
93  assert sliceable[::-10] == (99, -1, -10)
94  assert sliceable[50:60:1] == (50, 60, 1)
95  assert sliceable[50:60:-1] == (50, 60, -1)
96 
97 
99  cstats = ConstructorStats.get(m.Sequence)
100 
101  s = m.Sequence(5)
102  assert cstats.values() == ["of size", "5"]
103 
104  assert "Sequence" in repr(s)
105  assert len(s) == 5
106  assert s[0] == 0 and s[3] == 0
107  assert 12.34 not in s
108  s[0], s[3] = 12.34, 56.78
109  assert 12.34 in s
110  assert s[0] == approx(12.34, rel=1e-05)
111  assert s[3] == approx(56.78, rel=1e-05)
112 
113  rev = reversed(s)
114  assert cstats.values() == ["of size", "5"]
115 
116  rev2 = s[::-1]
117  assert cstats.values() == ["of size", "5"]
118 
119  it = iter(m.Sequence(0))
120  for _ in range(3): # __next__ must continue to raise StopIteration
121  with pytest.raises(StopIteration):
122  next(it)
123  assert cstats.values() == ["of size", "0"]
124 
125  expected = [0, 56.78, 0, 0, 12.34]
126  assert rev == approx(expected, rel=1e-05)
127  assert rev2 == approx(expected, rel=1e-05)
128  assert rev == rev2
129 
130  rev[0::2] = m.Sequence([2.0, 2.0, 2.0])
131  assert cstats.values() == ["of size", "3", "from std::vector"]
132 
133  assert rev == approx([2, 56.78, 2, 0, 2], rel=1e-05)
134 
135  assert cstats.alive() == 4
136  del it
137  assert cstats.alive() == 3
138  del s
139  assert cstats.alive() == 2
140  del rev
141  assert cstats.alive() == 1
142  del rev2
143  assert cstats.alive() == 0
144 
145  assert cstats.values() == []
146  assert cstats.default_constructions == 0
147  assert cstats.copy_constructions == 0
148  assert cstats.move_constructions >= 1
149  assert cstats.copy_assignments == 0
150  assert cstats.move_assignments == 0
151 
152 
154  """#2076: Exception raised by len(arg) should be propagated"""
155 
156  class BadLen(RuntimeError):
157  pass
158 
159  class SequenceLike:
160  def __getitem__(self, i):
161  return None
162 
163  def __len__(self):
164  raise BadLen()
165 
166  with pytest.raises(BadLen):
167  m.sequence_length(SequenceLike())
168 
169  assert m.sequence_length([1, 2, 3]) == 3
170  assert m.sequence_length("hello") == 5
171 
172 
174  sm = m.StringMap({"hi": "bye", "black": "white"})
175  assert sm["hi"] == "bye"
176  assert len(sm) == 2
177  assert sm["black"] == "white"
178 
179  with pytest.raises(KeyError):
180  assert sm["orange"]
181  sm["orange"] = "banana"
182  assert sm["orange"] == "banana"
183 
184  expected = {"hi": "bye", "black": "white", "orange": "banana"}
185  for k in sm:
186  assert sm[k] == expected[k]
187  for k, v in sm.items():
188  assert v == expected[k]
189  assert list(sm.values()) == [expected[k] for k in sm]
190 
191  it = iter(m.StringMap({}))
192  for _ in range(3): # __next__ must continue to raise StopIteration
193  with pytest.raises(StopIteration):
194  next(it)
195 
196 
198  t = (1, 2, 3)
199  assert m.object_to_list(t) == [1, 2, 3]
200  assert m.object_to_list(iter(t)) == [1, 2, 3]
201  assert m.iterator_to_list(iter(t)) == [1, 2, 3]
202 
203  with pytest.raises(TypeError) as excinfo:
204  m.object_to_list(1)
205  assert "object is not iterable" in str(excinfo.value)
206 
207  with pytest.raises(TypeError) as excinfo:
208  m.iterator_to_list(1)
209  assert "incompatible function arguments" in str(excinfo.value)
210 
211  def bad_next_call():
212  raise RuntimeError("py::iterator::advance() should propagate errors")
213 
214  with pytest.raises(RuntimeError) as excinfo:
215  m.iterator_to_list(iter(bad_next_call, None))
216  assert str(excinfo.value) == "py::iterator::advance() should propagate errors"
217 
218  lst = [1, None, 0, None]
219  assert m.count_none(lst) == 2
220  assert m.find_none(lst) is True
221  assert m.count_nonzeros({"a": 0, "b": 1, "c": 2}) == 2
222 
223  r = range(5)
224  assert all(m.tuple_iterator(tuple(r)))
225  assert all(m.list_iterator(list(r)))
226  assert all(m.sequence_iterator(r))
227 
228 
230  """#181: iterator passthrough did not compile"""
231  from pybind11_tests.sequences_and_iterators import iterator_passthrough
232 
233  values = [3, 5, 7, 9, 11, 13, 15]
234  assert list(iterator_passthrough(iter(values))) == values
235 
236 
238  """#388: Can't make iterators via make_iterator() with different r/v policies"""
239  import pybind11_tests.sequences_and_iterators as m
240 
241  assert list(m.make_iterator_1()) == [1, 2, 3]
242  assert list(m.make_iterator_2()) == [1, 2, 3]
243  assert not isinstance(m.make_iterator_1(), type(m.make_iterator_2()))
static const Eigen::internal::all_t all
iterator iter(handle obj)
Definition: pytypes.h:2273
bool isinstance(handle obj)
Definition: pytypes.h:700
static ConstructorStats & get(std::type_index type)
Definition: pytypes.h:1403
Definition: pytypes.h:1979
Double_ range(const Point2_ &p, const Point2_ &q)
str repr(handle h)
Definition: pytypes.h:2265
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2244
Definition: pytypes.h:1370


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:37:46