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