mirror of
https://github.com/pybind/pybind11.git
synced 2026-03-14 20:27:47 +00:00
type_caster_generic: add set_foreign_holder method for subclasses to implement (#5862)
* type_caster_generic: add set_foreign_holder method for subclasses to implement * style: pre-commit fixes * Rename try_shared_from_this -> set_via_shared_from_this to avoid confusion against try_get_shared_from_this * Add comment explaining the limits of the test * CI * style: pre-commit fixes * Fixes from code review * style: pre-commit fixes --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
@@ -1,5 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from contextlib import suppress
|
||||
|
||||
import pytest
|
||||
|
||||
from pybind11_tests import local_bindings as m
|
||||
@@ -11,6 +14,7 @@ def test_load_external():
|
||||
|
||||
assert m.load_external1(cm.ExternalType1(11)) == 11
|
||||
assert m.load_external2(cm.ExternalType2(22)) == 22
|
||||
assert m.load_external3(cm.ExternalType3(33)) == 33
|
||||
|
||||
with pytest.raises(TypeError) as excinfo:
|
||||
assert m.load_external2(cm.ExternalType1(21)) == 21
|
||||
@@ -20,6 +24,36 @@ def test_load_external():
|
||||
assert m.load_external1(cm.ExternalType2(12)) == 12
|
||||
assert "incompatible function arguments" in str(excinfo.value)
|
||||
|
||||
def test_shared(val, ctor, loader):
|
||||
obj = ctor(val)
|
||||
with suppress(AttributeError): # non-cpython VMs don't have getrefcount
|
||||
rc_before = sys.getrefcount(obj)
|
||||
wrapper = loader(obj)
|
||||
# wrapper holds a shared_ptr that keeps obj alive
|
||||
assert wrapper.use_count == 1
|
||||
assert wrapper.value == val
|
||||
with suppress(AttributeError):
|
||||
rc_after = sys.getrefcount(obj)
|
||||
assert rc_after > rc_before
|
||||
|
||||
test_shared(220, cm.ExternalType2, m.load_external2_shared)
|
||||
test_shared(330, cm.ExternalType3, m.load_external3_shared)
|
||||
|
||||
with pytest.raises(TypeError, match="incompatible function arguments"):
|
||||
test_shared(320, cm.ExternalType2, m.load_external3_shared)
|
||||
with pytest.raises(TypeError, match="incompatible function arguments"):
|
||||
test_shared(230, cm.ExternalType3, m.load_external2_shared)
|
||||
|
||||
with pytest.raises(
|
||||
RuntimeError, match="Foreign instance cannot be converted to std::unique_ptr"
|
||||
):
|
||||
m.load_external1_unique(cm.ExternalType1(2200))
|
||||
|
||||
with pytest.raises(
|
||||
RuntimeError, match="Foreign instance cannot be converted to std::unique_ptr"
|
||||
):
|
||||
m.load_external3_unique(cm.ExternalType3(3300))
|
||||
|
||||
|
||||
def test_local_bindings():
|
||||
"""Tests that duplicate `py::module_local` class bindings work across modules"""
|
||||
|
||||
Reference in New Issue
Block a user