github.com/kaydxh/golang@v0.0.131/pkg/gocv/cgo/third_path/pybind11/tests/test_pickling.py (about) 1 import pickle 2 import re 3 4 import pytest 5 6 import env 7 from pybind11_tests import pickling as m 8 9 10 def test_pickle_simple_callable(): 11 assert m.simple_callable() == 20220426 12 if env.PYPY: 13 serialized = pickle.dumps(m.simple_callable) 14 deserialized = pickle.loads(serialized) 15 assert deserialized() == 20220426 16 else: 17 # To document broken behavior: currently it fails universally with 18 # all C Python versions. 19 with pytest.raises(TypeError) as excinfo: 20 pickle.dumps(m.simple_callable) 21 assert re.search("can.*t pickle .*PyCapsule.* object", str(excinfo.value)) 22 23 24 @pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"]) 25 def test_roundtrip(cls_name): 26 cls = getattr(m, cls_name) 27 p = cls("test_value") 28 p.setExtra1(15) 29 p.setExtra2(48) 30 31 data = pickle.dumps(p, 2) # Must use pickle protocol >= 2 32 p2 = pickle.loads(data) 33 assert p2.value() == p.value() 34 assert p2.extra1() == p.extra1() 35 assert p2.extra2() == p.extra2() 36 37 38 @pytest.mark.xfail("env.PYPY") 39 @pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"]) 40 def test_roundtrip_with_dict(cls_name): 41 cls = getattr(m, cls_name) 42 p = cls("test_value") 43 p.extra = 15 44 p.dynamic = "Attribute" 45 46 data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL) 47 p2 = pickle.loads(data) 48 assert p2.value == p.value 49 assert p2.extra == p.extra 50 assert p2.dynamic == p.dynamic 51 52 53 def test_enum_pickle(): 54 from pybind11_tests import enums as e 55 56 data = pickle.dumps(e.EOne, 2) 57 assert e.EOne == pickle.loads(data) 58 59 60 # 61 # exercise_trampoline 62 # 63 class SimplePyDerived(m.SimpleBase): 64 pass 65 66 67 def test_roundtrip_simple_py_derived(): 68 p = SimplePyDerived() 69 p.num = 202 70 p.stored_in_dict = 303 71 data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL) 72 p2 = pickle.loads(data) 73 assert isinstance(p2, SimplePyDerived) 74 assert p2.num == 202 75 assert p2.stored_in_dict == 303 76 77 78 def test_roundtrip_simple_cpp_derived(): 79 p = m.make_SimpleCppDerivedAsBase() 80 assert m.check_dynamic_cast_SimpleCppDerived(p) 81 p.num = 404 82 if not env.PYPY: 83 # To ensure that this unit test is not accidentally invalidated. 84 with pytest.raises(AttributeError): 85 # Mimics the `setstate` C++ implementation. 86 setattr(p, "__dict__", {}) # noqa: B010 87 data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL) 88 p2 = pickle.loads(data) 89 assert isinstance(p2, m.SimpleBase) 90 assert p2.num == 404 91 # Issue #3062: pickleable base C++ classes can incur object slicing 92 # if derived typeid is not registered with pybind11 93 assert not m.check_dynamic_cast_SimpleCppDerived(p2)