test_local_bindings.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. # -*- coding: utf-8 -*-
  2. import pytest
  3. import env # noqa: F401
  4. from pybind11_tests import local_bindings as m
  5. def test_load_external():
  6. """Load a `py::module_local` type that's only registered in an external module"""
  7. import pybind11_cross_module_tests as cm
  8. assert m.load_external1(cm.ExternalType1(11)) == 11
  9. assert m.load_external2(cm.ExternalType2(22)) == 22
  10. with pytest.raises(TypeError) as excinfo:
  11. assert m.load_external2(cm.ExternalType1(21)) == 21
  12. assert "incompatible function arguments" in str(excinfo.value)
  13. with pytest.raises(TypeError) as excinfo:
  14. assert m.load_external1(cm.ExternalType2(12)) == 12
  15. assert "incompatible function arguments" in str(excinfo.value)
  16. def test_local_bindings():
  17. """Tests that duplicate `py::module_local` class bindings work across modules"""
  18. # Make sure we can load the second module with the conflicting (but local) definition:
  19. import pybind11_cross_module_tests as cm
  20. i1 = m.LocalType(5)
  21. assert i1.get() == 4
  22. assert i1.get3() == 8
  23. i2 = cm.LocalType(10)
  24. assert i2.get() == 11
  25. assert i2.get2() == 12
  26. assert not hasattr(i1, "get2")
  27. assert not hasattr(i2, "get3")
  28. # Loading within the local module
  29. assert m.local_value(i1) == 5
  30. assert cm.local_value(i2) == 10
  31. # Cross-module loading works as well (on failure, the type loader looks for
  32. # external module-local converters):
  33. assert m.local_value(i2) == 10
  34. assert cm.local_value(i1) == 5
  35. def test_nonlocal_failure():
  36. """Tests that attempting to register a non-local type in multiple modules fails"""
  37. import pybind11_cross_module_tests as cm
  38. with pytest.raises(RuntimeError) as excinfo:
  39. cm.register_nonlocal()
  40. assert (
  41. str(excinfo.value) == 'generic_type: type "NonLocalType" is already registered!'
  42. )
  43. def test_duplicate_local():
  44. """Tests expected failure when registering a class twice with py::local in the same module"""
  45. with pytest.raises(RuntimeError) as excinfo:
  46. m.register_local_external()
  47. import pybind11_tests
  48. assert str(excinfo.value) == (
  49. 'generic_type: type "LocalExternal" is already registered!'
  50. if hasattr(pybind11_tests, "class_")
  51. else "test_class not enabled"
  52. )
  53. def test_stl_bind_local():
  54. import pybind11_cross_module_tests as cm
  55. v1, v2 = m.LocalVec(), cm.LocalVec()
  56. v1.append(m.LocalType(1))
  57. v1.append(m.LocalType(2))
  58. v2.append(cm.LocalType(1))
  59. v2.append(cm.LocalType(2))
  60. # Cross module value loading:
  61. v1.append(cm.LocalType(3))
  62. v2.append(m.LocalType(3))
  63. assert [i.get() for i in v1] == [0, 1, 2]
  64. assert [i.get() for i in v2] == [2, 3, 4]
  65. v3, v4 = m.NonLocalVec(), cm.NonLocalVec2()
  66. v3.append(m.NonLocalType(1))
  67. v3.append(m.NonLocalType(2))
  68. v4.append(m.NonLocal2(3))
  69. v4.append(m.NonLocal2(4))
  70. assert [i.get() for i in v3] == [1, 2]
  71. assert [i.get() for i in v4] == [13, 14]
  72. d1, d2 = m.LocalMap(), cm.LocalMap()
  73. d1["a"] = v1[0]
  74. d1["b"] = v1[1]
  75. d2["c"] = v2[0]
  76. d2["d"] = v2[1]
  77. assert {i: d1[i].get() for i in d1} == {"a": 0, "b": 1}
  78. assert {i: d2[i].get() for i in d2} == {"c": 2, "d": 3}
  79. def test_stl_bind_global():
  80. import pybind11_cross_module_tests as cm
  81. with pytest.raises(RuntimeError) as excinfo:
  82. cm.register_nonlocal_map()
  83. assert (
  84. str(excinfo.value) == 'generic_type: type "NonLocalMap" is already registered!'
  85. )
  86. with pytest.raises(RuntimeError) as excinfo:
  87. cm.register_nonlocal_vec()
  88. assert (
  89. str(excinfo.value) == 'generic_type: type "NonLocalVec" is already registered!'
  90. )
  91. with pytest.raises(RuntimeError) as excinfo:
  92. cm.register_nonlocal_map2()
  93. assert (
  94. str(excinfo.value) == 'generic_type: type "NonLocalMap2" is already registered!'
  95. )
  96. def test_mixed_local_global():
  97. """Local types take precedence over globally registered types: a module with a `module_local`
  98. type can be registered even if the type is already registered globally. With the module,
  99. casting will go to the local type; outside the module casting goes to the global type."""
  100. import pybind11_cross_module_tests as cm
  101. m.register_mixed_global()
  102. m.register_mixed_local()
  103. a = []
  104. a.append(m.MixedGlobalLocal(1))
  105. a.append(m.MixedLocalGlobal(2))
  106. a.append(m.get_mixed_gl(3))
  107. a.append(m.get_mixed_lg(4))
  108. assert [x.get() for x in a] == [101, 1002, 103, 1004]
  109. cm.register_mixed_global_local()
  110. cm.register_mixed_local_global()
  111. a.append(m.MixedGlobalLocal(5))
  112. a.append(m.MixedLocalGlobal(6))
  113. a.append(cm.MixedGlobalLocal(7))
  114. a.append(cm.MixedLocalGlobal(8))
  115. a.append(m.get_mixed_gl(9))
  116. a.append(m.get_mixed_lg(10))
  117. a.append(cm.get_mixed_gl(11))
  118. a.append(cm.get_mixed_lg(12))
  119. assert [x.get() for x in a] == [
  120. 101,
  121. 1002,
  122. 103,
  123. 1004,
  124. 105,
  125. 1006,
  126. 207,
  127. 2008,
  128. 109,
  129. 1010,
  130. 211,
  131. 2012,
  132. ]
  133. def test_internal_locals_differ():
  134. """Makes sure the internal local type map differs across the two modules"""
  135. import pybind11_cross_module_tests as cm
  136. assert m.local_cpp_types_addr() != cm.local_cpp_types_addr()
  137. @pytest.mark.xfail("env.PYPY and sys.pypy_version_info < (7, 3, 2)")
  138. def test_stl_caster_vs_stl_bind(msg):
  139. """One module uses a generic vector caster from `<pybind11/stl.h>` while the other
  140. exports `std::vector<int>` via `py:bind_vector` and `py::module_local`"""
  141. import pybind11_cross_module_tests as cm
  142. v1 = cm.VectorInt([1, 2, 3])
  143. assert m.load_vector_via_caster(v1) == 6
  144. assert cm.load_vector_via_binding(v1) == 6
  145. v2 = [1, 2, 3]
  146. assert m.load_vector_via_caster(v2) == 6
  147. with pytest.raises(TypeError) as excinfo:
  148. cm.load_vector_via_binding(v2)
  149. assert (
  150. msg(excinfo.value)
  151. == """
  152. load_vector_via_binding(): incompatible function arguments. The following argument types are supported:
  153. 1. (arg0: pybind11_cross_module_tests.VectorInt) -> int
  154. Invoked with: [1, 2, 3]
  155. """ # noqa: E501 line too long
  156. )
  157. def test_cross_module_calls():
  158. import pybind11_cross_module_tests as cm
  159. v1 = m.LocalVec()
  160. v1.append(m.LocalType(1))
  161. v2 = cm.LocalVec()
  162. v2.append(cm.LocalType(2))
  163. # Returning the self pointer should get picked up as returning an existing
  164. # instance (even when that instance is of a foreign, non-local type).
  165. assert m.return_self(v1) is v1
  166. assert cm.return_self(v2) is v2
  167. assert m.return_self(v2) is v2
  168. assert cm.return_self(v1) is v1
  169. assert m.LocalVec is not cm.LocalVec
  170. # Returning a copy, on the other hand, always goes to the local type,
  171. # regardless of where the source type came from.
  172. assert type(m.return_copy(v1)) is m.LocalVec
  173. assert type(m.return_copy(v2)) is m.LocalVec
  174. assert type(cm.return_copy(v1)) is cm.LocalVec
  175. assert type(cm.return_copy(v2)) is cm.LocalVec
  176. # Test the example given in the documentation (which also tests inheritance casting):
  177. mycat = m.Cat("Fluffy")
  178. mydog = cm.Dog("Rover")
  179. assert mycat.get_name() == "Fluffy"
  180. assert mydog.name() == "Rover"
  181. assert m.Cat.__base__.__name__ == "Pet"
  182. assert cm.Dog.__base__.__name__ == "Pet"
  183. assert m.Cat.__base__ is not cm.Dog.__base__
  184. assert m.pet_name(mycat) == "Fluffy"
  185. assert m.pet_name(mydog) == "Rover"
  186. assert cm.pet_name(mycat) == "Fluffy"
  187. assert cm.pet_name(mydog) == "Rover"
  188. assert m.MixGL is not cm.MixGL
  189. a = m.MixGL(1)
  190. b = cm.MixGL(2)
  191. assert m.get_gl_value(a) == 11
  192. assert m.get_gl_value(b) == 12
  193. assert cm.get_gl_value(a) == 101
  194. assert cm.get_gl_value(b) == 102
  195. c, d = m.MixGL2(3), cm.MixGL2(4)
  196. with pytest.raises(TypeError) as excinfo:
  197. m.get_gl_value(c)
  198. assert "incompatible function arguments" in str(excinfo.value)
  199. with pytest.raises(TypeError) as excinfo:
  200. m.get_gl_value(d)
  201. assert "incompatible function arguments" in str(excinfo.value)