blob: 3ec3eb76b03cd209a288359b21ac6ce958326a20 [file] [log] [blame]
Dean Moldovan6fccf692016-10-11 01:12:48 +02001import pytest
Dean Moldovana0c1ccf2016-08-12 13:50:00 +02002from pybind11_tests import ExampleMandA, ConstructorStats
3
4
5def test_methods_and_attributes():
6 instance1 = ExampleMandA()
7 instance2 = ExampleMandA(32)
8
9 instance1.add1(instance2)
10 instance1.add2(instance2)
11 instance1.add3(instance2)
12 instance1.add4(instance2)
13 instance1.add5(instance2)
14 instance1.add6(32)
15 instance1.add7(32)
16 instance1.add8(32)
17 instance1.add9(32)
18 instance1.add10(32)
19
20 assert str(instance1) == "ExampleMandA[value=320]"
21 assert str(instance2) == "ExampleMandA[value=32]"
22 assert str(instance1.self1()) == "ExampleMandA[value=320]"
23 assert str(instance1.self2()) == "ExampleMandA[value=320]"
24 assert str(instance1.self3()) == "ExampleMandA[value=320]"
25 assert str(instance1.self4()) == "ExampleMandA[value=320]"
26 assert str(instance1.self5()) == "ExampleMandA[value=320]"
27
28 assert instance1.internal1() == 320
29 assert instance1.internal2() == 320
30 assert instance1.internal3() == 320
31 assert instance1.internal4() == 320
32 assert instance1.internal5() == 320
33
Dean Moldovan4e959c92016-12-08 11:07:52 +010034 assert instance1.overloaded(1, 1.0) == "(int, float)"
35 assert instance1.overloaded(2.0, 2) == "(float, int)"
Jason Rhinelandere5505892017-02-03 18:25:34 -050036 assert instance1.overloaded(3, 3) == "(int, int)"
37 assert instance1.overloaded(4., 4.) == "(float, float)"
38 assert instance1.overloaded_const(5, 5.0) == "(int, float) const"
39 assert instance1.overloaded_const(6.0, 6) == "(float, int) const"
40 assert instance1.overloaded_const(7, 7) == "(int, int) const"
41 assert instance1.overloaded_const(8., 8.) == "(float, float) const"
42 assert instance1.overloaded_float(1, 1) == "(float, float)"
43 assert instance1.overloaded_float(1, 1.) == "(float, float)"
44 assert instance1.overloaded_float(1., 1) == "(float, float)"
45 assert instance1.overloaded_float(1., 1.) == "(float, float)"
Dean Moldovan4e959c92016-12-08 11:07:52 +010046
Dean Moldovana0c1ccf2016-08-12 13:50:00 +020047 assert instance1.value == 320
48 instance1.value = 100
49 assert str(instance1) == "ExampleMandA[value=100]"
50
51 cstats = ConstructorStats.get(ExampleMandA)
52 assert cstats.alive() == 2
53 del instance1, instance2
54 assert cstats.alive() == 0
55 assert cstats.values() == ["32"]
56 assert cstats.default_constructions == 1
57 assert cstats.copy_constructions == 3
58 assert cstats.move_constructions >= 1
59 assert cstats.copy_assignments == 0
60 assert cstats.move_assignments == 0
Dean Moldovan6fccf692016-10-11 01:12:48 +020061
62
Dean Moldovan5b7e1902016-10-21 18:51:14 +020063def test_properties():
64 from pybind11_tests import TestProperties
65
66 instance = TestProperties()
67
68 assert instance.def_readonly == 1
69 with pytest.raises(AttributeError):
70 instance.def_readonly = 2
71
72 instance.def_readwrite = 2
73 assert instance.def_readwrite == 2
74
75 assert instance.def_property_readonly == 2
76 with pytest.raises(AttributeError):
77 instance.def_property_readonly = 3
78
79 instance.def_property = 3
80 assert instance.def_property == 3
81
82
Jason Rhinelander0a90b2d2017-04-16 20:30:52 -040083def test_copy_method():
84 """Issue #443: calling copied methods fails in Python 3"""
85 from pybind11_tests import ExampleMandA
86
87 ExampleMandA.add2c = ExampleMandA.add2
88 ExampleMandA.add2d = ExampleMandA.add2b
89 a = ExampleMandA(123)
90 assert a.value == 123
91 a.add2(ExampleMandA(-100))
92 assert a.value == 23
93 a.add2b(ExampleMandA(20))
94 assert a.value == 43
95 a.add2c(ExampleMandA(6))
96 assert a.value == 49
97 a.add2d(ExampleMandA(-7))
98 assert a.value == 42
99
100
Dean Moldovan5b7e1902016-10-21 18:51:14 +0200101def test_static_properties():
102 from pybind11_tests import TestProperties as Type
103
104 assert Type.def_readonly_static == 1
Dean Moldovanc91f8bd2017-02-13 18:11:24 +0100105 with pytest.raises(AttributeError) as excinfo:
Dean Moldovan5b7e1902016-10-21 18:51:14 +0200106 Type.def_readonly_static = 2
Dean Moldovanc91f8bd2017-02-13 18:11:24 +0100107 assert "can't set attribute" in str(excinfo)
Dean Moldovan5b7e1902016-10-21 18:51:14 +0200108
109 Type.def_readwrite_static = 2
110 assert Type.def_readwrite_static == 2
111
112 assert Type.def_property_readonly_static == 2
Dean Moldovanc91f8bd2017-02-13 18:11:24 +0100113 with pytest.raises(AttributeError) as excinfo:
Dean Moldovan5b7e1902016-10-21 18:51:14 +0200114 Type.def_property_readonly_static = 3
Dean Moldovanc91f8bd2017-02-13 18:11:24 +0100115 assert "can't set attribute" in str(excinfo)
Dean Moldovan5b7e1902016-10-21 18:51:14 +0200116
117 Type.def_property_static = 3
118 assert Type.def_property_static == 3
119
Dean Moldovanc91f8bd2017-02-13 18:11:24 +0100120 # Static property read and write via instance
121 instance = Type()
122
123 Type.def_readwrite_static = 0
124 assert Type.def_readwrite_static == 0
125 assert instance.def_readwrite_static == 0
126
127 instance.def_readwrite_static = 2
128 assert Type.def_readwrite_static == 2
129 assert instance.def_readwrite_static == 2
130
Dean Moldovane0e2ea32017-04-06 23:45:12 +0200131 # It should be possible to override properties in derived classes
132 from pybind11_tests import TestPropertiesOverride as TypeOverride
133
134 assert TypeOverride().def_readonly == 99
135 assert TypeOverride.def_readonly_static == 99
136
Dean Moldovanc91f8bd2017-02-13 18:11:24 +0100137
138def test_static_cls():
139 """Static property getter and setters expect the type object as the their only argument"""
140 from pybind11_tests import TestProperties as Type
141
142 instance = Type()
143 assert Type.static_cls is Type
144 assert instance.static_cls is Type
145
146 def check_self(self):
147 assert self is Type
148
149 Type.static_cls = check_self
150 instance.static_cls = check_self
151
Dean Moldovan5b7e1902016-10-21 18:51:14 +0200152
Dean Moldovandd016652017-02-16 23:02:56 +0100153def test_metaclass_override():
154 """Overriding pybind11's default metaclass changes the behavior of `static_property`"""
155 from pybind11_tests import MetaclassOverride
156
157 assert type(ExampleMandA).__name__ == "pybind11_type"
158 assert type(MetaclassOverride).__name__ == "type"
159
160 assert MetaclassOverride.readonly == 1
161 assert type(MetaclassOverride.__dict__["readonly"]).__name__ == "pybind11_static_property"
162
163 # Regular `type` replaces the property instead of calling `__set__()`
164 MetaclassOverride.readonly = 2
165 assert MetaclassOverride.readonly == 2
166 assert isinstance(MetaclassOverride.__dict__["readonly"], int)
167
168
Jason Rhinelanderd355f2f2017-04-16 22:31:13 -0400169def test_no_mixed_overloads():
170 from pybind11_tests import debug_enabled
171
172 with pytest.raises(RuntimeError) as excinfo:
173 ExampleMandA.add_mixed_overloads1()
174 assert (str(excinfo.value) ==
175 "overloading a method with both static and instance methods is not supported; " +
176 ("compile in debug mode for more details" if not debug_enabled else
177 "error while attempting to bind static method ExampleMandA.overload_mixed1"
178 "() -> str")
179 )
180
181 with pytest.raises(RuntimeError) as excinfo:
182 ExampleMandA.add_mixed_overloads2()
183 assert (str(excinfo.value) ==
184 "overloading a method with both static and instance methods is not supported; " +
185 ("compile in debug mode for more details" if not debug_enabled else
186 "error while attempting to bind instance method ExampleMandA.overload_mixed2"
187 "(self: pybind11_tests.ExampleMandA, arg0: int, arg1: int) -> str")
188 )
189
190
Dean Moldovan03f627e2016-11-01 11:44:57 +0100191@pytest.mark.parametrize("access", ["ro", "rw", "static_ro", "static_rw"])
192def test_property_return_value_policies(access):
193 from pybind11_tests import TestPropRVP
194
195 if not access.startswith("static"):
196 obj = TestPropRVP()
197 else:
198 obj = TestPropRVP
199
200 ref = getattr(obj, access + "_ref")
201 assert ref.value == 1
202 ref.value = 2
203 assert getattr(obj, access + "_ref").value == 2
204 ref.value = 1 # restore original value for static properties
205
206 copy = getattr(obj, access + "_copy")
207 assert copy.value == 1
208 copy.value = 2
209 assert getattr(obj, access + "_copy").value == 1
210
211 copy = getattr(obj, access + "_func")
212 assert copy.value == 1
213 copy.value = 2
214 assert getattr(obj, access + "_func").value == 1
215
216
217def test_property_rvalue_policy():
218 """When returning an rvalue, the return value policy is automatically changed from
Dean Moldovanbad17402016-11-20 21:21:54 +0100219 `reference(_internal)` to `move`. The following would not work otherwise.
220 """
Dean Moldovan03f627e2016-11-01 11:44:57 +0100221 from pybind11_tests import TestPropRVP
222
223 instance = TestPropRVP()
224 o = instance.rvalue
225 assert o.value == 1
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100226
227
228def test_property_rvalue_policy_static():
229 """When returning an rvalue, the return value policy is automatically changed from
230 `reference(_internal)` to `move`. The following would not work otherwise.
231 """
232 from pybind11_tests import TestPropRVP
Dean Moldovan03f627e2016-11-01 11:44:57 +0100233 o = TestPropRVP.static_rvalue
234 assert o.value == 1
235
236
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100237# https://bitbucket.org/pypy/pypy/issues/2447
238@pytest.unsupported_on_pypy
Dean Moldovan6fccf692016-10-11 01:12:48 +0200239def test_dynamic_attributes():
Dean Moldovanb8cb5ca2016-10-14 18:01:17 +0200240 from pybind11_tests import DynamicClass, CppDerivedDynamicClass
Dean Moldovan6fccf692016-10-11 01:12:48 +0200241
242 instance = DynamicClass()
243 assert not hasattr(instance, "foo")
244 assert "foo" not in dir(instance)
245
246 # Dynamically add attribute
247 instance.foo = 42
248 assert hasattr(instance, "foo")
249 assert instance.foo == 42
250 assert "foo" in dir(instance)
251
252 # __dict__ should be accessible and replaceable
253 assert "foo" in instance.__dict__
254 instance.__dict__ = {"bar": True}
255 assert not hasattr(instance, "foo")
256 assert hasattr(instance, "bar")
257
258 with pytest.raises(TypeError) as excinfo:
259 instance.__dict__ = []
260 assert str(excinfo.value) == "__dict__ must be set to a dictionary, not a 'list'"
261
262 cstats = ConstructorStats.get(DynamicClass)
263 assert cstats.alive() == 1
264 del instance
265 assert cstats.alive() == 0
266
267 # Derived classes should work as well
Dean Moldovanb8cb5ca2016-10-14 18:01:17 +0200268 class PythonDerivedDynamicClass(DynamicClass):
Dean Moldovan6fccf692016-10-11 01:12:48 +0200269 pass
270
Dean Moldovanb8cb5ca2016-10-14 18:01:17 +0200271 for cls in CppDerivedDynamicClass, PythonDerivedDynamicClass:
272 derived = cls()
273 derived.foobar = 100
274 assert derived.foobar == 100
Dean Moldovan6fccf692016-10-11 01:12:48 +0200275
Dean Moldovanb8cb5ca2016-10-14 18:01:17 +0200276 assert cstats.alive() == 1
277 del derived
278 assert cstats.alive() == 0
Dean Moldovan6fccf692016-10-11 01:12:48 +0200279
280
Wenzel Jakob64cb6992016-12-26 13:12:10 +0100281# https://bitbucket.org/pypy/pypy/issues/2447
282@pytest.unsupported_on_pypy
Dean Moldovan6fccf692016-10-11 01:12:48 +0200283def test_cyclic_gc():
284 from pybind11_tests import DynamicClass
285
286 # One object references itself
287 instance = DynamicClass()
288 instance.circular_reference = instance
289
290 cstats = ConstructorStats.get(DynamicClass)
291 assert cstats.alive() == 1
292 del instance
293 assert cstats.alive() == 0
294
295 # Two object reference each other
296 i1 = DynamicClass()
297 i2 = DynamicClass()
298 i1.cycle = i2
299 i2.cycle = i1
300
301 assert cstats.alive() == 2
302 del i1, i2
303 assert cstats.alive() == 0
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500304
305
306def test_noconvert_args(msg):
307 from pybind11_tests import ArgInspector, arg_inspect_func, floats_only, floats_preferred
308
309 a = ArgInspector()
310 assert msg(a.f("hi")) == """
311 loading ArgInspector1 argument WITH conversion allowed. Argument value = hi
312 """
313 assert msg(a.g("this is a", "this is b")) == """
314 loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a
315 loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b
316 13
317 loading ArgInspector2 argument WITH conversion allowed. Argument value = (default arg inspector 2)
318 """ # noqa: E501 line too long
319 assert msg(a.g("this is a", "this is b", 42)) == """
320 loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a
321 loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b
322 42
323 loading ArgInspector2 argument WITH conversion allowed. Argument value = (default arg inspector 2)
324 """ # noqa: E501 line too long
325 assert msg(a.g("this is a", "this is b", 42, "this is d")) == """
326 loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a
327 loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b
328 42
329 loading ArgInspector2 argument WITH conversion allowed. Argument value = this is d
330 """
331 assert (a.h("arg 1") ==
332 "loading ArgInspector2 argument WITHOUT conversion allowed. Argument value = arg 1")
333 assert msg(arg_inspect_func("A1", "A2")) == """
334 loading ArgInspector2 argument WITH conversion allowed. Argument value = A1
335 loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = A2
336 """
337
338 assert floats_preferred(4) == 2.0
339 assert floats_only(4.0) == 2.0
340 with pytest.raises(TypeError) as excinfo:
341 floats_only(4)
342 assert msg(excinfo.value) == """
343 floats_only(): incompatible function arguments. The following argument types are supported:
344 1. (f: float) -> float
345
346 Invoked with: 4
347 """
Jason Rhinelander1eaacd12017-02-08 02:45:51 -0500348
349
350def test_bad_arg_default(msg):
351 from pybind11_tests import debug_enabled, bad_arg_def_named, bad_arg_def_unnamed
352
353 with pytest.raises(RuntimeError) as excinfo:
354 bad_arg_def_named()
355 assert msg(excinfo.value) == (
356 "arg(): could not convert default argument 'a: NotRegistered' in function 'should_fail' "
357 "into a Python object (type not registered yet?)"
358 if debug_enabled else
359 "arg(): could not convert default argument into a Python object (type not registered "
360 "yet?). Compile in debug mode for more information."
361 )
362
363 with pytest.raises(RuntimeError) as excinfo:
364 bad_arg_def_unnamed()
365 assert msg(excinfo.value) == (
366 "arg(): could not convert default argument 'NotRegistered' in function 'should_fail' "
367 "into a Python object (type not registered yet?)"
368 if debug_enabled else
369 "arg(): could not convert default argument into a Python object (type not registered "
370 "yet?). Compile in debug mode for more information."
371 )
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400372
373
374def test_accepts_none():
375 from pybind11_tests import (NoneTester,
376 no_none1, no_none2, no_none3, no_none4, no_none5,
377 ok_none1, ok_none2, ok_none3, ok_none4, ok_none5)
378
379 a = NoneTester()
380 assert no_none1(a) == 42
381 assert no_none2(a) == 42
382 assert no_none3(a) == 42
383 assert no_none4(a) == 42
384 assert no_none5(a) == 42
385 assert ok_none1(a) == 42
386 assert ok_none2(a) == 42
387 assert ok_none3(a) == 42
388 assert ok_none4(a) == 42
389 assert ok_none5(a) == 42
390
391 with pytest.raises(TypeError) as excinfo:
392 no_none1(None)
393 assert "incompatible function arguments" in str(excinfo.value)
394 with pytest.raises(TypeError) as excinfo:
395 no_none2(None)
396 assert "incompatible function arguments" in str(excinfo.value)
397 with pytest.raises(TypeError) as excinfo:
398 no_none3(None)
399 assert "incompatible function arguments" in str(excinfo.value)
400 with pytest.raises(TypeError) as excinfo:
401 no_none4(None)
402 assert "incompatible function arguments" in str(excinfo.value)
403 with pytest.raises(TypeError) as excinfo:
404 no_none5(None)
405 assert "incompatible function arguments" in str(excinfo.value)
406
407 # The first one still raises because you can't pass None as a lvalue reference arg:
408 with pytest.raises(TypeError) as excinfo:
409 assert ok_none1(None) == -1
410 assert "incompatible function arguments" in str(excinfo.value)
411 # The rest take the argument as pointer or holder, and accept None:
412 assert ok_none2(None) == -1
413 assert ok_none3(None) == -1
414 assert ok_none4(None) == -1
415 assert ok_none5(None) == -1