test_opaque_types.py revision 12037:d28054ac6ec9
1import pytest
2
3
4def test_string_list():
5    from pybind11_tests import StringList, ClassWithSTLVecProperty, print_opaque_list
6
7    l = StringList()
8    l.push_back("Element 1")
9    l.push_back("Element 2")
10    assert print_opaque_list(l) == "Opaque list: [Element 1, Element 2]"
11    assert l.back() == "Element 2"
12
13    for i, k in enumerate(l, start=1):
14        assert k == "Element {}".format(i)
15    l.pop_back()
16    assert print_opaque_list(l) == "Opaque list: [Element 1]"
17
18    cvp = ClassWithSTLVecProperty()
19    assert print_opaque_list(cvp.stringList) == "Opaque list: []"
20
21    cvp.stringList = l
22    cvp.stringList.push_back("Element 3")
23    assert print_opaque_list(cvp.stringList) == "Opaque list: [Element 1, Element 3]"
24
25
26def test_pointers(msg):
27    from pybind11_tests import (return_void_ptr, get_void_ptr_value, ExampleMandA,
28                                print_opaque_list, return_null_str, get_null_str_value,
29                                return_unique_ptr, ConstructorStats)
30
31    living_before = ConstructorStats.get(ExampleMandA).alive()
32    assert get_void_ptr_value(return_void_ptr()) == 0x1234
33    assert get_void_ptr_value(ExampleMandA())  # Should also work for other C++ types
34    assert ConstructorStats.get(ExampleMandA).alive() == living_before
35
36    with pytest.raises(TypeError) as excinfo:
37        get_void_ptr_value([1, 2, 3])  # This should not work
38    assert msg(excinfo.value) == """
39        get_void_ptr_value(): incompatible function arguments. The following argument types are supported:
40            1. (arg0: capsule) -> int
41
42        Invoked with: [1, 2, 3]
43    """  # noqa: E501 line too long
44
45    assert return_null_str() is None
46    assert get_null_str_value(return_null_str()) is not None
47
48    ptr = return_unique_ptr()
49    assert "StringList" in repr(ptr)
50    assert print_opaque_list(ptr) == "Opaque list: [some value]"
51