Publish sealed evaluation sources, batch 24
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_trampoline_shared_from_this.py +247 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_trampoline_shared_ptr_cpp_arg.cpp +92 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_trampoline_shared_ptr_cpp_arg.py +154 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_trampoline_unique_ptr.cpp +63 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_trampoline_unique_ptr.py +31 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_unique_ptr_custom_deleter.cpp +30 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_unique_ptr_custom_deleter.py +8 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_unique_ptr_member.cpp +50 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_unique_ptr_member.py +26 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_virtual_py_cpp_mix.cpp +58 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_virtual_py_cpp_mix.py +66 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/CMakeLists.txt +91 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/embed.cpp +23 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/installed_embed/CMakeLists.txt +19 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/installed_function/CMakeLists.txt +29 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/installed_target/CMakeLists.txt +37 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/main.cpp +6 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/subdirectory_embed/CMakeLists.txt +38 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/subdirectory_function/CMakeLists.txt +32 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/subdirectory_target/CMakeLists.txt +38 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/test.py +10 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_const_name.cpp +55 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_const_name.py +31 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_constants_and_functions.cpp +158 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_constants_and_functions.py +58 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_copy_move.cpp +546 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_copy_move.py +144 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cpp_conduit.cpp +22 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cpp_conduit.py +183 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cpp_conduit_traveler_bindings.h +47 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cpp_conduit_traveler_types.h +25 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/CMakeLists.txt +68 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/bindings.cpp +20 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/catch.cpp +22 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/lib.cpp +13 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/lib.h +31 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/test_cross_module_rtti.cpp +50 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_custom_type_casters.cpp +217 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_custom_type_casters.py +126 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_custom_type_setup.cpp +49 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_custom_type_setup.py +50 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_docs_advanced_cast_custom.cpp +69 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_docs_advanced_cast_custom.py +40 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_docstring_options.cpp +129 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_docstring_options.py +72 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_eigen_matrix.cpp +448 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_eigen_matrix.py +839 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_eigen_tensor.cpp +18 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_eigen_tensor.inl +338 -0
- third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_eigen_tensor.py +316 -0
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_trampoline_shared_from_this.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import weakref
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
import env
|
| 9 |
+
import pybind11_tests.class_sh_trampoline_shared_from_this as m
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class PySft(m.Sft):
|
| 13 |
+
pass
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_release_and_shared_from_this():
|
| 17 |
+
# Exercises the most direct path from building a shared_from_this-visible
|
| 18 |
+
# shared_ptr to calling shared_from_this.
|
| 19 |
+
obj = PySft("PySft")
|
| 20 |
+
assert obj.history == "PySft"
|
| 21 |
+
assert m.use_count(obj) == 1
|
| 22 |
+
assert m.pass_shared_ptr(obj) == 2
|
| 23 |
+
assert obj.history == "PySft_PassSharedPtr"
|
| 24 |
+
assert m.use_count(obj) == 1
|
| 25 |
+
assert m.pass_shared_ptr(obj) == 2
|
| 26 |
+
assert obj.history == "PySft_PassSharedPtr_PassSharedPtr"
|
| 27 |
+
assert m.use_count(obj) == 1
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_release_and_shared_from_this_leak():
|
| 31 |
+
obj = PySft("")
|
| 32 |
+
while True:
|
| 33 |
+
m.pass_shared_ptr(obj)
|
| 34 |
+
assert not obj.history
|
| 35 |
+
assert m.use_count(obj) == 1
|
| 36 |
+
break # Comment out for manual leak checking (use `top` command).
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_release_and_stash():
|
| 40 |
+
# Exercises correct functioning of guarded_delete weak_ptr.
|
| 41 |
+
obj = PySft("PySft")
|
| 42 |
+
stash1 = m.SftSharedPtrStash(1)
|
| 43 |
+
stash1.Add(obj)
|
| 44 |
+
exp_hist = "PySft_Stash1Add"
|
| 45 |
+
assert obj.history == exp_hist
|
| 46 |
+
assert m.use_count(obj) == 2
|
| 47 |
+
assert stash1.history(0) == exp_hist
|
| 48 |
+
assert stash1.use_count(0) == 1
|
| 49 |
+
assert m.pass_shared_ptr(obj) == 3
|
| 50 |
+
exp_hist += "_PassSharedPtr"
|
| 51 |
+
assert obj.history == exp_hist
|
| 52 |
+
assert m.use_count(obj) == 2
|
| 53 |
+
assert stash1.history(0) == exp_hist
|
| 54 |
+
assert stash1.use_count(0) == 1
|
| 55 |
+
stash2 = m.SftSharedPtrStash(2)
|
| 56 |
+
stash2.Add(obj)
|
| 57 |
+
exp_hist += "_Stash2Add"
|
| 58 |
+
assert obj.history == exp_hist
|
| 59 |
+
assert m.use_count(obj) == 3
|
| 60 |
+
assert stash2.history(0) == exp_hist
|
| 61 |
+
assert stash2.use_count(0) == 2
|
| 62 |
+
stash2.Add(obj)
|
| 63 |
+
exp_hist += "_Stash2Add"
|
| 64 |
+
assert obj.history == exp_hist
|
| 65 |
+
assert m.use_count(obj) == 4
|
| 66 |
+
assert stash1.history(0) == exp_hist
|
| 67 |
+
assert stash1.use_count(0) == 3
|
| 68 |
+
assert stash2.history(0) == exp_hist
|
| 69 |
+
assert stash2.use_count(0) == 3
|
| 70 |
+
assert stash2.history(1) == exp_hist
|
| 71 |
+
assert stash2.use_count(1) == 3
|
| 72 |
+
del obj
|
| 73 |
+
assert stash2.history(0) == exp_hist
|
| 74 |
+
assert stash2.use_count(0) == 3
|
| 75 |
+
assert stash2.history(1) == exp_hist
|
| 76 |
+
assert stash2.use_count(1) == 3
|
| 77 |
+
stash2.Clear()
|
| 78 |
+
assert stash1.history(0) == exp_hist
|
| 79 |
+
assert stash1.use_count(0) == 1
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_release_and_stash_leak():
|
| 83 |
+
obj = PySft("")
|
| 84 |
+
while True:
|
| 85 |
+
stash1 = m.SftSharedPtrStash(1)
|
| 86 |
+
stash1.Add(obj)
|
| 87 |
+
assert not obj.history
|
| 88 |
+
assert m.use_count(obj) == 2
|
| 89 |
+
assert stash1.use_count(0) == 1
|
| 90 |
+
stash1.Add(obj)
|
| 91 |
+
assert not obj.history
|
| 92 |
+
assert m.use_count(obj) == 3
|
| 93 |
+
assert stash1.use_count(0) == 2
|
| 94 |
+
assert stash1.use_count(1) == 2
|
| 95 |
+
break # Comment out for manual leak checking (use `top` command).
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_release_and_stash_via_shared_from_this():
|
| 99 |
+
# Exercises that the smart_holder vptr is invisible to the shared_from_this mechanism.
|
| 100 |
+
obj = PySft("PySft")
|
| 101 |
+
stash1 = m.SftSharedPtrStash(1)
|
| 102 |
+
with pytest.raises(RuntimeError) as exc_info:
|
| 103 |
+
stash1.AddSharedFromThis(obj)
|
| 104 |
+
assert str(exc_info.value) == "bad_weak_ptr"
|
| 105 |
+
stash1.Add(obj)
|
| 106 |
+
assert obj.history == "PySft_Stash1Add"
|
| 107 |
+
assert stash1.use_count(0) == 1
|
| 108 |
+
stash1.AddSharedFromThis(obj)
|
| 109 |
+
assert obj.history == "PySft_Stash1Add_Stash1AddSharedFromThis"
|
| 110 |
+
assert stash1.use_count(0) == 2
|
| 111 |
+
assert stash1.use_count(1) == 2
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def test_release_and_stash_via_shared_from_this_leak():
|
| 115 |
+
obj = PySft("")
|
| 116 |
+
while True:
|
| 117 |
+
stash1 = m.SftSharedPtrStash(1)
|
| 118 |
+
with pytest.raises(RuntimeError) as exc_info:
|
| 119 |
+
stash1.AddSharedFromThis(obj)
|
| 120 |
+
assert str(exc_info.value) == "bad_weak_ptr"
|
| 121 |
+
stash1.Add(obj)
|
| 122 |
+
assert not obj.history
|
| 123 |
+
assert stash1.use_count(0) == 1
|
| 124 |
+
stash1.AddSharedFromThis(obj)
|
| 125 |
+
assert not obj.history
|
| 126 |
+
assert stash1.use_count(0) == 2
|
| 127 |
+
assert stash1.use_count(1) == 2
|
| 128 |
+
break # Comment out for manual leak checking (use `top` command).
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def test_pass_released_shared_ptr_as_unique_ptr():
|
| 132 |
+
# Exercises that returning a unique_ptr fails while a shared_from_this
|
| 133 |
+
# visible shared_ptr exists.
|
| 134 |
+
obj = PySft("PySft")
|
| 135 |
+
stash1 = m.SftSharedPtrStash(1)
|
| 136 |
+
stash1.Add(obj) # Releases shared_ptr to C++.
|
| 137 |
+
assert m.pass_unique_ptr_cref(obj) == "PySft_Stash1Add"
|
| 138 |
+
assert obj.history == "PySft_Stash1Add"
|
| 139 |
+
with pytest.raises(ValueError) as exc_info:
|
| 140 |
+
m.pass_unique_ptr_rref(obj)
|
| 141 |
+
assert str(exc_info.value) == (
|
| 142 |
+
"Python instance is currently owned by a std::shared_ptr."
|
| 143 |
+
)
|
| 144 |
+
assert obj.history == "PySft_Stash1Add"
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@pytest.mark.parametrize(
|
| 148 |
+
"make_f",
|
| 149 |
+
[
|
| 150 |
+
m.make_pure_cpp_sft_raw_ptr,
|
| 151 |
+
m.make_pure_cpp_sft_unq_ptr,
|
| 152 |
+
m.make_pure_cpp_sft_shd_ptr,
|
| 153 |
+
],
|
| 154 |
+
)
|
| 155 |
+
def test_pure_cpp_sft_raw_ptr(make_f):
|
| 156 |
+
# Exercises void_cast_raw_ptr logic for different situations.
|
| 157 |
+
obj = make_f("PureCppSft")
|
| 158 |
+
assert m.pass_shared_ptr(obj) == 3
|
| 159 |
+
assert obj.history == "PureCppSft_PassSharedPtr"
|
| 160 |
+
obj = make_f("PureCppSft")
|
| 161 |
+
stash1 = m.SftSharedPtrStash(1)
|
| 162 |
+
stash1.AddSharedFromThis(obj)
|
| 163 |
+
assert obj.history == "PureCppSft_Stash1AddSharedFromThis"
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_multiple_registered_instances_for_same_pointee():
|
| 167 |
+
obj0 = PySft("PySft")
|
| 168 |
+
obj0.attachment_in_dict = "Obj0"
|
| 169 |
+
assert m.pass_through_shd_ptr(obj0) is obj0
|
| 170 |
+
while True:
|
| 171 |
+
obj = m.Sft(obj0)
|
| 172 |
+
assert obj is not obj0
|
| 173 |
+
obj_pt = m.pass_through_shd_ptr(obj)
|
| 174 |
+
# Unpredictable! Because registered_instances is as std::unordered_multimap.
|
| 175 |
+
assert obj_pt is obj0 or obj_pt is obj
|
| 176 |
+
# Multiple registered_instances for the same pointee can lead to unpredictable results:
|
| 177 |
+
if obj_pt is obj0:
|
| 178 |
+
assert obj_pt.attachment_in_dict == "Obj0"
|
| 179 |
+
else:
|
| 180 |
+
assert not hasattr(obj_pt, "attachment_in_dict")
|
| 181 |
+
assert obj0.history == "PySft"
|
| 182 |
+
break # Comment out for manual leak checking (use `top` command).
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def test_multiple_registered_instances_for_same_pointee_leak():
|
| 186 |
+
obj0 = PySft("")
|
| 187 |
+
while True:
|
| 188 |
+
stash1 = m.SftSharedPtrStash(1)
|
| 189 |
+
stash1.Add(m.Sft(obj0))
|
| 190 |
+
assert stash1.use_count(0) == 1
|
| 191 |
+
stash1.Add(m.Sft(obj0))
|
| 192 |
+
assert stash1.use_count(0) == 1
|
| 193 |
+
assert stash1.use_count(1) == 1
|
| 194 |
+
assert not obj0.history
|
| 195 |
+
break # Comment out for manual leak checking (use `top` command).
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def test_multiple_registered_instances_for_same_pointee_recursive():
|
| 199 |
+
while True:
|
| 200 |
+
obj0 = PySft("PySft")
|
| 201 |
+
if not env.PYPY:
|
| 202 |
+
obj0_wr = weakref.ref(obj0)
|
| 203 |
+
obj = obj0
|
| 204 |
+
# This loop creates a chain of instances linked by shared_ptrs.
|
| 205 |
+
for _ in range(10):
|
| 206 |
+
obj_next = m.Sft(obj)
|
| 207 |
+
assert obj_next is not obj
|
| 208 |
+
obj = obj_next
|
| 209 |
+
del obj_next
|
| 210 |
+
assert obj.history == "PySft"
|
| 211 |
+
del obj0
|
| 212 |
+
if not env.PYPY and not env.GRAALPY:
|
| 213 |
+
assert obj0_wr() is not None
|
| 214 |
+
del obj # This releases the chain recursively.
|
| 215 |
+
if not env.PYPY and not env.GRAALPY:
|
| 216 |
+
assert obj0_wr() is None
|
| 217 |
+
break # Comment out for manual leak checking (use `top` command).
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# As of 2021-07-10 the pybind11 GitHub Actions valgrind build uses Python 3.9.
|
| 221 |
+
WORKAROUND_ENABLING_ROLLBACK_OF_PR3068 = env.LINUX and sys.version_info == (3, 9)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def test_std_make_shared_factory():
|
| 225 |
+
class PySftMakeShared(m.Sft):
|
| 226 |
+
def __init__(self, history):
|
| 227 |
+
super().__init__(history, 0)
|
| 228 |
+
|
| 229 |
+
obj = PySftMakeShared("PySftMakeShared")
|
| 230 |
+
assert obj.history == "PySftMakeShared"
|
| 231 |
+
if WORKAROUND_ENABLING_ROLLBACK_OF_PR3068:
|
| 232 |
+
try:
|
| 233 |
+
m.pass_through_shd_ptr(obj)
|
| 234 |
+
except RuntimeError as e:
|
| 235 |
+
str_exc_info_value = str(e)
|
| 236 |
+
else:
|
| 237 |
+
str_exc_info_value = "RuntimeError NOT RAISED"
|
| 238 |
+
else:
|
| 239 |
+
with pytest.raises(RuntimeError) as exc_info:
|
| 240 |
+
m.pass_through_shd_ptr(obj)
|
| 241 |
+
str_exc_info_value = str(exc_info.value)
|
| 242 |
+
assert (
|
| 243 |
+
str_exc_info_value
|
| 244 |
+
== "smart_holder_type_casters load_as_shared_ptr failure: not implemented:"
|
| 245 |
+
" trampoline-self-life-support for external shared_ptr to type inheriting"
|
| 246 |
+
" from std::enable_shared_from_this."
|
| 247 |
+
)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_trampoline_shared_ptr_cpp_arg.cpp
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright (c) 2021 The Pybind Development Team.
|
| 2 |
+
// All rights reserved. Use of this source code is governed by a
|
| 3 |
+
// BSD-style license that can be found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
#include "pybind11_tests.h"
|
| 6 |
+
|
| 7 |
+
#include <utility>
|
| 8 |
+
|
| 9 |
+
namespace pybind11_tests {
|
| 10 |
+
namespace class_sh_trampoline_shared_ptr_cpp_arg {
|
| 11 |
+
|
| 12 |
+
// For testing whether a python subclass of a C++ object dies when the
|
| 13 |
+
// last python reference is lost
|
| 14 |
+
struct SpBase {
|
| 15 |
+
// returns true if the base virtual function is called
|
| 16 |
+
virtual bool is_base_used() { return true; }
|
| 17 |
+
|
| 18 |
+
// returns true if there's an associated python instance
|
| 19 |
+
bool has_python_instance() {
|
| 20 |
+
auto *tinfo = py::detail::get_type_info(typeid(SpBase));
|
| 21 |
+
return (bool) py::detail::get_object_handle(this, tinfo);
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
SpBase() = default;
|
| 25 |
+
SpBase(const SpBase &) = delete;
|
| 26 |
+
virtual ~SpBase() = default;
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
std::shared_ptr<SpBase> pass_through_shd_ptr(const std::shared_ptr<SpBase> &obj) { return obj; }
|
| 30 |
+
|
| 31 |
+
struct PySpBase : SpBase, py::trampoline_self_life_support {
|
| 32 |
+
using SpBase::SpBase;
|
| 33 |
+
bool is_base_used() override { PYBIND11_OVERRIDE(bool, SpBase, is_base_used); }
|
| 34 |
+
};
|
| 35 |
+
|
| 36 |
+
struct SpBaseTester {
|
| 37 |
+
std::shared_ptr<SpBase> get_object() const { return m_obj; }
|
| 38 |
+
void set_object(std::shared_ptr<SpBase> obj) { m_obj = std::move(obj); }
|
| 39 |
+
bool is_base_used() { return m_obj->is_base_used(); }
|
| 40 |
+
bool has_instance() { return (bool) m_obj; }
|
| 41 |
+
bool has_python_instance() { return m_obj && m_obj->has_python_instance(); }
|
| 42 |
+
void set_nonpython_instance() { m_obj = std::make_shared<SpBase>(); }
|
| 43 |
+
std::shared_ptr<SpBase> m_obj;
|
| 44 |
+
};
|
| 45 |
+
|
| 46 |
+
// For testing that a C++ class without an alias does not retain the python
|
| 47 |
+
// portion of the object
|
| 48 |
+
struct SpGoAway {};
|
| 49 |
+
|
| 50 |
+
struct SpGoAwayTester {
|
| 51 |
+
std::shared_ptr<SpGoAway> m_obj;
|
| 52 |
+
};
|
| 53 |
+
|
| 54 |
+
} // namespace class_sh_trampoline_shared_ptr_cpp_arg
|
| 55 |
+
} // namespace pybind11_tests
|
| 56 |
+
|
| 57 |
+
using namespace pybind11_tests::class_sh_trampoline_shared_ptr_cpp_arg;
|
| 58 |
+
|
| 59 |
+
TEST_SUBMODULE(class_sh_trampoline_shared_ptr_cpp_arg, m) {
|
| 60 |
+
// For testing whether a python subclass of a C++ object dies when the
|
| 61 |
+
// last python reference is lost
|
| 62 |
+
|
| 63 |
+
py::classh<SpBase, PySpBase>(m, "SpBase")
|
| 64 |
+
.def(py::init<>())
|
| 65 |
+
.def(py::init([](int) { return std::make_shared<PySpBase>(); }))
|
| 66 |
+
.def("is_base_used", &SpBase::is_base_used)
|
| 67 |
+
.def("has_python_instance", &SpBase::has_python_instance);
|
| 68 |
+
|
| 69 |
+
m.def("pass_through_shd_ptr", pass_through_shd_ptr);
|
| 70 |
+
m.def("pass_through_shd_ptr_release_gil",
|
| 71 |
+
pass_through_shd_ptr,
|
| 72 |
+
py::call_guard<py::gil_scoped_release>()); // PR #4196
|
| 73 |
+
|
| 74 |
+
py::classh<SpBaseTester>(m, "SpBaseTester")
|
| 75 |
+
.def(py::init<>())
|
| 76 |
+
.def("get_object", &SpBaseTester::get_object)
|
| 77 |
+
.def("set_object", &SpBaseTester::set_object)
|
| 78 |
+
.def("is_base_used", &SpBaseTester::is_base_used)
|
| 79 |
+
.def("has_instance", &SpBaseTester::has_instance)
|
| 80 |
+
.def("has_python_instance", &SpBaseTester::has_python_instance)
|
| 81 |
+
.def("set_nonpython_instance", &SpBaseTester::set_nonpython_instance)
|
| 82 |
+
.def_readwrite("obj", &SpBaseTester::m_obj);
|
| 83 |
+
|
| 84 |
+
// For testing that a C++ class without an alias does not retain the python
|
| 85 |
+
// portion of the object
|
| 86 |
+
|
| 87 |
+
py::classh<SpGoAway>(m, "SpGoAway").def(py::init<>());
|
| 88 |
+
|
| 89 |
+
py::classh<SpGoAwayTester>(m, "SpGoAwayTester")
|
| 90 |
+
.def(py::init<>())
|
| 91 |
+
.def_readwrite("obj", &SpGoAwayTester::m_obj);
|
| 92 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_trampoline_shared_ptr_cpp_arg.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import env # noqa: F401
|
| 6 |
+
import pybind11_tests.class_sh_trampoline_shared_ptr_cpp_arg as m
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Cannot reliably trigger GC")
|
| 10 |
+
def test_shared_ptr_cpp_arg():
|
| 11 |
+
import weakref
|
| 12 |
+
|
| 13 |
+
class PyChild(m.SpBase):
|
| 14 |
+
def is_base_used(self):
|
| 15 |
+
return False
|
| 16 |
+
|
| 17 |
+
tester = m.SpBaseTester()
|
| 18 |
+
|
| 19 |
+
obj = PyChild()
|
| 20 |
+
objref = weakref.ref(obj)
|
| 21 |
+
|
| 22 |
+
# Pass the last python reference to the C++ function
|
| 23 |
+
tester.set_object(obj)
|
| 24 |
+
del obj
|
| 25 |
+
pytest.gc_collect()
|
| 26 |
+
|
| 27 |
+
# python reference is still around since C++ has it now
|
| 28 |
+
assert objref() is not None
|
| 29 |
+
assert tester.is_base_used() is False
|
| 30 |
+
assert tester.obj.is_base_used() is False
|
| 31 |
+
assert tester.get_object() is objref()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Cannot reliably trigger GC")
|
| 35 |
+
def test_shared_ptr_cpp_prop():
|
| 36 |
+
class PyChild(m.SpBase):
|
| 37 |
+
def is_base_used(self):
|
| 38 |
+
return False
|
| 39 |
+
|
| 40 |
+
tester = m.SpBaseTester()
|
| 41 |
+
|
| 42 |
+
# Set the last python reference as a property of the C++ object
|
| 43 |
+
tester.obj = PyChild()
|
| 44 |
+
pytest.gc_collect()
|
| 45 |
+
|
| 46 |
+
# python reference is still around since C++ has it now
|
| 47 |
+
assert tester.is_base_used() is False
|
| 48 |
+
assert tester.has_python_instance() is True
|
| 49 |
+
assert tester.obj.is_base_used() is False
|
| 50 |
+
assert tester.obj.has_python_instance() is True
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Cannot reliably trigger GC")
|
| 54 |
+
def test_shared_ptr_arg_identity():
|
| 55 |
+
import weakref
|
| 56 |
+
|
| 57 |
+
tester = m.SpBaseTester()
|
| 58 |
+
|
| 59 |
+
obj = m.SpBase()
|
| 60 |
+
objref = weakref.ref(obj)
|
| 61 |
+
|
| 62 |
+
tester.set_object(obj)
|
| 63 |
+
del obj
|
| 64 |
+
pytest.gc_collect()
|
| 65 |
+
|
| 66 |
+
# NOTE: the behavior below is DIFFERENT from PR #2839
|
| 67 |
+
# python reference is gone because it is not an Alias instance
|
| 68 |
+
assert objref() is None
|
| 69 |
+
assert tester.has_python_instance() is False
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Cannot reliably trigger GC")
|
| 73 |
+
def test_shared_ptr_alias_nonpython():
|
| 74 |
+
tester = m.SpBaseTester()
|
| 75 |
+
|
| 76 |
+
# C++ creates the object, a python instance shouldn't exist
|
| 77 |
+
tester.set_nonpython_instance()
|
| 78 |
+
assert tester.is_base_used() is True
|
| 79 |
+
assert tester.has_instance() is True
|
| 80 |
+
assert tester.has_python_instance() is False
|
| 81 |
+
|
| 82 |
+
# Now a python instance exists
|
| 83 |
+
cobj = tester.get_object()
|
| 84 |
+
assert cobj.has_python_instance()
|
| 85 |
+
assert tester.has_instance() is True
|
| 86 |
+
assert tester.has_python_instance() is True
|
| 87 |
+
|
| 88 |
+
# Now it's gone
|
| 89 |
+
del cobj
|
| 90 |
+
pytest.gc_collect()
|
| 91 |
+
assert tester.has_instance() is True
|
| 92 |
+
assert tester.has_python_instance() is False
|
| 93 |
+
|
| 94 |
+
# When we pass it as an arg to a new tester the python instance should
|
| 95 |
+
# disappear because it wasn't created with an alias
|
| 96 |
+
new_tester = m.SpBaseTester()
|
| 97 |
+
|
| 98 |
+
cobj = tester.get_object()
|
| 99 |
+
assert cobj.has_python_instance()
|
| 100 |
+
|
| 101 |
+
new_tester.set_object(cobj)
|
| 102 |
+
assert tester.has_python_instance() is True
|
| 103 |
+
assert new_tester.has_python_instance() is True
|
| 104 |
+
|
| 105 |
+
del cobj
|
| 106 |
+
pytest.gc_collect()
|
| 107 |
+
|
| 108 |
+
# Gone!
|
| 109 |
+
assert tester.has_instance() is True
|
| 110 |
+
assert tester.has_python_instance() is False
|
| 111 |
+
assert new_tester.has_instance() is True
|
| 112 |
+
assert new_tester.has_python_instance() is False
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Cannot reliably trigger GC")
|
| 116 |
+
def test_shared_ptr_goaway():
|
| 117 |
+
import weakref
|
| 118 |
+
|
| 119 |
+
tester = m.SpGoAwayTester()
|
| 120 |
+
|
| 121 |
+
obj = m.SpGoAway()
|
| 122 |
+
objref = weakref.ref(obj)
|
| 123 |
+
|
| 124 |
+
assert tester.obj is None
|
| 125 |
+
|
| 126 |
+
tester.obj = obj
|
| 127 |
+
del obj
|
| 128 |
+
pytest.gc_collect()
|
| 129 |
+
|
| 130 |
+
# python reference is no longer around
|
| 131 |
+
assert objref() is None
|
| 132 |
+
# C++ reference is still around
|
| 133 |
+
assert tester.obj is not None
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def test_infinite():
|
| 137 |
+
tester = m.SpBaseTester()
|
| 138 |
+
while True:
|
| 139 |
+
tester.set_object(m.SpBase())
|
| 140 |
+
break # Comment out for manual leak checking (use `top` command).
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@pytest.mark.parametrize(
|
| 144 |
+
"pass_through_func", [m.pass_through_shd_ptr, m.pass_through_shd_ptr_release_gil]
|
| 145 |
+
)
|
| 146 |
+
def test_std_make_shared_factory(pass_through_func):
|
| 147 |
+
class PyChild(m.SpBase):
|
| 148 |
+
def __init__(self):
|
| 149 |
+
super().__init__(0)
|
| 150 |
+
|
| 151 |
+
obj = PyChild()
|
| 152 |
+
while True:
|
| 153 |
+
assert pass_through_func(obj) is obj
|
| 154 |
+
break # Comment out for manual leak checking (use `top` command).
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_trampoline_unique_ptr.cpp
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright (c) 2021 The Pybind Development Team.
|
| 2 |
+
// All rights reserved. Use of this source code is governed by a
|
| 3 |
+
// BSD-style license that can be found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
#include "pybind11/trampoline_self_life_support.h"
|
| 6 |
+
#include "pybind11_tests.h"
|
| 7 |
+
|
| 8 |
+
#include <cstdint>
|
| 9 |
+
|
| 10 |
+
namespace pybind11_tests {
|
| 11 |
+
namespace class_sh_trampoline_unique_ptr {
|
| 12 |
+
|
| 13 |
+
class Class {
|
| 14 |
+
public:
|
| 15 |
+
virtual ~Class() = default;
|
| 16 |
+
|
| 17 |
+
void setVal(std::uint64_t val) { val_ = val; }
|
| 18 |
+
std::uint64_t getVal() const { return val_; }
|
| 19 |
+
|
| 20 |
+
virtual std::unique_ptr<Class> clone() const = 0;
|
| 21 |
+
virtual int foo() const = 0;
|
| 22 |
+
|
| 23 |
+
protected:
|
| 24 |
+
Class() = default;
|
| 25 |
+
|
| 26 |
+
// Some compilers complain about implicitly defined versions of some of the following:
|
| 27 |
+
Class(const Class &) = default;
|
| 28 |
+
|
| 29 |
+
private:
|
| 30 |
+
std::uint64_t val_ = 0;
|
| 31 |
+
};
|
| 32 |
+
|
| 33 |
+
} // namespace class_sh_trampoline_unique_ptr
|
| 34 |
+
} // namespace pybind11_tests
|
| 35 |
+
|
| 36 |
+
namespace pybind11_tests {
|
| 37 |
+
namespace class_sh_trampoline_unique_ptr {
|
| 38 |
+
|
| 39 |
+
class PyClass : public Class, public py::trampoline_self_life_support {
|
| 40 |
+
public:
|
| 41 |
+
std::unique_ptr<Class> clone() const override {
|
| 42 |
+
PYBIND11_OVERRIDE_PURE(std::unique_ptr<Class>, Class, clone);
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
int foo() const override { PYBIND11_OVERRIDE_PURE(int, Class, foo); }
|
| 46 |
+
};
|
| 47 |
+
|
| 48 |
+
} // namespace class_sh_trampoline_unique_ptr
|
| 49 |
+
} // namespace pybind11_tests
|
| 50 |
+
|
| 51 |
+
TEST_SUBMODULE(class_sh_trampoline_unique_ptr, m) {
|
| 52 |
+
using namespace pybind11_tests::class_sh_trampoline_unique_ptr;
|
| 53 |
+
|
| 54 |
+
py::classh<Class, PyClass>(m, "Class")
|
| 55 |
+
.def(py::init<>())
|
| 56 |
+
.def("set_val", &Class::setVal)
|
| 57 |
+
.def("get_val", &Class::getVal)
|
| 58 |
+
.def("clone", &Class::clone)
|
| 59 |
+
.def("foo", &Class::foo);
|
| 60 |
+
|
| 61 |
+
m.def("clone", [](const Class &obj) { return obj.clone(); });
|
| 62 |
+
m.def("clone_and_foo", [](const Class &obj) { return obj.clone()->foo(); });
|
| 63 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_trampoline_unique_ptr.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import pybind11_tests.class_sh_trampoline_unique_ptr as m
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class MyClass(m.Class):
|
| 7 |
+
def foo(self):
|
| 8 |
+
return 10 + self.get_val()
|
| 9 |
+
|
| 10 |
+
def clone(self):
|
| 11 |
+
cloned = MyClass()
|
| 12 |
+
cloned.set_val(self.get_val() + 3)
|
| 13 |
+
return cloned
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_m_clone():
|
| 17 |
+
obj = MyClass()
|
| 18 |
+
while True:
|
| 19 |
+
obj.set_val(5)
|
| 20 |
+
obj = m.clone(obj)
|
| 21 |
+
assert obj.get_val() == 5 + 3
|
| 22 |
+
assert obj.foo() == 10 + 5 + 3
|
| 23 |
+
return # Comment out for manual leak checking (use `top` command).
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_m_clone_and_foo():
|
| 27 |
+
obj = MyClass()
|
| 28 |
+
obj.set_val(7)
|
| 29 |
+
while True:
|
| 30 |
+
assert m.clone_and_foo(obj) == 10 + 7 + 3
|
| 31 |
+
return # Comment out for manual leak checking (use `top` command).
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_unique_ptr_custom_deleter.cpp
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "pybind11_tests.h"
|
| 2 |
+
|
| 3 |
+
#include <memory>
|
| 4 |
+
|
| 5 |
+
namespace pybind11_tests {
|
| 6 |
+
namespace class_sh_unique_ptr_custom_deleter {
|
| 7 |
+
|
| 8 |
+
// Reduced from a PyCLIF use case in the wild by @wangxf123456.
|
| 9 |
+
class Pet {
|
| 10 |
+
public:
|
| 11 |
+
using Ptr = std::unique_ptr<Pet, std::function<void(Pet *)>>;
|
| 12 |
+
|
| 13 |
+
std::string name;
|
| 14 |
+
|
| 15 |
+
static Ptr New(const std::string &name) {
|
| 16 |
+
return Ptr(new Pet(name), std::default_delete<Pet>());
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
private:
|
| 20 |
+
explicit Pet(const std::string &name) : name(name) {}
|
| 21 |
+
};
|
| 22 |
+
|
| 23 |
+
TEST_SUBMODULE(class_sh_unique_ptr_custom_deleter, m) {
|
| 24 |
+
py::classh<Pet>(m, "Pet").def_readwrite("name", &Pet::name);
|
| 25 |
+
|
| 26 |
+
m.def("create", &Pet::New);
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
} // namespace class_sh_unique_ptr_custom_deleter
|
| 30 |
+
} // namespace pybind11_tests
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_unique_ptr_custom_deleter.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pybind11_tests import class_sh_unique_ptr_custom_deleter as m
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_create():
|
| 7 |
+
pet = m.create("abc")
|
| 8 |
+
assert pet.name == "abc"
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_unique_ptr_member.cpp
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "pybind11_tests.h"
|
| 2 |
+
|
| 3 |
+
#include <memory>
|
| 4 |
+
|
| 5 |
+
namespace pybind11_tests {
|
| 6 |
+
namespace class_sh_unique_ptr_member {
|
| 7 |
+
|
| 8 |
+
class pointee { // NOT copyable.
|
| 9 |
+
public:
|
| 10 |
+
pointee() = default;
|
| 11 |
+
|
| 12 |
+
int get_int() const { return 213; }
|
| 13 |
+
|
| 14 |
+
pointee(const pointee &) = delete;
|
| 15 |
+
pointee(pointee &&) = delete;
|
| 16 |
+
pointee &operator=(const pointee &) = delete;
|
| 17 |
+
pointee &operator=(pointee &&) = delete;
|
| 18 |
+
};
|
| 19 |
+
|
| 20 |
+
inline std::unique_ptr<pointee> make_unique_pointee() {
|
| 21 |
+
return std::unique_ptr<pointee>(new pointee);
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
class ptr_owner {
|
| 25 |
+
public:
|
| 26 |
+
explicit ptr_owner(std::unique_ptr<pointee> ptr) : ptr_(std::move(ptr)) {}
|
| 27 |
+
|
| 28 |
+
bool is_owner() const { return bool(ptr_); }
|
| 29 |
+
|
| 30 |
+
std::unique_ptr<pointee> give_up_ownership_via_unique_ptr() { return std::move(ptr_); }
|
| 31 |
+
std::shared_ptr<pointee> give_up_ownership_via_shared_ptr() { return std::move(ptr_); }
|
| 32 |
+
|
| 33 |
+
private:
|
| 34 |
+
std::unique_ptr<pointee> ptr_;
|
| 35 |
+
};
|
| 36 |
+
|
| 37 |
+
TEST_SUBMODULE(class_sh_unique_ptr_member, m) {
|
| 38 |
+
py::classh<pointee>(m, "pointee").def(py::init<>()).def("get_int", &pointee::get_int);
|
| 39 |
+
|
| 40 |
+
m.def("make_unique_pointee", make_unique_pointee);
|
| 41 |
+
|
| 42 |
+
py::class_<ptr_owner>(m, "ptr_owner")
|
| 43 |
+
.def(py::init<std::unique_ptr<pointee>>(), py::arg("ptr"))
|
| 44 |
+
.def("is_owner", &ptr_owner::is_owner)
|
| 45 |
+
.def("give_up_ownership_via_unique_ptr", &ptr_owner::give_up_ownership_via_unique_ptr)
|
| 46 |
+
.def("give_up_ownership_via_shared_ptr", &ptr_owner::give_up_ownership_via_shared_ptr);
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
} // namespace class_sh_unique_ptr_member
|
| 50 |
+
} // namespace pybind11_tests
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_unique_ptr_member.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from pybind11_tests import class_sh_unique_ptr_member as m
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_make_unique_pointee():
|
| 9 |
+
obj = m.make_unique_pointee()
|
| 10 |
+
assert obj.get_int() == 213
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.mark.parametrize(
|
| 14 |
+
"give_up_ownership_via",
|
| 15 |
+
["give_up_ownership_via_unique_ptr", "give_up_ownership_via_shared_ptr"],
|
| 16 |
+
)
|
| 17 |
+
def test_pointee_and_ptr_owner(give_up_ownership_via):
|
| 18 |
+
obj = m.pointee()
|
| 19 |
+
assert obj.get_int() == 213
|
| 20 |
+
owner = m.ptr_owner(obj)
|
| 21 |
+
with pytest.raises(ValueError, match="Python instance was disowned"):
|
| 22 |
+
obj.get_int()
|
| 23 |
+
assert owner.is_owner()
|
| 24 |
+
reclaimed = getattr(owner, give_up_ownership_via)()
|
| 25 |
+
assert not owner.is_owner()
|
| 26 |
+
assert reclaimed.get_int() == 213
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_virtual_py_cpp_mix.cpp
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "pybind11_tests.h"
|
| 2 |
+
|
| 3 |
+
#include <memory>
|
| 4 |
+
|
| 5 |
+
namespace pybind11_tests {
|
| 6 |
+
namespace class_sh_virtual_py_cpp_mix {
|
| 7 |
+
|
| 8 |
+
class Base {
|
| 9 |
+
public:
|
| 10 |
+
virtual ~Base() = default;
|
| 11 |
+
virtual int get() const { return 101; }
|
| 12 |
+
|
| 13 |
+
// Some compilers complain about implicitly defined versions of some of the following:
|
| 14 |
+
Base() = default;
|
| 15 |
+
Base(const Base &) = default;
|
| 16 |
+
};
|
| 17 |
+
|
| 18 |
+
class CppDerivedPlain : public Base {
|
| 19 |
+
public:
|
| 20 |
+
int get() const override { return 202; }
|
| 21 |
+
};
|
| 22 |
+
|
| 23 |
+
class CppDerived : public Base {
|
| 24 |
+
public:
|
| 25 |
+
int get() const override { return 212; }
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
int get_from_cpp_plainc_ptr(const Base *b) { return b->get() + 4000; }
|
| 29 |
+
|
| 30 |
+
int get_from_cpp_unique_ptr(std::unique_ptr<Base> b) { return b->get() + 5000; }
|
| 31 |
+
|
| 32 |
+
struct BaseVirtualOverrider : Base, py::trampoline_self_life_support {
|
| 33 |
+
using Base::Base;
|
| 34 |
+
|
| 35 |
+
int get() const override { PYBIND11_OVERRIDE(int, Base, get); }
|
| 36 |
+
};
|
| 37 |
+
|
| 38 |
+
struct CppDerivedVirtualOverrider : CppDerived, py::trampoline_self_life_support {
|
| 39 |
+
using CppDerived::CppDerived;
|
| 40 |
+
|
| 41 |
+
int get() const override { PYBIND11_OVERRIDE(int, CppDerived, get); }
|
| 42 |
+
};
|
| 43 |
+
|
| 44 |
+
} // namespace class_sh_virtual_py_cpp_mix
|
| 45 |
+
} // namespace pybind11_tests
|
| 46 |
+
|
| 47 |
+
using namespace pybind11_tests::class_sh_virtual_py_cpp_mix;
|
| 48 |
+
|
| 49 |
+
TEST_SUBMODULE(class_sh_virtual_py_cpp_mix, m) {
|
| 50 |
+
py::classh<Base, BaseVirtualOverrider>(m, "Base").def(py::init<>()).def("get", &Base::get);
|
| 51 |
+
|
| 52 |
+
py::classh<CppDerivedPlain, Base>(m, "CppDerivedPlain").def(py::init<>());
|
| 53 |
+
|
| 54 |
+
py::classh<CppDerived, Base, CppDerivedVirtualOverrider>(m, "CppDerived").def(py::init<>());
|
| 55 |
+
|
| 56 |
+
m.def("get_from_cpp_plainc_ptr", get_from_cpp_plainc_ptr, py::arg("b"));
|
| 57 |
+
m.def("get_from_cpp_unique_ptr", get_from_cpp_unique_ptr, py::arg("b"));
|
| 58 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_class_sh_virtual_py_cpp_mix.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from pybind11_tests import class_sh_virtual_py_cpp_mix as m
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class PyBase(m.Base): # Avoiding name PyDerived, for more systematic naming.
|
| 9 |
+
def __init__(self):
|
| 10 |
+
m.Base.__init__(self)
|
| 11 |
+
|
| 12 |
+
def get(self):
|
| 13 |
+
return 323
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class PyCppDerived(m.CppDerived):
|
| 17 |
+
def __init__(self):
|
| 18 |
+
m.CppDerived.__init__(self)
|
| 19 |
+
|
| 20 |
+
def get(self):
|
| 21 |
+
return 434
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.mark.parametrize(
|
| 25 |
+
("ctor", "expected"),
|
| 26 |
+
[
|
| 27 |
+
(m.Base, 101),
|
| 28 |
+
(PyBase, 323),
|
| 29 |
+
(m.CppDerivedPlain, 202),
|
| 30 |
+
(m.CppDerived, 212),
|
| 31 |
+
(PyCppDerived, 434),
|
| 32 |
+
],
|
| 33 |
+
)
|
| 34 |
+
def test_base_get(ctor, expected):
|
| 35 |
+
obj = ctor()
|
| 36 |
+
assert obj.get() == expected
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.parametrize(
|
| 40 |
+
("ctor", "expected"),
|
| 41 |
+
[
|
| 42 |
+
(m.Base, 4101),
|
| 43 |
+
(PyBase, 4323),
|
| 44 |
+
(m.CppDerivedPlain, 4202),
|
| 45 |
+
(m.CppDerived, 4212),
|
| 46 |
+
(PyCppDerived, 4434),
|
| 47 |
+
],
|
| 48 |
+
)
|
| 49 |
+
def test_get_from_cpp_plainc_ptr(ctor, expected):
|
| 50 |
+
obj = ctor()
|
| 51 |
+
assert m.get_from_cpp_plainc_ptr(obj) == expected
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@pytest.mark.parametrize(
|
| 55 |
+
("ctor", "expected"),
|
| 56 |
+
[
|
| 57 |
+
(m.Base, 5101),
|
| 58 |
+
(PyBase, 5323),
|
| 59 |
+
(m.CppDerivedPlain, 5202),
|
| 60 |
+
(m.CppDerived, 5212),
|
| 61 |
+
(PyCppDerived, 5434),
|
| 62 |
+
],
|
| 63 |
+
)
|
| 64 |
+
def test_get_from_cpp_unique_ptr(ctor, expected):
|
| 65 |
+
obj = ctor()
|
| 66 |
+
assert m.get_from_cpp_unique_ptr(obj) == expected
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/CMakeLists.txt
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
add_custom_target(test_cmake_build)
|
| 2 |
+
|
| 3 |
+
function(pybind11_add_build_test name)
|
| 4 |
+
cmake_parse_arguments(ARG "INSTALL" "" "" ${ARGN})
|
| 5 |
+
|
| 6 |
+
set(build_options "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}")
|
| 7 |
+
|
| 8 |
+
list(APPEND build_options "-DPYBIND11_FINDPYTHON=${PYBIND11_FINDPYTHON}")
|
| 9 |
+
if(PYBIND11_FINDPYTHON)
|
| 10 |
+
if(DEFINED Python_ROOT_DIR)
|
| 11 |
+
list(APPEND build_options "-DPython_ROOT_DIR=${Python_ROOT_DIR}")
|
| 12 |
+
endif()
|
| 13 |
+
|
| 14 |
+
list(APPEND build_options "-DPython_EXECUTABLE=${Python_EXECUTABLE}")
|
| 15 |
+
else()
|
| 16 |
+
list(APPEND build_options "-DPYTHON_EXECUTABLE=${PYTHON_EXECUTABLE}")
|
| 17 |
+
endif()
|
| 18 |
+
|
| 19 |
+
if(DEFINED CMAKE_CXX_STANDARD)
|
| 20 |
+
list(APPEND build_options "-DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}")
|
| 21 |
+
endif()
|
| 22 |
+
|
| 23 |
+
if(NOT ARG_INSTALL)
|
| 24 |
+
list(APPEND build_options "-Dpybind11_SOURCE_DIR=${pybind11_SOURCE_DIR}")
|
| 25 |
+
else()
|
| 26 |
+
list(APPEND build_options "-DCMAKE_PREFIX_PATH=${pybind11_BINARY_DIR}/mock_install")
|
| 27 |
+
endif()
|
| 28 |
+
|
| 29 |
+
add_custom_target(
|
| 30 |
+
test_build_${name}
|
| 31 |
+
${CMAKE_CTEST_COMMAND}
|
| 32 |
+
--build-and-test
|
| 33 |
+
"${CMAKE_CURRENT_SOURCE_DIR}/${name}"
|
| 34 |
+
"${CMAKE_CURRENT_BINARY_DIR}/${name}"
|
| 35 |
+
--build-config
|
| 36 |
+
Release
|
| 37 |
+
--build-noclean
|
| 38 |
+
--build-generator
|
| 39 |
+
${CMAKE_GENERATOR}
|
| 40 |
+
$<$<BOOL:${CMAKE_GENERATOR_PLATFORM}>:--build-generator-platform>
|
| 41 |
+
${CMAKE_GENERATOR_PLATFORM}
|
| 42 |
+
--build-makeprogram
|
| 43 |
+
${CMAKE_MAKE_PROGRAM}
|
| 44 |
+
--build-target
|
| 45 |
+
check_${name}
|
| 46 |
+
--build-options
|
| 47 |
+
${build_options})
|
| 48 |
+
if(ARG_INSTALL)
|
| 49 |
+
add_dependencies(test_build_${name} mock_install)
|
| 50 |
+
endif()
|
| 51 |
+
add_dependencies(test_cmake_build test_build_${name})
|
| 52 |
+
endfunction()
|
| 53 |
+
|
| 54 |
+
if(PYBIND11_TEST_SMART_HOLDER)
|
| 55 |
+
add_compile_definitions(
|
| 56 |
+
-DPYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE)
|
| 57 |
+
endif()
|
| 58 |
+
|
| 59 |
+
possibly_uninitialized(PYTHON_MODULE_EXTENSION Python_INTERPRETER_ID)
|
| 60 |
+
|
| 61 |
+
pybind11_add_build_test(subdirectory_function)
|
| 62 |
+
pybind11_add_build_test(subdirectory_target)
|
| 63 |
+
if("${PYTHON_MODULE_EXTENSION}" MATCHES "pypy"
|
| 64 |
+
OR "${Python_INTERPRETER_ID}" STREQUAL "PyPy"
|
| 65 |
+
OR "${PYTHON_MODULE_EXTENSION}" MATCHES "graalpy")
|
| 66 |
+
message(STATUS "Skipping embed test on PyPy or GraalPy")
|
| 67 |
+
else()
|
| 68 |
+
pybind11_add_build_test(subdirectory_embed)
|
| 69 |
+
endif()
|
| 70 |
+
|
| 71 |
+
if(PYBIND11_INSTALL)
|
| 72 |
+
add_custom_target(
|
| 73 |
+
mock_install ${CMAKE_COMMAND} "-DCMAKE_INSTALL_PREFIX=${pybind11_BINARY_DIR}/mock_install" -P
|
| 74 |
+
"${pybind11_BINARY_DIR}/cmake_install.cmake")
|
| 75 |
+
|
| 76 |
+
if(NOT "${PYTHON_MODULE_EXTENSION}" MATCHES "graalpy")
|
| 77 |
+
pybind11_add_build_test(installed_function INSTALL)
|
| 78 |
+
endif()
|
| 79 |
+
pybind11_add_build_test(installed_target INSTALL)
|
| 80 |
+
if(NOT
|
| 81 |
+
("${PYTHON_MODULE_EXTENSION}" MATCHES "pypy"
|
| 82 |
+
OR "${Python_INTERPRETER_ID}" STREQUAL "PyPy"
|
| 83 |
+
OR "${PYTHON_MODULE_EXTENSION}" MATCHES "graalpy"))
|
| 84 |
+
pybind11_add_build_test(installed_embed INSTALL)
|
| 85 |
+
endif()
|
| 86 |
+
endif()
|
| 87 |
+
|
| 88 |
+
add_dependencies(check test_cmake_build)
|
| 89 |
+
|
| 90 |
+
add_subdirectory(subdirectory_target EXCLUDE_FROM_ALL)
|
| 91 |
+
add_subdirectory(subdirectory_embed EXCLUDE_FROM_ALL)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/embed.cpp
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <pybind11/embed.h>
|
| 2 |
+
namespace py = pybind11;
|
| 3 |
+
|
| 4 |
+
PYBIND11_EMBEDDED_MODULE(test_cmake_build, m) {
|
| 5 |
+
m.def("add", [](int i, int j) { return i + j; });
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
int main(int argc, char *argv[]) {
|
| 9 |
+
if (argc != 2) {
|
| 10 |
+
throw std::runtime_error("Expected test.py file as the first argument");
|
| 11 |
+
}
|
| 12 |
+
auto *test_py_file = argv[1];
|
| 13 |
+
|
| 14 |
+
py::scoped_interpreter guard{};
|
| 15 |
+
|
| 16 |
+
auto m = py::module_::import("test_cmake_build");
|
| 17 |
+
if (m.attr("add")(1, 2).cast<int>() != 3) {
|
| 18 |
+
throw std::runtime_error("embed.cpp failed");
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
py::module_::import("sys").attr("argv") = py::make_tuple("test.py", "embed.cpp");
|
| 22 |
+
py::eval_file(test_py_file, py::globals());
|
| 23 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/installed_embed/CMakeLists.txt
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cmake_minimum_required(VERSION 3.15...4.0)
|
| 2 |
+
|
| 3 |
+
project(test_installed_embed CXX)
|
| 4 |
+
|
| 5 |
+
find_package(pybind11 CONFIG REQUIRED)
|
| 6 |
+
message(STATUS "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}")
|
| 7 |
+
|
| 8 |
+
add_executable(test_installed_embed ../embed.cpp)
|
| 9 |
+
target_link_libraries(test_installed_embed PRIVATE pybind11::embed)
|
| 10 |
+
set_target_properties(test_installed_embed PROPERTIES OUTPUT_NAME test_cmake_build)
|
| 11 |
+
|
| 12 |
+
# Do not treat includes from IMPORTED target as SYSTEM (Python headers in pybind11::embed).
|
| 13 |
+
# This may be needed to resolve header conflicts, e.g. between Python release and debug headers.
|
| 14 |
+
set_target_properties(test_installed_embed PROPERTIES NO_SYSTEM_FROM_IMPORTED ON)
|
| 15 |
+
|
| 16 |
+
add_custom_target(
|
| 17 |
+
check_installed_embed
|
| 18 |
+
$<TARGET_FILE:test_installed_embed> ${PROJECT_SOURCE_DIR}/../test.py
|
| 19 |
+
DEPENDS test_installed_embed)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/installed_function/CMakeLists.txt
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cmake_minimum_required(VERSION 3.15...4.0)
|
| 2 |
+
|
| 3 |
+
project(test_installed_function CXX)
|
| 4 |
+
|
| 5 |
+
find_package(pybind11 CONFIG REQUIRED)
|
| 6 |
+
message(
|
| 7 |
+
STATUS "Found pybind11 v${pybind11_VERSION} ${pybind11_VERSION_TYPE}: ${pybind11_INCLUDE_DIRS}")
|
| 8 |
+
|
| 9 |
+
pybind11_add_module(test_installed_function SHARED NO_EXTRAS ../main.cpp)
|
| 10 |
+
set_target_properties(test_installed_function PROPERTIES OUTPUT_NAME test_cmake_build)
|
| 11 |
+
|
| 12 |
+
if(DEFINED Python_EXECUTABLE)
|
| 13 |
+
set(_Python_EXECUTABLE "${Python_EXECUTABLE}")
|
| 14 |
+
elseif(DEFINED PYTHON_EXECUTABLE)
|
| 15 |
+
set(_Python_EXECUTABLE "${PYTHON_EXECUTABLE}")
|
| 16 |
+
else()
|
| 17 |
+
message(FATAL_ERROR "No Python executable defined (should not be possible at this stage)")
|
| 18 |
+
endif()
|
| 19 |
+
|
| 20 |
+
add_custom_target(
|
| 21 |
+
check_installed_function
|
| 22 |
+
${CMAKE_COMMAND}
|
| 23 |
+
-E
|
| 24 |
+
env
|
| 25 |
+
PYTHONPATH=$<TARGET_FILE_DIR:test_installed_function>
|
| 26 |
+
${_Python_EXECUTABLE}
|
| 27 |
+
${PROJECT_SOURCE_DIR}/../test.py
|
| 28 |
+
${PROJECT_NAME}
|
| 29 |
+
DEPENDS test_installed_function)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/installed_target/CMakeLists.txt
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cmake_minimum_required(VERSION 3.15...4.0)
|
| 2 |
+
|
| 3 |
+
project(test_installed_target CXX)
|
| 4 |
+
|
| 5 |
+
find_package(pybind11 CONFIG REQUIRED)
|
| 6 |
+
message(STATUS "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}")
|
| 7 |
+
|
| 8 |
+
add_library(test_installed_target MODULE ../main.cpp)
|
| 9 |
+
|
| 10 |
+
target_link_libraries(test_installed_target PRIVATE pybind11::module)
|
| 11 |
+
set_target_properties(test_installed_target PROPERTIES OUTPUT_NAME test_cmake_build)
|
| 12 |
+
|
| 13 |
+
# Make sure result is, for example, test_installed_target.so, not libtest_installed_target.dylib
|
| 14 |
+
pybind11_extension(test_installed_target)
|
| 15 |
+
|
| 16 |
+
# Do not treat includes from IMPORTED target as SYSTEM (Python headers in pybind11::module).
|
| 17 |
+
# This may be needed to resolve header conflicts, e.g. between Python release and debug headers.
|
| 18 |
+
set_target_properties(test_installed_target PROPERTIES NO_SYSTEM_FROM_IMPORTED ON)
|
| 19 |
+
|
| 20 |
+
if(DEFINED Python_EXECUTABLE)
|
| 21 |
+
set(_Python_EXECUTABLE "${Python_EXECUTABLE}")
|
| 22 |
+
elseif(DEFINED PYTHON_EXECUTABLE)
|
| 23 |
+
set(_Python_EXECUTABLE "${PYTHON_EXECUTABLE}")
|
| 24 |
+
else()
|
| 25 |
+
message(FATAL_ERROR "No Python executable defined (should not be possible at this stage)")
|
| 26 |
+
endif()
|
| 27 |
+
|
| 28 |
+
add_custom_target(
|
| 29 |
+
check_installed_target
|
| 30 |
+
${CMAKE_COMMAND}
|
| 31 |
+
-E
|
| 32 |
+
env
|
| 33 |
+
PYTHONPATH=$<TARGET_FILE_DIR:test_installed_target>
|
| 34 |
+
${_Python_EXECUTABLE}
|
| 35 |
+
${PROJECT_SOURCE_DIR}/../test.py
|
| 36 |
+
${PROJECT_NAME}
|
| 37 |
+
DEPENDS test_installed_target)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/main.cpp
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <pybind11/pybind11.h>
|
| 2 |
+
namespace py = pybind11;
|
| 3 |
+
|
| 4 |
+
PYBIND11_MODULE(test_cmake_build, m, py::mod_gil_not_used()) {
|
| 5 |
+
m.def("add", [](int i, int j) { return i + j; });
|
| 6 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/subdirectory_embed/CMakeLists.txt
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cmake_minimum_required(VERSION 3.15...4.0)
|
| 2 |
+
|
| 3 |
+
project(test_subdirectory_embed CXX)
|
| 4 |
+
|
| 5 |
+
set(PYBIND11_INSTALL
|
| 6 |
+
ON
|
| 7 |
+
CACHE BOOL "")
|
| 8 |
+
set(PYBIND11_EXPORT_NAME test_export)
|
| 9 |
+
|
| 10 |
+
# Allow PYTHON_EXECUTABLE if in FINDPYTHON mode and building pybind11's tests
|
| 11 |
+
# (makes transition easier while we support both modes).
|
| 12 |
+
if(DEFINED PYTHON_EXECUTABLE AND NOT DEFINED Python_EXECUTABLE)
|
| 13 |
+
set(Python_EXECUTABLE "${PYTHON_EXECUTABLE}")
|
| 14 |
+
endif()
|
| 15 |
+
|
| 16 |
+
add_subdirectory("${pybind11_SOURCE_DIR}" pybind11)
|
| 17 |
+
|
| 18 |
+
# Test basic target functionality
|
| 19 |
+
add_executable(test_subdirectory_embed ../embed.cpp)
|
| 20 |
+
target_link_libraries(test_subdirectory_embed PRIVATE pybind11::embed)
|
| 21 |
+
set_target_properties(test_subdirectory_embed PROPERTIES OUTPUT_NAME test_cmake_build)
|
| 22 |
+
|
| 23 |
+
add_custom_target(
|
| 24 |
+
check_subdirectory_embed
|
| 25 |
+
$<TARGET_FILE:test_subdirectory_embed> "${PROJECT_SOURCE_DIR}/../test.py"
|
| 26 |
+
DEPENDS test_subdirectory_embed)
|
| 27 |
+
|
| 28 |
+
# Test custom export group -- PYBIND11_EXPORT_NAME
|
| 29 |
+
add_library(test_with_catch_lib ../embed.cpp)
|
| 30 |
+
target_link_libraries(test_with_catch_lib PRIVATE pybind11::embed)
|
| 31 |
+
|
| 32 |
+
install(
|
| 33 |
+
TARGETS test_with_catch_lib
|
| 34 |
+
EXPORT test_export
|
| 35 |
+
ARCHIVE DESTINATION bin
|
| 36 |
+
LIBRARY DESTINATION lib
|
| 37 |
+
RUNTIME DESTINATION lib)
|
| 38 |
+
install(EXPORT test_export DESTINATION lib/cmake/test_export/test_export-Targets.cmake)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/subdirectory_function/CMakeLists.txt
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cmake_minimum_required(VERSION 3.15...4.0)
|
| 2 |
+
|
| 3 |
+
project(test_subdirectory_function CXX)
|
| 4 |
+
|
| 5 |
+
# Allow PYTHON_EXECUTABLE if in FINDPYTHON mode and building pybind11's tests
|
| 6 |
+
# (makes transition easier while we support both modes).
|
| 7 |
+
if(DEFINED PYTHON_EXECUTABLE AND NOT DEFINED Python_EXECUTABLE)
|
| 8 |
+
set(Python_EXECUTABLE "${PYTHON_EXECUTABLE}")
|
| 9 |
+
endif()
|
| 10 |
+
|
| 11 |
+
add_subdirectory("${pybind11_SOURCE_DIR}" pybind11)
|
| 12 |
+
pybind11_add_module(test_subdirectory_function ../main.cpp)
|
| 13 |
+
set_target_properties(test_subdirectory_function PROPERTIES OUTPUT_NAME test_cmake_build)
|
| 14 |
+
|
| 15 |
+
if(DEFINED Python_EXECUTABLE)
|
| 16 |
+
set(_Python_EXECUTABLE "${Python_EXECUTABLE}")
|
| 17 |
+
elseif(DEFINED PYTHON_EXECUTABLE)
|
| 18 |
+
set(_Python_EXECUTABLE "${PYTHON_EXECUTABLE}")
|
| 19 |
+
else()
|
| 20 |
+
message(FATAL_ERROR "No Python executable defined (should not be possible at this stage)")
|
| 21 |
+
endif()
|
| 22 |
+
|
| 23 |
+
add_custom_target(
|
| 24 |
+
check_subdirectory_function
|
| 25 |
+
${CMAKE_COMMAND}
|
| 26 |
+
-E
|
| 27 |
+
env
|
| 28 |
+
PYTHONPATH=$<TARGET_FILE_DIR:test_subdirectory_function>
|
| 29 |
+
${_Python_EXECUTABLE}
|
| 30 |
+
${PROJECT_SOURCE_DIR}/../test.py
|
| 31 |
+
${PROJECT_NAME}
|
| 32 |
+
DEPENDS test_subdirectory_function)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/subdirectory_target/CMakeLists.txt
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cmake_minimum_required(VERSION 3.15...4.0)
|
| 2 |
+
|
| 3 |
+
project(test_subdirectory_target CXX)
|
| 4 |
+
|
| 5 |
+
# Allow PYTHON_EXECUTABLE if in FINDPYTHON mode and building pybind11's tests
|
| 6 |
+
# (makes transition easier while we support both modes).
|
| 7 |
+
if(DEFINED PYTHON_EXECUTABLE AND NOT DEFINED Python_EXECUTABLE)
|
| 8 |
+
set(Python_EXECUTABLE "${PYTHON_EXECUTABLE}")
|
| 9 |
+
endif()
|
| 10 |
+
|
| 11 |
+
add_subdirectory("${pybind11_SOURCE_DIR}" pybind11)
|
| 12 |
+
|
| 13 |
+
add_library(test_subdirectory_target MODULE ../main.cpp)
|
| 14 |
+
set_target_properties(test_subdirectory_target PROPERTIES OUTPUT_NAME test_cmake_build)
|
| 15 |
+
|
| 16 |
+
target_link_libraries(test_subdirectory_target PRIVATE pybind11::module)
|
| 17 |
+
|
| 18 |
+
# Make sure result is, for example, test_installed_target.so, not libtest_installed_target.dylib
|
| 19 |
+
pybind11_extension(test_subdirectory_target)
|
| 20 |
+
|
| 21 |
+
if(DEFINED Python_EXECUTABLE)
|
| 22 |
+
set(_Python_EXECUTABLE "${Python_EXECUTABLE}")
|
| 23 |
+
elseif(DEFINED PYTHON_EXECUTABLE)
|
| 24 |
+
set(_Python_EXECUTABLE "${PYTHON_EXECUTABLE}")
|
| 25 |
+
else()
|
| 26 |
+
message(FATAL_ERROR "No Python executable defined (should not be possible at this stage)")
|
| 27 |
+
endif()
|
| 28 |
+
|
| 29 |
+
add_custom_target(
|
| 30 |
+
check_subdirectory_target
|
| 31 |
+
${CMAKE_COMMAND}
|
| 32 |
+
-E
|
| 33 |
+
env
|
| 34 |
+
PYTHONPATH=$<TARGET_FILE_DIR:test_subdirectory_target>
|
| 35 |
+
${_Python_EXECUTABLE}
|
| 36 |
+
${PROJECT_SOURCE_DIR}/../test.py
|
| 37 |
+
${PROJECT_NAME}
|
| 38 |
+
DEPENDS test_subdirectory_target)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cmake_build/test.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
import test_cmake_build
|
| 6 |
+
|
| 7 |
+
assert isinstance(__file__, str) # Test this is properly set
|
| 8 |
+
|
| 9 |
+
assert test_cmake_build.add(1, 2) == 3
|
| 10 |
+
print(f"{sys.argv[1]} imports, runs, and adds: 1 + 2 = 3")
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_const_name.cpp
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright (c) 2021 The Pybind Development Team.
|
| 2 |
+
// All rights reserved. Use of this source code is governed by a
|
| 3 |
+
// BSD-style license that can be found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
#include "pybind11_tests.h"
|
| 6 |
+
|
| 7 |
+
// IUT = Implementation Under Test
|
| 8 |
+
#define CONST_NAME_TESTS(TEST_FUNC, IUT) \
|
| 9 |
+
std::string TEST_FUNC(int selector) { \
|
| 10 |
+
switch (selector) { \
|
| 11 |
+
case 0: \
|
| 12 |
+
return IUT("").text; \
|
| 13 |
+
case 1: \
|
| 14 |
+
return IUT("A").text; \
|
| 15 |
+
case 2: \
|
| 16 |
+
return IUT("Bd").text; \
|
| 17 |
+
case 3: \
|
| 18 |
+
return IUT("Cef").text; \
|
| 19 |
+
case 4: \
|
| 20 |
+
return IUT<int>().text; /*NOLINT(bugprone-macro-parentheses)*/ \
|
| 21 |
+
case 5: \
|
| 22 |
+
return IUT<std::string>().text; /*NOLINT(bugprone-macro-parentheses)*/ \
|
| 23 |
+
case 6: \
|
| 24 |
+
return IUT<true>("T1", "T2").text; /*NOLINT(bugprone-macro-parentheses)*/ \
|
| 25 |
+
case 7: \
|
| 26 |
+
return IUT<false>("U1", "U2").text; /*NOLINT(bugprone-macro-parentheses)*/ \
|
| 27 |
+
case 8: \
|
| 28 |
+
/*NOLINTNEXTLINE(bugprone-macro-parentheses)*/ \
|
| 29 |
+
return IUT<true>(IUT("D1"), IUT("D2")).text; \
|
| 30 |
+
case 9: \
|
| 31 |
+
/*NOLINTNEXTLINE(bugprone-macro-parentheses)*/ \
|
| 32 |
+
return IUT<false>(IUT("E1"), IUT("E2")).text; \
|
| 33 |
+
case 10: \
|
| 34 |
+
return IUT("KeepAtEnd").text; \
|
| 35 |
+
default: \
|
| 36 |
+
break; \
|
| 37 |
+
} \
|
| 38 |
+
throw std::runtime_error("Invalid selector value."); \
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
CONST_NAME_TESTS(const_name_tests, py::detail::const_name)
|
| 42 |
+
|
| 43 |
+
#ifdef PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY
|
| 44 |
+
CONST_NAME_TESTS(underscore_tests, py::detail::_)
|
| 45 |
+
#endif
|
| 46 |
+
|
| 47 |
+
TEST_SUBMODULE(const_name, m) {
|
| 48 |
+
m.def("const_name_tests", const_name_tests);
|
| 49 |
+
|
| 50 |
+
#if defined(PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY)
|
| 51 |
+
m.def("underscore_tests", underscore_tests);
|
| 52 |
+
#else
|
| 53 |
+
m.attr("underscore_tests") = "PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY not defined.";
|
| 54 |
+
#endif
|
| 55 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_const_name.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from pybind11_tests import const_name as m
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.mark.parametrize("func", [m.const_name_tests, m.underscore_tests])
|
| 9 |
+
@pytest.mark.parametrize(
|
| 10 |
+
("selector", "expected"),
|
| 11 |
+
enumerate(
|
| 12 |
+
(
|
| 13 |
+
"",
|
| 14 |
+
"A",
|
| 15 |
+
"Bd",
|
| 16 |
+
"Cef",
|
| 17 |
+
"%",
|
| 18 |
+
"%",
|
| 19 |
+
"T1",
|
| 20 |
+
"U2",
|
| 21 |
+
"D1",
|
| 22 |
+
"E2",
|
| 23 |
+
"KeepAtEnd",
|
| 24 |
+
)
|
| 25 |
+
),
|
| 26 |
+
)
|
| 27 |
+
def test_const_name(func, selector, expected):
|
| 28 |
+
if isinstance(func, str):
|
| 29 |
+
pytest.skip(func)
|
| 30 |
+
text = func(selector)
|
| 31 |
+
assert text == expected
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_constants_and_functions.cpp
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
tests/test_constants_and_functions.cpp -- global constants and functions, enumerations, raw
|
| 3 |
+
byte strings
|
| 4 |
+
|
| 5 |
+
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
|
| 6 |
+
|
| 7 |
+
All rights reserved. Use of this source code is governed by a
|
| 8 |
+
BSD-style license that can be found in the LICENSE file.
|
| 9 |
+
*/
|
| 10 |
+
|
| 11 |
+
#include "pybind11_tests.h"
|
| 12 |
+
|
| 13 |
+
enum MyEnum { EFirstEntry = 1, ESecondEntry };
|
| 14 |
+
|
| 15 |
+
std::string test_function1() { return "test_function()"; }
|
| 16 |
+
|
| 17 |
+
std::string test_function2(MyEnum k) { return "test_function(enum=" + std::to_string(k) + ")"; }
|
| 18 |
+
|
| 19 |
+
std::string test_function3(int i) { return "test_function(" + std::to_string(i) + ")"; }
|
| 20 |
+
|
| 21 |
+
py::str test_function4() { return "test_function()"; }
|
| 22 |
+
py::str test_function4(char *) { return "test_function(char *)"; }
|
| 23 |
+
py::str test_function4(int, float) { return "test_function(int, float)"; }
|
| 24 |
+
py::str test_function4(float, int) { return "test_function(float, int)"; }
|
| 25 |
+
|
| 26 |
+
py::bytes return_bytes() {
|
| 27 |
+
const char *data = "\x01\x00\x02\x00";
|
| 28 |
+
return std::string(data, 4);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
std::string print_bytes(const py::bytes &bytes) {
|
| 32 |
+
std::string ret = "bytes[";
|
| 33 |
+
const auto value = static_cast<std::string>(bytes);
|
| 34 |
+
for (char c : value) {
|
| 35 |
+
ret += std::to_string(static_cast<int>(c)) + ' ';
|
| 36 |
+
}
|
| 37 |
+
ret.back() = ']';
|
| 38 |
+
return ret;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
// Test that we properly handle C++17 exception specifiers (which are part of the function
|
| 42 |
+
// signature in C++17). These should all still work before C++17, but don't affect the function
|
| 43 |
+
// signature.
|
| 44 |
+
namespace test_exc_sp {
|
| 45 |
+
// [workaround(intel)] Unable to use noexcept instead of noexcept(true)
|
| 46 |
+
// Make the f1 test basically the same as the f2 test in C++17 mode for the Intel compiler as
|
| 47 |
+
// it fails to compile with a plain noexcept (tested with icc (ICC) 2021.1 Beta 20200827).
|
| 48 |
+
#if defined(__INTEL_COMPILER) && defined(PYBIND11_CPP17)
|
| 49 |
+
int f1(int x) noexcept(true) { return x + 1; }
|
| 50 |
+
#else
|
| 51 |
+
int f1(int x) noexcept { return x + 1; }
|
| 52 |
+
#endif
|
| 53 |
+
int f2(int x) noexcept(true) { return x + 2; }
|
| 54 |
+
int f3(int x) noexcept(false) { return x + 3; }
|
| 55 |
+
PYBIND11_WARNING_PUSH
|
| 56 |
+
PYBIND11_WARNING_DISABLE_GCC("-Wdeprecated")
|
| 57 |
+
#if defined(__clang_major__) && __clang_major__ >= 5
|
| 58 |
+
PYBIND11_WARNING_DISABLE_CLANG("-Wdeprecated-dynamic-exception-spec")
|
| 59 |
+
#else
|
| 60 |
+
PYBIND11_WARNING_DISABLE_CLANG("-Wdeprecated")
|
| 61 |
+
#endif
|
| 62 |
+
// NOLINTNEXTLINE(modernize-use-noexcept)
|
| 63 |
+
int f4(int x) throw() { return x + 4; } // Deprecated equivalent to noexcept(true)
|
| 64 |
+
PYBIND11_WARNING_POP
|
| 65 |
+
struct C {
|
| 66 |
+
int m1(int x) noexcept { return x - 1; }
|
| 67 |
+
int m2(int x) const noexcept { return x - 2; }
|
| 68 |
+
int m3(int x) noexcept(true) { return x - 3; }
|
| 69 |
+
int m4(int x) const noexcept(true) { return x - 4; }
|
| 70 |
+
int m5(int x) noexcept(false) { return x - 5; }
|
| 71 |
+
int m6(int x) const noexcept(false) { return x - 6; }
|
| 72 |
+
PYBIND11_WARNING_PUSH
|
| 73 |
+
PYBIND11_WARNING_DISABLE_GCC("-Wdeprecated")
|
| 74 |
+
PYBIND11_WARNING_DISABLE_CLANG("-Wdeprecated")
|
| 75 |
+
// NOLINTNEXTLINE(modernize-use-noexcept)
|
| 76 |
+
int m7(int x) throw() { return x - 7; }
|
| 77 |
+
// NOLINTNEXTLINE(modernize-use-noexcept)
|
| 78 |
+
int m8(int x) const throw() { return x - 8; }
|
| 79 |
+
PYBIND11_WARNING_POP
|
| 80 |
+
};
|
| 81 |
+
} // namespace test_exc_sp
|
| 82 |
+
|
| 83 |
+
TEST_SUBMODULE(constants_and_functions, m) {
|
| 84 |
+
// test_constants
|
| 85 |
+
m.attr("some_constant") = py::int_(14);
|
| 86 |
+
|
| 87 |
+
// test_function_overloading
|
| 88 |
+
m.def("test_function", &test_function1);
|
| 89 |
+
m.def("test_function", &test_function2);
|
| 90 |
+
m.def("test_function", &test_function3);
|
| 91 |
+
|
| 92 |
+
#if defined(PYBIND11_OVERLOAD_CAST)
|
| 93 |
+
m.def("test_function", py::overload_cast<>(&test_function4));
|
| 94 |
+
m.def("test_function", py::overload_cast<char *>(&test_function4));
|
| 95 |
+
m.def("test_function", py::overload_cast<int, float>(&test_function4));
|
| 96 |
+
m.def("test_function", py::overload_cast<float, int>(&test_function4));
|
| 97 |
+
#else
|
| 98 |
+
m.def("test_function", static_cast<py::str (*)()>(&test_function4));
|
| 99 |
+
m.def("test_function", static_cast<py::str (*)(char *)>(&test_function4));
|
| 100 |
+
m.def("test_function", static_cast<py::str (*)(int, float)>(&test_function4));
|
| 101 |
+
m.def("test_function", static_cast<py::str (*)(float, int)>(&test_function4));
|
| 102 |
+
#endif
|
| 103 |
+
|
| 104 |
+
py::enum_<MyEnum>(m, "MyEnum")
|
| 105 |
+
.value("EFirstEntry", EFirstEntry)
|
| 106 |
+
.value("ESecondEntry", ESecondEntry)
|
| 107 |
+
.export_values();
|
| 108 |
+
|
| 109 |
+
// test_bytes
|
| 110 |
+
m.def("return_bytes", &return_bytes);
|
| 111 |
+
m.def("print_bytes", &print_bytes);
|
| 112 |
+
|
| 113 |
+
// test_exception_specifiers
|
| 114 |
+
using namespace test_exc_sp;
|
| 115 |
+
py::class_<C>(m, "C")
|
| 116 |
+
.def(py::init<>())
|
| 117 |
+
.def("m1", &C::m1)
|
| 118 |
+
.def("m2", &C::m2)
|
| 119 |
+
.def("m3", &C::m3)
|
| 120 |
+
.def("m4", &C::m4)
|
| 121 |
+
.def("m5", &C::m5)
|
| 122 |
+
.def("m6", &C::m6)
|
| 123 |
+
.def("m7", &C::m7)
|
| 124 |
+
.def("m8", &C::m8);
|
| 125 |
+
m.def("f1", f1);
|
| 126 |
+
m.def("f2", f2);
|
| 127 |
+
|
| 128 |
+
PYBIND11_WARNING_PUSH
|
| 129 |
+
PYBIND11_WARNING_DISABLE_INTEL(878) // incompatible exception specifications
|
| 130 |
+
m.def("f3", f3);
|
| 131 |
+
PYBIND11_WARNING_POP
|
| 132 |
+
|
| 133 |
+
m.def("f4", f4);
|
| 134 |
+
|
| 135 |
+
// test_function_record_leaks
|
| 136 |
+
m.def("register_large_capture_with_invalid_arguments", [](py::module_ m) {
|
| 137 |
+
// This should always be enough to trigger the alternative branch
|
| 138 |
+
// where `sizeof(capture) > sizeof(rec->data)`
|
| 139 |
+
uint64_t capture[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
|
| 140 |
+
#if defined(__GNUC__) && __GNUC__ == 4 // CentOS7
|
| 141 |
+
py::detail::silence_unused_warnings(capture);
|
| 142 |
+
#endif
|
| 143 |
+
m.def(
|
| 144 |
+
"should_raise", [capture](int) { return capture[9] + 33; }, py::kw_only(), py::arg());
|
| 145 |
+
});
|
| 146 |
+
m.def("register_with_raising_repr", [](py::module_ m, const py::object &default_value) {
|
| 147 |
+
m.def(
|
| 148 |
+
"should_raise",
|
| 149 |
+
[](int, int, const py::object &) { return 42; },
|
| 150 |
+
"some docstring",
|
| 151 |
+
py::arg_v("x", 42),
|
| 152 |
+
py::arg_v("y", 42, "<the answer>"),
|
| 153 |
+
py::arg_v("z", default_value));
|
| 154 |
+
});
|
| 155 |
+
|
| 156 |
+
// test noexcept(true) lambda (#4565)
|
| 157 |
+
m.def("l1", []() noexcept(true) { return 0; });
|
| 158 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_constants_and_functions.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
m = pytest.importorskip("pybind11_tests.constants_and_functions")
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_constants():
|
| 9 |
+
assert m.some_constant == 14
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_function_overloading():
|
| 13 |
+
assert m.test_function() == "test_function()"
|
| 14 |
+
assert m.test_function(7) == "test_function(7)"
|
| 15 |
+
assert m.test_function(m.MyEnum.EFirstEntry) == "test_function(enum=1)"
|
| 16 |
+
assert m.test_function(m.MyEnum.ESecondEntry) == "test_function(enum=2)"
|
| 17 |
+
|
| 18 |
+
assert m.test_function() == "test_function()"
|
| 19 |
+
assert m.test_function("abcd") == "test_function(char *)"
|
| 20 |
+
assert m.test_function(1, 1.0) == "test_function(int, float)"
|
| 21 |
+
assert m.test_function(1, 1.0) == "test_function(int, float)"
|
| 22 |
+
assert m.test_function(2.0, 2) == "test_function(float, int)"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_bytes():
|
| 26 |
+
assert m.print_bytes(m.return_bytes()) == "bytes[1 0 2 0]"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_exception_specifiers():
|
| 30 |
+
c = m.C()
|
| 31 |
+
assert c.m1(2) == 1
|
| 32 |
+
assert c.m2(3) == 1
|
| 33 |
+
assert c.m3(5) == 2
|
| 34 |
+
assert c.m4(7) == 3
|
| 35 |
+
assert c.m5(10) == 5
|
| 36 |
+
assert c.m6(14) == 8
|
| 37 |
+
assert c.m7(20) == 13
|
| 38 |
+
assert c.m8(29) == 21
|
| 39 |
+
|
| 40 |
+
assert m.f1(33) == 34
|
| 41 |
+
assert m.f2(53) == 55
|
| 42 |
+
assert m.f3(86) == 89
|
| 43 |
+
assert m.f4(140) == 144
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_function_record_leaks():
|
| 47 |
+
class RaisingRepr:
|
| 48 |
+
def __repr__(self):
|
| 49 |
+
raise RuntimeError("Surprise!")
|
| 50 |
+
|
| 51 |
+
with pytest.raises(RuntimeError):
|
| 52 |
+
m.register_large_capture_with_invalid_arguments(m)
|
| 53 |
+
with pytest.raises(RuntimeError):
|
| 54 |
+
m.register_with_raising_repr(m, RaisingRepr())
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_noexcept_lambda():
|
| 58 |
+
assert m.l1() == 0
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_copy_move.cpp
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
tests/test_copy_move_policies.cpp -- 'copy' and 'move' return value policies
|
| 3 |
+
and related tests
|
| 4 |
+
|
| 5 |
+
Copyright (c) 2016 Ben North <ben@redfrontdoor.org>
|
| 6 |
+
|
| 7 |
+
All rights reserved. Use of this source code is governed by a
|
| 8 |
+
BSD-style license that can be found in the LICENSE file.
|
| 9 |
+
*/
|
| 10 |
+
|
| 11 |
+
#include <pybind11/stl.h>
|
| 12 |
+
|
| 13 |
+
#include "constructor_stats.h"
|
| 14 |
+
#include "pybind11_tests.h"
|
| 15 |
+
|
| 16 |
+
#include <type_traits>
|
| 17 |
+
|
| 18 |
+
template <typename derived>
|
| 19 |
+
struct empty {
|
| 20 |
+
static const derived &get_one() { return instance_; }
|
| 21 |
+
static derived instance_;
|
| 22 |
+
|
| 23 |
+
private:
|
| 24 |
+
empty() = default;
|
| 25 |
+
friend derived;
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct lacking_copy_ctor : public empty<lacking_copy_ctor> {
|
| 29 |
+
lacking_copy_ctor() = default;
|
| 30 |
+
lacking_copy_ctor(const lacking_copy_ctor &other) = delete;
|
| 31 |
+
};
|
| 32 |
+
|
| 33 |
+
template <>
|
| 34 |
+
lacking_copy_ctor empty<lacking_copy_ctor>::instance_ = {};
|
| 35 |
+
|
| 36 |
+
struct lacking_move_ctor : public empty<lacking_move_ctor> {
|
| 37 |
+
lacking_move_ctor() = default;
|
| 38 |
+
lacking_move_ctor(const lacking_move_ctor &other) = delete;
|
| 39 |
+
lacking_move_ctor(lacking_move_ctor &&other) = delete;
|
| 40 |
+
};
|
| 41 |
+
|
| 42 |
+
template <>
|
| 43 |
+
lacking_move_ctor empty<lacking_move_ctor>::instance_ = {};
|
| 44 |
+
|
| 45 |
+
/* Custom type caster move/copy test classes */
|
| 46 |
+
class MoveOnlyInt {
|
| 47 |
+
public:
|
| 48 |
+
MoveOnlyInt() { print_default_created(this); }
|
| 49 |
+
explicit MoveOnlyInt(int v) : value{v} { print_created(this, value); }
|
| 50 |
+
MoveOnlyInt(MoveOnlyInt &&m) noexcept {
|
| 51 |
+
print_move_created(this, m.value);
|
| 52 |
+
std::swap(value, m.value);
|
| 53 |
+
}
|
| 54 |
+
MoveOnlyInt &operator=(MoveOnlyInt &&m) noexcept {
|
| 55 |
+
print_move_assigned(this, m.value);
|
| 56 |
+
std::swap(value, m.value);
|
| 57 |
+
return *this;
|
| 58 |
+
}
|
| 59 |
+
MoveOnlyInt(const MoveOnlyInt &) = delete;
|
| 60 |
+
MoveOnlyInt &operator=(const MoveOnlyInt &) = delete;
|
| 61 |
+
~MoveOnlyInt() { print_destroyed(this); }
|
| 62 |
+
|
| 63 |
+
int value;
|
| 64 |
+
};
|
| 65 |
+
class MoveOrCopyInt {
|
| 66 |
+
public:
|
| 67 |
+
MoveOrCopyInt() { print_default_created(this); }
|
| 68 |
+
explicit MoveOrCopyInt(int v) : value{v} { print_created(this, value); }
|
| 69 |
+
MoveOrCopyInt(MoveOrCopyInt &&m) noexcept {
|
| 70 |
+
print_move_created(this, m.value);
|
| 71 |
+
std::swap(value, m.value);
|
| 72 |
+
}
|
| 73 |
+
MoveOrCopyInt &operator=(MoveOrCopyInt &&m) noexcept {
|
| 74 |
+
print_move_assigned(this, m.value);
|
| 75 |
+
std::swap(value, m.value);
|
| 76 |
+
return *this;
|
| 77 |
+
}
|
| 78 |
+
MoveOrCopyInt(const MoveOrCopyInt &c) {
|
| 79 |
+
print_copy_created(this, c.value);
|
| 80 |
+
// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
|
| 81 |
+
value = c.value;
|
| 82 |
+
}
|
| 83 |
+
MoveOrCopyInt &operator=(const MoveOrCopyInt &c) {
|
| 84 |
+
print_copy_assigned(this, c.value);
|
| 85 |
+
value = c.value;
|
| 86 |
+
return *this;
|
| 87 |
+
}
|
| 88 |
+
~MoveOrCopyInt() { print_destroyed(this); }
|
| 89 |
+
|
| 90 |
+
int value;
|
| 91 |
+
};
|
| 92 |
+
class CopyOnlyInt {
|
| 93 |
+
public:
|
| 94 |
+
CopyOnlyInt() { print_default_created(this); }
|
| 95 |
+
explicit CopyOnlyInt(int v) : value{v} { print_created(this, value); }
|
| 96 |
+
CopyOnlyInt(const CopyOnlyInt &c) {
|
| 97 |
+
print_copy_created(this, c.value);
|
| 98 |
+
// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
|
| 99 |
+
value = c.value;
|
| 100 |
+
}
|
| 101 |
+
CopyOnlyInt &operator=(const CopyOnlyInt &c) {
|
| 102 |
+
print_copy_assigned(this, c.value);
|
| 103 |
+
value = c.value;
|
| 104 |
+
return *this;
|
| 105 |
+
}
|
| 106 |
+
~CopyOnlyInt() { print_destroyed(this); }
|
| 107 |
+
|
| 108 |
+
int value;
|
| 109 |
+
};
|
| 110 |
+
PYBIND11_NAMESPACE_BEGIN(pybind11)
|
| 111 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
| 112 |
+
template <>
|
| 113 |
+
struct type_caster<MoveOnlyInt> {
|
| 114 |
+
PYBIND11_TYPE_CASTER(MoveOnlyInt, const_name("MoveOnlyInt"));
|
| 115 |
+
bool load(handle src, bool) {
|
| 116 |
+
value = MoveOnlyInt(src.cast<int>());
|
| 117 |
+
return true;
|
| 118 |
+
}
|
| 119 |
+
static handle cast(const MoveOnlyInt &m, return_value_policy r, handle p) {
|
| 120 |
+
return pybind11::cast(m.value, r, p);
|
| 121 |
+
}
|
| 122 |
+
};
|
| 123 |
+
|
| 124 |
+
template <>
|
| 125 |
+
struct type_caster<MoveOrCopyInt> {
|
| 126 |
+
PYBIND11_TYPE_CASTER(MoveOrCopyInt, const_name("MoveOrCopyInt"));
|
| 127 |
+
bool load(handle src, bool) {
|
| 128 |
+
value = MoveOrCopyInt(src.cast<int>());
|
| 129 |
+
return true;
|
| 130 |
+
}
|
| 131 |
+
static handle cast(const MoveOrCopyInt &m, return_value_policy r, handle p) {
|
| 132 |
+
return pybind11::cast(m.value, r, p);
|
| 133 |
+
}
|
| 134 |
+
};
|
| 135 |
+
|
| 136 |
+
template <>
|
| 137 |
+
struct type_caster<CopyOnlyInt> {
|
| 138 |
+
protected:
|
| 139 |
+
CopyOnlyInt value;
|
| 140 |
+
|
| 141 |
+
public:
|
| 142 |
+
static constexpr auto name = const_name("CopyOnlyInt");
|
| 143 |
+
bool load(handle src, bool) {
|
| 144 |
+
value = CopyOnlyInt(src.cast<int>());
|
| 145 |
+
return true;
|
| 146 |
+
}
|
| 147 |
+
static handle cast(const CopyOnlyInt &m, return_value_policy r, handle p) {
|
| 148 |
+
return pybind11::cast(m.value, r, p);
|
| 149 |
+
}
|
| 150 |
+
static handle cast(const CopyOnlyInt *src, return_value_policy policy, handle parent) {
|
| 151 |
+
if (!src) {
|
| 152 |
+
return none().release();
|
| 153 |
+
}
|
| 154 |
+
return cast(*src, policy, parent);
|
| 155 |
+
}
|
| 156 |
+
explicit operator CopyOnlyInt *() { return &value; }
|
| 157 |
+
explicit operator CopyOnlyInt &() { return value; }
|
| 158 |
+
template <typename T>
|
| 159 |
+
using cast_op_type = pybind11::detail::cast_op_type<T>;
|
| 160 |
+
};
|
| 161 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 162 |
+
PYBIND11_NAMESPACE_END(pybind11)
|
| 163 |
+
|
| 164 |
+
namespace {
|
| 165 |
+
|
| 166 |
+
py::object CastUnusualOpRefConstRef(const UnusualOpRef &cref) { return py::cast(cref); }
|
| 167 |
+
py::object CastUnusualOpRefMovable(UnusualOpRef &&mvbl) { return py::cast(std::move(mvbl)); }
|
| 168 |
+
|
| 169 |
+
} // namespace
|
| 170 |
+
|
| 171 |
+
TEST_SUBMODULE(copy_move_policies, m) {
|
| 172 |
+
// test_lacking_copy_ctor
|
| 173 |
+
py::class_<lacking_copy_ctor>(m, "lacking_copy_ctor")
|
| 174 |
+
.def_static("get_one", &lacking_copy_ctor::get_one, py::return_value_policy::copy);
|
| 175 |
+
// test_lacking_move_ctor
|
| 176 |
+
py::class_<lacking_move_ctor>(m, "lacking_move_ctor")
|
| 177 |
+
.def_static("get_one", &lacking_move_ctor::get_one, py::return_value_policy::move);
|
| 178 |
+
|
| 179 |
+
// test_move_and_copy_casts
|
| 180 |
+
// NOLINTNEXTLINE(performance-unnecessary-value-param)
|
| 181 |
+
m.def("move_and_copy_casts", [](const py::object &o) {
|
| 182 |
+
int r = 0;
|
| 183 |
+
r += py::cast<MoveOrCopyInt>(o).value; /* moves */
|
| 184 |
+
r += py::cast<MoveOnlyInt>(o).value; /* moves */
|
| 185 |
+
r += py::cast<CopyOnlyInt>(o).value; /* copies */
|
| 186 |
+
auto m1(py::cast<MoveOrCopyInt>(o)); /* moves */
|
| 187 |
+
auto m2(py::cast<MoveOnlyInt>(o)); /* moves */
|
| 188 |
+
auto m3(py::cast<CopyOnlyInt>(o)); /* copies */
|
| 189 |
+
r += m1.value + m2.value + m3.value;
|
| 190 |
+
|
| 191 |
+
return r;
|
| 192 |
+
});
|
| 193 |
+
|
| 194 |
+
// test_move_and_copy_loads
|
| 195 |
+
m.def("move_only", [](MoveOnlyInt m) { return m.value; });
|
| 196 |
+
// NOLINTNEXTLINE(performance-unnecessary-value-param): we want to test copying
|
| 197 |
+
m.def("move_or_copy", [](MoveOrCopyInt m) { return m.value; });
|
| 198 |
+
// NOLINTNEXTLINE(performance-unnecessary-value-param): we want to test copying
|
| 199 |
+
m.def("copy_only", [](CopyOnlyInt m) { return m.value; });
|
| 200 |
+
m.def("move_pair",
|
| 201 |
+
[](std::pair<MoveOnlyInt, MoveOrCopyInt> p) { return p.first.value + p.second.value; });
|
| 202 |
+
m.def("move_tuple", [](std::tuple<MoveOnlyInt, MoveOrCopyInt, MoveOnlyInt> t) {
|
| 203 |
+
return std::get<0>(t).value + std::get<1>(t).value + std::get<2>(t).value;
|
| 204 |
+
});
|
| 205 |
+
m.def("copy_tuple", [](std::tuple<CopyOnlyInt, CopyOnlyInt> t) {
|
| 206 |
+
return std::get<0>(t).value + std::get<1>(t).value;
|
| 207 |
+
});
|
| 208 |
+
m.def("move_copy_nested",
|
| 209 |
+
[](std::pair<MoveOnlyInt,
|
| 210 |
+
std::pair<std::tuple<MoveOrCopyInt, CopyOnlyInt, std::tuple<MoveOnlyInt>>,
|
| 211 |
+
MoveOrCopyInt>> x) {
|
| 212 |
+
return x.first.value + std::get<0>(x.second.first).value
|
| 213 |
+
+ std::get<1>(x.second.first).value
|
| 214 |
+
+ std::get<0>(std::get<2>(x.second.first)).value + x.second.second.value;
|
| 215 |
+
});
|
| 216 |
+
m.def("move_and_copy_cstats", []() {
|
| 217 |
+
ConstructorStats::gc();
|
| 218 |
+
// Reset counts to 0 so that previous tests don't affect later ones:
|
| 219 |
+
auto &mc = ConstructorStats::get<MoveOrCopyInt>();
|
| 220 |
+
mc.move_assignments = mc.move_constructions = mc.copy_assignments = mc.copy_constructions
|
| 221 |
+
= 0;
|
| 222 |
+
auto &mo = ConstructorStats::get<MoveOnlyInt>();
|
| 223 |
+
mo.move_assignments = mo.move_constructions = mo.copy_assignments = mo.copy_constructions
|
| 224 |
+
= 0;
|
| 225 |
+
auto &co = ConstructorStats::get<CopyOnlyInt>();
|
| 226 |
+
co.move_assignments = co.move_constructions = co.copy_assignments = co.copy_constructions
|
| 227 |
+
= 0;
|
| 228 |
+
py::dict d;
|
| 229 |
+
d["MoveOrCopyInt"] = py::cast(mc, py::return_value_policy::reference);
|
| 230 |
+
d["MoveOnlyInt"] = py::cast(mo, py::return_value_policy::reference);
|
| 231 |
+
d["CopyOnlyInt"] = py::cast(co, py::return_value_policy::reference);
|
| 232 |
+
return d;
|
| 233 |
+
});
|
| 234 |
+
#ifdef PYBIND11_HAS_OPTIONAL
|
| 235 |
+
// test_move_and_copy_load_optional
|
| 236 |
+
m.attr("has_optional") = true;
|
| 237 |
+
m.def("move_optional", [](std::optional<MoveOnlyInt> o) { return o->value; });
|
| 238 |
+
m.def("move_or_copy_optional", [](std::optional<MoveOrCopyInt> o) { return o->value; });
|
| 239 |
+
m.def("copy_optional", [](std::optional<CopyOnlyInt> o) { return o->value; });
|
| 240 |
+
m.def("move_optional_tuple",
|
| 241 |
+
[](std::optional<std::tuple<MoveOrCopyInt, MoveOnlyInt, CopyOnlyInt>> x) {
|
| 242 |
+
return std::get<0>(*x).value + std::get<1>(*x).value + std::get<2>(*x).value;
|
| 243 |
+
});
|
| 244 |
+
#else
|
| 245 |
+
m.attr("has_optional") = false;
|
| 246 |
+
#endif
|
| 247 |
+
|
| 248 |
+
// #70 compilation issue if operator new is not public - simple body added
|
| 249 |
+
// but not needed on most compilers; MSVC and nvcc don't like a local
|
| 250 |
+
// struct not having a method defined when declared, since it can not be
|
| 251 |
+
// added later.
|
| 252 |
+
struct PrivateOpNew {
|
| 253 |
+
int value = 1;
|
| 254 |
+
|
| 255 |
+
private:
|
| 256 |
+
void *operator new(size_t bytes) {
|
| 257 |
+
void *ptr = std::malloc(bytes);
|
| 258 |
+
if (ptr) {
|
| 259 |
+
return ptr;
|
| 260 |
+
}
|
| 261 |
+
throw std::bad_alloc{};
|
| 262 |
+
}
|
| 263 |
+
};
|
| 264 |
+
py::class_<PrivateOpNew>(m, "PrivateOpNew").def_readonly("value", &PrivateOpNew::value);
|
| 265 |
+
m.def("private_op_new_value", []() { return PrivateOpNew(); });
|
| 266 |
+
m.def(
|
| 267 |
+
"private_op_new_reference",
|
| 268 |
+
[]() -> const PrivateOpNew & {
|
| 269 |
+
static PrivateOpNew x{};
|
| 270 |
+
return x;
|
| 271 |
+
},
|
| 272 |
+
py::return_value_policy::reference);
|
| 273 |
+
|
| 274 |
+
// test_move_fallback
|
| 275 |
+
// #389: rvp::move should fall-through to copy on non-movable objects
|
| 276 |
+
struct MoveIssue1 {
|
| 277 |
+
int v;
|
| 278 |
+
explicit MoveIssue1(int v) : v{v} {}
|
| 279 |
+
MoveIssue1(const MoveIssue1 &c) = default;
|
| 280 |
+
MoveIssue1(MoveIssue1 &&) = delete;
|
| 281 |
+
};
|
| 282 |
+
py::class_<MoveIssue1>(m, "MoveIssue1")
|
| 283 |
+
.def(py::init<int>())
|
| 284 |
+
.def_readwrite("value", &MoveIssue1::v);
|
| 285 |
+
|
| 286 |
+
struct MoveIssue2 {
|
| 287 |
+
int v;
|
| 288 |
+
explicit MoveIssue2(int v) : v{v} {}
|
| 289 |
+
MoveIssue2(MoveIssue2 &&) = default;
|
| 290 |
+
};
|
| 291 |
+
py::class_<MoveIssue2>(m, "MoveIssue2")
|
| 292 |
+
.def(py::init<int>())
|
| 293 |
+
.def_readwrite("value", &MoveIssue2::v);
|
| 294 |
+
|
| 295 |
+
// #2742: Don't expect ownership of raw pointer to `new`ed object to be transferred with
|
| 296 |
+
// `py::return_value_policy::move`
|
| 297 |
+
m.def(
|
| 298 |
+
"get_moveissue1",
|
| 299 |
+
[](int i) { return std::unique_ptr<MoveIssue1>(new MoveIssue1(i)); },
|
| 300 |
+
py::return_value_policy::move);
|
| 301 |
+
m.def("get_moveissue2", [](int i) { return MoveIssue2(i); }, py::return_value_policy::move);
|
| 302 |
+
|
| 303 |
+
// Make sure that cast from pytype rvalue to other pytype works
|
| 304 |
+
m.def("get_pytype_rvalue_castissue", [](double i) { return py::float_(i).cast<py::int_>(); });
|
| 305 |
+
|
| 306 |
+
py::class_<UnusualOpRef>(m, "UnusualOpRef");
|
| 307 |
+
m.def("CallCastUnusualOpRefConstRef",
|
| 308 |
+
[]() { return CastUnusualOpRefConstRef(UnusualOpRef()); });
|
| 309 |
+
m.def("CallCastUnusualOpRefMovable", []() { return CastUnusualOpRefMovable(UnusualOpRef()); });
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
/*
|
| 313 |
+
* Rest of the file:
|
| 314 |
+
* static_assert based tests for pybind11 adaptations of
|
| 315 |
+
* std::is_move_constructible, std::is_copy_constructible and
|
| 316 |
+
* std::is_copy_assignable (no adaptation of std::is_move_assignable).
|
| 317 |
+
* Difference between pybind11 and std traits: pybind11 traits will also check
|
| 318 |
+
* the contained value_types.
|
| 319 |
+
*/
|
| 320 |
+
|
| 321 |
+
struct NotMovable {
|
| 322 |
+
NotMovable() = default;
|
| 323 |
+
NotMovable(NotMovable const &) = default;
|
| 324 |
+
NotMovable(NotMovable &&) = delete;
|
| 325 |
+
NotMovable &operator=(NotMovable const &) = default;
|
| 326 |
+
NotMovable &operator=(NotMovable &&) = delete;
|
| 327 |
+
};
|
| 328 |
+
static_assert(!std::is_move_constructible<NotMovable>::value,
|
| 329 |
+
"!std::is_move_constructible<NotMovable>::value");
|
| 330 |
+
static_assert(std::is_copy_constructible<NotMovable>::value,
|
| 331 |
+
"std::is_copy_constructible<NotMovable>::value");
|
| 332 |
+
static_assert(!pybind11::detail::is_move_constructible<NotMovable>::value,
|
| 333 |
+
"!pybind11::detail::is_move_constructible<NotMovable>::value");
|
| 334 |
+
static_assert(pybind11::detail::is_copy_constructible<NotMovable>::value,
|
| 335 |
+
"pybind11::detail::is_copy_constructible<NotMovable>::value");
|
| 336 |
+
static_assert(!std::is_move_assignable<NotMovable>::value,
|
| 337 |
+
"!std::is_move_assignable<NotMovable>::value");
|
| 338 |
+
static_assert(std::is_copy_assignable<NotMovable>::value,
|
| 339 |
+
"std::is_copy_assignable<NotMovable>::value");
|
| 340 |
+
// pybind11 does not have this
|
| 341 |
+
// static_assert(!pybind11::detail::is_move_assignable<NotMovable>::value,
|
| 342 |
+
// "!pybind11::detail::is_move_assignable<NotMovable>::value");
|
| 343 |
+
static_assert(pybind11::detail::is_copy_assignable<NotMovable>::value,
|
| 344 |
+
"pybind11::detail::is_copy_assignable<NotMovable>::value");
|
| 345 |
+
|
| 346 |
+
struct NotCopyable {
|
| 347 |
+
NotCopyable() = default;
|
| 348 |
+
NotCopyable(NotCopyable const &) = delete;
|
| 349 |
+
NotCopyable(NotCopyable &&) = default;
|
| 350 |
+
NotCopyable &operator=(NotCopyable const &) = delete;
|
| 351 |
+
NotCopyable &operator=(NotCopyable &&) = default;
|
| 352 |
+
};
|
| 353 |
+
static_assert(std::is_move_constructible<NotCopyable>::value,
|
| 354 |
+
"std::is_move_constructible<NotCopyable>::value");
|
| 355 |
+
static_assert(!std::is_copy_constructible<NotCopyable>::value,
|
| 356 |
+
"!std::is_copy_constructible<NotCopyable>::value");
|
| 357 |
+
static_assert(pybind11::detail::is_move_constructible<NotCopyable>::value,
|
| 358 |
+
"pybind11::detail::is_move_constructible<NotCopyable>::value");
|
| 359 |
+
static_assert(!pybind11::detail::is_copy_constructible<NotCopyable>::value,
|
| 360 |
+
"!pybind11::detail::is_copy_constructible<NotCopyable>::value");
|
| 361 |
+
static_assert(std::is_move_assignable<NotCopyable>::value,
|
| 362 |
+
"std::is_move_assignable<NotCopyable>::value");
|
| 363 |
+
static_assert(!std::is_copy_assignable<NotCopyable>::value,
|
| 364 |
+
"!std::is_copy_assignable<NotCopyable>::value");
|
| 365 |
+
// pybind11 does not have this
|
| 366 |
+
// static_assert(!pybind11::detail::is_move_assignable<NotCopyable>::value,
|
| 367 |
+
// "!pybind11::detail::is_move_assignable<NotCopyable>::value");
|
| 368 |
+
static_assert(!pybind11::detail::is_copy_assignable<NotCopyable>::value,
|
| 369 |
+
"!pybind11::detail::is_copy_assignable<NotCopyable>::value");
|
| 370 |
+
|
| 371 |
+
struct NotCopyableNotMovable {
|
| 372 |
+
NotCopyableNotMovable() = default;
|
| 373 |
+
NotCopyableNotMovable(NotCopyableNotMovable const &) = delete;
|
| 374 |
+
NotCopyableNotMovable(NotCopyableNotMovable &&) = delete;
|
| 375 |
+
NotCopyableNotMovable &operator=(NotCopyableNotMovable const &) = delete;
|
| 376 |
+
NotCopyableNotMovable &operator=(NotCopyableNotMovable &&) = delete;
|
| 377 |
+
};
|
| 378 |
+
static_assert(!std::is_move_constructible<NotCopyableNotMovable>::value,
|
| 379 |
+
"!std::is_move_constructible<NotCopyableNotMovable>::value");
|
| 380 |
+
static_assert(!std::is_copy_constructible<NotCopyableNotMovable>::value,
|
| 381 |
+
"!std::is_copy_constructible<NotCopyableNotMovable>::value");
|
| 382 |
+
static_assert(!pybind11::detail::is_move_constructible<NotCopyableNotMovable>::value,
|
| 383 |
+
"!pybind11::detail::is_move_constructible<NotCopyableNotMovable>::value");
|
| 384 |
+
static_assert(!pybind11::detail::is_copy_constructible<NotCopyableNotMovable>::value,
|
| 385 |
+
"!pybind11::detail::is_copy_constructible<NotCopyableNotMovable>::value");
|
| 386 |
+
static_assert(!std::is_move_assignable<NotCopyableNotMovable>::value,
|
| 387 |
+
"!std::is_move_assignable<NotCopyableNotMovable>::value");
|
| 388 |
+
static_assert(!std::is_copy_assignable<NotCopyableNotMovable>::value,
|
| 389 |
+
"!std::is_copy_assignable<NotCopyableNotMovable>::value");
|
| 390 |
+
// pybind11 does not have this
|
| 391 |
+
// static_assert(!pybind11::detail::is_move_assignable<NotCopyableNotMovable>::value,
|
| 392 |
+
// "!pybind11::detail::is_move_assignable<NotCopyableNotMovable>::value");
|
| 393 |
+
static_assert(!pybind11::detail::is_copy_assignable<NotCopyableNotMovable>::value,
|
| 394 |
+
"!pybind11::detail::is_copy_assignable<NotCopyableNotMovable>::value");
|
| 395 |
+
|
| 396 |
+
struct NotMovableVector : std::vector<NotMovable> {};
|
| 397 |
+
static_assert(std::is_move_constructible<NotMovableVector>::value,
|
| 398 |
+
"std::is_move_constructible<NotMovableVector>::value");
|
| 399 |
+
static_assert(std::is_copy_constructible<NotMovableVector>::value,
|
| 400 |
+
"std::is_copy_constructible<NotMovableVector>::value");
|
| 401 |
+
static_assert(!pybind11::detail::is_move_constructible<NotMovableVector>::value,
|
| 402 |
+
"!pybind11::detail::is_move_constructible<NotMovableVector>::value");
|
| 403 |
+
static_assert(pybind11::detail::is_copy_constructible<NotMovableVector>::value,
|
| 404 |
+
"pybind11::detail::is_copy_constructible<NotMovableVector>::value");
|
| 405 |
+
static_assert(std::is_move_assignable<NotMovableVector>::value,
|
| 406 |
+
"std::is_move_assignable<NotMovableVector>::value");
|
| 407 |
+
static_assert(std::is_copy_assignable<NotMovableVector>::value,
|
| 408 |
+
"std::is_copy_assignable<NotMovableVector>::value");
|
| 409 |
+
// pybind11 does not have this
|
| 410 |
+
// static_assert(!pybind11::detail::is_move_assignable<NotMovableVector>::value,
|
| 411 |
+
// "!pybind11::detail::is_move_assignable<NotMovableVector>::value");
|
| 412 |
+
static_assert(pybind11::detail::is_copy_assignable<NotMovableVector>::value,
|
| 413 |
+
"pybind11::detail::is_copy_assignable<NotMovableVector>::value");
|
| 414 |
+
|
| 415 |
+
struct NotCopyableVector : std::vector<NotCopyable> {};
|
| 416 |
+
static_assert(std::is_move_constructible<NotCopyableVector>::value,
|
| 417 |
+
"std::is_move_constructible<NotCopyableVector>::value");
|
| 418 |
+
static_assert(std::is_copy_constructible<NotCopyableVector>::value,
|
| 419 |
+
"std::is_copy_constructible<NotCopyableVector>::value");
|
| 420 |
+
static_assert(pybind11::detail::is_move_constructible<NotCopyableVector>::value,
|
| 421 |
+
"pybind11::detail::is_move_constructible<NotCopyableVector>::value");
|
| 422 |
+
static_assert(!pybind11::detail::is_copy_constructible<NotCopyableVector>::value,
|
| 423 |
+
"!pybind11::detail::is_copy_constructible<NotCopyableVector>::value");
|
| 424 |
+
static_assert(std::is_move_assignable<NotCopyableVector>::value,
|
| 425 |
+
"std::is_move_assignable<NotCopyableVector>::value");
|
| 426 |
+
static_assert(std::is_copy_assignable<NotCopyableVector>::value,
|
| 427 |
+
"std::is_copy_assignable<NotCopyableVector>::value");
|
| 428 |
+
// pybind11 does not have this
|
| 429 |
+
// static_assert(!pybind11::detail::is_move_assignable<NotCopyableVector>::value,
|
| 430 |
+
// "!pybind11::detail::is_move_assignable<NotCopyableVector>::value");
|
| 431 |
+
static_assert(!pybind11::detail::is_copy_assignable<NotCopyableVector>::value,
|
| 432 |
+
"!pybind11::detail::is_copy_assignable<NotCopyableVector>::value");
|
| 433 |
+
|
| 434 |
+
struct NotCopyableNotMovableVector : std::vector<NotCopyableNotMovable> {};
|
| 435 |
+
static_assert(std::is_move_constructible<NotCopyableNotMovableVector>::value,
|
| 436 |
+
"std::is_move_constructible<NotCopyableNotMovableVector>::value");
|
| 437 |
+
static_assert(std::is_copy_constructible<NotCopyableNotMovableVector>::value,
|
| 438 |
+
"std::is_copy_constructible<NotCopyableNotMovableVector>::value");
|
| 439 |
+
static_assert(!pybind11::detail::is_move_constructible<NotCopyableNotMovableVector>::value,
|
| 440 |
+
"!pybind11::detail::is_move_constructible<NotCopyableNotMovableVector>::value");
|
| 441 |
+
static_assert(!pybind11::detail::is_copy_constructible<NotCopyableNotMovableVector>::value,
|
| 442 |
+
"!pybind11::detail::is_copy_constructible<NotCopyableNotMovableVector>::value");
|
| 443 |
+
static_assert(std::is_move_assignable<NotCopyableNotMovableVector>::value,
|
| 444 |
+
"std::is_move_assignable<NotCopyableNotMovableVector>::value");
|
| 445 |
+
static_assert(std::is_copy_assignable<NotCopyableNotMovableVector>::value,
|
| 446 |
+
"std::is_copy_assignable<NotCopyableNotMovableVector>::value");
|
| 447 |
+
// pybind11 does not have this
|
| 448 |
+
// static_assert(!pybind11::detail::is_move_assignable<NotCopyableNotMovableVector>::value,
|
| 449 |
+
// "!pybind11::detail::is_move_assignable<NotCopyableNotMovableVector>::value");
|
| 450 |
+
static_assert(!pybind11::detail::is_copy_assignable<NotCopyableNotMovableVector>::value,
|
| 451 |
+
"!pybind11::detail::is_copy_assignable<NotCopyableNotMovableVector>::value");
|
| 452 |
+
|
| 453 |
+
struct NotMovableMap : std::map<int, NotMovable> {};
|
| 454 |
+
static_assert(std::is_move_constructible<NotMovableMap>::value,
|
| 455 |
+
"std::is_move_constructible<NotMovableMap>::value");
|
| 456 |
+
static_assert(std::is_copy_constructible<NotMovableMap>::value,
|
| 457 |
+
"std::is_copy_constructible<NotMovableMap>::value");
|
| 458 |
+
static_assert(!pybind11::detail::is_move_constructible<NotMovableMap>::value,
|
| 459 |
+
"!pybind11::detail::is_move_constructible<NotMovableMap>::value");
|
| 460 |
+
static_assert(pybind11::detail::is_copy_constructible<NotMovableMap>::value,
|
| 461 |
+
"pybind11::detail::is_copy_constructible<NotMovableMap>::value");
|
| 462 |
+
static_assert(std::is_move_assignable<NotMovableMap>::value,
|
| 463 |
+
"std::is_move_assignable<NotMovableMap>::value");
|
| 464 |
+
static_assert(std::is_copy_assignable<NotMovableMap>::value,
|
| 465 |
+
"std::is_copy_assignable<NotMovableMap>::value");
|
| 466 |
+
// pybind11 does not have this
|
| 467 |
+
// static_assert(!pybind11::detail::is_move_assignable<NotMovableMap>::value,
|
| 468 |
+
// "!pybind11::detail::is_move_assignable<NotMovableMap>::value");
|
| 469 |
+
static_assert(pybind11::detail::is_copy_assignable<NotMovableMap>::value,
|
| 470 |
+
"pybind11::detail::is_copy_assignable<NotMovableMap>::value");
|
| 471 |
+
|
| 472 |
+
struct NotCopyableMap : std::map<int, NotCopyable> {};
|
| 473 |
+
static_assert(std::is_move_constructible<NotCopyableMap>::value,
|
| 474 |
+
"std::is_move_constructible<NotCopyableMap>::value");
|
| 475 |
+
static_assert(std::is_copy_constructible<NotCopyableMap>::value,
|
| 476 |
+
"std::is_copy_constructible<NotCopyableMap>::value");
|
| 477 |
+
static_assert(pybind11::detail::is_move_constructible<NotCopyableMap>::value,
|
| 478 |
+
"pybind11::detail::is_move_constructible<NotCopyableMap>::value");
|
| 479 |
+
static_assert(!pybind11::detail::is_copy_constructible<NotCopyableMap>::value,
|
| 480 |
+
"!pybind11::detail::is_copy_constructible<NotCopyableMap>::value");
|
| 481 |
+
static_assert(std::is_move_assignable<NotCopyableMap>::value,
|
| 482 |
+
"std::is_move_assignable<NotCopyableMap>::value");
|
| 483 |
+
static_assert(std::is_copy_assignable<NotCopyableMap>::value,
|
| 484 |
+
"std::is_copy_assignable<NotCopyableMap>::value");
|
| 485 |
+
// pybind11 does not have this
|
| 486 |
+
// static_assert(!pybind11::detail::is_move_assignable<NotCopyableMap>::value,
|
| 487 |
+
// "!pybind11::detail::is_move_assignable<NotCopyableMap>::value");
|
| 488 |
+
static_assert(!pybind11::detail::is_copy_assignable<NotCopyableMap>::value,
|
| 489 |
+
"!pybind11::detail::is_copy_assignable<NotCopyableMap>::value");
|
| 490 |
+
|
| 491 |
+
struct NotCopyableNotMovableMap : std::map<int, NotCopyableNotMovable> {};
|
| 492 |
+
static_assert(std::is_move_constructible<NotCopyableNotMovableMap>::value,
|
| 493 |
+
"std::is_move_constructible<NotCopyableNotMovableMap>::value");
|
| 494 |
+
static_assert(std::is_copy_constructible<NotCopyableNotMovableMap>::value,
|
| 495 |
+
"std::is_copy_constructible<NotCopyableNotMovableMap>::value");
|
| 496 |
+
static_assert(!pybind11::detail::is_move_constructible<NotCopyableNotMovableMap>::value,
|
| 497 |
+
"!pybind11::detail::is_move_constructible<NotCopyableNotMovableMap>::value");
|
| 498 |
+
static_assert(!pybind11::detail::is_copy_constructible<NotCopyableNotMovableMap>::value,
|
| 499 |
+
"!pybind11::detail::is_copy_constructible<NotCopyableNotMovableMap>::value");
|
| 500 |
+
static_assert(std::is_move_assignable<NotCopyableNotMovableMap>::value,
|
| 501 |
+
"std::is_move_assignable<NotCopyableNotMovableMap>::value");
|
| 502 |
+
static_assert(std::is_copy_assignable<NotCopyableNotMovableMap>::value,
|
| 503 |
+
"std::is_copy_assignable<NotCopyableNotMovableMap>::value");
|
| 504 |
+
// pybind11 does not have this
|
| 505 |
+
// static_assert(!pybind11::detail::is_move_assignable<NotCopyableNotMovableMap>::value,
|
| 506 |
+
// "!pybind11::detail::is_move_assignable<NotCopyableNotMovableMap>::value");
|
| 507 |
+
static_assert(!pybind11::detail::is_copy_assignable<NotCopyableNotMovableMap>::value,
|
| 508 |
+
"!pybind11::detail::is_copy_assignable<NotCopyableNotMovableMap>::value");
|
| 509 |
+
|
| 510 |
+
struct RecursiveVector : std::vector<RecursiveVector> {};
|
| 511 |
+
static_assert(std::is_move_constructible<RecursiveVector>::value,
|
| 512 |
+
"std::is_move_constructible<RecursiveVector>::value");
|
| 513 |
+
static_assert(std::is_copy_constructible<RecursiveVector>::value,
|
| 514 |
+
"std::is_copy_constructible<RecursiveVector>::value");
|
| 515 |
+
static_assert(pybind11::detail::is_move_constructible<RecursiveVector>::value,
|
| 516 |
+
"pybind11::detail::is_move_constructible<RecursiveVector>::value");
|
| 517 |
+
static_assert(pybind11::detail::is_copy_constructible<RecursiveVector>::value,
|
| 518 |
+
"pybind11::detail::is_copy_constructible<RecursiveVector>::value");
|
| 519 |
+
static_assert(std::is_move_assignable<RecursiveVector>::value,
|
| 520 |
+
"std::is_move_assignable<RecursiveVector>::value");
|
| 521 |
+
static_assert(std::is_copy_assignable<RecursiveVector>::value,
|
| 522 |
+
"std::is_copy_assignable<RecursiveVector>::value");
|
| 523 |
+
// pybind11 does not have this
|
| 524 |
+
// static_assert(!pybind11::detail::is_move_assignable<RecursiveVector>::value,
|
| 525 |
+
// "!pybind11::detail::is_move_assignable<RecursiveVector>::value");
|
| 526 |
+
static_assert(pybind11::detail::is_copy_assignable<RecursiveVector>::value,
|
| 527 |
+
"pybind11::detail::is_copy_assignable<RecursiveVector>::value");
|
| 528 |
+
|
| 529 |
+
struct RecursiveMap : std::map<int, RecursiveMap> {};
|
| 530 |
+
static_assert(std::is_move_constructible<RecursiveMap>::value,
|
| 531 |
+
"std::is_move_constructible<RecursiveMap>::value");
|
| 532 |
+
static_assert(std::is_copy_constructible<RecursiveMap>::value,
|
| 533 |
+
"std::is_copy_constructible<RecursiveMap>::value");
|
| 534 |
+
static_assert(pybind11::detail::is_move_constructible<RecursiveMap>::value,
|
| 535 |
+
"pybind11::detail::is_move_constructible<RecursiveMap>::value");
|
| 536 |
+
static_assert(pybind11::detail::is_copy_constructible<RecursiveMap>::value,
|
| 537 |
+
"pybind11::detail::is_copy_constructible<RecursiveMap>::value");
|
| 538 |
+
static_assert(std::is_move_assignable<RecursiveMap>::value,
|
| 539 |
+
"std::is_move_assignable<RecursiveMap>::value");
|
| 540 |
+
static_assert(std::is_copy_assignable<RecursiveMap>::value,
|
| 541 |
+
"std::is_copy_assignable<RecursiveMap>::value");
|
| 542 |
+
// pybind11 does not have this
|
| 543 |
+
// static_assert(!pybind11::detail::is_move_assignable<RecursiveMap>::value,
|
| 544 |
+
// "!pybind11::detail::is_move_assignable<RecursiveMap>::value");
|
| 545 |
+
static_assert(pybind11::detail::is_copy_assignable<RecursiveMap>::value,
|
| 546 |
+
"pybind11::detail::is_copy_assignable<RecursiveMap>::value");
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_copy_move.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import env # noqa: F401
|
| 6 |
+
from pybind11_tests import copy_move_policies as m
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_lacking_copy_ctor():
|
| 10 |
+
with pytest.raises(RuntimeError) as excinfo:
|
| 11 |
+
m.lacking_copy_ctor.get_one()
|
| 12 |
+
assert "is non-copyable!" in str(excinfo.value)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_lacking_move_ctor():
|
| 16 |
+
with pytest.raises(RuntimeError) as excinfo:
|
| 17 |
+
m.lacking_move_ctor.get_one()
|
| 18 |
+
assert "is neither movable nor copyable!" in str(excinfo.value)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Cannot reliably trigger GC")
|
| 22 |
+
def test_move_and_copy_casts():
|
| 23 |
+
"""Cast some values in C++ via custom type casters and count the number of moves/copies."""
|
| 24 |
+
|
| 25 |
+
cstats = m.move_and_copy_cstats()
|
| 26 |
+
c_m, c_mc, c_c = (
|
| 27 |
+
cstats["MoveOnlyInt"],
|
| 28 |
+
cstats["MoveOrCopyInt"],
|
| 29 |
+
cstats["CopyOnlyInt"],
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# The type move constructions/assignments below each get incremented: the move assignment comes
|
| 33 |
+
# from the type_caster load; the move construction happens when extracting that via a cast or
|
| 34 |
+
# loading into an argument.
|
| 35 |
+
assert m.move_and_copy_casts(3) == 18
|
| 36 |
+
assert c_m.copy_assignments + c_m.copy_constructions == 0
|
| 37 |
+
assert c_m.move_assignments == 2
|
| 38 |
+
assert c_m.move_constructions >= 2
|
| 39 |
+
assert c_mc.alive() == 0
|
| 40 |
+
assert c_mc.copy_assignments + c_mc.copy_constructions == 0
|
| 41 |
+
assert c_mc.move_assignments == 2
|
| 42 |
+
assert c_mc.move_constructions >= 2
|
| 43 |
+
assert c_c.alive() == 0
|
| 44 |
+
assert c_c.copy_assignments == 2
|
| 45 |
+
assert c_c.copy_constructions >= 2
|
| 46 |
+
assert c_m.alive() + c_mc.alive() + c_c.alive() == 0
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Cannot reliably trigger GC")
|
| 50 |
+
def test_move_and_copy_loads():
|
| 51 |
+
"""Call some functions that load arguments via custom type casters and count the number of
|
| 52 |
+
moves/copies."""
|
| 53 |
+
|
| 54 |
+
cstats = m.move_and_copy_cstats()
|
| 55 |
+
c_m, c_mc, c_c = (
|
| 56 |
+
cstats["MoveOnlyInt"],
|
| 57 |
+
cstats["MoveOrCopyInt"],
|
| 58 |
+
cstats["CopyOnlyInt"],
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
assert m.move_only(10) == 10 # 1 move, c_m
|
| 62 |
+
assert m.move_or_copy(11) == 11 # 1 move, c_mc
|
| 63 |
+
assert m.copy_only(12) == 12 # 1 copy, c_c
|
| 64 |
+
assert m.move_pair((13, 14)) == 27 # 1 c_m move, 1 c_mc move
|
| 65 |
+
assert m.move_tuple((15, 16, 17)) == 48 # 2 c_m moves, 1 c_mc move
|
| 66 |
+
assert m.copy_tuple((18, 19)) == 37 # 2 c_c copies
|
| 67 |
+
# Direct constructions: 2 c_m moves, 2 c_mc moves, 1 c_c copy
|
| 68 |
+
# Extra moves/copies when moving pairs/tuples: 3 c_m, 3 c_mc, 2 c_c
|
| 69 |
+
assert m.move_copy_nested((1, ((2, 3, (4,)), 5))) == 15
|
| 70 |
+
|
| 71 |
+
assert c_m.copy_assignments + c_m.copy_constructions == 0
|
| 72 |
+
assert c_m.move_assignments == 6
|
| 73 |
+
assert c_m.move_constructions == 9
|
| 74 |
+
assert c_mc.copy_assignments + c_mc.copy_constructions == 0
|
| 75 |
+
assert c_mc.move_assignments == 5
|
| 76 |
+
assert c_mc.move_constructions == 8
|
| 77 |
+
assert c_c.copy_assignments == 4
|
| 78 |
+
assert c_c.copy_constructions == 6
|
| 79 |
+
assert c_m.alive() + c_mc.alive() + c_c.alive() == 0
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@pytest.mark.skipif(not m.has_optional, reason="no <optional>")
|
| 83 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Cannot reliably trigger GC")
|
| 84 |
+
def test_move_and_copy_load_optional():
|
| 85 |
+
"""Tests move/copy loads of std::optional arguments"""
|
| 86 |
+
|
| 87 |
+
cstats = m.move_and_copy_cstats()
|
| 88 |
+
c_m, c_mc, c_c = (
|
| 89 |
+
cstats["MoveOnlyInt"],
|
| 90 |
+
cstats["MoveOrCopyInt"],
|
| 91 |
+
cstats["CopyOnlyInt"],
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
# The extra move/copy constructions below come from the std::optional move (which has to move
|
| 95 |
+
# its arguments):
|
| 96 |
+
assert m.move_optional(10) == 10 # c_m: 1 move assign, 2 move construct
|
| 97 |
+
assert m.move_or_copy_optional(11) == 11 # c_mc: 1 move assign, 2 move construct
|
| 98 |
+
assert m.copy_optional(12) == 12 # c_c: 1 copy assign, 2 copy construct
|
| 99 |
+
# 1 move assign + move construct moves each of c_m, c_mc, 1 c_c copy
|
| 100 |
+
# +1 move/copy construct each from moving the tuple
|
| 101 |
+
# +1 move/copy construct each from moving the optional (which moves the tuple again)
|
| 102 |
+
assert m.move_optional_tuple((3, 4, 5)) == 12
|
| 103 |
+
|
| 104 |
+
assert c_m.copy_assignments + c_m.copy_constructions == 0
|
| 105 |
+
assert c_m.move_assignments == 2
|
| 106 |
+
assert c_m.move_constructions == 5
|
| 107 |
+
assert c_mc.copy_assignments + c_mc.copy_constructions == 0
|
| 108 |
+
assert c_mc.move_assignments == 2
|
| 109 |
+
assert c_mc.move_constructions == 5
|
| 110 |
+
assert c_c.copy_assignments == 2
|
| 111 |
+
assert c_c.copy_constructions == 5
|
| 112 |
+
assert c_m.alive() + c_mc.alive() + c_c.alive() == 0
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_private_op_new():
|
| 116 |
+
"""An object with a private `operator new` cannot be returned by value"""
|
| 117 |
+
|
| 118 |
+
with pytest.raises(RuntimeError) as excinfo:
|
| 119 |
+
m.private_op_new_value()
|
| 120 |
+
assert "is neither movable nor copyable" in str(excinfo.value)
|
| 121 |
+
|
| 122 |
+
assert m.private_op_new_reference().value == 1
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_move_fallback():
|
| 126 |
+
"""#389: rvp::move should fall-through to copy on non-movable objects"""
|
| 127 |
+
|
| 128 |
+
m1 = m.get_moveissue1(1)
|
| 129 |
+
assert m1.value == 1
|
| 130 |
+
m2 = m.get_moveissue2(2)
|
| 131 |
+
assert m2.value == 2
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def test_pytype_rvalue_cast():
|
| 135 |
+
"""Make sure that cast from pytype rvalue to other pytype works"""
|
| 136 |
+
|
| 137 |
+
value = m.get_pytype_rvalue_castissue(1.0)
|
| 138 |
+
assert value == 1
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_unusual_op_ref():
|
| 142 |
+
# Merely to test that this still exists and built successfully.
|
| 143 |
+
assert m.CallCastUnusualOpRefConstRef().__class__.__name__ == "UnusualOpRef"
|
| 144 |
+
assert m.CallCastUnusualOpRefMovable().__class__.__name__ == "UnusualOpRef"
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cpp_conduit.cpp
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright (c) 2024 The pybind Community.
|
| 2 |
+
|
| 3 |
+
#include "pybind11_tests.h"
|
| 4 |
+
#include "test_cpp_conduit_traveler_bindings.h"
|
| 5 |
+
|
| 6 |
+
#include <typeinfo>
|
| 7 |
+
|
| 8 |
+
namespace pybind11_tests {
|
| 9 |
+
namespace test_cpp_conduit {
|
| 10 |
+
|
| 11 |
+
TEST_SUBMODULE(cpp_conduit, m) {
|
| 12 |
+
m.attr("PYBIND11_PLATFORM_ABI_ID") = py::bytes(PYBIND11_PLATFORM_ABI_ID);
|
| 13 |
+
m.attr("cpp_type_info_capsule_Traveler")
|
| 14 |
+
= py::capsule(&typeid(Traveler), typeid(std::type_info).name());
|
| 15 |
+
m.attr("cpp_type_info_capsule_int") = py::capsule(&typeid(int), typeid(std::type_info).name());
|
| 16 |
+
|
| 17 |
+
wrap_traveler(m);
|
| 18 |
+
wrap_lonely_traveler(m);
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
} // namespace test_cpp_conduit
|
| 22 |
+
} // namespace pybind11_tests
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cpp_conduit.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2024 The pybind Community.
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import importlib
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
import env
|
| 11 |
+
from pybind11_tests import cpp_conduit as home_planet
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def import_warns_freethreaded(name):
|
| 15 |
+
if name not in sys.modules and not env.sys_is_gil_enabled():
|
| 16 |
+
with pytest.warns(
|
| 17 |
+
RuntimeWarning, match=f"has been enabled to load module '{name}'"
|
| 18 |
+
):
|
| 19 |
+
return importlib.import_module(name)
|
| 20 |
+
|
| 21 |
+
return importlib.import_module(name)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
exo_planet_c_api = import_warns_freethreaded("exo_planet_c_api")
|
| 25 |
+
exo_planet_pybind11 = import_warns_freethreaded("exo_planet_pybind11")
|
| 26 |
+
home_planet_very_lonely_traveler = import_warns_freethreaded(
|
| 27 |
+
"home_planet_very_lonely_traveler"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_traveler_getattr_actually_exists():
|
| 32 |
+
t_h = home_planet.Traveler("home")
|
| 33 |
+
assert t_h.any_name == "Traveler GetAttr: any_name luggage: home"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_premium_traveler_getattr_actually_exists():
|
| 37 |
+
t_h = home_planet.PremiumTraveler("home", 7)
|
| 38 |
+
assert t_h.secret_name == "PremiumTraveler GetAttr: secret_name points: 7"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_call_cpp_conduit_success():
|
| 42 |
+
t_h = home_planet.Traveler("home")
|
| 43 |
+
cap = t_h._pybind11_conduit_v1_(
|
| 44 |
+
home_planet.PYBIND11_PLATFORM_ABI_ID,
|
| 45 |
+
home_planet.cpp_type_info_capsule_Traveler,
|
| 46 |
+
b"raw_pointer_ephemeral",
|
| 47 |
+
)
|
| 48 |
+
assert cap.__class__.__name__ == "PyCapsule" or (
|
| 49 |
+
# Note: this will become unnecessary in the next GraalPy release
|
| 50 |
+
env.GRAALPY and cap.__class__.__name__ == "capsule"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_call_cpp_conduit_platform_abi_id_mismatch():
|
| 55 |
+
t_h = home_planet.Traveler("home")
|
| 56 |
+
cap = t_h._pybind11_conduit_v1_(
|
| 57 |
+
home_planet.PYBIND11_PLATFORM_ABI_ID + b"MISMATCH",
|
| 58 |
+
home_planet.cpp_type_info_capsule_Traveler,
|
| 59 |
+
b"raw_pointer_ephemeral",
|
| 60 |
+
)
|
| 61 |
+
assert cap is None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_call_cpp_conduit_cpp_type_info_capsule_mismatch():
|
| 65 |
+
t_h = home_planet.Traveler("home")
|
| 66 |
+
cap = t_h._pybind11_conduit_v1_(
|
| 67 |
+
home_planet.PYBIND11_PLATFORM_ABI_ID,
|
| 68 |
+
home_planet.cpp_type_info_capsule_int,
|
| 69 |
+
b"raw_pointer_ephemeral",
|
| 70 |
+
)
|
| 71 |
+
assert cap is None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_call_cpp_conduit_pointer_kind_invalid():
|
| 75 |
+
t_h = home_planet.Traveler("home")
|
| 76 |
+
with pytest.raises(
|
| 77 |
+
RuntimeError, match='^Invalid pointer_kind: "raw_pointer_ephemreal"$'
|
| 78 |
+
):
|
| 79 |
+
t_h._pybind11_conduit_v1_(
|
| 80 |
+
home_planet.PYBIND11_PLATFORM_ABI_ID,
|
| 81 |
+
home_planet.cpp_type_info_capsule_Traveler,
|
| 82 |
+
b"raw_pointer_ephemreal",
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_home_only_basic():
|
| 87 |
+
t_h = home_planet.Traveler("home")
|
| 88 |
+
assert t_h.luggage == "home"
|
| 89 |
+
assert home_planet.get_luggage(t_h) == "home"
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_home_only_premium():
|
| 93 |
+
p_h = home_planet.PremiumTraveler("home", 2)
|
| 94 |
+
assert p_h.luggage == "home"
|
| 95 |
+
assert home_planet.get_luggage(p_h) == "home"
|
| 96 |
+
assert home_planet.get_points(p_h) == 2
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_exo_only_basic():
|
| 100 |
+
t_e = exo_planet_pybind11.Traveler("exo")
|
| 101 |
+
assert t_e.luggage == "exo"
|
| 102 |
+
assert exo_planet_pybind11.get_luggage(t_e) == "exo"
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def test_exo_only_premium():
|
| 106 |
+
p_e = exo_planet_pybind11.PremiumTraveler("exo", 3)
|
| 107 |
+
assert p_e.luggage == "exo"
|
| 108 |
+
assert exo_planet_pybind11.get_luggage(p_e) == "exo"
|
| 109 |
+
assert exo_planet_pybind11.get_points(p_e) == 3
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_home_passed_to_exo_basic():
|
| 113 |
+
t_h = home_planet.Traveler("home")
|
| 114 |
+
assert exo_planet_pybind11.get_luggage(t_h) == "home"
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_exo_passed_to_home_basic():
|
| 118 |
+
t_e = exo_planet_pybind11.Traveler("exo")
|
| 119 |
+
assert home_planet.get_luggage(t_e) == "exo"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_home_passed_to_exo_premium():
|
| 123 |
+
p_h = home_planet.PremiumTraveler("home", 2)
|
| 124 |
+
assert exo_planet_pybind11.get_luggage(p_h) == "home"
|
| 125 |
+
assert exo_planet_pybind11.get_points(p_h) == 2
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_exo_passed_to_home_premium():
|
| 129 |
+
p_e = exo_planet_pybind11.PremiumTraveler("exo", 3)
|
| 130 |
+
assert home_planet.get_luggage(p_e) == "exo"
|
| 131 |
+
assert home_planet.get_points(p_e) == 3
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@pytest.mark.parametrize(
|
| 135 |
+
"traveler_type", [home_planet.Traveler, exo_planet_pybind11.Traveler]
|
| 136 |
+
)
|
| 137 |
+
def test_exo_planet_c_api_traveler(traveler_type):
|
| 138 |
+
t = traveler_type("socks")
|
| 139 |
+
assert exo_planet_c_api.GetLuggage(t) == "socks"
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@pytest.mark.parametrize(
|
| 143 |
+
"premium_traveler_type",
|
| 144 |
+
[home_planet.PremiumTraveler, exo_planet_pybind11.PremiumTraveler],
|
| 145 |
+
)
|
| 146 |
+
def test_exo_planet_c_api_premium_traveler(premium_traveler_type):
|
| 147 |
+
pt = premium_traveler_type("gucci", 5)
|
| 148 |
+
assert exo_planet_c_api.GetLuggage(pt) == "gucci"
|
| 149 |
+
assert exo_planet_c_api.GetPoints(pt) == 5
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def test_home_planet_wrap_very_lonely_traveler():
|
| 153 |
+
# This does not exercise the cpp_conduit feature, but is here to
|
| 154 |
+
# demonstrate that the cpp_conduit feature does not solve
|
| 155 |
+
# cross-extension base-and-derived class interoperability issues.
|
| 156 |
+
# Here is the proof that the following works for extensions with
|
| 157 |
+
# matching `PYBIND11_INTERNALS_ID`s:
|
| 158 |
+
# test_cpp_conduit.cpp:
|
| 159 |
+
# py::class_<LonelyTraveler>
|
| 160 |
+
# home_planet_very_lonely_traveler.cpp:
|
| 161 |
+
# py::class_<VeryLonelyTraveler, LonelyTraveler>
|
| 162 |
+
# See test_exo_planet_pybind11_wrap_very_lonely_traveler() for the negative
|
| 163 |
+
# test.
|
| 164 |
+
assert home_planet.LonelyTraveler is not None # Verify that the base class exists.
|
| 165 |
+
home_planet_very_lonely_traveler.wrap_very_lonely_traveler()
|
| 166 |
+
# Ensure that the derived class exists.
|
| 167 |
+
assert home_planet_very_lonely_traveler.VeryLonelyTraveler is not None
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def test_exo_planet_pybind11_wrap_very_lonely_traveler():
|
| 171 |
+
# See comment under test_home_planet_wrap_very_lonely_traveler() first.
|
| 172 |
+
# Here the `PYBIND11_INTERNALS_ID`s don't match between:
|
| 173 |
+
# test_cpp_conduit.cpp:
|
| 174 |
+
# py::class_<LonelyTraveler>
|
| 175 |
+
# exo_planet_pybind11.cpp:
|
| 176 |
+
# py::class_<VeryLonelyTraveler, LonelyTraveler>
|
| 177 |
+
assert home_planet.LonelyTraveler is not None # Verify that the base class exists.
|
| 178 |
+
with pytest.raises(
|
| 179 |
+
RuntimeError,
|
| 180 |
+
match='^generic_type: type "VeryLonelyTraveler" referenced unknown base type '
|
| 181 |
+
'"pybind11_tests::test_cpp_conduit::LonelyTraveler"$',
|
| 182 |
+
):
|
| 183 |
+
exo_planet_pybind11.wrap_very_lonely_traveler()
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cpp_conduit_traveler_bindings.h
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright (c) 2024 The pybind Community.
|
| 2 |
+
|
| 3 |
+
#pragma once
|
| 4 |
+
|
| 5 |
+
#include <pybind11/pybind11.h>
|
| 6 |
+
|
| 7 |
+
#include "test_cpp_conduit_traveler_types.h"
|
| 8 |
+
|
| 9 |
+
#include <string>
|
| 10 |
+
|
| 11 |
+
namespace pybind11_tests {
|
| 12 |
+
namespace test_cpp_conduit {
|
| 13 |
+
|
| 14 |
+
namespace py = pybind11;
|
| 15 |
+
|
| 16 |
+
inline void wrap_traveler(py::module_ m) {
|
| 17 |
+
py::class_<Traveler>(m, "Traveler")
|
| 18 |
+
.def(py::init<std::string>())
|
| 19 |
+
.def_readwrite("luggage", &Traveler::luggage)
|
| 20 |
+
// See issue #3788:
|
| 21 |
+
.def("__getattr__", [](const Traveler &self, const std::string &key) {
|
| 22 |
+
return "Traveler GetAttr: " + key + " luggage: " + self.luggage;
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
m.def("get_luggage", [](const Traveler &person) { return person.luggage; });
|
| 26 |
+
|
| 27 |
+
py::class_<PremiumTraveler, Traveler>(m, "PremiumTraveler")
|
| 28 |
+
.def(py::init<std::string, int>())
|
| 29 |
+
.def_readwrite("points", &PremiumTraveler::points)
|
| 30 |
+
// See issue #3788:
|
| 31 |
+
.def("__getattr__", [](const PremiumTraveler &self, const std::string &key) {
|
| 32 |
+
return "PremiumTraveler GetAttr: " + key + " points: " + std::to_string(self.points);
|
| 33 |
+
});
|
| 34 |
+
|
| 35 |
+
m.def("get_points", [](const PremiumTraveler &person) { return person.points; });
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
inline void wrap_lonely_traveler(py::module_ m) {
|
| 39 |
+
py::class_<LonelyTraveler>(std::move(m), "LonelyTraveler");
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
inline void wrap_very_lonely_traveler(py::module_ m) {
|
| 43 |
+
py::class_<VeryLonelyTraveler, LonelyTraveler>(std::move(m), "VeryLonelyTraveler");
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
} // namespace test_cpp_conduit
|
| 47 |
+
} // namespace pybind11_tests
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cpp_conduit_traveler_types.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright (c) 2024 The pybind Community.
|
| 2 |
+
|
| 3 |
+
#pragma once
|
| 4 |
+
|
| 5 |
+
#include <string>
|
| 6 |
+
|
| 7 |
+
namespace pybind11_tests {
|
| 8 |
+
namespace test_cpp_conduit {
|
| 9 |
+
|
| 10 |
+
struct Traveler {
|
| 11 |
+
explicit Traveler(const std::string &luggage) : luggage(luggage) {}
|
| 12 |
+
std::string luggage;
|
| 13 |
+
};
|
| 14 |
+
|
| 15 |
+
struct PremiumTraveler : Traveler {
|
| 16 |
+
explicit PremiumTraveler(const std::string &luggage, int points)
|
| 17 |
+
: Traveler(luggage), points(points) {}
|
| 18 |
+
int points;
|
| 19 |
+
};
|
| 20 |
+
|
| 21 |
+
struct LonelyTraveler {};
|
| 22 |
+
struct VeryLonelyTraveler : LonelyTraveler {};
|
| 23 |
+
|
| 24 |
+
} // namespace test_cpp_conduit
|
| 25 |
+
} // namespace pybind11_tests
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/CMakeLists.txt
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
possibly_uninitialized(PYTHON_MODULE_EXTENSION Python_INTERPRETER_ID)
|
| 2 |
+
|
| 3 |
+
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
|
| 4 |
+
|
| 5 |
+
if("${PYTHON_MODULE_EXTENSION}" MATCHES "pypy"
|
| 6 |
+
OR "${Python_INTERPRETER_ID}" STREQUAL "PyPy"
|
| 7 |
+
OR "${PYTHON_MODULE_EXTENSION}" MATCHES "graalpy")
|
| 8 |
+
message(STATUS "Skipping visibility test on PyPy or GraalPy")
|
| 9 |
+
add_custom_target(test_cross_module_rtti
|
| 10 |
+
)# Dummy target on PyPy or GraalPy. Embedding is not supported.
|
| 11 |
+
set(_suppress_unused_variable_warning "${DOWNLOAD_CATCH}")
|
| 12 |
+
return()
|
| 13 |
+
endif()
|
| 14 |
+
|
| 15 |
+
if(TARGET Python::Module AND NOT TARGET Python::Python)
|
| 16 |
+
message(STATUS "Skipping visibility test since no embed libs found")
|
| 17 |
+
add_custom_target(test_cross_module_rtti) # Dummy target since embedding is not supported.
|
| 18 |
+
set(_suppress_unused_variable_warning "${DOWNLOAD_CATCH}")
|
| 19 |
+
return()
|
| 20 |
+
endif()
|
| 21 |
+
|
| 22 |
+
find_package(Catch 2.13.10)
|
| 23 |
+
|
| 24 |
+
if(CATCH_FOUND)
|
| 25 |
+
message(STATUS "Building interpreter tests using Catch v${CATCH_VERSION}")
|
| 26 |
+
else()
|
| 27 |
+
message(STATUS "Catch not detected. Interpreter tests will be skipped. Install Catch headers"
|
| 28 |
+
" manually or use `cmake -DDOWNLOAD_CATCH=ON` to fetch them automatically.")
|
| 29 |
+
return()
|
| 30 |
+
endif()
|
| 31 |
+
|
| 32 |
+
include(GenerateExportHeader)
|
| 33 |
+
|
| 34 |
+
add_library(test_cross_module_rtti_lib SHARED lib.h lib.cpp)
|
| 35 |
+
add_library(test_cross_module_rtti_lib::test_cross_module_rtti_lib ALIAS
|
| 36 |
+
test_cross_module_rtti_lib)
|
| 37 |
+
target_include_directories(test_cross_module_rtti_lib PUBLIC ${CMAKE_CURRENT_BINARY_DIR})
|
| 38 |
+
target_include_directories(test_cross_module_rtti_lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
| 39 |
+
target_compile_features(test_cross_module_rtti_lib PUBLIC cxx_std_11)
|
| 40 |
+
|
| 41 |
+
generate_export_header(test_cross_module_rtti_lib)
|
| 42 |
+
|
| 43 |
+
pybind11_add_module(test_cross_module_rtti_bindings SHARED bindings.cpp)
|
| 44 |
+
target_link_libraries(test_cross_module_rtti_bindings
|
| 45 |
+
PUBLIC test_cross_module_rtti_lib::test_cross_module_rtti_lib)
|
| 46 |
+
|
| 47 |
+
add_executable(test_cross_module_rtti_main catch.cpp test_cross_module_rtti.cpp)
|
| 48 |
+
target_link_libraries(
|
| 49 |
+
test_cross_module_rtti_main PUBLIC test_cross_module_rtti_lib::test_cross_module_rtti_lib
|
| 50 |
+
pybind11::embed Catch2::Catch2)
|
| 51 |
+
|
| 52 |
+
# Ensure that we have built the python bindings since we load them in main
|
| 53 |
+
add_dependencies(test_cross_module_rtti_main test_cross_module_rtti_bindings)
|
| 54 |
+
|
| 55 |
+
pybind11_enable_warnings(test_cross_module_rtti_main)
|
| 56 |
+
pybind11_enable_warnings(test_cross_module_rtti_bindings)
|
| 57 |
+
pybind11_enable_warnings(test_cross_module_rtti_lib)
|
| 58 |
+
|
| 59 |
+
add_custom_target(
|
| 60 |
+
test_cross_module_rtti
|
| 61 |
+
COMMAND "$<TARGET_FILE:test_cross_module_rtti_main>"
|
| 62 |
+
DEPENDS test_cross_module_rtti_main
|
| 63 |
+
WORKING_DIRECTORY "$<TARGET_FILE_DIR:test_cross_module_rtti_main>")
|
| 64 |
+
|
| 65 |
+
set_target_properties(test_cross_module_rtti_bindings PROPERTIES LIBRARY_OUTPUT_DIRECTORY
|
| 66 |
+
"${CMAKE_CURRENT_BINARY_DIR}")
|
| 67 |
+
|
| 68 |
+
add_dependencies(check test_cross_module_rtti)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/bindings.cpp
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <pybind11/pybind11.h>
|
| 2 |
+
|
| 3 |
+
#include <lib.h>
|
| 4 |
+
|
| 5 |
+
class BaseTrampoline : public lib::Base, public pybind11::trampoline_self_life_support {
|
| 6 |
+
public:
|
| 7 |
+
using lib::Base::Base;
|
| 8 |
+
int get() const override { PYBIND11_OVERLOAD(int, lib::Base, get); }
|
| 9 |
+
};
|
| 10 |
+
|
| 11 |
+
PYBIND11_MODULE(test_cross_module_rtti_bindings, m) {
|
| 12 |
+
pybind11::classh<lib::Base, BaseTrampoline>(m, "Base")
|
| 13 |
+
.def(pybind11::init<int, int>())
|
| 14 |
+
.def_readwrite("a", &lib::Base::a)
|
| 15 |
+
.def_readwrite("b", &lib::Base::b);
|
| 16 |
+
|
| 17 |
+
m.def("get_foo", [](int a, int b) -> std::shared_ptr<lib::Base> {
|
| 18 |
+
return std::make_shared<lib::Foo>(a, b);
|
| 19 |
+
});
|
| 20 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/catch.cpp
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// The Catch implementation is compiled here. This is a standalone
|
| 2 |
+
// translation unit to avoid recompiling it for every test change.
|
| 3 |
+
|
| 4 |
+
#include <pybind11/embed.h>
|
| 5 |
+
|
| 6 |
+
// Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to
|
| 7 |
+
// catch 2.0.1; this should be fixed in the next catch release after 2.0.1).
|
| 8 |
+
PYBIND11_WARNING_DISABLE_MSVC(4996)
|
| 9 |
+
|
| 10 |
+
// Catch uses _ internally, which breaks gettext style defines
|
| 11 |
+
#ifdef _
|
| 12 |
+
# undef _
|
| 13 |
+
#endif
|
| 14 |
+
|
| 15 |
+
#define CATCH_CONFIG_RUNNER
|
| 16 |
+
#include <catch.hpp>
|
| 17 |
+
|
| 18 |
+
int main(int argc, char *argv[]) {
|
| 19 |
+
pybind11::scoped_interpreter guard{};
|
| 20 |
+
auto result = Catch::Session().run(argc, argv);
|
| 21 |
+
return result < 0xff ? result : 0xff;
|
| 22 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/lib.cpp
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <lib.h>
|
| 2 |
+
|
| 3 |
+
namespace lib {
|
| 4 |
+
|
| 5 |
+
Base::Base(int a, int b) : a(a), b(b) {}
|
| 6 |
+
|
| 7 |
+
int Base::get() const { return a + b; }
|
| 8 |
+
|
| 9 |
+
Foo::Foo(int a, int b) : Base{a, b} {}
|
| 10 |
+
|
| 11 |
+
int Foo::get() const { return 2 * a + b; }
|
| 12 |
+
|
| 13 |
+
} // namespace lib
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/lib.h
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <memory>
|
| 4 |
+
#include <test_cross_module_rtti_lib_export.h>
|
| 5 |
+
|
| 6 |
+
#if defined(_MSC_VER)
|
| 7 |
+
__pragma(warning(disable : 4251))
|
| 8 |
+
#endif
|
| 9 |
+
|
| 10 |
+
namespace lib {
|
| 11 |
+
|
| 12 |
+
class TEST_CROSS_MODULE_RTTI_LIB_EXPORT Base : public std::enable_shared_from_this<Base> {
|
| 13 |
+
public:
|
| 14 |
+
Base(int a, int b);
|
| 15 |
+
Base(const Base &) = default;
|
| 16 |
+
virtual ~Base() = default;
|
| 17 |
+
|
| 18 |
+
virtual int get() const;
|
| 19 |
+
|
| 20 |
+
int a;
|
| 21 |
+
int b;
|
| 22 |
+
};
|
| 23 |
+
|
| 24 |
+
class TEST_CROSS_MODULE_RTTI_LIB_EXPORT Foo : public Base {
|
| 25 |
+
public:
|
| 26 |
+
Foo(int a, int b);
|
| 27 |
+
|
| 28 |
+
int get() const override;
|
| 29 |
+
};
|
| 30 |
+
|
| 31 |
+
} // namespace lib
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_cross_module_rtti/test_cross_module_rtti.cpp
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
#include <pybind11/embed.h>
|
| 3 |
+
#include <pybind11/pybind11.h>
|
| 4 |
+
|
| 5 |
+
#include <catch.hpp>
|
| 6 |
+
#include <lib.h>
|
| 7 |
+
|
| 8 |
+
static constexpr auto script = R"(
|
| 9 |
+
import test_cross_module_rtti_bindings
|
| 10 |
+
|
| 11 |
+
class Bar(test_cross_module_rtti_bindings.Base):
|
| 12 |
+
def __init__(self, a, b):
|
| 13 |
+
test_cross_module_rtti_bindings.Base.__init__(self, a, b)
|
| 14 |
+
|
| 15 |
+
def get(self):
|
| 16 |
+
return 4 * self.a + self.b
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_bar(a, b):
|
| 20 |
+
return Bar(a, b)
|
| 21 |
+
|
| 22 |
+
)";
|
| 23 |
+
|
| 24 |
+
TEST_CASE("Simple case where without is_alias") {
|
| 25 |
+
// "Simple" case this will not have `python_instance_is_alias` set in type_cast_base.h:771
|
| 26 |
+
auto bindings = pybind11::module_::import("test_cross_module_rtti_bindings");
|
| 27 |
+
auto holder = bindings.attr("get_foo")(1, 2);
|
| 28 |
+
auto foo = holder.cast<std::shared_ptr<lib::Base>>();
|
| 29 |
+
REQUIRE(foo->get() == 4); // 2 * 1 + 2 = 4
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
TEST_CASE("Complex case where with it_alias") {
|
| 33 |
+
// "Complex" case this will have `python_instance_is_alias` set in type_cast_base.h:771
|
| 34 |
+
pybind11::exec(script);
|
| 35 |
+
auto main = pybind11::module::import("__main__");
|
| 36 |
+
|
| 37 |
+
// The critical part of "Bar" is that it will have the `is_alias` `instance` flag set.
|
| 38 |
+
// I'm not quite sure what is required to get that flag, this code is derived from a
|
| 39 |
+
// larger code where this issue was observed.
|
| 40 |
+
auto holder2 = main.attr("get_bar")(1, 2);
|
| 41 |
+
|
| 42 |
+
// this will trigger `std::get_deleter<memory::guarded_delete>` in type_cast_base.h:772
|
| 43 |
+
// This will fail since the program will see two different typeids for `memory::guarded_delete`
|
| 44 |
+
// on from the bindings module and one from "main", which will both have
|
| 45 |
+
// `__is_type_name_unique` as true and but still have different values. Hence we will not find
|
| 46 |
+
// the deleter and the cast fill fail. See "__eq(__type_name_t __lhs, __type_name_t __rhs)" in
|
| 47 |
+
// typeinfo in libc++
|
| 48 |
+
auto bar = holder2.cast<std::shared_ptr<lib::Base>>();
|
| 49 |
+
REQUIRE(bar->get() == 6); // 4 * 1 + 2 = 6
|
| 50 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_custom_type_casters.cpp
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
tests/test_custom_type_casters.cpp -- tests type_caster<T>
|
| 3 |
+
|
| 4 |
+
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
|
| 5 |
+
|
| 6 |
+
All rights reserved. Use of this source code is governed by a
|
| 7 |
+
BSD-style license that can be found in the LICENSE file.
|
| 8 |
+
*/
|
| 9 |
+
|
| 10 |
+
#include "constructor_stats.h"
|
| 11 |
+
#include "pybind11_tests.h"
|
| 12 |
+
|
| 13 |
+
// py::arg/py::arg_v testing: these arguments just record their argument when invoked
|
| 14 |
+
class ArgInspector1 {
|
| 15 |
+
public:
|
| 16 |
+
std::string arg = "(default arg inspector 1)";
|
| 17 |
+
};
|
| 18 |
+
class ArgInspector2 {
|
| 19 |
+
public:
|
| 20 |
+
std::string arg = "(default arg inspector 2)";
|
| 21 |
+
};
|
| 22 |
+
class ArgAlwaysConverts {};
|
| 23 |
+
|
| 24 |
+
namespace PYBIND11_NAMESPACE {
|
| 25 |
+
namespace detail {
|
| 26 |
+
template <>
|
| 27 |
+
struct type_caster<ArgInspector1> {
|
| 28 |
+
public:
|
| 29 |
+
// Classic
|
| 30 |
+
#ifdef PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY
|
| 31 |
+
PYBIND11_TYPE_CASTER(ArgInspector1, _("ArgInspector1"));
|
| 32 |
+
#else
|
| 33 |
+
PYBIND11_TYPE_CASTER(ArgInspector1, const_name("ArgInspector1"));
|
| 34 |
+
#endif
|
| 35 |
+
|
| 36 |
+
bool load(handle src, bool convert) {
|
| 37 |
+
value.arg = "loading ArgInspector1 argument " + std::string(convert ? "WITH" : "WITHOUT")
|
| 38 |
+
+ " conversion allowed. "
|
| 39 |
+
"Argument value = "
|
| 40 |
+
+ (std::string) str(src);
|
| 41 |
+
return true;
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
static handle cast(const ArgInspector1 &src, return_value_policy, handle) {
|
| 45 |
+
return str(src.arg).release();
|
| 46 |
+
}
|
| 47 |
+
};
|
| 48 |
+
template <>
|
| 49 |
+
struct type_caster<ArgInspector2> {
|
| 50 |
+
public:
|
| 51 |
+
PYBIND11_TYPE_CASTER(ArgInspector2, const_name("ArgInspector2"));
|
| 52 |
+
|
| 53 |
+
bool load(handle src, bool convert) {
|
| 54 |
+
value.arg = "loading ArgInspector2 argument " + std::string(convert ? "WITH" : "WITHOUT")
|
| 55 |
+
+ " conversion allowed. "
|
| 56 |
+
"Argument value = "
|
| 57 |
+
+ (std::string) str(src);
|
| 58 |
+
return true;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
static handle cast(const ArgInspector2 &src, return_value_policy, handle) {
|
| 62 |
+
return str(src.arg).release();
|
| 63 |
+
}
|
| 64 |
+
};
|
| 65 |
+
template <>
|
| 66 |
+
struct type_caster<ArgAlwaysConverts> {
|
| 67 |
+
public:
|
| 68 |
+
PYBIND11_TYPE_CASTER(ArgAlwaysConverts, const_name("ArgAlwaysConverts"));
|
| 69 |
+
|
| 70 |
+
bool load(handle, bool convert) { return convert; }
|
| 71 |
+
|
| 72 |
+
static handle cast(const ArgAlwaysConverts &, return_value_policy, handle) {
|
| 73 |
+
return py::none().release();
|
| 74 |
+
}
|
| 75 |
+
};
|
| 76 |
+
} // namespace detail
|
| 77 |
+
} // namespace PYBIND11_NAMESPACE
|
| 78 |
+
|
| 79 |
+
// test_custom_caster_destruction
|
| 80 |
+
class DestructionTester {
|
| 81 |
+
public:
|
| 82 |
+
DestructionTester() { print_default_created(this); }
|
| 83 |
+
~DestructionTester() { print_destroyed(this); }
|
| 84 |
+
DestructionTester(const DestructionTester &) { print_copy_created(this); }
|
| 85 |
+
DestructionTester(DestructionTester &&) noexcept { print_move_created(this); }
|
| 86 |
+
DestructionTester &operator=(const DestructionTester &) {
|
| 87 |
+
print_copy_assigned(this);
|
| 88 |
+
return *this;
|
| 89 |
+
}
|
| 90 |
+
DestructionTester &operator=(DestructionTester &&) noexcept {
|
| 91 |
+
print_move_assigned(this);
|
| 92 |
+
return *this;
|
| 93 |
+
}
|
| 94 |
+
};
|
| 95 |
+
namespace PYBIND11_NAMESPACE {
|
| 96 |
+
namespace detail {
|
| 97 |
+
template <>
|
| 98 |
+
struct type_caster<DestructionTester> {
|
| 99 |
+
PYBIND11_TYPE_CASTER(DestructionTester, const_name("DestructionTester"));
|
| 100 |
+
bool load(handle, bool) { return true; }
|
| 101 |
+
|
| 102 |
+
static handle cast(const DestructionTester &, return_value_policy, handle) {
|
| 103 |
+
return py::bool_(true).release();
|
| 104 |
+
}
|
| 105 |
+
};
|
| 106 |
+
} // namespace detail
|
| 107 |
+
} // namespace PYBIND11_NAMESPACE
|
| 108 |
+
|
| 109 |
+
// Define type caster outside of `pybind11::detail` and then alias it.
|
| 110 |
+
namespace other_lib {
|
| 111 |
+
struct MyType {};
|
| 112 |
+
// Corrupt `py` shorthand alias for surrounding context.
|
| 113 |
+
namespace py {}
|
| 114 |
+
// Corrupt unqualified relative `pybind11` namespace.
|
| 115 |
+
namespace PYBIND11_NAMESPACE {}
|
| 116 |
+
// Correct alias.
|
| 117 |
+
namespace py_ = ::pybind11;
|
| 118 |
+
// Define caster. This is effectively no-op, we only ensure it compiles and we
|
| 119 |
+
// don't have any symbol collision when using macro mixin.
|
| 120 |
+
struct my_caster {
|
| 121 |
+
PYBIND11_TYPE_CASTER(MyType, py_::detail::const_name("MyType"));
|
| 122 |
+
bool load(py_::handle, bool) { return true; }
|
| 123 |
+
|
| 124 |
+
static py_::handle cast(const MyType &, py_::return_value_policy, py_::handle) {
|
| 125 |
+
return py_::bool_(true).release();
|
| 126 |
+
}
|
| 127 |
+
};
|
| 128 |
+
} // namespace other_lib
|
| 129 |
+
// Effectively "alias" it into correct namespace (via inheritance).
|
| 130 |
+
namespace PYBIND11_NAMESPACE {
|
| 131 |
+
namespace detail {
|
| 132 |
+
template <>
|
| 133 |
+
struct type_caster<other_lib::MyType> : public other_lib::my_caster {};
|
| 134 |
+
} // namespace detail
|
| 135 |
+
} // namespace PYBIND11_NAMESPACE
|
| 136 |
+
|
| 137 |
+
// This simply is required to compile
|
| 138 |
+
namespace ADL_issue {
|
| 139 |
+
template <typename OutStringType = std::string, typename... Args>
|
| 140 |
+
OutStringType concat(Args &&...) {
|
| 141 |
+
return OutStringType();
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
struct test {};
|
| 145 |
+
} // namespace ADL_issue
|
| 146 |
+
|
| 147 |
+
TEST_SUBMODULE(custom_type_casters, m) {
|
| 148 |
+
// test_custom_type_casters
|
| 149 |
+
|
| 150 |
+
// test_noconvert_args
|
| 151 |
+
//
|
| 152 |
+
// Test converting. The ArgAlwaysConverts is just there to make the first no-conversion pass
|
| 153 |
+
// fail so that our call always ends up happening via the second dispatch (the one that allows
|
| 154 |
+
// some conversion).
|
| 155 |
+
class ArgInspector {
|
| 156 |
+
public:
|
| 157 |
+
ArgInspector1 f(ArgInspector1 a, ArgAlwaysConverts) { return a; }
|
| 158 |
+
std::string g(const ArgInspector1 &a,
|
| 159 |
+
const ArgInspector1 &b,
|
| 160 |
+
int c,
|
| 161 |
+
ArgInspector2 *d,
|
| 162 |
+
ArgAlwaysConverts) {
|
| 163 |
+
return a.arg + "\n" + b.arg + "\n" + std::to_string(c) + "\n" + d->arg;
|
| 164 |
+
}
|
| 165 |
+
static ArgInspector2 h(ArgInspector2 a, ArgAlwaysConverts) { return a; }
|
| 166 |
+
};
|
| 167 |
+
// [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
|
| 168 |
+
py::class_<ArgInspector>(m, "ArgInspector")
|
| 169 |
+
.def(py::init<>())
|
| 170 |
+
.def("f", &ArgInspector::f, py::arg(), py::arg() = ArgAlwaysConverts())
|
| 171 |
+
.def("g",
|
| 172 |
+
&ArgInspector::g,
|
| 173 |
+
"a"_a.noconvert(),
|
| 174 |
+
"b"_a,
|
| 175 |
+
"c"_a.noconvert() = 13,
|
| 176 |
+
"d"_a = ArgInspector2(),
|
| 177 |
+
py::arg() = ArgAlwaysConverts())
|
| 178 |
+
.def_static("h", &ArgInspector::h, py::arg{}.noconvert(), py::arg() = ArgAlwaysConverts());
|
| 179 |
+
m.def(
|
| 180 |
+
"arg_inspect_func",
|
| 181 |
+
[](const ArgInspector2 &a, const ArgInspector1 &b, ArgAlwaysConverts) {
|
| 182 |
+
return a.arg + "\n" + b.arg;
|
| 183 |
+
},
|
| 184 |
+
py::arg{}.noconvert(false),
|
| 185 |
+
py::arg_v(nullptr, ArgInspector1()).noconvert(true),
|
| 186 |
+
py::arg() = ArgAlwaysConverts());
|
| 187 |
+
|
| 188 |
+
m.def("floats_preferred", [](double f) { return 0.5 * f; }, "f"_a);
|
| 189 |
+
m.def("floats_only", [](double f) { return 0.5 * f; }, "f"_a.noconvert());
|
| 190 |
+
m.def("ints_preferred", [](int i) { return i / 2; }, "i"_a);
|
| 191 |
+
m.def("ints_only", [](int i) { return i / 2; }, "i"_a.noconvert());
|
| 192 |
+
|
| 193 |
+
// test_custom_caster_destruction
|
| 194 |
+
// Test that `take_ownership` works on types with a custom type caster when given a pointer
|
| 195 |
+
|
| 196 |
+
// default policy: don't take ownership:
|
| 197 |
+
m.def("custom_caster_no_destroy", []() {
|
| 198 |
+
static auto *dt = new DestructionTester();
|
| 199 |
+
return dt;
|
| 200 |
+
});
|
| 201 |
+
|
| 202 |
+
m.def(
|
| 203 |
+
"custom_caster_destroy",
|
| 204 |
+
[]() { return new DestructionTester(); },
|
| 205 |
+
py::return_value_policy::take_ownership); // Takes ownership: destroy when finished
|
| 206 |
+
m.def(
|
| 207 |
+
"custom_caster_destroy_const",
|
| 208 |
+
[]() -> const DestructionTester * { return new DestructionTester(); },
|
| 209 |
+
py::return_value_policy::take_ownership); // Likewise (const doesn't inhibit destruction)
|
| 210 |
+
m.def("destruction_tester_cstats",
|
| 211 |
+
&ConstructorStats::get<DestructionTester>,
|
| 212 |
+
py::return_value_policy::reference);
|
| 213 |
+
|
| 214 |
+
m.def("other_lib_type", [](other_lib::MyType x) { return x; });
|
| 215 |
+
|
| 216 |
+
m.def("_adl_issue", [](const ADL_issue::test &) {});
|
| 217 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_custom_type_casters.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import env # noqa: F401
|
| 6 |
+
from pybind11_tests import custom_type_casters as m
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_noconvert_args(msg):
|
| 10 |
+
a = m.ArgInspector()
|
| 11 |
+
assert (
|
| 12 |
+
msg(a.f("hi"))
|
| 13 |
+
== """
|
| 14 |
+
loading ArgInspector1 argument WITH conversion allowed. Argument value = hi
|
| 15 |
+
"""
|
| 16 |
+
)
|
| 17 |
+
assert (
|
| 18 |
+
msg(a.g("this is a", "this is b"))
|
| 19 |
+
== """
|
| 20 |
+
loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a
|
| 21 |
+
loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b
|
| 22 |
+
13
|
| 23 |
+
loading ArgInspector2 argument WITH conversion allowed. Argument value = (default arg inspector 2)
|
| 24 |
+
"""
|
| 25 |
+
)
|
| 26 |
+
assert (
|
| 27 |
+
msg(a.g("this is a", "this is b", 42))
|
| 28 |
+
== """
|
| 29 |
+
loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a
|
| 30 |
+
loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b
|
| 31 |
+
42
|
| 32 |
+
loading ArgInspector2 argument WITH conversion allowed. Argument value = (default arg inspector 2)
|
| 33 |
+
"""
|
| 34 |
+
)
|
| 35 |
+
assert (
|
| 36 |
+
msg(a.g("this is a", "this is b", 42, "this is d"))
|
| 37 |
+
== """
|
| 38 |
+
loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a
|
| 39 |
+
loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b
|
| 40 |
+
42
|
| 41 |
+
loading ArgInspector2 argument WITH conversion allowed. Argument value = this is d
|
| 42 |
+
"""
|
| 43 |
+
)
|
| 44 |
+
assert (
|
| 45 |
+
a.h("arg 1")
|
| 46 |
+
== "loading ArgInspector2 argument WITHOUT conversion allowed. Argument value = arg 1"
|
| 47 |
+
)
|
| 48 |
+
assert (
|
| 49 |
+
msg(m.arg_inspect_func("A1", "A2"))
|
| 50 |
+
== """
|
| 51 |
+
loading ArgInspector2 argument WITH conversion allowed. Argument value = A1
|
| 52 |
+
loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = A2
|
| 53 |
+
"""
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
assert m.floats_preferred(4) == 2.0
|
| 57 |
+
assert m.floats_only(4.0) == 2.0
|
| 58 |
+
with pytest.raises(TypeError) as excinfo:
|
| 59 |
+
m.floats_only(4)
|
| 60 |
+
assert (
|
| 61 |
+
msg(excinfo.value)
|
| 62 |
+
== """
|
| 63 |
+
floats_only(): incompatible function arguments. The following argument types are supported:
|
| 64 |
+
1. (f: float) -> float
|
| 65 |
+
|
| 66 |
+
Invoked with: 4
|
| 67 |
+
"""
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
assert m.ints_preferred(4) == 2
|
| 71 |
+
assert m.ints_preferred(True) == 0
|
| 72 |
+
with pytest.raises(TypeError) as excinfo:
|
| 73 |
+
m.ints_preferred(4.0)
|
| 74 |
+
assert (
|
| 75 |
+
msg(excinfo.value)
|
| 76 |
+
== """
|
| 77 |
+
ints_preferred(): incompatible function arguments. The following argument types are supported:
|
| 78 |
+
1. (i: typing.SupportsInt) -> int
|
| 79 |
+
|
| 80 |
+
Invoked with: 4.0
|
| 81 |
+
"""
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
assert m.ints_only(4) == 2
|
| 85 |
+
with pytest.raises(TypeError) as excinfo:
|
| 86 |
+
m.ints_only(4.0)
|
| 87 |
+
assert (
|
| 88 |
+
msg(excinfo.value)
|
| 89 |
+
== """
|
| 90 |
+
ints_only(): incompatible function arguments. The following argument types are supported:
|
| 91 |
+
1. (i: int) -> int
|
| 92 |
+
|
| 93 |
+
Invoked with: 4.0
|
| 94 |
+
"""
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Cannot reliably trigger GC")
|
| 99 |
+
def test_custom_caster_destruction():
|
| 100 |
+
"""Tests that returning a pointer to a type that gets converted with a custom type caster gets
|
| 101 |
+
destroyed when the function has py::return_value_policy::take_ownership policy applied.
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
cstats = m.destruction_tester_cstats()
|
| 105 |
+
# This one *doesn't* have take_ownership: the pointer should be used but not destroyed:
|
| 106 |
+
z = m.custom_caster_no_destroy()
|
| 107 |
+
assert cstats.alive() == 1
|
| 108 |
+
assert cstats.default_constructions == 1
|
| 109 |
+
assert z
|
| 110 |
+
|
| 111 |
+
# take_ownership applied: this constructs a new object, casts it, then destroys it:
|
| 112 |
+
z = m.custom_caster_destroy()
|
| 113 |
+
assert z
|
| 114 |
+
assert cstats.default_constructions == 2
|
| 115 |
+
|
| 116 |
+
# Same, but with a const pointer return (which should *not* inhibit destruction):
|
| 117 |
+
z = m.custom_caster_destroy_const()
|
| 118 |
+
assert z
|
| 119 |
+
assert cstats.default_constructions == 3
|
| 120 |
+
|
| 121 |
+
# Make sure we still only have the original object (from ..._no_destroy()) alive:
|
| 122 |
+
assert cstats.alive() == 1
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_custom_caster_other_lib():
|
| 126 |
+
assert m.other_lib_type(True)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_custom_type_setup.cpp
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
tests/test_custom_type_setup.cpp -- Tests `pybind11::custom_type_setup`
|
| 3 |
+
|
| 4 |
+
Copyright (c) Google LLC
|
| 5 |
+
|
| 6 |
+
All rights reserved. Use of this source code is governed by a
|
| 7 |
+
BSD-style license that can be found in the LICENSE file.
|
| 8 |
+
*/
|
| 9 |
+
|
| 10 |
+
#include <pybind11/pybind11.h>
|
| 11 |
+
|
| 12 |
+
#include "pybind11_tests.h"
|
| 13 |
+
|
| 14 |
+
namespace py = pybind11;
|
| 15 |
+
|
| 16 |
+
namespace {
|
| 17 |
+
|
| 18 |
+
struct OwnsPythonObjects {
|
| 19 |
+
py::object value = py::none();
|
| 20 |
+
};
|
| 21 |
+
} // namespace
|
| 22 |
+
|
| 23 |
+
TEST_SUBMODULE(custom_type_setup, m) {
|
| 24 |
+
py::class_<OwnsPythonObjects> cls(
|
| 25 |
+
m, "OwnsPythonObjects", py::custom_type_setup([](PyHeapTypeObject *heap_type) {
|
| 26 |
+
auto *type = &heap_type->ht_type;
|
| 27 |
+
type->tp_flags |= Py_TPFLAGS_HAVE_GC;
|
| 28 |
+
type->tp_traverse = [](PyObject *self_base, visitproc visit, void *arg) {
|
| 29 |
+
// https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
|
| 30 |
+
#if PY_VERSION_HEX >= 0x03090000
|
| 31 |
+
Py_VISIT(Py_TYPE(self_base));
|
| 32 |
+
#endif
|
| 33 |
+
if (py::detail::is_holder_constructed(self_base)) {
|
| 34 |
+
auto &self = py::cast<OwnsPythonObjects &>(py::handle(self_base));
|
| 35 |
+
Py_VISIT(self.value.ptr());
|
| 36 |
+
}
|
| 37 |
+
return 0;
|
| 38 |
+
};
|
| 39 |
+
type->tp_clear = [](PyObject *self_base) {
|
| 40 |
+
if (py::detail::is_holder_constructed(self_base)) {
|
| 41 |
+
auto &self = py::cast<OwnsPythonObjects &>(py::handle(self_base));
|
| 42 |
+
self.value = py::none();
|
| 43 |
+
}
|
| 44 |
+
return 0;
|
| 45 |
+
};
|
| 46 |
+
}));
|
| 47 |
+
cls.def(py::init<>());
|
| 48 |
+
cls.def_readwrite("value", &OwnsPythonObjects::value);
|
| 49 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_custom_type_setup.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import gc
|
| 4 |
+
import weakref
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
import env # noqa: F401
|
| 9 |
+
from pybind11_tests import custom_type_setup as m
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@pytest.fixture
|
| 13 |
+
def gc_tester():
|
| 14 |
+
"""Tests that an object is garbage collected.
|
| 15 |
+
|
| 16 |
+
Assumes that any unreferenced objects are fully collected after calling
|
| 17 |
+
`gc.collect()`. That is true on CPython, but does not appear to reliably
|
| 18 |
+
hold on PyPy.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
weak_refs = []
|
| 22 |
+
|
| 23 |
+
def add_ref(obj):
|
| 24 |
+
# PyPy does not support `gc.is_tracked`.
|
| 25 |
+
if hasattr(gc, "is_tracked"):
|
| 26 |
+
assert gc.is_tracked(obj)
|
| 27 |
+
weak_refs.append(weakref.ref(obj))
|
| 28 |
+
|
| 29 |
+
yield add_ref
|
| 30 |
+
|
| 31 |
+
gc.collect()
|
| 32 |
+
for ref in weak_refs:
|
| 33 |
+
assert ref() is None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# PyPy does not seem to reliably garbage collect.
|
| 37 |
+
@pytest.mark.skipif("env.PYPY or env.GRAALPY")
|
| 38 |
+
def test_self_cycle(gc_tester):
|
| 39 |
+
obj = m.OwnsPythonObjects()
|
| 40 |
+
obj.value = obj
|
| 41 |
+
gc_tester(obj)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# PyPy does not seem to reliably garbage collect.
|
| 45 |
+
@pytest.mark.skipif("env.PYPY or env.GRAALPY")
|
| 46 |
+
def test_indirect_cycle(gc_tester):
|
| 47 |
+
obj = m.OwnsPythonObjects()
|
| 48 |
+
obj_list = [obj]
|
| 49 |
+
obj.value = obj_list
|
| 50 |
+
gc_tester(obj)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_docs_advanced_cast_custom.cpp
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// #########################################################################
|
| 2 |
+
// PLEASE UPDATE docs/advanced/cast/custom.rst IF ANY CHANGES ARE MADE HERE.
|
| 3 |
+
// #########################################################################
|
| 4 |
+
|
| 5 |
+
#include "pybind11_tests.h"
|
| 6 |
+
|
| 7 |
+
namespace user_space {
|
| 8 |
+
|
| 9 |
+
struct Point2D {
|
| 10 |
+
double x;
|
| 11 |
+
double y;
|
| 12 |
+
};
|
| 13 |
+
|
| 14 |
+
Point2D negate(const Point2D &point) { return Point2D{-point.x, -point.y}; }
|
| 15 |
+
|
| 16 |
+
} // namespace user_space
|
| 17 |
+
|
| 18 |
+
namespace pybind11 {
|
| 19 |
+
namespace detail {
|
| 20 |
+
|
| 21 |
+
template <>
|
| 22 |
+
struct type_caster<user_space::Point2D> {
|
| 23 |
+
// This macro inserts a lot of boilerplate code and sets the type hint.
|
| 24 |
+
// `io_name` is used to specify different type hints for arguments and return values.
|
| 25 |
+
// The signature of our negate function would then look like:
|
| 26 |
+
// `negate(collections.abc.Sequence[float]) -> tuple[float, float]`
|
| 27 |
+
PYBIND11_TYPE_CASTER(user_space::Point2D,
|
| 28 |
+
io_name("collections.abc.Sequence[float]", "tuple[float, float]"));
|
| 29 |
+
|
| 30 |
+
// C++ -> Python: convert `Point2D` to `tuple[float, float]`. The second and third arguments
|
| 31 |
+
// are used to indicate the return value policy and parent object (for
|
| 32 |
+
// return_value_policy::reference_internal) and are often ignored by custom casters.
|
| 33 |
+
// The return value should reflect the type hint specified by the second argument of `io_name`.
|
| 34 |
+
static handle
|
| 35 |
+
cast(const user_space::Point2D &number, return_value_policy /*policy*/, handle /*parent*/) {
|
| 36 |
+
return py::make_tuple(number.x, number.y).release();
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
// Python -> C++: convert a `PyObject` into a `Point2D` and return false upon failure. The
|
| 40 |
+
// second argument indicates whether implicit conversions should be allowed.
|
| 41 |
+
// The accepted types should reflect the type hint specified by the first argument of
|
| 42 |
+
// `io_name`.
|
| 43 |
+
bool load(handle src, bool /*convert*/) {
|
| 44 |
+
// Check if handle is a Sequence
|
| 45 |
+
if (!py::isinstance<py::sequence>(src)) {
|
| 46 |
+
return false;
|
| 47 |
+
}
|
| 48 |
+
auto seq = py::reinterpret_borrow<py::sequence>(src);
|
| 49 |
+
// Check if exactly two values are in the Sequence
|
| 50 |
+
if (seq.size() != 2) {
|
| 51 |
+
return false;
|
| 52 |
+
}
|
| 53 |
+
// Check if each element is either a float or an int
|
| 54 |
+
for (auto item : seq) {
|
| 55 |
+
if (!py::isinstance<py::float_>(item) && !py::isinstance<py::int_>(item)) {
|
| 56 |
+
return false;
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
value.x = seq[0].cast<double>();
|
| 60 |
+
value.y = seq[1].cast<double>();
|
| 61 |
+
return true;
|
| 62 |
+
}
|
| 63 |
+
};
|
| 64 |
+
|
| 65 |
+
} // namespace detail
|
| 66 |
+
} // namespace pybind11
|
| 67 |
+
|
| 68 |
+
// Bind the negate function
|
| 69 |
+
TEST_SUBMODULE(docs_advanced_cast_custom, m) { m.def("negate", user_space::negate); }
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_docs_advanced_cast_custom.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Sequence
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from conftest import SanitizedString
|
| 7 |
+
|
| 8 |
+
from pybind11_tests import docs_advanced_cast_custom as m
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def assert_negate_function(
|
| 12 |
+
input_sequence: Sequence[float],
|
| 13 |
+
target: tuple[float, float],
|
| 14 |
+
) -> None:
|
| 15 |
+
output = m.negate(input_sequence)
|
| 16 |
+
assert isinstance(output, tuple)
|
| 17 |
+
assert len(output) == 2
|
| 18 |
+
assert isinstance(output[0], float)
|
| 19 |
+
assert isinstance(output[1], float)
|
| 20 |
+
assert output == target
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_negate(doc: SanitizedString) -> None:
|
| 24 |
+
assert (
|
| 25 |
+
doc(m.negate)
|
| 26 |
+
== "negate(arg0: collections.abc.Sequence[float]) -> tuple[float, float]"
|
| 27 |
+
)
|
| 28 |
+
assert_negate_function([1.0, -1.0], (-1.0, 1.0))
|
| 29 |
+
assert_negate_function((1.0, -1.0), (-1.0, 1.0))
|
| 30 |
+
assert_negate_function([1, -1], (-1.0, 1.0))
|
| 31 |
+
assert_negate_function((1, -1), (-1.0, 1.0))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_docs() -> None:
|
| 35 |
+
###########################################################################
|
| 36 |
+
# PLEASE UPDATE docs/advanced/cast/custom.rst IF ANY CHANGES ARE MADE HERE.
|
| 37 |
+
###########################################################################
|
| 38 |
+
point1 = [1.0, -1.0]
|
| 39 |
+
point2 = m.negate(point1)
|
| 40 |
+
assert point2 == (-1.0, 1.0)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_docstring_options.cpp
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
tests/test_docstring_options.cpp -- generation of docstrings and signatures
|
| 3 |
+
|
| 4 |
+
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
|
| 5 |
+
|
| 6 |
+
All rights reserved. Use of this source code is governed by a
|
| 7 |
+
BSD-style license that can be found in the LICENSE file.
|
| 8 |
+
*/
|
| 9 |
+
|
| 10 |
+
#include "pybind11_tests.h"
|
| 11 |
+
|
| 12 |
+
TEST_SUBMODULE(docstring_options, m) {
|
| 13 |
+
// test_docstring_options
|
| 14 |
+
{
|
| 15 |
+
py::options options;
|
| 16 |
+
options.disable_function_signatures();
|
| 17 |
+
|
| 18 |
+
m.def("test_function1", [](int, int) {}, py::arg("a"), py::arg("b"));
|
| 19 |
+
m.def("test_function2", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
|
| 20 |
+
|
| 21 |
+
m.def("test_overloaded1", [](int) {}, py::arg("i"), "Overload docstring");
|
| 22 |
+
m.def("test_overloaded1", [](double) {}, py::arg("d"));
|
| 23 |
+
|
| 24 |
+
m.def("test_overloaded2", [](int) {}, py::arg("i"), "overload docstring 1");
|
| 25 |
+
m.def("test_overloaded2", [](double) {}, py::arg("d"), "overload docstring 2");
|
| 26 |
+
|
| 27 |
+
m.def("test_overloaded3", [](int) {}, py::arg("i"));
|
| 28 |
+
m.def("test_overloaded3", [](double) {}, py::arg("d"), "Overload docstr");
|
| 29 |
+
|
| 30 |
+
options.enable_function_signatures();
|
| 31 |
+
|
| 32 |
+
m.def("test_function3", [](int, int) {}, py::arg("a"), py::arg("b"));
|
| 33 |
+
m.def("test_function4", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
|
| 34 |
+
|
| 35 |
+
options.disable_function_signatures().disable_user_defined_docstrings();
|
| 36 |
+
|
| 37 |
+
m.def("test_function5", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
|
| 38 |
+
|
| 39 |
+
{
|
| 40 |
+
py::options nested_options;
|
| 41 |
+
nested_options.enable_user_defined_docstrings();
|
| 42 |
+
m.def(
|
| 43 |
+
"test_function6",
|
| 44 |
+
[](int, int) {},
|
| 45 |
+
py::arg("a"),
|
| 46 |
+
py::arg("b"),
|
| 47 |
+
"A custom docstring");
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
m.def("test_function7", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
|
| 52 |
+
|
| 53 |
+
{
|
| 54 |
+
py::options options;
|
| 55 |
+
options.disable_user_defined_docstrings();
|
| 56 |
+
options.disable_function_signatures();
|
| 57 |
+
|
| 58 |
+
m.def("test_function8", []() {});
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
{
|
| 62 |
+
py::options options;
|
| 63 |
+
options.disable_user_defined_docstrings();
|
| 64 |
+
|
| 65 |
+
struct DocstringTestFoo {
|
| 66 |
+
int value;
|
| 67 |
+
void setValue(int v) { value = v; }
|
| 68 |
+
int getValue() const { return value; }
|
| 69 |
+
};
|
| 70 |
+
py::class_<DocstringTestFoo>(m, "DocstringTestFoo", "This is a class docstring")
|
| 71 |
+
.def_property("value_prop",
|
| 72 |
+
&DocstringTestFoo::getValue,
|
| 73 |
+
&DocstringTestFoo::setValue,
|
| 74 |
+
"This is a property docstring");
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
{
|
| 78 |
+
enum class DocstringTestEnum1 { Member1, Member2 };
|
| 79 |
+
|
| 80 |
+
py::enum_<DocstringTestEnum1>(m, "DocstringTestEnum1", "Enum docstring")
|
| 81 |
+
.value("Member1", DocstringTestEnum1::Member1)
|
| 82 |
+
.value("Member2", DocstringTestEnum1::Member2);
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
{
|
| 86 |
+
py::options options;
|
| 87 |
+
options.enable_enum_members_docstring();
|
| 88 |
+
|
| 89 |
+
enum class DocstringTestEnum2 { Member1, Member2 };
|
| 90 |
+
|
| 91 |
+
py::enum_<DocstringTestEnum2>(m, "DocstringTestEnum2", "Enum docstring")
|
| 92 |
+
.value("Member1", DocstringTestEnum2::Member1)
|
| 93 |
+
.value("Member2", DocstringTestEnum2::Member2);
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
{
|
| 97 |
+
py::options options;
|
| 98 |
+
options.disable_enum_members_docstring();
|
| 99 |
+
|
| 100 |
+
enum class DocstringTestEnum3 { Member1, Member2 };
|
| 101 |
+
|
| 102 |
+
py::enum_<DocstringTestEnum3>(m, "DocstringTestEnum3", "Enum docstring")
|
| 103 |
+
.value("Member1", DocstringTestEnum3::Member1)
|
| 104 |
+
.value("Member2", DocstringTestEnum3::Member2);
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
{
|
| 108 |
+
py::options options;
|
| 109 |
+
options.disable_user_defined_docstrings();
|
| 110 |
+
|
| 111 |
+
enum class DocstringTestEnum4 { Member1, Member2 };
|
| 112 |
+
|
| 113 |
+
py::enum_<DocstringTestEnum4>(m, "DocstringTestEnum4", "Enum docstring")
|
| 114 |
+
.value("Member1", DocstringTestEnum4::Member1)
|
| 115 |
+
.value("Member2", DocstringTestEnum4::Member2);
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
{
|
| 119 |
+
py::options options;
|
| 120 |
+
options.disable_user_defined_docstrings();
|
| 121 |
+
options.disable_enum_members_docstring();
|
| 122 |
+
|
| 123 |
+
enum class DocstringTestEnum5 { Member1, Member2 };
|
| 124 |
+
|
| 125 |
+
py::enum_<DocstringTestEnum5>(m, "DocstringTestEnum5", "Enum docstring")
|
| 126 |
+
.value("Member1", DocstringTestEnum5::Member1)
|
| 127 |
+
.value("Member2", DocstringTestEnum5::Member2);
|
| 128 |
+
}
|
| 129 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_docstring_options.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pybind11_tests import docstring_options as m
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_docstring_options():
|
| 7 |
+
# options.disable_function_signatures()
|
| 8 |
+
assert not m.test_function1.__doc__
|
| 9 |
+
|
| 10 |
+
assert m.test_function2.__doc__ == "A custom docstring"
|
| 11 |
+
|
| 12 |
+
# docstring specified on just the first overload definition:
|
| 13 |
+
assert m.test_overloaded1.__doc__ == "Overload docstring"
|
| 14 |
+
|
| 15 |
+
# docstring on both overloads:
|
| 16 |
+
assert m.test_overloaded2.__doc__ == "overload docstring 1\noverload docstring 2"
|
| 17 |
+
|
| 18 |
+
# docstring on only second overload:
|
| 19 |
+
assert m.test_overloaded3.__doc__ == "Overload docstr"
|
| 20 |
+
|
| 21 |
+
# options.enable_function_signatures()
|
| 22 |
+
assert m.test_function3.__doc__.startswith(
|
| 23 |
+
"test_function3(a: typing.SupportsInt, b: typing.SupportsInt) -> None"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
assert m.test_function4.__doc__.startswith(
|
| 27 |
+
"test_function4(a: typing.SupportsInt, b: typing.SupportsInt) -> None"
|
| 28 |
+
)
|
| 29 |
+
assert m.test_function4.__doc__.endswith("A custom docstring\n")
|
| 30 |
+
|
| 31 |
+
# options.disable_function_signatures()
|
| 32 |
+
# options.disable_user_defined_docstrings()
|
| 33 |
+
assert not m.test_function5.__doc__
|
| 34 |
+
|
| 35 |
+
# nested options.enable_user_defined_docstrings()
|
| 36 |
+
assert m.test_function6.__doc__ == "A custom docstring"
|
| 37 |
+
|
| 38 |
+
# RAII destructor
|
| 39 |
+
assert m.test_function7.__doc__.startswith(
|
| 40 |
+
"test_function7(a: typing.SupportsInt, b: typing.SupportsInt) -> None"
|
| 41 |
+
)
|
| 42 |
+
assert m.test_function7.__doc__.endswith("A custom docstring\n")
|
| 43 |
+
|
| 44 |
+
# when all options are disabled, no docstring (instead of an empty one) should be generated
|
| 45 |
+
assert m.test_function8.__doc__ is None
|
| 46 |
+
|
| 47 |
+
# Suppression of user-defined docstrings for non-function objects
|
| 48 |
+
assert not m.DocstringTestFoo.__doc__
|
| 49 |
+
assert not m.DocstringTestFoo.value_prop.__doc__
|
| 50 |
+
|
| 51 |
+
# Check existig behaviour of enum docstings
|
| 52 |
+
assert (
|
| 53 |
+
m.DocstringTestEnum1.__doc__
|
| 54 |
+
== "Enum docstring\n\nMembers:\n\n Member1\n\n Member2"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# options.enable_enum_members_docstring()
|
| 58 |
+
assert (
|
| 59 |
+
m.DocstringTestEnum2.__doc__
|
| 60 |
+
== "Enum docstring\n\nMembers:\n\n Member1\n\n Member2"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# options.disable_enum_members_docstring()
|
| 64 |
+
assert m.DocstringTestEnum3.__doc__ == "Enum docstring"
|
| 65 |
+
|
| 66 |
+
# options.disable_user_defined_docstrings()
|
| 67 |
+
assert m.DocstringTestEnum4.__doc__ == "Members:\n\n Member1\n\n Member2"
|
| 68 |
+
|
| 69 |
+
# options.disable_user_defined_docstrings()
|
| 70 |
+
# options.disable_enum_members_docstring()
|
| 71 |
+
# When all options are disabled, no docstring (instead of an empty one) should be generated
|
| 72 |
+
assert m.DocstringTestEnum5.__doc__ is None
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_eigen_matrix.cpp
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
tests/eigen.cpp -- automatic conversion of Eigen types
|
| 3 |
+
|
| 4 |
+
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
|
| 5 |
+
|
| 6 |
+
All rights reserved. Use of this source code is governed by a
|
| 7 |
+
BSD-style license that can be found in the LICENSE file.
|
| 8 |
+
*/
|
| 9 |
+
|
| 10 |
+
#include <pybind11/eigen/matrix.h>
|
| 11 |
+
#include <pybind11/stl.h>
|
| 12 |
+
|
| 13 |
+
#include "constructor_stats.h"
|
| 14 |
+
#include "pybind11_tests.h"
|
| 15 |
+
|
| 16 |
+
PYBIND11_WARNING_DISABLE_MSVC(4996)
|
| 17 |
+
|
| 18 |
+
#include <Eigen/Cholesky>
|
| 19 |
+
|
| 20 |
+
using MatrixXdR = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
|
| 21 |
+
|
| 22 |
+
// Sets/resets a testing reference matrix to have values of 10*r + c, where r and c are the
|
| 23 |
+
// (1-based) row/column number.
|
| 24 |
+
template <typename M>
|
| 25 |
+
void reset_ref(M &x) {
|
| 26 |
+
for (int i = 0; i < x.rows(); i++) {
|
| 27 |
+
for (int j = 0; j < x.cols(); j++) {
|
| 28 |
+
x(i, j) = 11 + 10 * i + j;
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
// Returns a static, column-major matrix
|
| 34 |
+
Eigen::MatrixXd &get_cm() {
|
| 35 |
+
static Eigen::MatrixXd *x;
|
| 36 |
+
if (!x) {
|
| 37 |
+
x = new Eigen::MatrixXd(3, 3);
|
| 38 |
+
reset_ref(*x);
|
| 39 |
+
}
|
| 40 |
+
return *x;
|
| 41 |
+
}
|
| 42 |
+
// Likewise, but row-major
|
| 43 |
+
MatrixXdR &get_rm() {
|
| 44 |
+
static MatrixXdR *x;
|
| 45 |
+
if (!x) {
|
| 46 |
+
x = new MatrixXdR(3, 3);
|
| 47 |
+
reset_ref(*x);
|
| 48 |
+
}
|
| 49 |
+
return *x;
|
| 50 |
+
}
|
| 51 |
+
// Resets the values of the static matrices returned by get_cm()/get_rm()
|
| 52 |
+
void reset_refs() {
|
| 53 |
+
reset_ref(get_cm());
|
| 54 |
+
reset_ref(get_rm());
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// Returns element 2,1 from a matrix (used to test copy/nocopy)
|
| 58 |
+
double get_elem(const Eigen::Ref<const Eigen::MatrixXd> &m) { return m(2, 1); }
|
| 59 |
+
|
| 60 |
+
// Returns a matrix with 10*r + 100*c added to each matrix element (to help test that the matrix
|
| 61 |
+
// reference is referencing rows/columns correctly).
|
| 62 |
+
template <typename MatrixArgType>
|
| 63 |
+
Eigen::MatrixXd adjust_matrix(MatrixArgType m) {
|
| 64 |
+
Eigen::MatrixXd ret(m);
|
| 65 |
+
for (int c = 0; c < m.cols(); c++) {
|
| 66 |
+
for (int r = 0; r < m.rows(); r++) {
|
| 67 |
+
ret(r, c) += 10 * r + 100 * c; // NOLINT(clang-analyzer-core.uninitialized.Assign)
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
return ret;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
struct CustomOperatorNew {
|
| 74 |
+
CustomOperatorNew() = default;
|
| 75 |
+
|
| 76 |
+
Eigen::Matrix4d a = Eigen::Matrix4d::Zero();
|
| 77 |
+
Eigen::Matrix4d b = Eigen::Matrix4d::Identity();
|
| 78 |
+
|
| 79 |
+
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
|
| 80 |
+
};
|
| 81 |
+
|
| 82 |
+
TEST_SUBMODULE(eigen_matrix, m) {
|
| 83 |
+
using FixedMatrixR = Eigen::Matrix<float, 5, 6, Eigen::RowMajor>;
|
| 84 |
+
using FixedMatrixC = Eigen::Matrix<float, 5, 6>;
|
| 85 |
+
using DenseMatrixR = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
|
| 86 |
+
using DenseMatrixC = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>;
|
| 87 |
+
using FourRowMatrixC = Eigen::Matrix<float, 4, Eigen::Dynamic>;
|
| 88 |
+
using FourColMatrixC = Eigen::Matrix<float, Eigen::Dynamic, 4>;
|
| 89 |
+
using FourRowMatrixR = Eigen::Matrix<float, 4, Eigen::Dynamic>;
|
| 90 |
+
using FourColMatrixR = Eigen::Matrix<float, Eigen::Dynamic, 4>;
|
| 91 |
+
using SparseMatrixR = Eigen::SparseMatrix<float, Eigen::RowMajor>;
|
| 92 |
+
using SparseMatrixC = Eigen::SparseMatrix<float>;
|
| 93 |
+
|
| 94 |
+
// various tests
|
| 95 |
+
m.def("double_col", [](const Eigen::VectorXf &x) -> Eigen::VectorXf { return 2.0f * x; });
|
| 96 |
+
m.def("double_row",
|
| 97 |
+
[](const Eigen::RowVectorXf &x) -> Eigen::RowVectorXf { return 2.0f * x; });
|
| 98 |
+
m.def("double_complex",
|
| 99 |
+
[](const Eigen::VectorXcf &x) -> Eigen::VectorXcf { return 2.0f * x; });
|
| 100 |
+
m.def("double_threec", [](py::EigenDRef<Eigen::Vector3f> x) { x *= 2; });
|
| 101 |
+
m.def("double_threer", [](py::EigenDRef<Eigen::RowVector3f> x) { x *= 2; });
|
| 102 |
+
m.def("double_mat_cm", [](const Eigen::MatrixXf &x) -> Eigen::MatrixXf { return 2.0f * x; });
|
| 103 |
+
m.def("double_mat_rm", [](const DenseMatrixR &x) -> DenseMatrixR { return 2.0f * x; });
|
| 104 |
+
|
| 105 |
+
// test_eigen_ref_to_python
|
| 106 |
+
// Different ways of passing via Eigen::Ref; the first and second are the Eigen-recommended
|
| 107 |
+
m.def("cholesky1",
|
| 108 |
+
[](const Eigen::Ref<MatrixXdR> &x) -> Eigen::MatrixXd { return x.llt().matrixL(); });
|
| 109 |
+
m.def("cholesky2", [](const Eigen::Ref<const MatrixXdR> &x) -> Eigen::MatrixXd {
|
| 110 |
+
return x.llt().matrixL();
|
| 111 |
+
});
|
| 112 |
+
m.def("cholesky3",
|
| 113 |
+
[](const Eigen::Ref<MatrixXdR> &x) -> Eigen::MatrixXd { return x.llt().matrixL(); });
|
| 114 |
+
m.def("cholesky4", [](const Eigen::Ref<const MatrixXdR> &x) -> Eigen::MatrixXd {
|
| 115 |
+
return x.llt().matrixL();
|
| 116 |
+
});
|
| 117 |
+
|
| 118 |
+
// test_eigen_ref_mutators
|
| 119 |
+
// Mutators: these add some value to the given element using Eigen, but Eigen should be mapping
|
| 120 |
+
// into the numpy array data and so the result should show up there. There are three versions:
|
| 121 |
+
// one that works on a contiguous-row matrix (numpy's default), one for a contiguous-column
|
| 122 |
+
// matrix, and one for any matrix.
|
| 123 |
+
auto add_rm = [](Eigen::Ref<MatrixXdR> x, int r, int c, double v) { x(r, c) += v; };
|
| 124 |
+
auto add_cm = [](Eigen::Ref<Eigen::MatrixXd> x, int r, int c, double v) { x(r, c) += v; };
|
| 125 |
+
|
| 126 |
+
// Mutators (Eigen maps into numpy variables):
|
| 127 |
+
m.def("add_rm", add_rm); // Only takes row-contiguous
|
| 128 |
+
m.def("add_cm", add_cm); // Only takes column-contiguous
|
| 129 |
+
// Overloaded versions that will accept either row or column contiguous:
|
| 130 |
+
m.def("add1", add_rm);
|
| 131 |
+
m.def("add1", add_cm);
|
| 132 |
+
m.def("add2", add_cm);
|
| 133 |
+
m.def("add2", add_rm);
|
| 134 |
+
// This one accepts a matrix of any stride:
|
| 135 |
+
m.def("add_any",
|
| 136 |
+
[](py::EigenDRef<Eigen::MatrixXd> x, int r, int c, double v) { x(r, c) += v; });
|
| 137 |
+
|
| 138 |
+
// Return mutable references (numpy maps into eigen variables)
|
| 139 |
+
m.def("get_cm_ref", []() { return Eigen::Ref<Eigen::MatrixXd>(get_cm()); });
|
| 140 |
+
m.def("get_rm_ref", []() { return Eigen::Ref<MatrixXdR>(get_rm()); });
|
| 141 |
+
// The same references, but non-mutable (numpy maps into eigen variables, but is !writeable)
|
| 142 |
+
m.def("get_cm_const_ref", []() { return Eigen::Ref<const Eigen::MatrixXd>(get_cm()); });
|
| 143 |
+
m.def("get_rm_const_ref", []() { return Eigen::Ref<const MatrixXdR>(get_rm()); });
|
| 144 |
+
|
| 145 |
+
m.def("reset_refs", reset_refs); // Restores get_{cm,rm}_ref to original values
|
| 146 |
+
|
| 147 |
+
// Increments and returns ref to (same) matrix
|
| 148 |
+
m.def(
|
| 149 |
+
"incr_matrix",
|
| 150 |
+
[](Eigen::Ref<Eigen::MatrixXd> m, double v) {
|
| 151 |
+
m += Eigen::MatrixXd::Constant(m.rows(), m.cols(), v);
|
| 152 |
+
return m;
|
| 153 |
+
},
|
| 154 |
+
py::return_value_policy::reference);
|
| 155 |
+
|
| 156 |
+
// Same, but accepts a matrix of any strides
|
| 157 |
+
m.def(
|
| 158 |
+
"incr_matrix_any",
|
| 159 |
+
[](py::EigenDRef<Eigen::MatrixXd> m, double v) {
|
| 160 |
+
m += Eigen::MatrixXd::Constant(m.rows(), m.cols(), v);
|
| 161 |
+
return m;
|
| 162 |
+
},
|
| 163 |
+
py::return_value_policy::reference);
|
| 164 |
+
|
| 165 |
+
// Returns an eigen slice of even rows
|
| 166 |
+
m.def(
|
| 167 |
+
"even_rows",
|
| 168 |
+
[](py::EigenDRef<Eigen::MatrixXd> m) {
|
| 169 |
+
return py::EigenDMap<Eigen::MatrixXd>(
|
| 170 |
+
m.data(),
|
| 171 |
+
(m.rows() + 1) / 2,
|
| 172 |
+
m.cols(),
|
| 173 |
+
py::EigenDStride(m.outerStride(), 2 * m.innerStride()));
|
| 174 |
+
},
|
| 175 |
+
py::return_value_policy::reference);
|
| 176 |
+
|
| 177 |
+
// Returns an eigen slice of even columns
|
| 178 |
+
m.def(
|
| 179 |
+
"even_cols",
|
| 180 |
+
[](py::EigenDRef<Eigen::MatrixXd> m) {
|
| 181 |
+
return py::EigenDMap<Eigen::MatrixXd>(
|
| 182 |
+
m.data(),
|
| 183 |
+
m.rows(),
|
| 184 |
+
(m.cols() + 1) / 2,
|
| 185 |
+
py::EigenDStride(2 * m.outerStride(), m.innerStride()));
|
| 186 |
+
},
|
| 187 |
+
py::return_value_policy::reference);
|
| 188 |
+
|
| 189 |
+
// Returns diagonals: a vector-like object with an inner stride != 1
|
| 190 |
+
m.def("diagonal", [](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal(); });
|
| 191 |
+
m.def("diagonal_1",
|
| 192 |
+
[](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal<1>(); });
|
| 193 |
+
m.def("diagonal_n",
|
| 194 |
+
[](const Eigen::Ref<const Eigen::MatrixXd> &x, int index) { return x.diagonal(index); });
|
| 195 |
+
|
| 196 |
+
// Return a block of a matrix (gives non-standard strides)
|
| 197 |
+
m.def("block",
|
| 198 |
+
[m](const py::object &x_obj,
|
| 199 |
+
int start_row,
|
| 200 |
+
int start_col,
|
| 201 |
+
int block_rows,
|
| 202 |
+
int block_cols) {
|
| 203 |
+
return m.attr("_block")(x_obj, x_obj, start_row, start_col, block_rows, block_cols);
|
| 204 |
+
});
|
| 205 |
+
|
| 206 |
+
m.def(
|
| 207 |
+
"_block",
|
| 208 |
+
[](const py::object &x_obj,
|
| 209 |
+
const Eigen::Ref<const Eigen::MatrixXd> &x,
|
| 210 |
+
int start_row,
|
| 211 |
+
int start_col,
|
| 212 |
+
int block_rows,
|
| 213 |
+
int block_cols) {
|
| 214 |
+
// See PR #4217 for background. This test is a bit over the top, but might be useful
|
| 215 |
+
// as a concrete example to point to when explaining the dangling reference trap.
|
| 216 |
+
auto i0 = py::make_tuple(0, 0);
|
| 217 |
+
auto x0_orig = x_obj[*i0].cast<double>();
|
| 218 |
+
if (x(0, 0) != x0_orig) {
|
| 219 |
+
throw std::runtime_error(
|
| 220 |
+
"Something in the type_caster for Eigen::Ref is terribly wrong.");
|
| 221 |
+
}
|
| 222 |
+
double x0_mod = x0_orig + 1;
|
| 223 |
+
x_obj[*i0] = x0_mod;
|
| 224 |
+
auto copy_detected = (x(0, 0) != x0_mod);
|
| 225 |
+
x_obj[*i0] = x0_orig;
|
| 226 |
+
if (copy_detected) {
|
| 227 |
+
throw std::runtime_error("type_caster for Eigen::Ref made a copy.");
|
| 228 |
+
}
|
| 229 |
+
return x.block(start_row, start_col, block_rows, block_cols);
|
| 230 |
+
},
|
| 231 |
+
py::keep_alive<0, 1>());
|
| 232 |
+
|
| 233 |
+
// test_eigen_return_references, test_eigen_keepalive
|
| 234 |
+
// return value referencing/copying tests:
|
| 235 |
+
class ReturnTester {
|
| 236 |
+
Eigen::MatrixXd mat = create();
|
| 237 |
+
|
| 238 |
+
public:
|
| 239 |
+
ReturnTester() { print_created(this); }
|
| 240 |
+
ReturnTester(const ReturnTester &) = default;
|
| 241 |
+
~ReturnTester() { print_destroyed(this); }
|
| 242 |
+
static Eigen::MatrixXd create() { return Eigen::MatrixXd::Ones(10, 10); }
|
| 243 |
+
// NOLINTNEXTLINE(readability-const-return-type)
|
| 244 |
+
static const Eigen::MatrixXd createConst() { return Eigen::MatrixXd::Ones(10, 10); }
|
| 245 |
+
Eigen::MatrixXd &get() { return mat; }
|
| 246 |
+
Eigen::MatrixXd *getPtr() { return &mat; }
|
| 247 |
+
const Eigen::MatrixXd &view() { return mat; }
|
| 248 |
+
const Eigen::MatrixXd *viewPtr() { return &mat; }
|
| 249 |
+
Eigen::Ref<Eigen::MatrixXd> ref() { return mat; }
|
| 250 |
+
Eigen::Ref<const Eigen::MatrixXd> refConst() { return mat; }
|
| 251 |
+
Eigen::Block<Eigen::MatrixXd> block(int r, int c, int nrow, int ncol) {
|
| 252 |
+
return mat.block(r, c, nrow, ncol);
|
| 253 |
+
}
|
| 254 |
+
Eigen::Block<const Eigen::MatrixXd> blockConst(int r, int c, int nrow, int ncol) const {
|
| 255 |
+
return mat.block(r, c, nrow, ncol);
|
| 256 |
+
}
|
| 257 |
+
py::EigenDMap<Eigen::Matrix2d> corners() {
|
| 258 |
+
return py::EigenDMap<Eigen::Matrix2d>(
|
| 259 |
+
mat.data(),
|
| 260 |
+
py::EigenDStride(mat.outerStride() * (mat.outerSize() - 1),
|
| 261 |
+
mat.innerStride() * (mat.innerSize() - 1)));
|
| 262 |
+
}
|
| 263 |
+
py::EigenDMap<const Eigen::Matrix2d> cornersConst() const {
|
| 264 |
+
return py::EigenDMap<const Eigen::Matrix2d>(
|
| 265 |
+
mat.data(),
|
| 266 |
+
py::EigenDStride(mat.outerStride() * (mat.outerSize() - 1),
|
| 267 |
+
mat.innerStride() * (mat.innerSize() - 1)));
|
| 268 |
+
}
|
| 269 |
+
};
|
| 270 |
+
using rvp = py::return_value_policy;
|
| 271 |
+
py::class_<ReturnTester>(m, "ReturnTester")
|
| 272 |
+
.def(py::init<>())
|
| 273 |
+
.def_static("create", &ReturnTester::create)
|
| 274 |
+
.def_static("create_const", &ReturnTester::createConst)
|
| 275 |
+
.def("get", &ReturnTester::get, rvp::reference_internal)
|
| 276 |
+
.def("get_ptr", &ReturnTester::getPtr, rvp::reference_internal)
|
| 277 |
+
.def("view", &ReturnTester::view, rvp::reference_internal)
|
| 278 |
+
.def("view_ptr", &ReturnTester::view, rvp::reference_internal)
|
| 279 |
+
.def("copy_get", &ReturnTester::get) // Default rvp: copy
|
| 280 |
+
.def("copy_view", &ReturnTester::view) // "
|
| 281 |
+
.def("ref", &ReturnTester::ref) // Default for Ref is to reference
|
| 282 |
+
.def("ref_const", &ReturnTester::refConst) // Likewise, but const
|
| 283 |
+
.def("ref_safe", &ReturnTester::ref, rvp::reference_internal)
|
| 284 |
+
.def("ref_const_safe", &ReturnTester::refConst, rvp::reference_internal)
|
| 285 |
+
.def("copy_ref", &ReturnTester::ref, rvp::copy)
|
| 286 |
+
.def("copy_ref_const", &ReturnTester::refConst, rvp::copy)
|
| 287 |
+
.def("block", &ReturnTester::block)
|
| 288 |
+
.def("block_safe", &ReturnTester::block, rvp::reference_internal)
|
| 289 |
+
.def("block_const", &ReturnTester::blockConst, rvp::reference_internal)
|
| 290 |
+
.def("copy_block", &ReturnTester::block, rvp::copy)
|
| 291 |
+
.def("corners", &ReturnTester::corners, rvp::reference_internal)
|
| 292 |
+
.def("corners_const", &ReturnTester::cornersConst, rvp::reference_internal);
|
| 293 |
+
|
| 294 |
+
// test_special_matrix_objects
|
| 295 |
+
// Returns a DiagonalMatrix with diagonal (1,2,3,...)
|
| 296 |
+
m.def("incr_diag", [](int k) {
|
| 297 |
+
Eigen::DiagonalMatrix<int, Eigen::Dynamic> m(k);
|
| 298 |
+
for (int i = 0; i < k; i++) {
|
| 299 |
+
m.diagonal()[i] = i + 1;
|
| 300 |
+
}
|
| 301 |
+
return m;
|
| 302 |
+
});
|
| 303 |
+
|
| 304 |
+
// Returns a SelfAdjointView referencing the lower triangle of m
|
| 305 |
+
m.def("symmetric_lower",
|
| 306 |
+
[](const Eigen::MatrixXi &m) { return m.selfadjointView<Eigen::Lower>(); });
|
| 307 |
+
// Returns a SelfAdjointView referencing the lower triangle of m
|
| 308 |
+
m.def("symmetric_upper",
|
| 309 |
+
[](const Eigen::MatrixXi &m) { return m.selfadjointView<Eigen::Upper>(); });
|
| 310 |
+
|
| 311 |
+
// Test matrix for various functions below.
|
| 312 |
+
Eigen::MatrixXf mat(5, 6);
|
| 313 |
+
mat << 0, 3, 0, 0, 0, 11, 22, 0, 0, 0, 17, 11, 7, 5, 0, 1, 0, 11, 0, 0, 0, 0, 0, 11, 0, 0, 14,
|
| 314 |
+
0, 8, 11;
|
| 315 |
+
|
| 316 |
+
// test_fixed, and various other tests
|
| 317 |
+
m.def("fixed_r", [mat]() -> FixedMatrixR { return FixedMatrixR(mat); });
|
| 318 |
+
// Our Eigen does a hack which respects constness through the numpy writeable flag.
|
| 319 |
+
// Therefore, the const return actually affects this type despite being an rvalue.
|
| 320 |
+
// NOLINTNEXTLINE(readability-const-return-type)
|
| 321 |
+
m.def("fixed_r_const", [mat]() -> const FixedMatrixR { return FixedMatrixR(mat); });
|
| 322 |
+
m.def("fixed_c", [mat]() -> FixedMatrixC { return FixedMatrixC(mat); });
|
| 323 |
+
m.def("fixed_copy_r", [](const FixedMatrixR &m) -> FixedMatrixR { return m; });
|
| 324 |
+
m.def("fixed_copy_c", [](const FixedMatrixC &m) -> FixedMatrixC { return m; });
|
| 325 |
+
// test_mutator_descriptors
|
| 326 |
+
m.def("fixed_mutator_r", [](const Eigen::Ref<FixedMatrixR> &) {});
|
| 327 |
+
m.def("fixed_mutator_c", [](const Eigen::Ref<FixedMatrixC> &) {});
|
| 328 |
+
m.def("fixed_mutator_a", [](const py::EigenDRef<FixedMatrixC> &) {});
|
| 329 |
+
// test_dense
|
| 330 |
+
m.def("dense_r", [mat]() -> DenseMatrixR { return DenseMatrixR(mat); });
|
| 331 |
+
m.def("dense_c", [mat]() -> DenseMatrixC { return DenseMatrixC(mat); });
|
| 332 |
+
m.def("dense_copy_r", [](const DenseMatrixR &m) -> DenseMatrixR { return m; });
|
| 333 |
+
m.def("dense_copy_c", [](const DenseMatrixC &m) -> DenseMatrixC { return m; });
|
| 334 |
+
// test_defaults
|
| 335 |
+
bool have_numpy = true;
|
| 336 |
+
try {
|
| 337 |
+
py::module_::import("numpy");
|
| 338 |
+
} catch (const py::error_already_set &) {
|
| 339 |
+
have_numpy = false;
|
| 340 |
+
}
|
| 341 |
+
if (have_numpy) {
|
| 342 |
+
py::module_::import("numpy");
|
| 343 |
+
Eigen::Matrix<double, 3, 3> defaultMatrix = Eigen::Matrix3d::Identity();
|
| 344 |
+
m.def("defaults_mat", [](const Eigen::Matrix3d &) {}, py::arg("mat") = defaultMatrix);
|
| 345 |
+
|
| 346 |
+
Eigen::VectorXd defaultVector = Eigen::VectorXd::Ones(32);
|
| 347 |
+
m.def("defaults_vec", [](const Eigen::VectorXd &) {}, py::arg("vec") = defaultMatrix);
|
| 348 |
+
}
|
| 349 |
+
// test_sparse, test_sparse_signature
|
| 350 |
+
m.def("sparse_r", [mat]() -> SparseMatrixR {
|
| 351 |
+
// NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
|
| 352 |
+
return Eigen::SparseView<Eigen::MatrixXf>(mat);
|
| 353 |
+
});
|
| 354 |
+
m.def("sparse_c",
|
| 355 |
+
[mat]() -> SparseMatrixC { return Eigen::SparseView<Eigen::MatrixXf>(mat); });
|
| 356 |
+
m.def("sparse_copy_r", [](const SparseMatrixR &m) -> SparseMatrixR { return m; });
|
| 357 |
+
m.def("sparse_copy_c", [](const SparseMatrixC &m) -> SparseMatrixC { return m; });
|
| 358 |
+
// test_partially_fixed
|
| 359 |
+
m.def("partial_copy_four_rm_r", [](const FourRowMatrixR &m) -> FourRowMatrixR { return m; });
|
| 360 |
+
m.def("partial_copy_four_rm_c", [](const FourColMatrixR &m) -> FourColMatrixR { return m; });
|
| 361 |
+
m.def("partial_copy_four_cm_r", [](const FourRowMatrixC &m) -> FourRowMatrixC { return m; });
|
| 362 |
+
m.def("partial_copy_four_cm_c", [](const FourColMatrixC &m) -> FourColMatrixC { return m; });
|
| 363 |
+
|
| 364 |
+
// test_cpp_casting
|
| 365 |
+
// Test that we can cast a numpy object to a Eigen::MatrixXd explicitly
|
| 366 |
+
m.def("cpp_copy", [](py::handle m) { return m.cast<Eigen::MatrixXd>()(1, 0); });
|
| 367 |
+
m.def("cpp_ref_c", [](py::handle m) { return m.cast<Eigen::Ref<Eigen::MatrixXd>>()(1, 0); });
|
| 368 |
+
m.def("cpp_ref_r", [](py::handle m) { return m.cast<Eigen::Ref<MatrixXdR>>()(1, 0); });
|
| 369 |
+
m.def("cpp_ref_any",
|
| 370 |
+
[](py::handle m) { return m.cast<py::EigenDRef<Eigen::MatrixXd>>()(1, 0); });
|
| 371 |
+
|
| 372 |
+
// [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
|
| 373 |
+
|
| 374 |
+
// test_nocopy_wrapper
|
| 375 |
+
// Test that we can prevent copying into an argument that would normally copy: First a version
|
| 376 |
+
// that would allow copying (if types or strides don't match) for comparison:
|
| 377 |
+
m.def("get_elem", &get_elem);
|
| 378 |
+
// Now this alternative that calls the tells pybind to fail rather than copy:
|
| 379 |
+
m.def(
|
| 380 |
+
"get_elem_nocopy",
|
| 381 |
+
[](const Eigen::Ref<const Eigen::MatrixXd> &m) -> double { return get_elem(m); },
|
| 382 |
+
py::arg{}.noconvert());
|
| 383 |
+
// Also test a row-major-only no-copy const ref:
|
| 384 |
+
m.def(
|
| 385 |
+
"get_elem_rm_nocopy",
|
| 386 |
+
[](Eigen::Ref<const Eigen::Matrix<long, -1, -1, Eigen::RowMajor>> &m) -> long {
|
| 387 |
+
return m(2, 1);
|
| 388 |
+
},
|
| 389 |
+
py::arg{}.noconvert());
|
| 390 |
+
|
| 391 |
+
// test_issue738, test_zero_length
|
| 392 |
+
// Issue #738: 1×N or N×1 2D matrices were neither accepted nor properly copied with an
|
| 393 |
+
// incompatible stride value on the length-1 dimension--but that should be allowed (without
|
| 394 |
+
// requiring a copy!) because the stride value can be safely ignored on a size-1 dimension.
|
| 395 |
+
// Similarly, 0×N or N×0 matrices were not accepted--again, these should be allowed since
|
| 396 |
+
// they contain no data. This particularly affects numpy ≥ 1.23, which sets the strides to
|
| 397 |
+
// 0 if any dimension size is 0.
|
| 398 |
+
m.def("iss738_f1",
|
| 399 |
+
&adjust_matrix<const Eigen::Ref<const Eigen::MatrixXd> &>,
|
| 400 |
+
py::arg{}.noconvert());
|
| 401 |
+
m.def("iss738_f2",
|
| 402 |
+
&adjust_matrix<const Eigen::Ref<const Eigen::Matrix<double, -1, -1, Eigen::RowMajor>> &>,
|
| 403 |
+
py::arg{}.noconvert());
|
| 404 |
+
|
| 405 |
+
// test_issue1105
|
| 406 |
+
// Issue #1105: when converting from a numpy two-dimensional (Nx1) or (1xN) value into a dense
|
| 407 |
+
// eigen Vector or RowVector, the argument would fail to load because the numpy copy would
|
| 408 |
+
// fail: numpy won't broadcast a Nx1 into a 1-dimensional vector.
|
| 409 |
+
m.def("iss1105_col", [](const Eigen::VectorXd &) { return true; });
|
| 410 |
+
m.def("iss1105_row", [](const Eigen::RowVectorXd &) { return true; });
|
| 411 |
+
|
| 412 |
+
// test_named_arguments
|
| 413 |
+
// Make sure named arguments are working properly:
|
| 414 |
+
m.def(
|
| 415 |
+
"matrix_multiply",
|
| 416 |
+
[](const py::EigenDRef<const Eigen::MatrixXd> &A,
|
| 417 |
+
const py::EigenDRef<const Eigen::MatrixXd> &B) -> Eigen::MatrixXd {
|
| 418 |
+
if (A.cols() != B.rows()) {
|
| 419 |
+
throw std::domain_error("Nonconformable matrices!");
|
| 420 |
+
}
|
| 421 |
+
return A * B;
|
| 422 |
+
},
|
| 423 |
+
py::arg("A"),
|
| 424 |
+
py::arg("B"));
|
| 425 |
+
|
| 426 |
+
// test_custom_operator_new
|
| 427 |
+
py::class_<CustomOperatorNew>(m, "CustomOperatorNew")
|
| 428 |
+
.def(py::init<>())
|
| 429 |
+
.def_readonly("a", &CustomOperatorNew::a)
|
| 430 |
+
.def_readonly("b", &CustomOperatorNew::b);
|
| 431 |
+
|
| 432 |
+
// test_eigen_ref_life_support
|
| 433 |
+
// In case of a failure (the caster's temp array does not live long enough), creating
|
| 434 |
+
// a new array (np.ones(10)) increases the chances that the temp array will be garbage
|
| 435 |
+
// collected and/or that its memory will be overridden with different values.
|
| 436 |
+
m.def("get_elem_direct", [](const Eigen::Ref<const Eigen::VectorXd> &v) {
|
| 437 |
+
py::module_::import("numpy").attr("ones")(10);
|
| 438 |
+
return v(5);
|
| 439 |
+
});
|
| 440 |
+
m.def("get_elem_indirect", [](std::vector<Eigen::Ref<const Eigen::VectorXd>> v) {
|
| 441 |
+
py::module_::import("numpy").attr("ones")(10);
|
| 442 |
+
return v[0](5);
|
| 443 |
+
});
|
| 444 |
+
m.def("round_trip_vector", [](const Eigen::VectorXf &x) -> Eigen::VectorXf { return x; });
|
| 445 |
+
m.def("round_trip_dense", [](const DenseMatrixR &m) -> DenseMatrixR { return m; });
|
| 446 |
+
m.def("round_trip_dense_ref",
|
| 447 |
+
[](const Eigen::Ref<DenseMatrixR> &m) -> Eigen::Ref<DenseMatrixR> { return m; });
|
| 448 |
+
}
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_eigen_matrix.py
ADDED
|
@@ -0,0 +1,839 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import env # noqa: F401
|
| 6 |
+
from pybind11_tests import ConstructorStats
|
| 7 |
+
|
| 8 |
+
np = pytest.importorskip("numpy")
|
| 9 |
+
m = pytest.importorskip("pybind11_tests.eigen_matrix")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
ref = np.array(
|
| 13 |
+
[
|
| 14 |
+
[0.0, 3, 0, 0, 0, 11],
|
| 15 |
+
[22, 0, 0, 0, 17, 11],
|
| 16 |
+
[7, 5, 0, 1, 0, 11],
|
| 17 |
+
[0, 0, 0, 0, 0, 11],
|
| 18 |
+
[0, 0, 14, 0, 8, 11],
|
| 19 |
+
]
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def assert_equal_ref(mat):
|
| 24 |
+
np.testing.assert_array_equal(mat, ref)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def assert_sparse_equal_ref(sparse_mat):
|
| 28 |
+
assert_equal_ref(sparse_mat.toarray())
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_fixed():
|
| 32 |
+
assert_equal_ref(m.fixed_c())
|
| 33 |
+
assert_equal_ref(m.fixed_r())
|
| 34 |
+
assert_equal_ref(m.fixed_copy_r(m.fixed_r()))
|
| 35 |
+
assert_equal_ref(m.fixed_copy_c(m.fixed_c()))
|
| 36 |
+
assert_equal_ref(m.fixed_copy_r(m.fixed_c()))
|
| 37 |
+
assert_equal_ref(m.fixed_copy_c(m.fixed_r()))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_dense():
|
| 41 |
+
assert_equal_ref(m.dense_r())
|
| 42 |
+
assert_equal_ref(m.dense_c())
|
| 43 |
+
assert_equal_ref(m.dense_copy_r(m.dense_r()))
|
| 44 |
+
assert_equal_ref(m.dense_copy_c(m.dense_c()))
|
| 45 |
+
assert_equal_ref(m.dense_copy_r(m.dense_c()))
|
| 46 |
+
assert_equal_ref(m.dense_copy_c(m.dense_r()))
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_partially_fixed():
|
| 50 |
+
ref2 = np.array([[0.0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
|
| 51 |
+
np.testing.assert_array_equal(m.partial_copy_four_rm_r(ref2), ref2)
|
| 52 |
+
np.testing.assert_array_equal(m.partial_copy_four_rm_c(ref2), ref2)
|
| 53 |
+
np.testing.assert_array_equal(m.partial_copy_four_rm_r(ref2[:, 1]), ref2[:, [1]])
|
| 54 |
+
np.testing.assert_array_equal(m.partial_copy_four_rm_c(ref2[0, :]), ref2[[0], :])
|
| 55 |
+
np.testing.assert_array_equal(
|
| 56 |
+
m.partial_copy_four_rm_r(ref2[:, (0, 2)]), ref2[:, (0, 2)]
|
| 57 |
+
)
|
| 58 |
+
np.testing.assert_array_equal(
|
| 59 |
+
m.partial_copy_four_rm_c(ref2[(3, 1, 2), :]), ref2[(3, 1, 2), :]
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
np.testing.assert_array_equal(m.partial_copy_four_cm_r(ref2), ref2)
|
| 63 |
+
np.testing.assert_array_equal(m.partial_copy_four_cm_c(ref2), ref2)
|
| 64 |
+
np.testing.assert_array_equal(m.partial_copy_four_cm_r(ref2[:, 1]), ref2[:, [1]])
|
| 65 |
+
np.testing.assert_array_equal(m.partial_copy_four_cm_c(ref2[0, :]), ref2[[0], :])
|
| 66 |
+
np.testing.assert_array_equal(
|
| 67 |
+
m.partial_copy_four_cm_r(ref2[:, (0, 2)]), ref2[:, (0, 2)]
|
| 68 |
+
)
|
| 69 |
+
np.testing.assert_array_equal(
|
| 70 |
+
m.partial_copy_four_cm_c(ref2[(3, 1, 2), :]), ref2[(3, 1, 2), :]
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# TypeError should be raise for a shape mismatch
|
| 74 |
+
functions = [
|
| 75 |
+
m.partial_copy_four_rm_r,
|
| 76 |
+
m.partial_copy_four_rm_c,
|
| 77 |
+
m.partial_copy_four_cm_r,
|
| 78 |
+
m.partial_copy_four_cm_c,
|
| 79 |
+
]
|
| 80 |
+
matrix_with_wrong_shape = [[1, 2], [3, 4]]
|
| 81 |
+
for f in functions:
|
| 82 |
+
with pytest.raises(TypeError) as excinfo:
|
| 83 |
+
f(matrix_with_wrong_shape)
|
| 84 |
+
assert "incompatible function arguments" in str(excinfo.value)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_mutator_descriptors():
|
| 88 |
+
zr = np.arange(30, dtype="float32").reshape(5, 6) # row-major
|
| 89 |
+
zc = zr.reshape(6, 5).transpose() # column-major
|
| 90 |
+
|
| 91 |
+
m.fixed_mutator_r(zr)
|
| 92 |
+
m.fixed_mutator_c(zc)
|
| 93 |
+
m.fixed_mutator_a(zr)
|
| 94 |
+
m.fixed_mutator_a(zc)
|
| 95 |
+
with pytest.raises(TypeError) as excinfo:
|
| 96 |
+
m.fixed_mutator_r(zc)
|
| 97 |
+
assert (
|
| 98 |
+
'(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], "[5, 6]",'
|
| 99 |
+
' "flags.writeable", "flags.c_contiguous"]) -> None' in str(excinfo.value)
|
| 100 |
+
)
|
| 101 |
+
with pytest.raises(TypeError) as excinfo:
|
| 102 |
+
m.fixed_mutator_c(zr)
|
| 103 |
+
assert (
|
| 104 |
+
'(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], "[5, 6]",'
|
| 105 |
+
' "flags.writeable", "flags.f_contiguous"]) -> None' in str(excinfo.value)
|
| 106 |
+
)
|
| 107 |
+
with pytest.raises(TypeError) as excinfo:
|
| 108 |
+
m.fixed_mutator_a(np.array([[1, 2], [3, 4]], dtype="float32"))
|
| 109 |
+
assert (
|
| 110 |
+
'(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], "[5, 6]", "flags.writeable"]) -> None'
|
| 111 |
+
in str(excinfo.value)
|
| 112 |
+
)
|
| 113 |
+
zr.flags.writeable = False
|
| 114 |
+
with pytest.raises(TypeError):
|
| 115 |
+
m.fixed_mutator_r(zr)
|
| 116 |
+
with pytest.raises(TypeError):
|
| 117 |
+
m.fixed_mutator_a(zr)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def test_cpp_casting():
|
| 121 |
+
assert m.cpp_copy(m.fixed_r()) == 22.0
|
| 122 |
+
assert m.cpp_copy(m.fixed_c()) == 22.0
|
| 123 |
+
z = np.array([[5.0, 6], [7, 8]])
|
| 124 |
+
assert m.cpp_copy(z) == 7.0
|
| 125 |
+
assert m.cpp_copy(m.get_cm_ref()) == 21.0
|
| 126 |
+
assert m.cpp_copy(m.get_rm_ref()) == 21.0
|
| 127 |
+
assert m.cpp_ref_c(m.get_cm_ref()) == 21.0
|
| 128 |
+
assert m.cpp_ref_r(m.get_rm_ref()) == 21.0
|
| 129 |
+
with pytest.raises(RuntimeError) as excinfo:
|
| 130 |
+
# Can't reference m.fixed_c: it contains floats, m.cpp_ref_any wants doubles
|
| 131 |
+
m.cpp_ref_any(m.fixed_c())
|
| 132 |
+
assert "Unable to cast Python instance" in str(excinfo.value)
|
| 133 |
+
with pytest.raises(RuntimeError) as excinfo:
|
| 134 |
+
# Can't reference m.fixed_r: it contains floats, m.cpp_ref_any wants doubles
|
| 135 |
+
m.cpp_ref_any(m.fixed_r())
|
| 136 |
+
assert "Unable to cast Python instance" in str(excinfo.value)
|
| 137 |
+
assert m.cpp_ref_any(m.ReturnTester.create()) == 1.0
|
| 138 |
+
|
| 139 |
+
assert m.cpp_ref_any(m.get_cm_ref()) == 21.0
|
| 140 |
+
assert m.cpp_ref_any(m.get_cm_ref()) == 21.0
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_pass_readonly_array():
|
| 144 |
+
z = np.full((5, 6), 42.0)
|
| 145 |
+
z.flags.writeable = False
|
| 146 |
+
np.testing.assert_array_equal(z, m.fixed_copy_r(z))
|
| 147 |
+
np.testing.assert_array_equal(m.fixed_r_const(), m.fixed_r())
|
| 148 |
+
assert not m.fixed_r_const().flags.writeable
|
| 149 |
+
np.testing.assert_array_equal(m.fixed_copy_r(m.fixed_r_const()), m.fixed_r_const())
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def test_nonunit_stride_from_python():
|
| 153 |
+
counting_mat = np.arange(9.0, dtype=np.float32).reshape((3, 3))
|
| 154 |
+
second_row = counting_mat[1, :]
|
| 155 |
+
second_col = counting_mat[:, 1]
|
| 156 |
+
np.testing.assert_array_equal(m.double_row(second_row), 2.0 * second_row)
|
| 157 |
+
np.testing.assert_array_equal(m.double_col(second_row), 2.0 * second_row)
|
| 158 |
+
np.testing.assert_array_equal(m.double_complex(second_row), 2.0 * second_row)
|
| 159 |
+
np.testing.assert_array_equal(m.double_row(second_col), 2.0 * second_col)
|
| 160 |
+
np.testing.assert_array_equal(m.double_col(second_col), 2.0 * second_col)
|
| 161 |
+
np.testing.assert_array_equal(m.double_complex(second_col), 2.0 * second_col)
|
| 162 |
+
|
| 163 |
+
counting_3d = np.arange(27.0, dtype=np.float32).reshape((3, 3, 3))
|
| 164 |
+
slices = [counting_3d[0, :, :], counting_3d[:, 0, :], counting_3d[:, :, 0]]
|
| 165 |
+
for ref_mat in slices:
|
| 166 |
+
np.testing.assert_array_equal(m.double_mat_cm(ref_mat), 2.0 * ref_mat)
|
| 167 |
+
np.testing.assert_array_equal(m.double_mat_rm(ref_mat), 2.0 * ref_mat)
|
| 168 |
+
|
| 169 |
+
# Mutator:
|
| 170 |
+
m.double_threer(second_row)
|
| 171 |
+
m.double_threec(second_col)
|
| 172 |
+
np.testing.assert_array_equal(counting_mat, [[0.0, 2, 2], [6, 16, 10], [6, 14, 8]])
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def test_negative_stride_from_python(msg):
|
| 176 |
+
"""Eigen doesn't support (as of yet) negative strides. When a function takes an Eigen matrix by
|
| 177 |
+
copy or const reference, we can pass a numpy array that has negative strides. Otherwise, an
|
| 178 |
+
exception will be thrown as Eigen will not be able to map the numpy array."""
|
| 179 |
+
|
| 180 |
+
counting_mat = np.arange(9.0, dtype=np.float32).reshape((3, 3))
|
| 181 |
+
counting_mat = counting_mat[::-1, ::-1]
|
| 182 |
+
second_row = counting_mat[1, :]
|
| 183 |
+
second_col = counting_mat[:, 1]
|
| 184 |
+
np.testing.assert_array_equal(m.double_row(second_row), 2.0 * second_row)
|
| 185 |
+
np.testing.assert_array_equal(m.double_col(second_row), 2.0 * second_row)
|
| 186 |
+
np.testing.assert_array_equal(m.double_complex(second_row), 2.0 * second_row)
|
| 187 |
+
np.testing.assert_array_equal(m.double_row(second_col), 2.0 * second_col)
|
| 188 |
+
np.testing.assert_array_equal(m.double_col(second_col), 2.0 * second_col)
|
| 189 |
+
np.testing.assert_array_equal(m.double_complex(second_col), 2.0 * second_col)
|
| 190 |
+
|
| 191 |
+
counting_3d = np.arange(27.0, dtype=np.float32).reshape((3, 3, 3))
|
| 192 |
+
counting_3d = counting_3d[::-1, ::-1, ::-1]
|
| 193 |
+
slices = [counting_3d[0, :, :], counting_3d[:, 0, :], counting_3d[:, :, 0]]
|
| 194 |
+
for ref_mat in slices:
|
| 195 |
+
np.testing.assert_array_equal(m.double_mat_cm(ref_mat), 2.0 * ref_mat)
|
| 196 |
+
np.testing.assert_array_equal(m.double_mat_rm(ref_mat), 2.0 * ref_mat)
|
| 197 |
+
|
| 198 |
+
# Mutator:
|
| 199 |
+
with pytest.raises(TypeError) as excinfo:
|
| 200 |
+
m.double_threer(second_row)
|
| 201 |
+
assert (
|
| 202 |
+
msg(excinfo.value)
|
| 203 |
+
== """
|
| 204 |
+
double_threer(): incompatible function arguments. The following argument types are supported:
|
| 205 |
+
1. (arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], "[1, 3]", "flags.writeable"]) -> None
|
| 206 |
+
|
| 207 |
+
Invoked with: """
|
| 208 |
+
+ repr(np.array([5.0, 4.0, 3.0], dtype="float32"))
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
with pytest.raises(TypeError) as excinfo:
|
| 212 |
+
m.double_threec(second_col)
|
| 213 |
+
assert (
|
| 214 |
+
msg(excinfo.value)
|
| 215 |
+
== """
|
| 216 |
+
double_threec(): incompatible function arguments. The following argument types are supported:
|
| 217 |
+
1. (arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], "[3, 1]", "flags.writeable"]) -> None
|
| 218 |
+
|
| 219 |
+
Invoked with: """
|
| 220 |
+
+ repr(np.array([7.0, 4.0, 1.0], dtype="float32"))
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def test_block_runtime_error_type_caster_eigen_ref_made_a_copy():
|
| 225 |
+
with pytest.raises(RuntimeError) as excinfo:
|
| 226 |
+
m.block(ref, 0, 0, 0, 0)
|
| 227 |
+
assert str(excinfo.value) == "type_caster for Eigen::Ref made a copy."
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def test_nonunit_stride_to_python():
|
| 231 |
+
assert np.all(m.diagonal(ref) == ref.diagonal())
|
| 232 |
+
assert np.all(m.diagonal_1(ref) == ref.diagonal(1))
|
| 233 |
+
for i in range(-5, 7):
|
| 234 |
+
assert np.all(m.diagonal_n(ref, i) == ref.diagonal(i)), f"m.diagonal_n({i})"
|
| 235 |
+
|
| 236 |
+
# Must be order="F", otherwise the type_caster will make a copy and
|
| 237 |
+
# m.block() will return a dangling reference (heap-use-after-free).
|
| 238 |
+
rof = np.asarray(ref, order="F")
|
| 239 |
+
assert np.all(m.block(rof, 2, 1, 3, 3) == rof[2:5, 1:4])
|
| 240 |
+
assert np.all(m.block(rof, 1, 4, 4, 2) == rof[1:, 4:])
|
| 241 |
+
assert np.all(m.block(rof, 1, 4, 3, 2) == rof[1:4, 4:])
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def test_eigen_ref_to_python():
|
| 245 |
+
chols = [m.cholesky1, m.cholesky2, m.cholesky3, m.cholesky4]
|
| 246 |
+
for i, chol in enumerate(chols, start=1):
|
| 247 |
+
mymat = chol(np.array([[1.0, 2, 4], [2, 13, 23], [4, 23, 77]]))
|
| 248 |
+
assert np.all(mymat == np.array([[1, 0, 0], [2, 3, 0], [4, 5, 6]])), (
|
| 249 |
+
f"cholesky{i}"
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def assign_both(a1, a2, r, c, v):
|
| 254 |
+
a1[r, c] = v
|
| 255 |
+
a2[r, c] = v
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def array_copy_but_one(a, r, c, v):
|
| 259 |
+
z = np.array(a, copy=True)
|
| 260 |
+
z[r, c] = v
|
| 261 |
+
return z
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def test_eigen_return_references():
|
| 265 |
+
"""Tests various ways of returning references and non-referencing copies"""
|
| 266 |
+
|
| 267 |
+
primary = np.ones((10, 10))
|
| 268 |
+
a = m.ReturnTester()
|
| 269 |
+
a_get1 = a.get()
|
| 270 |
+
assert not a_get1.flags.owndata
|
| 271 |
+
assert a_get1.flags.writeable
|
| 272 |
+
assign_both(a_get1, primary, 3, 3, 5)
|
| 273 |
+
a_get2 = a.get_ptr()
|
| 274 |
+
assert not a_get2.flags.owndata
|
| 275 |
+
assert a_get2.flags.writeable
|
| 276 |
+
assign_both(a_get1, primary, 2, 3, 6)
|
| 277 |
+
|
| 278 |
+
a_view1 = a.view()
|
| 279 |
+
assert not a_view1.flags.owndata
|
| 280 |
+
assert not a_view1.flags.writeable
|
| 281 |
+
with pytest.raises(ValueError):
|
| 282 |
+
a_view1[2, 3] = 4
|
| 283 |
+
a_view2 = a.view_ptr()
|
| 284 |
+
assert not a_view2.flags.owndata
|
| 285 |
+
assert not a_view2.flags.writeable
|
| 286 |
+
with pytest.raises(ValueError):
|
| 287 |
+
a_view2[2, 3] = 4
|
| 288 |
+
|
| 289 |
+
a_copy1 = a.copy_get()
|
| 290 |
+
assert a_copy1.flags.owndata
|
| 291 |
+
assert a_copy1.flags.writeable
|
| 292 |
+
np.testing.assert_array_equal(a_copy1, primary)
|
| 293 |
+
a_copy1[7, 7] = -44 # Shouldn't affect anything else
|
| 294 |
+
c1want = array_copy_but_one(primary, 7, 7, -44)
|
| 295 |
+
a_copy2 = a.copy_view()
|
| 296 |
+
assert a_copy2.flags.owndata
|
| 297 |
+
assert a_copy2.flags.writeable
|
| 298 |
+
np.testing.assert_array_equal(a_copy2, primary)
|
| 299 |
+
a_copy2[4, 4] = -22 # Shouldn't affect anything else
|
| 300 |
+
c2want = array_copy_but_one(primary, 4, 4, -22)
|
| 301 |
+
|
| 302 |
+
a_ref1 = a.ref()
|
| 303 |
+
assert not a_ref1.flags.owndata
|
| 304 |
+
assert a_ref1.flags.writeable
|
| 305 |
+
assign_both(a_ref1, primary, 1, 1, 15)
|
| 306 |
+
a_ref2 = a.ref_const()
|
| 307 |
+
assert not a_ref2.flags.owndata
|
| 308 |
+
assert not a_ref2.flags.writeable
|
| 309 |
+
with pytest.raises(ValueError):
|
| 310 |
+
a_ref2[5, 5] = 33
|
| 311 |
+
a_ref3 = a.ref_safe()
|
| 312 |
+
assert not a_ref3.flags.owndata
|
| 313 |
+
assert a_ref3.flags.writeable
|
| 314 |
+
assign_both(a_ref3, primary, 0, 7, 99)
|
| 315 |
+
a_ref4 = a.ref_const_safe()
|
| 316 |
+
assert not a_ref4.flags.owndata
|
| 317 |
+
assert not a_ref4.flags.writeable
|
| 318 |
+
with pytest.raises(ValueError):
|
| 319 |
+
a_ref4[7, 0] = 987654321
|
| 320 |
+
|
| 321 |
+
a_copy3 = a.copy_ref()
|
| 322 |
+
assert a_copy3.flags.owndata
|
| 323 |
+
assert a_copy3.flags.writeable
|
| 324 |
+
np.testing.assert_array_equal(a_copy3, primary)
|
| 325 |
+
a_copy3[8, 1] = 11
|
| 326 |
+
c3want = array_copy_but_one(primary, 8, 1, 11)
|
| 327 |
+
a_copy4 = a.copy_ref_const()
|
| 328 |
+
assert a_copy4.flags.owndata
|
| 329 |
+
assert a_copy4.flags.writeable
|
| 330 |
+
np.testing.assert_array_equal(a_copy4, primary)
|
| 331 |
+
a_copy4[8, 4] = 88
|
| 332 |
+
c4want = array_copy_but_one(primary, 8, 4, 88)
|
| 333 |
+
|
| 334 |
+
a_block1 = a.block(3, 3, 2, 2)
|
| 335 |
+
assert not a_block1.flags.owndata
|
| 336 |
+
assert a_block1.flags.writeable
|
| 337 |
+
a_block1[0, 0] = 55
|
| 338 |
+
primary[3, 3] = 55
|
| 339 |
+
a_block2 = a.block_safe(2, 2, 3, 2)
|
| 340 |
+
assert not a_block2.flags.owndata
|
| 341 |
+
assert a_block2.flags.writeable
|
| 342 |
+
a_block2[2, 1] = -123
|
| 343 |
+
primary[4, 3] = -123
|
| 344 |
+
a_block3 = a.block_const(6, 7, 4, 3)
|
| 345 |
+
assert not a_block3.flags.owndata
|
| 346 |
+
assert not a_block3.flags.writeable
|
| 347 |
+
with pytest.raises(ValueError):
|
| 348 |
+
a_block3[2, 2] = -44444
|
| 349 |
+
|
| 350 |
+
a_copy5 = a.copy_block(2, 2, 2, 3)
|
| 351 |
+
assert a_copy5.flags.owndata
|
| 352 |
+
assert a_copy5.flags.writeable
|
| 353 |
+
np.testing.assert_array_equal(a_copy5, primary[2:4, 2:5])
|
| 354 |
+
a_copy5[1, 1] = 777
|
| 355 |
+
c5want = array_copy_but_one(primary[2:4, 2:5], 1, 1, 777)
|
| 356 |
+
|
| 357 |
+
a_corn1 = a.corners()
|
| 358 |
+
assert not a_corn1.flags.owndata
|
| 359 |
+
assert a_corn1.flags.writeable
|
| 360 |
+
a_corn1 *= 50
|
| 361 |
+
a_corn1[1, 1] = 999
|
| 362 |
+
primary[0, 0] = 50
|
| 363 |
+
primary[0, 9] = 50
|
| 364 |
+
primary[9, 0] = 50
|
| 365 |
+
primary[9, 9] = 999
|
| 366 |
+
a_corn2 = a.corners_const()
|
| 367 |
+
assert not a_corn2.flags.owndata
|
| 368 |
+
assert not a_corn2.flags.writeable
|
| 369 |
+
with pytest.raises(ValueError):
|
| 370 |
+
a_corn2[1, 0] = 51
|
| 371 |
+
|
| 372 |
+
# All of the changes made all the way along should be visible everywhere
|
| 373 |
+
# now (except for the copies, of course)
|
| 374 |
+
np.testing.assert_array_equal(a_get1, primary)
|
| 375 |
+
np.testing.assert_array_equal(a_get2, primary)
|
| 376 |
+
np.testing.assert_array_equal(a_view1, primary)
|
| 377 |
+
np.testing.assert_array_equal(a_view2, primary)
|
| 378 |
+
np.testing.assert_array_equal(a_ref1, primary)
|
| 379 |
+
np.testing.assert_array_equal(a_ref2, primary)
|
| 380 |
+
np.testing.assert_array_equal(a_ref3, primary)
|
| 381 |
+
np.testing.assert_array_equal(a_ref4, primary)
|
| 382 |
+
np.testing.assert_array_equal(a_block1, primary[3:5, 3:5])
|
| 383 |
+
np.testing.assert_array_equal(a_block2, primary[2:5, 2:4])
|
| 384 |
+
np.testing.assert_array_equal(a_block3, primary[6:10, 7:10])
|
| 385 |
+
np.testing.assert_array_equal(
|
| 386 |
+
a_corn1, primary[0 :: primary.shape[0] - 1, 0 :: primary.shape[1] - 1]
|
| 387 |
+
)
|
| 388 |
+
np.testing.assert_array_equal(
|
| 389 |
+
a_corn2, primary[0 :: primary.shape[0] - 1, 0 :: primary.shape[1] - 1]
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
np.testing.assert_array_equal(a_copy1, c1want)
|
| 393 |
+
np.testing.assert_array_equal(a_copy2, c2want)
|
| 394 |
+
np.testing.assert_array_equal(a_copy3, c3want)
|
| 395 |
+
np.testing.assert_array_equal(a_copy4, c4want)
|
| 396 |
+
np.testing.assert_array_equal(a_copy5, c5want)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Cannot reliably trigger GC")
|
| 400 |
+
def assert_keeps_alive(cl, method, *args):
|
| 401 |
+
cstats = ConstructorStats.get(cl)
|
| 402 |
+
start_with = cstats.alive()
|
| 403 |
+
a = cl()
|
| 404 |
+
assert cstats.alive() == start_with + 1
|
| 405 |
+
z = method(a, *args)
|
| 406 |
+
assert cstats.alive() == start_with + 1
|
| 407 |
+
del a
|
| 408 |
+
# Here's the keep alive in action:
|
| 409 |
+
assert cstats.alive() == start_with + 1
|
| 410 |
+
del z
|
| 411 |
+
# Keep alive should have expired:
|
| 412 |
+
assert cstats.alive() == start_with
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Cannot reliably trigger GC")
|
| 416 |
+
def test_eigen_keepalive():
|
| 417 |
+
a = m.ReturnTester()
|
| 418 |
+
cstats = ConstructorStats.get(m.ReturnTester)
|
| 419 |
+
assert cstats.alive() == 1
|
| 420 |
+
unsafe = [a.ref(), a.ref_const(), a.block(1, 2, 3, 4)]
|
| 421 |
+
copies = [
|
| 422 |
+
a.copy_get(),
|
| 423 |
+
a.copy_view(),
|
| 424 |
+
a.copy_ref(),
|
| 425 |
+
a.copy_ref_const(),
|
| 426 |
+
a.copy_block(4, 3, 2, 1),
|
| 427 |
+
]
|
| 428 |
+
del a
|
| 429 |
+
assert cstats.alive() == 0
|
| 430 |
+
del unsafe
|
| 431 |
+
del copies
|
| 432 |
+
|
| 433 |
+
for meth in [
|
| 434 |
+
m.ReturnTester.get,
|
| 435 |
+
m.ReturnTester.get_ptr,
|
| 436 |
+
m.ReturnTester.view,
|
| 437 |
+
m.ReturnTester.view_ptr,
|
| 438 |
+
m.ReturnTester.ref_safe,
|
| 439 |
+
m.ReturnTester.ref_const_safe,
|
| 440 |
+
m.ReturnTester.corners,
|
| 441 |
+
m.ReturnTester.corners_const,
|
| 442 |
+
]:
|
| 443 |
+
assert_keeps_alive(m.ReturnTester, meth)
|
| 444 |
+
|
| 445 |
+
for meth in [m.ReturnTester.block_safe, m.ReturnTester.block_const]:
|
| 446 |
+
assert_keeps_alive(m.ReturnTester, meth, 4, 3, 2, 1)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def test_eigen_ref_mutators():
|
| 450 |
+
"""Tests Eigen's ability to mutate numpy values"""
|
| 451 |
+
|
| 452 |
+
orig = np.array([[1.0, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 453 |
+
zr = np.array(orig)
|
| 454 |
+
zc = np.array(orig, order="F")
|
| 455 |
+
m.add_rm(zr, 1, 0, 100)
|
| 456 |
+
assert np.all(zr == np.array([[1.0, 2, 3], [104, 5, 6], [7, 8, 9]]))
|
| 457 |
+
m.add_cm(zc, 1, 0, 200)
|
| 458 |
+
assert np.all(zc == np.array([[1.0, 2, 3], [204, 5, 6], [7, 8, 9]]))
|
| 459 |
+
|
| 460 |
+
m.add_any(zr, 1, 0, 20)
|
| 461 |
+
assert np.all(zr == np.array([[1.0, 2, 3], [124, 5, 6], [7, 8, 9]]))
|
| 462 |
+
m.add_any(zc, 1, 0, 10)
|
| 463 |
+
assert np.all(zc == np.array([[1.0, 2, 3], [214, 5, 6], [7, 8, 9]]))
|
| 464 |
+
|
| 465 |
+
# Can't reference a col-major array with a row-major Ref, and vice versa:
|
| 466 |
+
with pytest.raises(TypeError):
|
| 467 |
+
m.add_rm(zc, 1, 0, 1)
|
| 468 |
+
with pytest.raises(TypeError):
|
| 469 |
+
m.add_cm(zr, 1, 0, 1)
|
| 470 |
+
|
| 471 |
+
# Overloads:
|
| 472 |
+
m.add1(zr, 1, 0, -100)
|
| 473 |
+
m.add2(zr, 1, 0, -20)
|
| 474 |
+
assert np.all(zr == orig)
|
| 475 |
+
m.add1(zc, 1, 0, -200)
|
| 476 |
+
m.add2(zc, 1, 0, -10)
|
| 477 |
+
assert np.all(zc == orig)
|
| 478 |
+
|
| 479 |
+
# a non-contiguous slice (this won't work on either the row- or
|
| 480 |
+
# column-contiguous refs, but should work for the any)
|
| 481 |
+
cornersr = zr[0::2, 0::2]
|
| 482 |
+
cornersc = zc[0::2, 0::2]
|
| 483 |
+
|
| 484 |
+
assert np.all(cornersr == np.array([[1.0, 3], [7, 9]]))
|
| 485 |
+
assert np.all(cornersc == np.array([[1.0, 3], [7, 9]]))
|
| 486 |
+
|
| 487 |
+
with pytest.raises(TypeError):
|
| 488 |
+
m.add_rm(cornersr, 0, 1, 25)
|
| 489 |
+
with pytest.raises(TypeError):
|
| 490 |
+
m.add_cm(cornersr, 0, 1, 25)
|
| 491 |
+
with pytest.raises(TypeError):
|
| 492 |
+
m.add_rm(cornersc, 0, 1, 25)
|
| 493 |
+
with pytest.raises(TypeError):
|
| 494 |
+
m.add_cm(cornersc, 0, 1, 25)
|
| 495 |
+
m.add_any(cornersr, 0, 1, 25)
|
| 496 |
+
m.add_any(cornersc, 0, 1, 44)
|
| 497 |
+
assert np.all(zr == np.array([[1.0, 2, 28], [4, 5, 6], [7, 8, 9]]))
|
| 498 |
+
assert np.all(zc == np.array([[1.0, 2, 47], [4, 5, 6], [7, 8, 9]]))
|
| 499 |
+
|
| 500 |
+
# You shouldn't be allowed to pass a non-writeable array to a mutating Eigen method:
|
| 501 |
+
zro = zr[0:4, 0:4]
|
| 502 |
+
zro.flags.writeable = False
|
| 503 |
+
with pytest.raises(TypeError):
|
| 504 |
+
m.add_rm(zro, 0, 0, 0)
|
| 505 |
+
with pytest.raises(TypeError):
|
| 506 |
+
m.add_any(zro, 0, 0, 0)
|
| 507 |
+
with pytest.raises(TypeError):
|
| 508 |
+
m.add1(zro, 0, 0, 0)
|
| 509 |
+
with pytest.raises(TypeError):
|
| 510 |
+
m.add2(zro, 0, 0, 0)
|
| 511 |
+
|
| 512 |
+
# integer array shouldn't be passable to a double-matrix-accepting mutating func:
|
| 513 |
+
zi = np.array([[1, 2], [3, 4]])
|
| 514 |
+
with pytest.raises(TypeError):
|
| 515 |
+
m.add_rm(zi)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def test_numpy_ref_mutators():
|
| 519 |
+
"""Tests numpy mutating Eigen matrices (for returned Eigen::Ref<...>s)"""
|
| 520 |
+
|
| 521 |
+
m.reset_refs() # In case another test already changed it
|
| 522 |
+
|
| 523 |
+
zc = m.get_cm_ref()
|
| 524 |
+
zcro = m.get_cm_const_ref()
|
| 525 |
+
zr = m.get_rm_ref()
|
| 526 |
+
zrro = m.get_rm_const_ref()
|
| 527 |
+
|
| 528 |
+
assert [zc[1, 2], zcro[1, 2], zr[1, 2], zrro[1, 2]] == [23] * 4
|
| 529 |
+
|
| 530 |
+
assert not zc.flags.owndata
|
| 531 |
+
assert zc.flags.writeable
|
| 532 |
+
assert not zr.flags.owndata
|
| 533 |
+
assert zr.flags.writeable
|
| 534 |
+
assert not zcro.flags.owndata
|
| 535 |
+
assert not zcro.flags.writeable
|
| 536 |
+
assert not zrro.flags.owndata
|
| 537 |
+
assert not zrro.flags.writeable
|
| 538 |
+
|
| 539 |
+
zc[1, 2] = 99
|
| 540 |
+
expect = np.array([[11.0, 12, 13], [21, 22, 99], [31, 32, 33]])
|
| 541 |
+
# We should have just changed zc, of course, but also zcro and the original eigen matrix
|
| 542 |
+
assert np.all(zc == expect)
|
| 543 |
+
assert np.all(zcro == expect)
|
| 544 |
+
assert np.all(m.get_cm_ref() == expect)
|
| 545 |
+
|
| 546 |
+
zr[1, 2] = 99
|
| 547 |
+
assert np.all(zr == expect)
|
| 548 |
+
assert np.all(zrro == expect)
|
| 549 |
+
assert np.all(m.get_rm_ref() == expect)
|
| 550 |
+
|
| 551 |
+
# Make sure the readonly ones are numpy-readonly:
|
| 552 |
+
with pytest.raises(ValueError):
|
| 553 |
+
zcro[1, 2] = 6
|
| 554 |
+
with pytest.raises(ValueError):
|
| 555 |
+
zrro[1, 2] = 6
|
| 556 |
+
|
| 557 |
+
# We should be able to explicitly copy like this (and since we're copying,
|
| 558 |
+
# the const should drop away)
|
| 559 |
+
y1 = np.array(m.get_cm_const_ref())
|
| 560 |
+
|
| 561 |
+
assert y1.flags.owndata
|
| 562 |
+
assert y1.flags.writeable
|
| 563 |
+
# We should get copies of the eigen data, which was modified above:
|
| 564 |
+
assert y1[1, 2] == 99
|
| 565 |
+
y1[1, 2] += 12
|
| 566 |
+
assert y1[1, 2] == 111
|
| 567 |
+
assert zc[1, 2] == 99 # Make sure we aren't referencing the original
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def test_both_ref_mutators():
|
| 571 |
+
"""Tests a complex chain of nested eigen/numpy references"""
|
| 572 |
+
|
| 573 |
+
m.reset_refs() # In case another test already changed it
|
| 574 |
+
|
| 575 |
+
z = m.get_cm_ref() # numpy -> eigen
|
| 576 |
+
z[0, 2] -= 3
|
| 577 |
+
z2 = m.incr_matrix(z, 1) # numpy -> eigen -> numpy -> eigen
|
| 578 |
+
z2[1, 1] += 6
|
| 579 |
+
z3 = m.incr_matrix(z, 2) # (numpy -> eigen)^3
|
| 580 |
+
z3[2, 2] += -5
|
| 581 |
+
z4 = m.incr_matrix(z, 3) # (numpy -> eigen)^4
|
| 582 |
+
z4[1, 1] -= 1
|
| 583 |
+
z5 = m.incr_matrix(z, 4) # (numpy -> eigen)^5
|
| 584 |
+
z5[0, 0] = 0
|
| 585 |
+
assert np.all(z == z2)
|
| 586 |
+
assert np.all(z == z3)
|
| 587 |
+
assert np.all(z == z4)
|
| 588 |
+
assert np.all(z == z5)
|
| 589 |
+
expect = np.array([[0.0, 22, 20], [31, 37, 33], [41, 42, 38]])
|
| 590 |
+
assert np.all(z == expect)
|
| 591 |
+
|
| 592 |
+
y = np.array(range(100), dtype="float64").reshape(10, 10)
|
| 593 |
+
y2 = m.incr_matrix_any(y, 10) # np -> eigen -> np
|
| 594 |
+
y3 = m.incr_matrix_any(
|
| 595 |
+
y2[0::2, 0::2], -33
|
| 596 |
+
) # np -> eigen -> np slice -> np -> eigen -> np
|
| 597 |
+
y4 = m.even_rows(y3) # numpy -> eigen slice -> (... y3)
|
| 598 |
+
y5 = m.even_cols(y4) # numpy -> eigen slice -> (... y4)
|
| 599 |
+
y6 = m.incr_matrix_any(y5, 1000) # numpy -> eigen -> (... y5)
|
| 600 |
+
|
| 601 |
+
# Apply same mutations using just numpy:
|
| 602 |
+
yexpect = np.array(range(100), dtype="float64").reshape(10, 10)
|
| 603 |
+
yexpect += 10
|
| 604 |
+
yexpect[0::2, 0::2] -= 33
|
| 605 |
+
yexpect[0::4, 0::4] += 1000
|
| 606 |
+
assert np.all(y6 == yexpect[0::4, 0::4])
|
| 607 |
+
assert np.all(y5 == yexpect[0::4, 0::4])
|
| 608 |
+
assert np.all(y4 == yexpect[0::4, 0::2])
|
| 609 |
+
assert np.all(y3 == yexpect[0::2, 0::2])
|
| 610 |
+
assert np.all(y2 == yexpect)
|
| 611 |
+
assert np.all(y == yexpect)
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def test_nocopy_wrapper():
|
| 615 |
+
# get_elem requires a column-contiguous matrix reference, but should be
|
| 616 |
+
# callable with other types of matrix (via copying):
|
| 617 |
+
int_matrix_colmajor = np.array(
|
| 618 |
+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype="l", order="F"
|
| 619 |
+
)
|
| 620 |
+
dbl_matrix_colmajor = np.array(
|
| 621 |
+
int_matrix_colmajor, dtype="double", order="F", copy=True
|
| 622 |
+
)
|
| 623 |
+
int_matrix_rowmajor = np.array(int_matrix_colmajor, order="C", copy=True)
|
| 624 |
+
dbl_matrix_rowmajor = np.array(
|
| 625 |
+
int_matrix_rowmajor, dtype="double", order="C", copy=True
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
# All should be callable via get_elem:
|
| 629 |
+
assert m.get_elem(int_matrix_colmajor) == 8
|
| 630 |
+
assert m.get_elem(dbl_matrix_colmajor) == 8
|
| 631 |
+
assert m.get_elem(int_matrix_rowmajor) == 8
|
| 632 |
+
assert m.get_elem(dbl_matrix_rowmajor) == 8
|
| 633 |
+
|
| 634 |
+
# All but the second should fail with m.get_elem_nocopy:
|
| 635 |
+
with pytest.raises(TypeError) as excinfo:
|
| 636 |
+
m.get_elem_nocopy(int_matrix_colmajor)
|
| 637 |
+
assert "get_elem_nocopy(): incompatible function arguments." in str(excinfo.value)
|
| 638 |
+
assert ', "flags.f_contiguous"' in str(excinfo.value)
|
| 639 |
+
assert m.get_elem_nocopy(dbl_matrix_colmajor) == 8
|
| 640 |
+
with pytest.raises(TypeError) as excinfo:
|
| 641 |
+
m.get_elem_nocopy(int_matrix_rowmajor)
|
| 642 |
+
assert "get_elem_nocopy(): incompatible function arguments." in str(excinfo.value)
|
| 643 |
+
assert ', "flags.f_contiguous"' in str(excinfo.value)
|
| 644 |
+
with pytest.raises(TypeError) as excinfo:
|
| 645 |
+
m.get_elem_nocopy(dbl_matrix_rowmajor)
|
| 646 |
+
assert "get_elem_nocopy(): incompatible function arguments." in str(excinfo.value)
|
| 647 |
+
assert ', "flags.f_contiguous"' in str(excinfo.value)
|
| 648 |
+
|
| 649 |
+
# For the row-major test, we take a long matrix in row-major, so only the third is allowed:
|
| 650 |
+
with pytest.raises(TypeError) as excinfo:
|
| 651 |
+
m.get_elem_rm_nocopy(int_matrix_colmajor)
|
| 652 |
+
assert "get_elem_rm_nocopy(): incompatible function arguments." in str(
|
| 653 |
+
excinfo.value
|
| 654 |
+
)
|
| 655 |
+
assert ', "flags.c_contiguous"' in str(excinfo.value)
|
| 656 |
+
with pytest.raises(TypeError) as excinfo:
|
| 657 |
+
m.get_elem_rm_nocopy(dbl_matrix_colmajor)
|
| 658 |
+
assert "get_elem_rm_nocopy(): incompatible function arguments." in str(
|
| 659 |
+
excinfo.value
|
| 660 |
+
)
|
| 661 |
+
assert ', "flags.c_contiguous"' in str(excinfo.value)
|
| 662 |
+
assert m.get_elem_rm_nocopy(int_matrix_rowmajor) == 8
|
| 663 |
+
with pytest.raises(TypeError) as excinfo:
|
| 664 |
+
m.get_elem_rm_nocopy(dbl_matrix_rowmajor)
|
| 665 |
+
assert "get_elem_rm_nocopy(): incompatible function arguments." in str(
|
| 666 |
+
excinfo.value
|
| 667 |
+
)
|
| 668 |
+
assert ', "flags.c_contiguous"' in str(excinfo.value)
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def test_eigen_ref_life_support():
|
| 672 |
+
"""Ensure the lifetime of temporary arrays created by the `Ref` caster
|
| 673 |
+
|
| 674 |
+
The `Ref` caster sometimes creates a copy which needs to stay alive. This needs to
|
| 675 |
+
happen both for directs casts (just the array) or indirectly (e.g. list of arrays).
|
| 676 |
+
"""
|
| 677 |
+
|
| 678 |
+
a = np.full(shape=10, fill_value=8, dtype=np.int8)
|
| 679 |
+
assert m.get_elem_direct(a) == 8
|
| 680 |
+
|
| 681 |
+
list_of_a = [a]
|
| 682 |
+
assert m.get_elem_indirect(list_of_a) == 8
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
def test_special_matrix_objects():
|
| 686 |
+
assert np.all(m.incr_diag(7) == np.diag([1.0, 2, 3, 4, 5, 6, 7]))
|
| 687 |
+
|
| 688 |
+
asymm = np.array([[1.0, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
|
| 689 |
+
symm_lower = np.array(asymm)
|
| 690 |
+
symm_upper = np.array(asymm)
|
| 691 |
+
for i in range(4):
|
| 692 |
+
for j in range(i + 1, 4):
|
| 693 |
+
symm_lower[i, j] = symm_lower[j, i]
|
| 694 |
+
symm_upper[j, i] = symm_upper[i, j]
|
| 695 |
+
|
| 696 |
+
assert np.all(m.symmetric_lower(asymm) == symm_lower)
|
| 697 |
+
assert np.all(m.symmetric_upper(asymm) == symm_upper)
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
def test_dense_signature(doc):
|
| 701 |
+
assert (
|
| 702 |
+
doc(m.double_col)
|
| 703 |
+
== """
|
| 704 |
+
double_col(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float32, "[m, 1]"]) -> typing.Annotated[numpy.typing.NDArray[numpy.float32], "[m, 1]"]
|
| 705 |
+
"""
|
| 706 |
+
)
|
| 707 |
+
assert (
|
| 708 |
+
doc(m.double_row)
|
| 709 |
+
== """
|
| 710 |
+
double_row(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float32, "[1, n]"]) -> typing.Annotated[numpy.typing.NDArray[numpy.float32], "[1, n]"]
|
| 711 |
+
"""
|
| 712 |
+
)
|
| 713 |
+
assert doc(m.double_complex) == (
|
| 714 |
+
"""
|
| 715 |
+
double_complex(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.complex64, "[m, 1]"])"""
|
| 716 |
+
""" -> typing.Annotated[numpy.typing.NDArray[numpy.complex64], "[m, 1]"]
|
| 717 |
+
"""
|
| 718 |
+
)
|
| 719 |
+
assert doc(m.double_mat_rm) == (
|
| 720 |
+
"""
|
| 721 |
+
double_mat_rm(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float32, "[m, n]"])"""
|
| 722 |
+
""" -> typing.Annotated[numpy.typing.NDArray[numpy.float32], "[m, n]"]
|
| 723 |
+
"""
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
def test_defaults(doc):
|
| 728 |
+
assert "\n" not in str(doc(m.defaults_mat))
|
| 729 |
+
assert "\n" not in str(doc(m.defaults_vec))
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def test_named_arguments():
|
| 733 |
+
a = np.array([[1.0, 2], [3, 4], [5, 6]])
|
| 734 |
+
b = np.ones((2, 1))
|
| 735 |
+
|
| 736 |
+
assert np.all(m.matrix_multiply(a, b) == np.array([[3.0], [7], [11]]))
|
| 737 |
+
assert np.all(m.matrix_multiply(A=a, B=b) == np.array([[3.0], [7], [11]]))
|
| 738 |
+
assert np.all(m.matrix_multiply(B=b, A=a) == np.array([[3.0], [7], [11]]))
|
| 739 |
+
|
| 740 |
+
with pytest.raises(ValueError) as excinfo:
|
| 741 |
+
m.matrix_multiply(b, a)
|
| 742 |
+
assert str(excinfo.value) == "Nonconformable matrices!"
|
| 743 |
+
|
| 744 |
+
with pytest.raises(ValueError) as excinfo:
|
| 745 |
+
m.matrix_multiply(A=b, B=a)
|
| 746 |
+
assert str(excinfo.value) == "Nonconformable matrices!"
|
| 747 |
+
|
| 748 |
+
with pytest.raises(ValueError) as excinfo:
|
| 749 |
+
m.matrix_multiply(B=a, A=b)
|
| 750 |
+
assert str(excinfo.value) == "Nonconformable matrices!"
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
def test_sparse():
|
| 754 |
+
pytest.importorskip("scipy")
|
| 755 |
+
assert_sparse_equal_ref(m.sparse_r())
|
| 756 |
+
assert_sparse_equal_ref(m.sparse_c())
|
| 757 |
+
assert_sparse_equal_ref(m.sparse_copy_r(m.sparse_r()))
|
| 758 |
+
assert_sparse_equal_ref(m.sparse_copy_c(m.sparse_c()))
|
| 759 |
+
assert_sparse_equal_ref(m.sparse_copy_r(m.sparse_c()))
|
| 760 |
+
assert_sparse_equal_ref(m.sparse_copy_c(m.sparse_r()))
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
def test_sparse_signature(doc):
|
| 764 |
+
pytest.importorskip("scipy")
|
| 765 |
+
assert (
|
| 766 |
+
doc(m.sparse_copy_r)
|
| 767 |
+
== """
|
| 768 |
+
sparse_copy_r(arg0: scipy.sparse.csr_matrix[numpy.float32]) -> scipy.sparse.csr_matrix[numpy.float32]
|
| 769 |
+
"""
|
| 770 |
+
)
|
| 771 |
+
assert (
|
| 772 |
+
doc(m.sparse_copy_c)
|
| 773 |
+
== """
|
| 774 |
+
sparse_copy_c(arg0: scipy.sparse.csc_matrix[numpy.float32]) -> scipy.sparse.csc_matrix[numpy.float32]
|
| 775 |
+
"""
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
def test_issue738():
|
| 780 |
+
"""Ignore strides on a length-1 dimension (even if they would be incompatible length > 1)"""
|
| 781 |
+
assert np.all(m.iss738_f1(np.array([[1.0, 2, 3]])) == np.array([[1.0, 102, 203]]))
|
| 782 |
+
assert np.all(
|
| 783 |
+
m.iss738_f1(np.array([[1.0], [2], [3]])) == np.array([[1.0], [12], [23]])
|
| 784 |
+
)
|
| 785 |
+
|
| 786 |
+
assert np.all(m.iss738_f2(np.array([[1.0, 2, 3]])) == np.array([[1.0, 102, 203]]))
|
| 787 |
+
assert np.all(
|
| 788 |
+
m.iss738_f2(np.array([[1.0], [2], [3]])) == np.array([[1.0], [12], [23]])
|
| 789 |
+
)
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
@pytest.mark.parametrize("func", [m.iss738_f1, m.iss738_f2])
|
| 793 |
+
@pytest.mark.parametrize("sizes", [(0, 2), (2, 0)])
|
| 794 |
+
def test_zero_length(func, sizes):
|
| 795 |
+
"""Ignore strides on a length-0 dimension (even if they would be incompatible length > 1)"""
|
| 796 |
+
assert np.all(func(np.zeros(sizes)) == np.zeros(sizes))
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
def test_issue1105():
|
| 800 |
+
"""Issue 1105: 1xN or Nx1 input arrays weren't accepted for eigen
|
| 801 |
+
compile-time row vectors or column vector"""
|
| 802 |
+
assert m.iss1105_row(np.ones((1, 7)))
|
| 803 |
+
assert m.iss1105_col(np.ones((7, 1)))
|
| 804 |
+
|
| 805 |
+
# These should still fail (incompatible dimensions):
|
| 806 |
+
with pytest.raises(TypeError) as excinfo:
|
| 807 |
+
m.iss1105_row(np.ones((7, 1)))
|
| 808 |
+
assert "incompatible function arguments" in str(excinfo.value)
|
| 809 |
+
with pytest.raises(TypeError) as excinfo:
|
| 810 |
+
m.iss1105_col(np.ones((1, 7)))
|
| 811 |
+
assert "incompatible function arguments" in str(excinfo.value)
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def test_custom_operator_new():
|
| 815 |
+
"""Using Eigen types as member variables requires a class-specific
|
| 816 |
+
operator new with proper alignment"""
|
| 817 |
+
|
| 818 |
+
o = m.CustomOperatorNew()
|
| 819 |
+
np.testing.assert_allclose(o.a, 0.0)
|
| 820 |
+
np.testing.assert_allclose(o.b.diagonal(), 1.0)
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
def test_arraylike_signature(doc):
|
| 824 |
+
assert doc(m.round_trip_vector) == (
|
| 825 |
+
'round_trip_vector(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float32, "[m, 1]"])'
|
| 826 |
+
' -> typing.Annotated[numpy.typing.NDArray[numpy.float32], "[m, 1]"]'
|
| 827 |
+
)
|
| 828 |
+
assert doc(m.round_trip_dense) == (
|
| 829 |
+
'round_trip_dense(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float32, "[m, n]"])'
|
| 830 |
+
' -> typing.Annotated[numpy.typing.NDArray[numpy.float32], "[m, n]"]'
|
| 831 |
+
)
|
| 832 |
+
assert doc(m.round_trip_dense_ref) == (
|
| 833 |
+
'round_trip_dense_ref(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], "[m, n]", "flags.writeable", "flags.c_contiguous"])'
|
| 834 |
+
' -> typing.Annotated[numpy.typing.NDArray[numpy.float32], "[m, n]", "flags.writeable", "flags.c_contiguous"]'
|
| 835 |
+
)
|
| 836 |
+
m.round_trip_vector([1.0, 2.0])
|
| 837 |
+
m.round_trip_dense([[1.0, 2.0], [3.0, 4.0]])
|
| 838 |
+
with pytest.raises(TypeError, match="incompatible function arguments"):
|
| 839 |
+
m.round_trip_dense_ref([[1.0, 2.0], [3.0, 4.0]])
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_eigen_tensor.cpp
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
tests/eigen_tensor.cpp -- automatic conversion of Eigen Tensor
|
| 3 |
+
|
| 4 |
+
All rights reserved. Use of this source code is governed by a
|
| 5 |
+
BSD-style license that can be found in the LICENSE file.
|
| 6 |
+
*/
|
| 7 |
+
|
| 8 |
+
#define PYBIND11_TEST_EIGEN_TENSOR_NAMESPACE eigen_tensor
|
| 9 |
+
|
| 10 |
+
#ifdef EIGEN_AVOID_STL_ARRAY
|
| 11 |
+
# undef EIGEN_AVOID_STL_ARRAY
|
| 12 |
+
#endif
|
| 13 |
+
|
| 14 |
+
#include "test_eigen_tensor.inl"
|
| 15 |
+
|
| 16 |
+
#include "pybind11_tests.h"
|
| 17 |
+
|
| 18 |
+
test_initializer egien_tensor("eigen_tensor", eigen_tensor_test::test_module);
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_eigen_tensor.inl
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
tests/eigen_tensor.cpp -- automatic conversion of Eigen Tensor
|
| 3 |
+
|
| 4 |
+
All rights reserved. Use of this source code is governed by a
|
| 5 |
+
BSD-style license that can be found in the LICENSE file.
|
| 6 |
+
*/
|
| 7 |
+
|
| 8 |
+
#include <pybind11/eigen/tensor.h>
|
| 9 |
+
|
| 10 |
+
PYBIND11_NAMESPACE_BEGIN(eigen_tensor_test)
|
| 11 |
+
|
| 12 |
+
namespace py = pybind11;
|
| 13 |
+
|
| 14 |
+
PYBIND11_WARNING_DISABLE_MSVC(4127)
|
| 15 |
+
|
| 16 |
+
template <typename M>
|
| 17 |
+
void reset_tensor(M &x) {
|
| 18 |
+
for (int i = 0; i < x.dimension(0); i++) {
|
| 19 |
+
for (int j = 0; j < x.dimension(1); j++) {
|
| 20 |
+
for (int k = 0; k < x.dimension(2); k++) {
|
| 21 |
+
x(i, j, k) = i * (5 * 2) + j * 2 + k;
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
}
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
template <typename M>
|
| 28 |
+
bool check_tensor(M &x) {
|
| 29 |
+
for (int i = 0; i < x.dimension(0); i++) {
|
| 30 |
+
for (int j = 0; j < x.dimension(1); j++) {
|
| 31 |
+
for (int k = 0; k < x.dimension(2); k++) {
|
| 32 |
+
if (x(i, j, k) != (i * (5 * 2) + j * 2 + k)) {
|
| 33 |
+
return false;
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
return true;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
template <int Options>
|
| 42 |
+
Eigen::Tensor<double, 3, Options> &get_tensor() {
|
| 43 |
+
static Eigen::Tensor<double, 3, Options> *x;
|
| 44 |
+
|
| 45 |
+
if (!x) {
|
| 46 |
+
x = new Eigen::Tensor<double, 3, Options>(3, 5, 2);
|
| 47 |
+
reset_tensor(*x);
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
return *x;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
template <int Options>
|
| 54 |
+
Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> &get_tensor_map() {
|
| 55 |
+
static Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> *x;
|
| 56 |
+
|
| 57 |
+
if (!x) {
|
| 58 |
+
x = new Eigen::TensorMap<Eigen::Tensor<double, 3, Options>>(get_tensor<Options>());
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
return *x;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
template <int Options>
|
| 65 |
+
Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options> &get_fixed_tensor() {
|
| 66 |
+
static Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options> *x;
|
| 67 |
+
|
| 68 |
+
if (!x) {
|
| 69 |
+
Eigen::aligned_allocator<Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>>
|
| 70 |
+
allocator;
|
| 71 |
+
x = new (allocator.allocate(1))
|
| 72 |
+
Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>();
|
| 73 |
+
reset_tensor(*x);
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
return *x;
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
template <int Options>
|
| 80 |
+
const Eigen::Tensor<double, 3, Options> &get_const_tensor() {
|
| 81 |
+
return get_tensor<Options>();
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
template <int Options>
|
| 85 |
+
struct CustomExample {
|
| 86 |
+
CustomExample() : member(get_tensor<Options>()), view_member(member) {}
|
| 87 |
+
|
| 88 |
+
Eigen::Tensor<double, 3, Options> member;
|
| 89 |
+
Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> view_member;
|
| 90 |
+
};
|
| 91 |
+
|
| 92 |
+
template <int Options>
|
| 93 |
+
void init_tensor_module(pybind11::module &m) {
|
| 94 |
+
const char *needed_options = "";
|
| 95 |
+
if (Options == Eigen::ColMajor) {
|
| 96 |
+
needed_options = "F";
|
| 97 |
+
} else {
|
| 98 |
+
needed_options = "C";
|
| 99 |
+
}
|
| 100 |
+
m.attr("needed_options") = needed_options;
|
| 101 |
+
|
| 102 |
+
m.def("setup", []() {
|
| 103 |
+
reset_tensor(get_tensor<Options>());
|
| 104 |
+
reset_tensor(get_fixed_tensor<Options>());
|
| 105 |
+
});
|
| 106 |
+
|
| 107 |
+
m.def("is_ok", []() {
|
| 108 |
+
return check_tensor(get_tensor<Options>()) && check_tensor(get_fixed_tensor<Options>());
|
| 109 |
+
});
|
| 110 |
+
|
| 111 |
+
py::class_<CustomExample<Options>>(m, "CustomExample", py::module_local())
|
| 112 |
+
.def(py::init<>())
|
| 113 |
+
.def_readonly(
|
| 114 |
+
"member", &CustomExample<Options>::member, py::return_value_policy::reference_internal)
|
| 115 |
+
.def_readonly("member_view",
|
| 116 |
+
&CustomExample<Options>::view_member,
|
| 117 |
+
py::return_value_policy::reference_internal);
|
| 118 |
+
|
| 119 |
+
m.def(
|
| 120 |
+
"copy_fixed_tensor",
|
| 121 |
+
[]() { return &get_fixed_tensor<Options>(); },
|
| 122 |
+
py::return_value_policy::copy);
|
| 123 |
+
|
| 124 |
+
m.def("copy_tensor", []() { return &get_tensor<Options>(); }, py::return_value_policy::copy);
|
| 125 |
+
|
| 126 |
+
m.def(
|
| 127 |
+
"copy_const_tensor",
|
| 128 |
+
[]() { return &get_const_tensor<Options>(); },
|
| 129 |
+
py::return_value_policy::copy);
|
| 130 |
+
|
| 131 |
+
m.def(
|
| 132 |
+
"move_fixed_tensor_copy",
|
| 133 |
+
[]() -> Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options> {
|
| 134 |
+
return get_fixed_tensor<Options>();
|
| 135 |
+
},
|
| 136 |
+
py::return_value_policy::move);
|
| 137 |
+
|
| 138 |
+
m.def(
|
| 139 |
+
"move_tensor_copy",
|
| 140 |
+
[]() -> Eigen::Tensor<double, 3, Options> { return get_tensor<Options>(); },
|
| 141 |
+
py::return_value_policy::move);
|
| 142 |
+
|
| 143 |
+
m.def(
|
| 144 |
+
"move_const_tensor",
|
| 145 |
+
[]() -> const Eigen::Tensor<double, 3, Options> & { return get_const_tensor<Options>(); },
|
| 146 |
+
py::return_value_policy::move);
|
| 147 |
+
|
| 148 |
+
m.def(
|
| 149 |
+
"take_fixed_tensor",
|
| 150 |
+
[]() {
|
| 151 |
+
Eigen::aligned_allocator<
|
| 152 |
+
Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>>
|
| 153 |
+
allocator;
|
| 154 |
+
static auto *obj = new (allocator.allocate(1))
|
| 155 |
+
Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>(
|
| 156 |
+
get_fixed_tensor<Options>());
|
| 157 |
+
return obj; // take_ownership will fail.
|
| 158 |
+
},
|
| 159 |
+
py::return_value_policy::take_ownership);
|
| 160 |
+
|
| 161 |
+
m.def(
|
| 162 |
+
"take_tensor",
|
| 163 |
+
[]() {
|
| 164 |
+
static auto *obj = new Eigen::Tensor<double, 3, Options>(get_tensor<Options>());
|
| 165 |
+
return obj; // take_ownership will fail.
|
| 166 |
+
},
|
| 167 |
+
py::return_value_policy::take_ownership);
|
| 168 |
+
|
| 169 |
+
m.def(
|
| 170 |
+
"take_const_tensor",
|
| 171 |
+
[]() -> const Eigen::Tensor<double, 3, Options> * {
|
| 172 |
+
static auto *obj = new Eigen::Tensor<double, 3, Options>(get_tensor<Options>());
|
| 173 |
+
return obj; // take_ownership will fail.
|
| 174 |
+
},
|
| 175 |
+
py::return_value_policy::take_ownership);
|
| 176 |
+
|
| 177 |
+
m.def(
|
| 178 |
+
"take_view_tensor",
|
| 179 |
+
[]() -> const Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> * {
|
| 180 |
+
static auto *obj
|
| 181 |
+
= new Eigen::TensorMap<Eigen::Tensor<double, 3, Options>>(get_tensor<Options>());
|
| 182 |
+
return obj; // take_ownership will fail.
|
| 183 |
+
},
|
| 184 |
+
py::return_value_policy::take_ownership);
|
| 185 |
+
|
| 186 |
+
m.def(
|
| 187 |
+
"reference_tensor",
|
| 188 |
+
[]() { return &get_tensor<Options>(); },
|
| 189 |
+
py::return_value_policy::reference);
|
| 190 |
+
|
| 191 |
+
m.def(
|
| 192 |
+
"reference_tensor_v2",
|
| 193 |
+
[]() -> Eigen::Tensor<double, 3, Options> & { return get_tensor<Options>(); },
|
| 194 |
+
py::return_value_policy::reference);
|
| 195 |
+
|
| 196 |
+
m.def(
|
| 197 |
+
"reference_tensor_internal",
|
| 198 |
+
[]() { return &get_tensor<Options>(); },
|
| 199 |
+
py::return_value_policy::reference_internal);
|
| 200 |
+
|
| 201 |
+
m.def(
|
| 202 |
+
"reference_fixed_tensor",
|
| 203 |
+
[]() { return &get_tensor<Options>(); },
|
| 204 |
+
py::return_value_policy::reference);
|
| 205 |
+
|
| 206 |
+
m.def(
|
| 207 |
+
"reference_const_tensor",
|
| 208 |
+
[]() { return &get_const_tensor<Options>(); },
|
| 209 |
+
py::return_value_policy::reference);
|
| 210 |
+
|
| 211 |
+
m.def(
|
| 212 |
+
"reference_const_tensor_v2",
|
| 213 |
+
[]() -> const Eigen::Tensor<double, 3, Options> & { return get_const_tensor<Options>(); },
|
| 214 |
+
py::return_value_policy::reference);
|
| 215 |
+
|
| 216 |
+
m.def(
|
| 217 |
+
"reference_view_of_tensor",
|
| 218 |
+
[]() -> Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> {
|
| 219 |
+
return get_tensor_map<Options>();
|
| 220 |
+
},
|
| 221 |
+
py::return_value_policy::reference);
|
| 222 |
+
|
| 223 |
+
m.def(
|
| 224 |
+
"reference_view_of_tensor_v2",
|
| 225 |
+
// NOLINTNEXTLINE(readability-const-return-type)
|
| 226 |
+
[]() -> const Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> {
|
| 227 |
+
return get_tensor_map<Options>(); // NOLINT(readability-const-return-type)
|
| 228 |
+
}, // NOLINT(readability-const-return-type)
|
| 229 |
+
py::return_value_policy::reference);
|
| 230 |
+
|
| 231 |
+
m.def(
|
| 232 |
+
"reference_view_of_tensor_v3",
|
| 233 |
+
[]() -> Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> * {
|
| 234 |
+
return &get_tensor_map<Options>();
|
| 235 |
+
},
|
| 236 |
+
py::return_value_policy::reference);
|
| 237 |
+
|
| 238 |
+
m.def(
|
| 239 |
+
"reference_view_of_tensor_v4",
|
| 240 |
+
[]() -> const Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> * {
|
| 241 |
+
return &get_tensor_map<Options>();
|
| 242 |
+
},
|
| 243 |
+
py::return_value_policy::reference);
|
| 244 |
+
|
| 245 |
+
m.def(
|
| 246 |
+
"reference_view_of_tensor_v5",
|
| 247 |
+
[]() -> Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> & {
|
| 248 |
+
return get_tensor_map<Options>();
|
| 249 |
+
},
|
| 250 |
+
py::return_value_policy::reference);
|
| 251 |
+
|
| 252 |
+
m.def(
|
| 253 |
+
"reference_view_of_tensor_v6",
|
| 254 |
+
[]() -> const Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> & {
|
| 255 |
+
return get_tensor_map<Options>();
|
| 256 |
+
},
|
| 257 |
+
py::return_value_policy::reference);
|
| 258 |
+
|
| 259 |
+
m.def(
|
| 260 |
+
"reference_view_of_fixed_tensor",
|
| 261 |
+
[]() {
|
| 262 |
+
return Eigen::TensorMap<
|
| 263 |
+
Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>>(
|
| 264 |
+
get_fixed_tensor<Options>());
|
| 265 |
+
},
|
| 266 |
+
py::return_value_policy::reference);
|
| 267 |
+
|
| 268 |
+
m.def("round_trip_tensor",
|
| 269 |
+
[](const Eigen::Tensor<double, 3, Options> &tensor) { return tensor; });
|
| 270 |
+
|
| 271 |
+
m.def(
|
| 272 |
+
"round_trip_tensor_noconvert",
|
| 273 |
+
[](const Eigen::Tensor<double, 3, Options> &tensor) { return tensor; },
|
| 274 |
+
py::arg("tensor").noconvert());
|
| 275 |
+
|
| 276 |
+
m.def("round_trip_tensor2",
|
| 277 |
+
[](const Eigen::Tensor<int32_t, 3, Options> &tensor) { return tensor; });
|
| 278 |
+
|
| 279 |
+
m.def("round_trip_fixed_tensor",
|
| 280 |
+
[](const Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options> &tensor) {
|
| 281 |
+
return tensor;
|
| 282 |
+
});
|
| 283 |
+
|
| 284 |
+
m.def(
|
| 285 |
+
"round_trip_view_tensor",
|
| 286 |
+
[](Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> view) { return view; },
|
| 287 |
+
py::return_value_policy::reference);
|
| 288 |
+
|
| 289 |
+
m.def(
|
| 290 |
+
"round_trip_view_tensor_ref",
|
| 291 |
+
[](Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> &view) { return view; },
|
| 292 |
+
py::return_value_policy::reference);
|
| 293 |
+
|
| 294 |
+
m.def(
|
| 295 |
+
"round_trip_view_tensor_ptr",
|
| 296 |
+
[](Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> *view) { return view; },
|
| 297 |
+
py::return_value_policy::reference);
|
| 298 |
+
|
| 299 |
+
m.def(
|
| 300 |
+
"round_trip_aligned_view_tensor",
|
| 301 |
+
[](Eigen::TensorMap<Eigen::Tensor<double, 3, Options>, Eigen::Aligned> view) {
|
| 302 |
+
return view;
|
| 303 |
+
},
|
| 304 |
+
py::return_value_policy::reference);
|
| 305 |
+
|
| 306 |
+
m.def(
|
| 307 |
+
"round_trip_const_view_tensor",
|
| 308 |
+
[](Eigen::TensorMap<const Eigen::Tensor<double, 3, Options>> view) {
|
| 309 |
+
return Eigen::Tensor<double, 3, Options>(view);
|
| 310 |
+
},
|
| 311 |
+
py::return_value_policy::move);
|
| 312 |
+
|
| 313 |
+
m.def(
|
| 314 |
+
"round_trip_rank_0",
|
| 315 |
+
[](const Eigen::Tensor<double, 0, Options> &tensor) { return tensor; },
|
| 316 |
+
py::return_value_policy::move);
|
| 317 |
+
|
| 318 |
+
m.def(
|
| 319 |
+
"round_trip_rank_0_noconvert",
|
| 320 |
+
[](const Eigen::Tensor<double, 0, Options> &tensor) { return tensor; },
|
| 321 |
+
py::arg("tensor").noconvert(),
|
| 322 |
+
py::return_value_policy::move);
|
| 323 |
+
|
| 324 |
+
m.def(
|
| 325 |
+
"round_trip_rank_0_view",
|
| 326 |
+
[](Eigen::TensorMap<Eigen::Tensor<double, 0, Options>> &tensor) { return tensor; },
|
| 327 |
+
py::return_value_policy::reference);
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
void test_module(py::module_ &m) {
|
| 331 |
+
auto f_style = m.def_submodule("f_style");
|
| 332 |
+
auto c_style = m.def_submodule("c_style");
|
| 333 |
+
|
| 334 |
+
init_tensor_module<Eigen::ColMajor>(f_style);
|
| 335 |
+
init_tensor_module<Eigen::RowMajor>(c_style);
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
PYBIND11_NAMESPACE_END(eigen_tensor_test)
|
third_party/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/test_eigen_tensor.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
import env # noqa: F401
|
| 8 |
+
|
| 9 |
+
np = pytest.importorskip("numpy")
|
| 10 |
+
eigen_tensor = pytest.importorskip("pybind11_tests.eigen_tensor")
|
| 11 |
+
submodules = [eigen_tensor.c_style, eigen_tensor.f_style]
|
| 12 |
+
try:
|
| 13 |
+
import eigen_tensor_avoid_stl_array as avoid
|
| 14 |
+
|
| 15 |
+
submodules += [avoid.c_style, avoid.f_style]
|
| 16 |
+
except ImportError as e:
|
| 17 |
+
# Ensure config, build, toolchain, etc. issues are not masked here:
|
| 18 |
+
msg = (
|
| 19 |
+
"import eigen_tensor_avoid_stl_array FAILED, while "
|
| 20 |
+
"import pybind11_tests.eigen_tensor succeeded. "
|
| 21 |
+
"Please ensure that "
|
| 22 |
+
"test_eigen_tensor.cpp & "
|
| 23 |
+
"eigen_tensor_avoid_stl_array.cpp "
|
| 24 |
+
"are built together (or both are not built if Eigen is not available)."
|
| 25 |
+
)
|
| 26 |
+
raise RuntimeError(msg) from e
|
| 27 |
+
|
| 28 |
+
tensor_ref = np.empty((3, 5, 2), dtype=np.int64)
|
| 29 |
+
|
| 30 |
+
for i in range(tensor_ref.shape[0]):
|
| 31 |
+
for j in range(tensor_ref.shape[1]):
|
| 32 |
+
for k in range(tensor_ref.shape[2]):
|
| 33 |
+
tensor_ref[i, j, k] = i * (5 * 2) + j * 2 + k
|
| 34 |
+
|
| 35 |
+
indices = (2, 3, 1)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@pytest.fixture(autouse=True)
|
| 39 |
+
def cleanup():
|
| 40 |
+
for module in submodules:
|
| 41 |
+
module.setup()
|
| 42 |
+
|
| 43 |
+
yield
|
| 44 |
+
|
| 45 |
+
for module in submodules:
|
| 46 |
+
assert module.is_ok()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_import_avoid_stl_array():
|
| 50 |
+
pytest.importorskip("eigen_tensor_avoid_stl_array")
|
| 51 |
+
assert len(submodules) == 4
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def assert_equal_tensor_ref(mat, writeable=True, modified=None):
|
| 55 |
+
assert mat.flags.writeable == writeable
|
| 56 |
+
|
| 57 |
+
copy = np.array(tensor_ref)
|
| 58 |
+
if modified is not None:
|
| 59 |
+
copy[indices] = modified
|
| 60 |
+
|
| 61 |
+
np.testing.assert_array_equal(mat, copy)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@pytest.mark.parametrize("m", submodules)
|
| 65 |
+
@pytest.mark.parametrize("member_name", ["member", "member_view"])
|
| 66 |
+
@pytest.mark.skipif("env.GRAALPY", reason="Different refcounting mechanism")
|
| 67 |
+
def test_reference_internal(m, member_name):
|
| 68 |
+
if not hasattr(sys, "getrefcount"):
|
| 69 |
+
pytest.skip("No reference counting")
|
| 70 |
+
foo = m.CustomExample()
|
| 71 |
+
counts = sys.getrefcount(foo)
|
| 72 |
+
mem = getattr(foo, member_name)
|
| 73 |
+
assert_equal_tensor_ref(mem, writeable=False)
|
| 74 |
+
new_counts = sys.getrefcount(foo)
|
| 75 |
+
assert new_counts == counts + 1
|
| 76 |
+
assert_equal_tensor_ref(mem, writeable=False)
|
| 77 |
+
del mem
|
| 78 |
+
assert sys.getrefcount(foo) == counts
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
assert_equal_funcs = [
|
| 82 |
+
"copy_tensor",
|
| 83 |
+
"copy_fixed_tensor",
|
| 84 |
+
"copy_const_tensor",
|
| 85 |
+
"move_tensor_copy",
|
| 86 |
+
"move_fixed_tensor_copy",
|
| 87 |
+
"take_tensor",
|
| 88 |
+
"take_fixed_tensor",
|
| 89 |
+
"reference_tensor",
|
| 90 |
+
"reference_tensor_v2",
|
| 91 |
+
"reference_fixed_tensor",
|
| 92 |
+
"reference_view_of_tensor",
|
| 93 |
+
"reference_view_of_tensor_v3",
|
| 94 |
+
"reference_view_of_tensor_v5",
|
| 95 |
+
"reference_view_of_fixed_tensor",
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
assert_equal_const_funcs = [
|
| 99 |
+
"reference_view_of_tensor_v2",
|
| 100 |
+
"reference_view_of_tensor_v4",
|
| 101 |
+
"reference_view_of_tensor_v6",
|
| 102 |
+
"reference_const_tensor",
|
| 103 |
+
"reference_const_tensor_v2",
|
| 104 |
+
]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@pytest.mark.parametrize("m", submodules)
|
| 108 |
+
@pytest.mark.parametrize("func_name", assert_equal_funcs + assert_equal_const_funcs)
|
| 109 |
+
def test_convert_tensor_to_py(m, func_name):
|
| 110 |
+
writeable = func_name in assert_equal_funcs
|
| 111 |
+
assert_equal_tensor_ref(getattr(m, func_name)(), writeable=writeable)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@pytest.mark.parametrize("m", submodules)
|
| 115 |
+
def test_bad_cpp_to_python_casts(m):
|
| 116 |
+
with pytest.raises(
|
| 117 |
+
RuntimeError, match="Cannot use reference internal when there is no parent"
|
| 118 |
+
):
|
| 119 |
+
m.reference_tensor_internal()
|
| 120 |
+
|
| 121 |
+
with pytest.raises(RuntimeError, match="Cannot move from a constant reference"):
|
| 122 |
+
m.move_const_tensor()
|
| 123 |
+
|
| 124 |
+
with pytest.raises(
|
| 125 |
+
RuntimeError, match="Cannot take ownership of a const reference"
|
| 126 |
+
):
|
| 127 |
+
m.take_const_tensor()
|
| 128 |
+
|
| 129 |
+
with pytest.raises(
|
| 130 |
+
RuntimeError,
|
| 131 |
+
match="Invalid return_value_policy for Eigen Map type, must be either reference or reference_internal",
|
| 132 |
+
):
|
| 133 |
+
m.take_view_tensor()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@pytest.mark.parametrize("m", submodules)
|
| 137 |
+
def test_bad_python_to_cpp_casts(m):
|
| 138 |
+
with pytest.raises(
|
| 139 |
+
TypeError, match=r"^round_trip_tensor\(\): incompatible function arguments"
|
| 140 |
+
):
|
| 141 |
+
m.round_trip_tensor(np.zeros((2, 3)))
|
| 142 |
+
|
| 143 |
+
with pytest.raises(TypeError, match=r"^Cannot cast array data from dtype"):
|
| 144 |
+
m.round_trip_tensor(np.zeros(dtype=np.str_, shape=(2, 3, 1)))
|
| 145 |
+
|
| 146 |
+
with pytest.raises(
|
| 147 |
+
TypeError,
|
| 148 |
+
match=r"^round_trip_tensor_noconvert\(\): incompatible function arguments",
|
| 149 |
+
):
|
| 150 |
+
m.round_trip_tensor_noconvert(tensor_ref)
|
| 151 |
+
|
| 152 |
+
assert_equal_tensor_ref(
|
| 153 |
+
m.round_trip_tensor_noconvert(tensor_ref.astype(np.float64))
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
bad_options = "C" if m.needed_options == "F" else "F"
|
| 157 |
+
# Shape, dtype and the order need to be correct for a TensorMap cast
|
| 158 |
+
with pytest.raises(
|
| 159 |
+
TypeError, match=r"^round_trip_view_tensor\(\): incompatible function arguments"
|
| 160 |
+
):
|
| 161 |
+
m.round_trip_view_tensor(
|
| 162 |
+
np.zeros((3, 5, 2), dtype=np.float64, order=bad_options)
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
with pytest.raises(
|
| 166 |
+
TypeError, match=r"^round_trip_view_tensor\(\): incompatible function arguments"
|
| 167 |
+
):
|
| 168 |
+
m.round_trip_view_tensor(
|
| 169 |
+
np.zeros((3, 5, 2), dtype=np.float32, order=m.needed_options)
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
with pytest.raises(
|
| 173 |
+
TypeError, match=r"^round_trip_view_tensor\(\): incompatible function arguments"
|
| 174 |
+
):
|
| 175 |
+
m.round_trip_view_tensor(
|
| 176 |
+
np.zeros((3, 5), dtype=np.float64, order=m.needed_options)
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
temp = np.zeros((3, 5, 2), dtype=np.float64, order=m.needed_options)
|
| 180 |
+
with pytest.raises(
|
| 181 |
+
TypeError, match=r"^round_trip_view_tensor\(\): incompatible function arguments"
|
| 182 |
+
):
|
| 183 |
+
m.round_trip_view_tensor(
|
| 184 |
+
temp[:, ::-1, :],
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
temp = np.zeros((3, 5, 2), dtype=np.float64, order=m.needed_options)
|
| 188 |
+
temp.setflags(write=False)
|
| 189 |
+
with pytest.raises(
|
| 190 |
+
TypeError, match=r"^round_trip_view_tensor\(\): incompatible function arguments"
|
| 191 |
+
):
|
| 192 |
+
m.round_trip_view_tensor(temp)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@pytest.mark.parametrize("m", submodules)
|
| 196 |
+
def test_references_actually_refer(m):
|
| 197 |
+
a = m.reference_tensor()
|
| 198 |
+
temp = a[indices]
|
| 199 |
+
a[indices] = 100
|
| 200 |
+
assert_equal_tensor_ref(m.copy_const_tensor(), modified=100)
|
| 201 |
+
a[indices] = temp
|
| 202 |
+
assert_equal_tensor_ref(m.copy_const_tensor())
|
| 203 |
+
|
| 204 |
+
a = m.reference_view_of_tensor()
|
| 205 |
+
a[indices] = 100
|
| 206 |
+
assert_equal_tensor_ref(m.copy_const_tensor(), modified=100)
|
| 207 |
+
a[indices] = temp
|
| 208 |
+
assert_equal_tensor_ref(m.copy_const_tensor())
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@pytest.mark.parametrize("m", submodules)
|
| 212 |
+
def test_round_trip(m):
|
| 213 |
+
assert_equal_tensor_ref(m.round_trip_tensor(tensor_ref))
|
| 214 |
+
|
| 215 |
+
with pytest.raises(TypeError, match="^Cannot cast array data from"):
|
| 216 |
+
assert_equal_tensor_ref(m.round_trip_tensor2(tensor_ref))
|
| 217 |
+
|
| 218 |
+
assert_equal_tensor_ref(m.round_trip_tensor2(np.array(tensor_ref, dtype=np.int32)))
|
| 219 |
+
assert_equal_tensor_ref(m.round_trip_fixed_tensor(tensor_ref))
|
| 220 |
+
assert_equal_tensor_ref(m.round_trip_aligned_view_tensor(m.reference_tensor()))
|
| 221 |
+
|
| 222 |
+
copy = np.array(tensor_ref, dtype=np.float64, order=m.needed_options)
|
| 223 |
+
assert_equal_tensor_ref(m.round_trip_view_tensor(copy))
|
| 224 |
+
assert_equal_tensor_ref(m.round_trip_view_tensor_ref(copy))
|
| 225 |
+
assert_equal_tensor_ref(m.round_trip_view_tensor_ptr(copy))
|
| 226 |
+
copy.setflags(write=False)
|
| 227 |
+
assert_equal_tensor_ref(m.round_trip_const_view_tensor(copy))
|
| 228 |
+
|
| 229 |
+
np.testing.assert_array_equal(
|
| 230 |
+
tensor_ref[:, ::-1, :], m.round_trip_tensor(tensor_ref[:, ::-1, :])
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
assert m.round_trip_rank_0(np.float64(3.5)) == 3.5
|
| 234 |
+
assert m.round_trip_rank_0(3.5) == 3.5
|
| 235 |
+
|
| 236 |
+
with pytest.raises(
|
| 237 |
+
TypeError,
|
| 238 |
+
match=r"^round_trip_rank_0_noconvert\(\): incompatible function arguments",
|
| 239 |
+
):
|
| 240 |
+
m.round_trip_rank_0_noconvert(np.float64(3.5))
|
| 241 |
+
|
| 242 |
+
with pytest.raises(
|
| 243 |
+
TypeError,
|
| 244 |
+
match=r"^round_trip_rank_0_noconvert\(\): incompatible function arguments",
|
| 245 |
+
):
|
| 246 |
+
m.round_trip_rank_0_noconvert(3.5)
|
| 247 |
+
|
| 248 |
+
with pytest.raises(
|
| 249 |
+
TypeError, match=r"^round_trip_rank_0_view\(\): incompatible function arguments"
|
| 250 |
+
):
|
| 251 |
+
m.round_trip_rank_0_view(np.float64(3.5))
|
| 252 |
+
|
| 253 |
+
with pytest.raises(
|
| 254 |
+
TypeError, match=r"^round_trip_rank_0_view\(\): incompatible function arguments"
|
| 255 |
+
):
|
| 256 |
+
m.round_trip_rank_0_view(3.5)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@pytest.mark.parametrize("m", submodules)
|
| 260 |
+
def test_round_trip_references_actually_refer(m):
|
| 261 |
+
# Need to create a copy that matches the type on the C side
|
| 262 |
+
copy = np.array(tensor_ref, dtype=np.float64, order=m.needed_options)
|
| 263 |
+
a = m.round_trip_view_tensor(copy)
|
| 264 |
+
temp = a[indices]
|
| 265 |
+
a[indices] = 100
|
| 266 |
+
assert_equal_tensor_ref(copy, modified=100)
|
| 267 |
+
a[indices] = temp
|
| 268 |
+
assert_equal_tensor_ref(copy)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@pytest.mark.parametrize("m", submodules)
|
| 272 |
+
def test_doc_string(m, doc):
|
| 273 |
+
assert (
|
| 274 |
+
doc(m.copy_tensor)
|
| 275 |
+
== 'copy_tensor() -> typing.Annotated[numpy.typing.NDArray[numpy.float64], "[?, ?, ?]"]'
|
| 276 |
+
)
|
| 277 |
+
assert (
|
| 278 |
+
doc(m.copy_fixed_tensor)
|
| 279 |
+
== 'copy_fixed_tensor() -> typing.Annotated[numpy.typing.NDArray[numpy.float64], "[3, 5, 2]"]'
|
| 280 |
+
)
|
| 281 |
+
assert (
|
| 282 |
+
doc(m.reference_const_tensor)
|
| 283 |
+
== 'reference_const_tensor() -> typing.Annotated[numpy.typing.NDArray[numpy.float64], "[?, ?, ?]"]'
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
order_flag = f'"flags.{m.needed_options.lower()}_contiguous"'
|
| 287 |
+
assert doc(m.round_trip_view_tensor) == (
|
| 288 |
+
f'round_trip_view_tensor(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float64], "[?, ?, ?]", "flags.writeable", {order_flag}])'
|
| 289 |
+
f' -> typing.Annotated[numpy.typing.NDArray[numpy.float64], "[?, ?, ?]", "flags.writeable", {order_flag}]'
|
| 290 |
+
)
|
| 291 |
+
assert doc(m.round_trip_const_view_tensor) == (
|
| 292 |
+
f'round_trip_const_view_tensor(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float64], "[?, ?, ?]", {order_flag}])'
|
| 293 |
+
' -> typing.Annotated[numpy.typing.NDArray[numpy.float64], "[?, ?, ?]"]'
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@pytest.mark.parametrize("m", submodules)
|
| 298 |
+
def test_arraylike_signature(m, doc):
|
| 299 |
+
order_flag = f'"flags.{m.needed_options.lower()}_contiguous"'
|
| 300 |
+
assert doc(m.round_trip_tensor) == (
|
| 301 |
+
'round_trip_tensor(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, "[?, ?, ?]"])'
|
| 302 |
+
' -> typing.Annotated[numpy.typing.NDArray[numpy.float64], "[?, ?, ?]"]'
|
| 303 |
+
)
|
| 304 |
+
assert doc(m.round_trip_tensor_noconvert) == (
|
| 305 |
+
'round_trip_tensor_noconvert(tensor: typing.Annotated[numpy.typing.NDArray[numpy.float64], "[?, ?, ?]"])'
|
| 306 |
+
' -> typing.Annotated[numpy.typing.NDArray[numpy.float64], "[?, ?, ?]"]'
|
| 307 |
+
)
|
| 308 |
+
assert doc(m.round_trip_view_tensor) == (
|
| 309 |
+
f'round_trip_view_tensor(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float64], "[?, ?, ?]", "flags.writeable", {order_flag}])'
|
| 310 |
+
f' -> typing.Annotated[numpy.typing.NDArray[numpy.float64], "[?, ?, ?]", "flags.writeable", {order_flag}]'
|
| 311 |
+
)
|
| 312 |
+
m.round_trip_tensor(tensor_ref.tolist())
|
| 313 |
+
with pytest.raises(TypeError, match="incompatible function arguments"):
|
| 314 |
+
m.round_trip_tensor_noconvert(tensor_ref.tolist())
|
| 315 |
+
with pytest.raises(TypeError, match="incompatible function arguments"):
|
| 316 |
+
m.round_trip_view_tensor(tensor_ref.tolist())
|