test_pytypes.py
Go to the documentation of this file.
1 from __future__ import annotations
2 
3 import contextlib
4 import sys
5 import types
6 
7 import pytest
8 
9 import env
10 from pybind11_tests import detailed_error_messages_enabled
11 from pybind11_tests import pytypes as m
12 
13 
15  assert m.obj_class_name(None) == "NoneType"
16  assert m.obj_class_name(list) == "list"
17  assert m.obj_class_name([]) == "list"
18 
19 
21  assert m.handle_from_move_only_type_with_operator_PyObject_ncnst()
22  assert m.handle_from_move_only_type_with_operator_PyObject_const()
23 
24 
25 def test_bool(doc):
26  assert doc(m.get_bool) == "get_bool() -> bool"
27 
28 
29 def test_int(doc):
30  assert doc(m.get_int) == "get_int() -> int"
31 
32 
33 def test_iterator(doc):
34  assert doc(m.get_iterator) == "get_iterator() -> Iterator"
35 
36 
37 @pytest.mark.parametrize(
38  ("pytype", "from_iter_func"),
39  [
40  (frozenset, m.get_frozenset_from_iterable),
41  (list, m.get_list_from_iterable),
42  (set, m.get_set_from_iterable),
43  (tuple, m.get_tuple_from_iterable),
44  ],
45 )
46 def test_from_iterable(pytype, from_iter_func):
47  my_iter = iter(range(10))
48  s = from_iter_func(my_iter)
49  assert type(s) == pytype
50  assert s == pytype(range(10))
51 
52 
53 def test_iterable(doc):
54  assert doc(m.get_iterable) == "get_iterable() -> Iterable"
55 
56 
57 def test_float(doc):
58  assert doc(m.get_float) == "get_float() -> float"
59 
60 
61 def test_list(capture, doc):
62  assert m.list_no_args() == []
63  assert m.list_ssize_t() == []
64  assert m.list_size_t() == []
65  lins = [1, 2]
66  m.list_insert_ssize_t(lins)
67  assert lins == [1, 83, 2]
68  m.list_insert_size_t(lins)
69  assert lins == [1, 83, 2, 57]
70  m.list_clear(lins)
71  assert lins == []
72 
73  with capture:
74  lst = m.get_list()
75  assert lst == ["inserted-0", "overwritten", "inserted-2"]
76 
77  lst.append("value2")
78  m.print_list(lst)
79  assert (
80  capture.unordered
81  == """
82  Entry at position 0: value
83  list item 0: inserted-0
84  list item 1: overwritten
85  list item 2: inserted-2
86  list item 3: value2
87  """
88  )
89 
90  assert doc(m.get_list) == "get_list() -> list"
91  assert doc(m.print_list) == "print_list(arg0: list) -> None"
92 
93 
94 def test_none(doc):
95  assert doc(m.get_none) == "get_none() -> None"
96  assert doc(m.print_none) == "print_none(arg0: None) -> None"
97 
98 
99 def test_set(capture, doc):
100  s = m.get_set()
101  assert isinstance(s, set)
102  assert s == {"key1", "key2", "key3"}
103 
104  s.add("key4")
105  with capture:
106  m.print_anyset(s)
107  assert (
108  capture.unordered
109  == """
110  key: key1
111  key: key2
112  key: key3
113  key: key4
114  """
115  )
116 
117  m.set_add(s, "key5")
118  assert m.anyset_size(s) == 5
119 
120  m.set_clear(s)
121  assert m.anyset_empty(s)
122 
123  assert not m.anyset_contains(set(), 42)
124  assert m.anyset_contains({42}, 42)
125  assert m.anyset_contains({"foo"}, "foo")
126 
127  assert doc(m.get_set) == "get_set() -> set"
128  assert doc(m.print_anyset) == "print_anyset(arg0: Union[set, frozenset]) -> None"
129 
130 
131 def test_frozenset(capture, doc):
132  s = m.get_frozenset()
133  assert isinstance(s, frozenset)
134  assert s == frozenset({"key1", "key2", "key3"})
135 
136  with capture:
137  m.print_anyset(s)
138  assert (
139  capture.unordered
140  == """
141  key: key1
142  key: key2
143  key: key3
144  """
145  )
146  assert m.anyset_size(s) == 3
147  assert not m.anyset_empty(s)
148 
149  assert not m.anyset_contains(frozenset(), 42)
150  assert m.anyset_contains(frozenset({42}), 42)
151  assert m.anyset_contains(frozenset({"foo"}), "foo")
152 
153  assert doc(m.get_frozenset) == "get_frozenset() -> frozenset"
154 
155 
156 def test_dict(capture, doc):
157  d = m.get_dict()
158  assert d == {"key": "value"}
159 
160  with capture:
161  d["key2"] = "value2"
162  m.print_dict(d)
163  assert (
164  capture.unordered
165  == """
166  key: key, value=value
167  key: key2, value=value2
168  """
169  )
170 
171  assert not m.dict_contains({}, 42)
172  assert m.dict_contains({42: None}, 42)
173  assert m.dict_contains({"foo": None}, "foo")
174 
175  assert doc(m.get_dict) == "get_dict() -> dict"
176  assert doc(m.print_dict) == "print_dict(arg0: dict) -> None"
177 
178  assert m.dict_keyword_constructor() == {"x": 1, "y": 2, "z": 3}
179 
180 
182  d = {"key": None}
183 
184  def __contains__(self, m):
185  return m in self.d
186 
187 
188 @pytest.mark.parametrize(
189  ("arg", "func"),
190  [
191  (set(), m.anyset_contains),
192  ({}, m.dict_contains),
193  (CustomContains(), m.obj_contains),
194  ],
195 )
196 @pytest.mark.xfail("env.PYPY and sys.pypy_version_info < (7, 3, 10)", strict=False)
198  class Unhashable:
199  __hash__ = None
200 
201  with pytest.raises(TypeError) as exc_info:
202  func(arg, Unhashable())
203  assert "unhashable type:" in str(exc_info.value)
204 
205 
207  assert m.tuple_no_args() == ()
208  assert m.tuple_ssize_t() == ()
209  assert m.tuple_size_t() == ()
210  assert m.get_tuple() == (42, None, "spam")
211 
212 
214  ns = m.get_simple_namespace()
215  assert ns.attr == 42
216  assert ns.x == "foo"
217  assert ns.right == 2
218  assert not hasattr(ns, "wrong")
219 
220 
221 def test_str(doc):
222  assert m.str_from_char_ssize_t().encode().decode() == "red"
223  assert m.str_from_char_size_t().encode().decode() == "blue"
224  assert m.str_from_string().encode().decode() == "baz"
225  assert m.str_from_bytes().encode().decode() == "boo"
226 
227  assert doc(m.str_from_bytes) == "str_from_bytes() -> str"
228 
229  class A:
230  def __str__(self):
231  return "this is a str"
232 
233  def __repr__(self):
234  return "this is a repr"
235 
236  assert m.str_from_object(A()) == "this is a str"
237  assert m.repr_from_object(A()) == "this is a repr"
238  assert m.str_from_handle(A()) == "this is a str"
239 
240  s1, s2 = m.str_format()
241  assert s1 == "1 + 2 = 3"
242  assert s1 == s2
243 
244  malformed_utf8 = b"\x80"
245  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
246  assert m.str_from_object(malformed_utf8) is malformed_utf8
247  else:
248  assert m.str_from_object(malformed_utf8) == "b'\\x80'"
249  assert m.str_from_handle(malformed_utf8) == "b'\\x80'"
250 
251  assert m.str_from_string_from_str("this is a str") == "this is a str"
252  ucs_surrogates_str = "\udcc3"
253  with pytest.raises(UnicodeEncodeError):
254  m.str_from_string_from_str(ucs_surrogates_str)
255 
256 
257 @pytest.mark.parametrize(
258  "func",
259  [
260  m.str_from_bytes_input,
261  m.str_from_cstr_input,
262  m.str_from_std_string_input,
263  ],
264 )
266  input_str = "\ud83d\ude4f".encode("utf-8", "surrogatepass")
267  with pytest.raises(UnicodeDecodeError):
268  func(input_str)
269 
270 
271 def test_bytes(doc):
272  assert m.bytes_from_char_ssize_t().decode() == "green"
273  assert m.bytes_from_char_size_t().decode() == "purple"
274  assert m.bytes_from_string().decode() == "foo"
275  assert m.bytes_from_str().decode() == "bar"
276 
277  assert doc(m.bytes_from_str) == "bytes_from_str() -> bytes"
278 
279 
281  assert m.bytearray_from_char_ssize_t().decode() == "$%"
282  assert m.bytearray_from_char_size_t().decode() == "@$!"
283  assert m.bytearray_from_string().decode() == "foo"
284  assert m.bytearray_size() == len("foo")
285 
286 
287 def test_capsule(capture):
288  pytest.gc_collect()
289  with capture:
290  a = m.return_capsule_with_destructor()
291  del a
292  pytest.gc_collect()
293  assert (
294  capture.unordered
295  == """
296  creating capsule
297  destructing capsule
298  """
299  )
300 
301  with capture:
302  a = m.return_renamed_capsule_with_destructor()
303  del a
304  pytest.gc_collect()
305  assert (
306  capture.unordered
307  == """
308  creating capsule
309  renaming capsule
310  destructing capsule
311  """
312  )
313 
314  with capture:
315  a = m.return_capsule_with_destructor_2()
316  del a
317  pytest.gc_collect()
318  assert (
319  capture.unordered
320  == """
321  creating capsule
322  destructing capsule: 1234
323  """
324  )
325 
326  with capture:
327  a = m.return_capsule_with_destructor_3()
328  del a
329  pytest.gc_collect()
330  assert (
331  capture.unordered
332  == """
333  creating capsule
334  destructing capsule: 1233
335  original name: oname
336  """
337  )
338 
339  with capture:
340  a = m.return_renamed_capsule_with_destructor_2()
341  del a
342  pytest.gc_collect()
343  assert (
344  capture.unordered
345  == """
346  creating capsule
347  renaming capsule
348  destructing capsule: 1234
349  """
350  )
351 
352  with capture:
353  a = m.return_capsule_with_name_and_destructor()
354  del a
355  pytest.gc_collect()
356  assert (
357  capture.unordered
358  == """
359  created capsule (1234, 'pointer type description')
360  destructing capsule (1234, 'pointer type description')
361  """
362  )
363 
364  with capture:
365  a = m.return_capsule_with_explicit_nullptr_dtor()
366  del a
367  pytest.gc_collect()
368  assert (
369  capture.unordered
370  == """
371  creating capsule with explicit nullptr dtor
372  """
373  )
374 
375 
377  class SubTestObject:
378  attr_obj = 1
379  attr_char = 2
380 
381  class TestObject:
382  basic_attr = 1
383  begin_end = [1, 2, 3]
384  d = {"operator[object]": 1, "operator[char *]": 2}
385  sub = SubTestObject()
386 
387  def func(self, x, *args):
388  return self.basic_attr + x + sum(args)
389 
390  d = m.accessor_api(TestObject())
391  assert d["basic_attr"] == 1
392  assert d["begin_end"] == [1, 2, 3]
393  assert d["operator[object]"] == 1
394  assert d["operator[char *]"] == 2
395  assert d["attr(object)"] == 1
396  assert d["attr(char *)"] == 2
397  assert d["missing_attr_ptr"] == "raised"
398  assert d["missing_attr_chain"] == "raised"
399  assert d["is_none"] is False
400  assert d["operator()"] == 2
401  assert d["operator*"] == 7
402  assert d["implicit_list"] == [1, 2, 3]
403  assert all(x in TestObject.__dict__ for x in d["implicit_dict"])
404 
405  assert m.tuple_accessor(()) == (0, 1, 2)
406 
407  d = m.accessor_assignment()
408  assert d["get"] == 0
409  assert d["deferred_get"] == 0
410  assert d["set"] == 1
411  assert d["deferred_set"] == 1
412  assert d["var"] == 99
413 
414 
416  inc_refs = m.accessor_moves()
417  if inc_refs:
418  assert inc_refs == [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
419  else:
420  pytest.skip("Not defined: PYBIND11_HANDLE_REF_DEBUG")
421 
422 
424  """C++ default and converting constructors are equivalent to type calls in Python"""
425  types = [bytes, bytearray, str, bool, int, float, tuple, list, dict, set]
426  expected = {t.__name__: t() for t in types}
427  assert m.default_constructors() == expected
428 
429  data = {
430  bytes: b"41", # Currently no supported or working conversions.
431  bytearray: bytearray(b"41"),
432  str: 42,
433  bool: "Not empty",
434  int: "42",
435  float: "+1e3",
436  tuple: range(3),
437  list: range(3),
438  dict: [("two", 2), ("one", 1), ("three", 3)],
439  set: [4, 4, 5, 6, 6, 6],
440  frozenset: [4, 4, 5, 6, 6, 6],
441  memoryview: b"abc",
442  }
443  inputs = {k.__name__: v for k, v in data.items()}
444  expected = {k.__name__: k(v) for k, v in data.items()}
445 
446  assert m.converting_constructors(inputs) == expected
447  assert m.cast_functions(inputs) == expected
448 
449  # Converting constructors and cast functions should just reference rather
450  # than copy when no conversion is needed:
451  noconv1 = m.converting_constructors(expected)
452  for k in noconv1:
453  assert noconv1[k] is expected[k]
454 
455  noconv2 = m.cast_functions(expected)
456  for k in noconv2:
457  assert noconv2[k] is expected[k]
458 
459 
461  non_converting_test_cases = [
462  ("bytes", range(10)),
463  ("none", 42),
464  ("ellipsis", 42),
465  ("type", 42),
466  ]
467  for t, v in non_converting_test_cases:
468  for move in [True, False]:
469  with pytest.raises(TypeError) as excinfo:
470  m.nonconverting_constructor(t, v, move)
471  expected_error = (
472  f"Object of type '{type(v).__name__}' is not an instance of '{t}'"
473  )
474  assert str(excinfo.value) == expected_error
475 
476 
478  # specifically to exercise pybind11::str::raw_str
479  cvt = m.convert_to_pybind11_str
480  assert cvt("Str") == "Str"
481  assert cvt(b"Bytes") == "b'Bytes'"
482  assert cvt(None) == "None"
483  assert cvt(False) == "False"
484  assert cvt(True) == "True"
485  assert cvt(42) == "42"
486  assert cvt(2**65) == "36893488147419103232"
487  assert cvt(-1.50) == "-1.5"
488  assert cvt(()) == "()"
489  assert cvt((18,)) == "(18,)"
490  assert cvt([]) == "[]"
491  assert cvt([28]) == "[28]"
492  assert cvt({}) == "{}"
493  assert cvt({3: 4}) == "{3: 4}"
494  assert cvt(set()) == "set()"
495  assert cvt({3}) == "{3}"
496 
497  valid_orig = "DZ"
498  valid_utf8 = valid_orig.encode("utf-8")
499  valid_cvt = cvt(valid_utf8)
500  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
501  assert valid_cvt is valid_utf8
502  else:
503  assert type(valid_cvt) is str
504  assert valid_cvt == "b'\\xc7\\xb1'"
505 
506  malformed_utf8 = b"\x80"
507  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
508  assert cvt(malformed_utf8) is malformed_utf8
509  else:
510  malformed_cvt = cvt(malformed_utf8)
511  assert type(malformed_cvt) is str
512  assert malformed_cvt == "b'\\x80'"
513 
514 
516  """Tests implicit casting when assigning or appending to dicts and lists."""
517  z = m.get_implicit_casting()
518  assert z["d"] == {
519  "char*_i1": "abc",
520  "char*_i2": "abc",
521  "char*_e": "abc",
522  "char*_p": "abc",
523  "str_i1": "str",
524  "str_i2": "str1",
525  "str_e": "str2",
526  "str_p": "str3",
527  "int_i1": 42,
528  "int_i2": 42,
529  "int_e": 43,
530  "int_p": 44,
531  }
532  assert z["l"] == [3, 6, 9, 12, 15]
533 
534 
535 def test_print(capture):
536  with capture:
537  m.print_function()
538  assert (
539  capture
540  == """
541  Hello, World!
542  1 2.0 three True -- multiple args
543  *args-and-a-custom-separator
544  no new line here -- next print
545  flush
546  py::print + str.format = this
547  """
548  )
549  assert capture.stderr == "this goes to stderr"
550 
551  with pytest.raises(RuntimeError) as excinfo:
552  m.print_failure()
553  assert str(excinfo.value) == "Unable to convert call argument " + (
554  "'1' of type 'UnregisteredType' to Python object"
555  if detailed_error_messages_enabled
556  else "'1' to Python object (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)"
557  )
558 
559 
560 def test_hash():
561  class Hashable:
562  def __init__(self, value):
563  self.value = value
564 
565  def __hash__(self):
566  return self.value
567 
568  class Unhashable:
569  __hash__ = None
570 
571  assert m.hash_function(Hashable(42)) == 42
572  with pytest.raises(TypeError):
573  m.hash_function(Unhashable())
574 
575 
577  for a, b in [(1, 1), (3, 5)]:
578  li = [
579  a == b,
580  a != b,
581  a < b,
582  a <= b,
583  a > b,
584  a >= b,
585  a + b,
586  a - b,
587  a * b,
588  a / b,
589  a | b,
590  a & b,
591  a ^ b,
592  a >> b,
593  a << b,
594  ]
595  assert m.test_number_protocol(a, b) == li
596 
597 
599  li = list(range(100))
600  assert li[::2] == m.test_list_slicing(li)
601 
602 
604  # See issue #2361
605  assert m.issue2361_str_implicit_copy_none() == "None"
606  with pytest.raises(TypeError) as excinfo:
607  assert m.issue2361_dict_implicit_copy_none()
608  assert "NoneType" in str(excinfo.value)
609  assert "iterable" in str(excinfo.value)
610 
611 
612 @pytest.mark.parametrize(
613  ("method", "args", "fmt", "expected_view"),
614  [
615  (m.test_memoryview_object, (b"red",), "B", b"red"),
616  (m.test_memoryview_buffer_info, (b"green",), "B", b"green"),
617  (m.test_memoryview_from_buffer, (False,), "h", [3, 1, 4, 1, 5]),
618  (m.test_memoryview_from_buffer, (True,), "H", [2, 7, 1, 8]),
619  (m.test_memoryview_from_buffer_nativeformat, (), "@i", [4, 7, 5]),
620  ],
621 )
622 def test_memoryview(method, args, fmt, expected_view):
623  view = method(*args)
624  assert isinstance(view, memoryview)
625  assert view.format == fmt
626  assert list(view) == list(expected_view)
627 
628 
629 @pytest.mark.xfail("env.PYPY", reason="getrefcount is not available")
630 @pytest.mark.parametrize(
631  "method",
632  [
633  m.test_memoryview_object,
634  m.test_memoryview_buffer_info,
635  ],
636 )
638  # Avoiding a literal to avoid an immortal object in free-threaded builds
639  buf = "\x0a\x0b\x0c\x0d".encode("ascii")
640  ref_before = sys.getrefcount(buf)
641  view = method(buf)
642  ref_after = sys.getrefcount(buf)
643  assert ref_before < ref_after
644  assert list(view) == list(buf)
645 
646 
648  view = m.test_memoryview_from_buffer_empty_shape()
649  assert isinstance(view, memoryview)
650  assert view.format == "B"
651  assert bytes(view) == b""
652 
653 
655  with pytest.raises(RuntimeError):
656  m.test_memoryview_from_buffer_invalid_strides()
657 
658 
660  with pytest.raises(ValueError):
661  m.test_memoryview_from_buffer_nullptr()
662 
663 
665  view = m.test_memoryview_from_memory()
666  assert isinstance(view, memoryview)
667  assert view.format == "B"
668  assert bytes(view) == b"\xff\xe1\xab\x37"
669 
670 
672  assert m.get_len(list(range(42))) == 42
673  with pytest.raises(TypeError) as exc_info:
674  m.get_len(i for i in range(42))
675  assert str(exc_info.value) in [
676  "object of type 'generator' has no len()",
677  "'generator' has no length",
678  ] # PyPy
679 
680 
682  assert m.isinstance_pybind11_bytes(b"")
683  assert not m.isinstance_pybind11_bytes("")
684 
685  assert m.isinstance_pybind11_str("")
686  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
687  assert m.isinstance_pybind11_str(b"")
688  else:
689  assert not m.isinstance_pybind11_str(b"")
690 
691 
693  assert m.pass_to_pybind11_bytes(b"Bytes") == 5
694  with pytest.raises(TypeError):
695  m.pass_to_pybind11_bytes("Str")
696 
697  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
698  assert m.pass_to_pybind11_str(b"Bytes") == 5
699  else:
700  with pytest.raises(TypeError):
701  m.pass_to_pybind11_str(b"Bytes")
702  assert m.pass_to_pybind11_str("Str") == 3
703 
704  assert m.pass_to_std_string(b"Bytes") == 5
705  assert m.pass_to_std_string("Str") == 3
706 
707  malformed_utf8 = b"\x80"
708  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
709  assert m.pass_to_pybind11_str(malformed_utf8) == 1
710  else:
711  with pytest.raises(TypeError):
712  m.pass_to_pybind11_str(malformed_utf8)
713 
714 
715 @pytest.mark.parametrize(
716  ("create_weakref", "create_weakref_with_callback"),
717  [
718  (m.weakref_from_handle, m.weakref_from_handle_and_function),
719  (m.weakref_from_object, m.weakref_from_object_and_function),
720  ],
721 )
722 def test_weakref(create_weakref, create_weakref_with_callback):
723  from weakref import getweakrefcount
724 
725  # Apparently, you cannot weakly reference an object()
726  class WeaklyReferenced:
727  pass
728 
729  callback_called = False
730 
731  def callback(_):
732  nonlocal callback_called
733  callback_called = True
734 
735  obj = WeaklyReferenced()
736  assert getweakrefcount(obj) == 0
737  wr = create_weakref(obj)
738  assert getweakrefcount(obj) == 1
739 
740  obj = WeaklyReferenced()
741  assert getweakrefcount(obj) == 0
742  wr = create_weakref_with_callback(obj, callback) # noqa: F841
743  assert getweakrefcount(obj) == 1
744  assert not callback_called
745  del obj
746  pytest.gc_collect()
747  assert callback_called
748 
749 
750 @pytest.mark.parametrize(
751  ("create_weakref", "has_callback"),
752  [
753  (m.weakref_from_handle, False),
754  (m.weakref_from_object, False),
755  (m.weakref_from_handle_and_function, True),
756  (m.weakref_from_object_and_function, True),
757  ],
758 )
759 def test_weakref_err(create_weakref, has_callback):
760  class C:
761  __slots__ = []
762 
763  def callback(_):
764  pass
765 
766  ob = C()
767  # Should raise TypeError on CPython
768  with pytest.raises(TypeError) if not env.PYPY else contextlib.nullcontext():
769  _ = create_weakref(ob, callback) if has_callback else create_weakref(ob)
770 
771 
773  assert m.tuple_iterator() == 12
774  assert m.dict_iterator() == 305 + 711
775  assert m.passed_iterator(iter((-7, 3))) == -4
776 
777 
779  lst = [39, 43, 92, 49, 22, 29, 93, 98, 26, 57, 8]
780  tup = tuple(lst)
781  assert m.sequence_item_get_ssize_t(lst) == 43
782  assert m.sequence_item_set_ssize_t(lst) is None
783  assert lst[1] == "peppa"
784  assert m.sequence_item_get_size_t(lst) == 92
785  assert m.sequence_item_set_size_t(lst) is None
786  assert lst[2] == "george"
787  assert m.list_item_get_ssize_t(lst) == 49
788  assert m.list_item_set_ssize_t(lst) is None
789  assert lst[3] == "rebecca"
790  assert m.list_item_get_size_t(lst) == 22
791  assert m.list_item_set_size_t(lst) is None
792  assert lst[4] == "richard"
793  assert m.tuple_item_get_ssize_t(tup) == 29
794  assert m.tuple_item_set_ssize_t() == ("emely", "edmond")
795  assert m.tuple_item_get_size_t(tup) == 93
796  assert m.tuple_item_set_size_t() == ("candy", "cat")
797 
798 
800  r1 = m.square_float_(2.0)
801  assert r1 == 4.0
802 
803 
805  pop = 1000
806  tup = tuple(range(pop))
807  m.tuple_rvalue_getter(tup)
808 
809 
811  pop = 1000
812  my_list = list(range(pop))
813  m.list_rvalue_getter(my_list)
814 
815 
817  pop = 1000
818  my_dict = {i: i for i in range(pop)}
819  assert m.populate_dict_rvalue(pop) == my_dict
820 
821 
823  pop = 1000
824  o = types.SimpleNamespace(**{str(i): i for i in range(pop)})
825  new_o = m.populate_obj_str_attrs(o, pop)
826  new_attrs = {k: v for k, v in new_o.__dict__.items() if not k.startswith("_")}
827  assert all(isinstance(v, str) for v in new_attrs.values())
828  assert len(new_attrs) == pop
829 
830 
831 @pytest.mark.parametrize(
832  ("a", "b"),
833  [("foo", "bar"), (1, 2), (1.0, 2.0), (list(range(3)), list(range(3, 6)))],
834 )
836  expected = a + b
837  assert m.inplace_append(a, b) == expected
838 
839 
840 @pytest.mark.parametrize(
841  ("a", "b"), [(3, 2), (3.0, 2.0), (set(range(3)), set(range(2)))]
842 )
844  expected = a - b
845  assert m.inplace_subtract(a, b) == expected
846 
847 
848 @pytest.mark.parametrize(("a", "b"), [(3, 2), (3.0, 2.0), ([1], 3)])
850  expected = a * b
851  assert m.inplace_multiply(a, b) == expected
852 
853 
854 @pytest.mark.parametrize(("a", "b"), [(6, 3), (6.0, 3.0)])
856  expected = a / b
857  assert m.inplace_divide(a, b) == expected
858 
859 
860 @pytest.mark.parametrize(
861  ("a", "b"),
862  [
863  (False, True),
864  (
865  set(),
866  {
867  1,
868  },
869  ),
870  ],
871 )
872 def test_inplace_or(a, b):
873  expected = a | b
874  assert m.inplace_or(a, b) == expected
875 
876 
877 @pytest.mark.parametrize(
878  ("a", "b"),
879  [
880  (True, False),
881  (
882  {1, 2, 3},
883  {
884  1,
885  },
886  ),
887  ],
888 )
890  expected = a & b
891  assert m.inplace_and(a, b) == expected
892 
893 
894 @pytest.mark.parametrize(("a", "b"), [(8, 1), (-3, 2)])
896  expected = a << b
897  assert m.inplace_lshift(a, b) == expected
898 
899 
900 @pytest.mark.parametrize(("a", "b"), [(8, 1), (-2, 2)])
902  expected = a >> b
903  assert m.inplace_rshift(a, b) == expected
904 
905 
907  assert (
908  doc(m.annotate_tuple_float_str)
909  == "annotate_tuple_float_str(arg0: tuple[float, str]) -> None"
910  )
911 
912 
914  assert (
915  doc(m.annotate_tuple_empty) == "annotate_tuple_empty(arg0: tuple[()]) -> None"
916  )
917 
918 
920  assert (
921  doc(m.annotate_tuple_variable_length)
922  == "annotate_tuple_variable_length(arg0: tuple[float, ...]) -> None"
923  )
924 
925 
927  assert (
928  doc(m.annotate_dict_str_int)
929  == "annotate_dict_str_int(arg0: dict[str, int]) -> None"
930  )
931 
932 
934  assert doc(m.annotate_list_int) == "annotate_list_int(arg0: list[int]) -> None"
935 
936 
938  assert doc(m.annotate_set_str) == "annotate_set_str(arg0: set[str]) -> None"
939 
940 
942  assert (
943  doc(m.annotate_iterable_str)
944  == "annotate_iterable_str(arg0: Iterable[str]) -> None"
945  )
946 
947 
949  assert (
950  doc(m.annotate_iterator_int)
951  == "annotate_iterator_int(arg0: Iterator[int]) -> None"
952  )
953 
954 
956  assert (
957  doc(m.annotate_fn)
958  == "annotate_fn(arg0: Callable[[list[str], str], int]) -> None"
959  )
960 
961 
963  assert (
964  doc(m.annotate_fn_only_return)
965  == "annotate_fn_only_return(arg0: Callable[..., int]) -> None"
966  )
967 
968 
970  assert doc(m.annotate_type) == "annotate_type(arg0: type[int]) -> type"
971 
972 
974  assert (
975  doc(m.annotate_union)
976  == "annotate_union(arg0: list[Union[str, int, object]], arg1: str, arg2: int, arg3: object) -> list[Union[str, int, object]]"
977  )
978 
979 
981  assert (
982  doc(m.union_typing_only)
983  == "union_typing_only(arg0: list[Union[str]]) -> list[Union[int]]"
984  )
985 
986 
988  assert (
989  doc(m.annotate_union_to_object)
990  == "annotate_union_to_object(arg0: Union[int, str]) -> object"
991  )
992 
993 
995  assert (
996  doc(m.annotate_optional)
997  == "annotate_optional(arg0: list) -> list[Optional[str]]"
998  )
999 
1000 
1002  assert (
1003  doc(m.annotate_type_guard)
1004  == "annotate_type_guard(arg0: object) -> TypeGuard[str]"
1005  )
1006 
1007 
1009  assert doc(m.annotate_type_is) == "annotate_type_is(arg0: object) -> TypeIs[str]"
1010 
1011 
1013  assert doc(m.annotate_no_return) == "annotate_no_return() -> NoReturn"
1014 
1015 
1017  assert doc(m.annotate_never) == "annotate_never() -> Never"
1018 
1019 
1021  assert (
1022  doc(m.annotate_optional_to_object)
1023  == "annotate_optional_to_object(arg0: Optional[int]) -> object"
1024  )
1025 
1026 
1027 @pytest.mark.skipif(
1028  not m.if_defined__cpp_nontype_template_parameter_class,
1029  reason="C++20 feature not available.",
1030 )
1031 def test_literal(doc):
1032  assert (
1033  doc(m.annotate_literal)
1034  == 'annotate_literal(arg0: Literal[26, 0x1A, "hello world", b"hello world", u"hello world", True, Color.RED, None]) -> object'
1035  )
1036 
1037 
1038 @pytest.mark.skipif(
1039  not m.if_defined__cpp_nontype_template_parameter_class,
1040  reason="C++20 feature not available.",
1041 )
1042 def test_typevar(doc):
1043  assert (
1044  doc(m.annotate_generic_containers)
1045  == "annotate_generic_containers(arg0: list[T]) -> list[V]"
1046  )
1047 
1048  assert doc(m.annotate_listT_to_T) == "annotate_listT_to_T(arg0: list[T]) -> T"
1049 
1050  assert doc(m.annotate_object_to_T) == "annotate_object_to_T(arg0: object) -> T"
test_pytypes.test_dict_annotations
def test_dict_annotations(doc)
Definition: test_pytypes.py:926
test_pytypes.test_dict
def test_dict(capture, doc)
Definition: test_pytypes.py:156
test_pytypes.test_populate_dict_rvalue
def test_populate_dict_rvalue()
Definition: test_pytypes.py:816
test_pytypes.test_implicit_casting
def test_implicit_casting()
Definition: test_pytypes.py:515
test_pytypes.test_str
def test_str(doc)
Definition: test_pytypes.py:221
encode
int encode(Index i, Index j)
Definition: indexed_view.cpp:45
test_pytypes.test_obj_class_name
def test_obj_class_name()
Definition: test_pytypes.py:14
bytes
Definition: pytypes.h:1662
set
Definition: pytypes.h:2232
test_pytypes.test_iterator
def test_iterator(doc)
Definition: test_pytypes.py:33
test_pytypes.test_optional_object_annotations
def test_optional_object_annotations(doc)
Definition: test_pytypes.py:1020
test_pytypes.test_pybind11_str_raw_str
def test_pybind11_str_raw_str()
Definition: test_pytypes.py:477
test_pytypes.test_frozenset
def test_frozenset(capture, doc)
Definition: test_pytypes.py:131
list
Definition: pytypes.h:2166
test_pytypes.test_test_memoryview_from_buffer_invalid_strides
def test_test_memoryview_from_buffer_invalid_strides()
Definition: test_pytypes.py:654
test_pytypes.test_test_memoryview_from_buffer_nullptr
def test_test_memoryview_from_buffer_nullptr()
Definition: test_pytypes.py:659
test_pytypes.test_type_guard_annotations
def test_type_guard_annotations(doc)
Definition: test_pytypes.py:1001
test_pytypes.test_bytearray
def test_bytearray()
Definition: test_pytypes.py:280
test_pytypes.test_iterable_annotations
def test_iterable_annotations(doc)
Definition: test_pytypes.py:941
test_pytypes.test_typevar
def test_typevar(doc)
Definition: test_pytypes.py:1042
test_pytypes.test_inplace_or
def test_inplace_or(a, b)
Definition: test_pytypes.py:872
test_pytypes.test_populate_obj_str_attrs
def test_populate_obj_str_attrs()
Definition: test_pytypes.py:822
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:870
test_pytypes.test_optional_annotations
def test_optional_annotations(doc)
Definition: test_pytypes.py:994
test_pytypes.test_memoryview_refcount
def test_memoryview_refcount(method)
Definition: test_pytypes.py:637
type
Definition: pytypes.h:1525
test_pytypes.test_inplace_rshift
def test_inplace_rshift(a, b)
Definition: test_pytypes.py:901
test_pytypes.test_hash
def test_hash()
Definition: test_pytypes.py:560
test_pytypes.test_bool
def test_bool(doc)
Definition: test_pytypes.py:25
test_pytypes.CustomContains
Definition: test_pytypes.py:181
test_pytypes.test_union_typing_only
def test_union_typing_only(doc)
Definition: test_pytypes.py:980
test_pytypes.test_builtin_functions
def test_builtin_functions()
Definition: test_pytypes.py:671
test_pytypes.test_tuple
def test_tuple()
Definition: test_pytypes.py:206
test_pytypes.test_set_annotations
def test_set_annotations(doc)
Definition: test_pytypes.py:937
test_pytypes.test_list
def test_list(capture, doc)
Definition: test_pytypes.py:61
test_pytypes.test_tuple_empty_annotations
def test_tuple_empty_annotations(doc)
Definition: test_pytypes.py:913
test_pytypes.test_pass_bytes_or_unicode_to_string_types
def test_pass_bytes_or_unicode_to_string_types()
Definition: test_pytypes.py:692
test_pytypes.test_memoryview_from_memory
def test_memoryview_from_memory()
Definition: test_pytypes.py:664
test_pytypes.test_constructors
def test_constructors()
Definition: test_pytypes.py:423
test_pytypes.test_external_float_
def test_external_float_()
Definition: test_pytypes.py:799
test_pytypes.test_print
def test_print(capture)
Definition: test_pytypes.py:535
gtsam::range
Double_ range(const Point2_ &p, const Point2_ &q)
Definition: slam/expressions.h:30
test_pytypes.test_list_annotations
def test_list_annotations(doc)
Definition: test_pytypes.py:933
doc
Annotation for documentation.
Definition: attr.h:45
test_pytypes.test_unhashable_exceptions
def test_unhashable_exceptions(arg, func)
Definition: test_pytypes.py:197
A
Definition: test_numpy_dtypes.cpp:298
isinstance
bool isinstance(handle obj)
Definition: pytypes.h:842
test_pytypes.test_union_annotations
def test_union_annotations(doc)
Definition: test_pytypes.py:973
gtwrap.interface_parser.function.__repr__
str __repr__(self)
Definition: interface_parser/function.py:53
test_pytypes.CustomContains.d
d
Definition: test_pytypes.py:182
test_pytypes.test_set
def test_set(capture, doc)
Definition: test_pytypes.py:99
Eigen::all
static const Eigen::internal::all_t all
Definition: IndexedViewHelper.h:171
test_pytypes.test_implementation_details
def test_implementation_details()
Definition: test_pytypes.py:778
test_pytypes.test_never_annotation
def test_never_annotation(doc)
Definition: test_pytypes.py:1016
test_pytypes.test_cpp_iterators
def test_cpp_iterators()
Definition: test_pytypes.py:772
func
int func(const int &a)
Definition: testDSF.cpp:221
decode
IndexPair decode(Index ij)
Definition: indexed_view.cpp:49
test_pytypes.test_tuple_rvalue_getter
def test_tuple_rvalue_getter()
Definition: test_pytypes.py:804
test_pytypes.test_accessors
def test_accessors()
Definition: test_pytypes.py:376
test_pytypes.test_type_is_annotations
def test_type_is_annotations(doc)
Definition: test_pytypes.py:1008
bytearray
Definition: pytypes.h:1756
test_pytypes.test_inplace_lshift
def test_inplace_lshift(a, b)
Definition: test_pytypes.py:895
test_pytypes.test_literal
def test_literal(doc)
Definition: test_pytypes.py:1031
test_pytypes.test_handle_from_move_only_type_with_operator_PyObject
def test_handle_from_move_only_type_with_operator_PyObject()
Definition: test_pytypes.py:20
test_pytypes.test_int
def test_int(doc)
Definition: test_pytypes.py:29
gtwrap.interface_parser.function.__init__
def __init__(self, Union[Type, TemplatedType] ctype, str name, ParseResults default=None)
Definition: interface_parser/function.py:41
test_pytypes.test_accessor_moves
def test_accessor_moves()
Definition: test_pytypes.py:415
test_pytypes.test_none
def test_none(doc)
Definition: test_pytypes.py:94
str
Definition: pytypes.h:1558
test_pytypes.test_tuple_nonempty_annotations
def test_tuple_nonempty_annotations(doc)
Definition: test_pytypes.py:906
test_pytypes.test_list_rvalue_getter
def test_list_rvalue_getter()
Definition: test_pytypes.py:810
test_pytypes.test_bytes
def test_bytes(doc)
Definition: test_pytypes.py:271
C
Matrix< Scalar, Dynamic, Dynamic > C
Definition: bench_gemm.cpp:50
test_pytypes.test_weakref_err
def test_weakref_err(create_weakref, has_callback)
Definition: test_pytypes.py:759
test_pytypes.test_weakref
def test_weakref(create_weakref, create_weakref_with_callback)
Definition: test_pytypes.py:722
test_pytypes.test_inplace_and
def test_inplace_and(a, b)
Definition: test_pytypes.py:889
test_pytypes.test_from_iterable
def test_from_iterable(pytype, from_iter_func)
Definition: test_pytypes.py:46
iter
iterator iter(handle obj)
Definition: pytypes.h:2475
test_pytypes.test_tuple_variable_length_annotations
def test_tuple_variable_length_annotations(doc)
Definition: test_pytypes.py:919
tuple
Definition: pytypes.h:2077
test_pytypes.test_simple_namespace
def test_simple_namespace()
Definition: test_pytypes.py:213
test_pytypes.test_inplace_divide
def test_inplace_divide(a, b)
Definition: test_pytypes.py:855
test_pytypes.test_iterator_annotations
def test_iterator_annotations(doc)
Definition: test_pytypes.py:948
test_pytypes.test_memoryview_from_buffer_empty_shape
def test_memoryview_from_buffer_empty_shape()
Definition: test_pytypes.py:647
test_pytypes.test_inplace_append
def test_inplace_append(a, b)
Definition: test_pytypes.py:835
test_pytypes.CustomContains.__contains__
def __contains__(self, m)
Definition: test_pytypes.py:184
test_pytypes.test_iterable
def test_iterable(doc)
Definition: test_pytypes.py:53
test_pytypes.test_memoryview
def test_memoryview(method, args, fmt, expected_view)
Definition: test_pytypes.py:622
test_pytypes.test_float
def test_float(doc)
Definition: test_pytypes.py:57
test_pytypes.test_inplace_multiply
def test_inplace_multiply(a, b)
Definition: test_pytypes.py:849
len
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2446
test_pytypes.test_type_annotation
def test_type_annotation(doc)
Definition: test_pytypes.py:969
test_pytypes.test_fn_return_only
def test_fn_return_only(doc)
Definition: test_pytypes.py:962
test_pytypes.test_fn_annotations
def test_fn_annotations(doc)
Definition: test_pytypes.py:955
func
Definition: benchGeometry.cpp:23
test_pytypes.test_non_converting_constructors
def test_non_converting_constructors()
Definition: test_pytypes.py:460
align_3::t
Point2 t(10, 10)
frozenset
Definition: pytypes.h:2247
test_pytypes.test_surrogate_pairs_unicode_error
def test_surrogate_pairs_unicode_error(func)
Definition: test_pytypes.py:265
test_pytypes.test_list_slicing
def test_list_slicing()
Definition: test_pytypes.py:598
test_pytypes.test_no_return_annotation
def test_no_return_annotation(doc)
Definition: test_pytypes.py:1012
test_pytypes.test_inplace_subtract
def test_inplace_subtract(a, b)
Definition: test_pytypes.py:843
test_pytypes.test_isinstance_string_types
def test_isinstance_string_types()
Definition: test_pytypes.py:681
test_pytypes.test_number_protocol
def test_number_protocol()
Definition: test_pytypes.py:576
test_pytypes.test_capsule
def test_capsule(capture)
Definition: test_pytypes.py:287
test_pytypes.test_issue2361
def test_issue2361()
Definition: test_pytypes.py:603
test_pytypes.test_union_object_annotations
def test_union_object_annotations(doc)
Definition: test_pytypes.py:987


gtsam
Author(s):
autogenerated on Sat Nov 16 2024 04:07:05