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