μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
test_pickling.py
Go to the documentation of this file.
1# -*- coding: utf-8 -*-
2import pytest
3
4import env
5from pybind11_tests import pickling as m
6
7try:
8 import cPickle as pickle # Use cPickle on Python 2.7
9except ImportError:
10 import pickle
11
12
13@pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"])
14def test_roundtrip(cls_name):
15 cls = getattr(m, cls_name)
16 p = cls("test_value")
17 p.setExtra1(15)
18 p.setExtra2(48)
19
20 data = pickle.dumps(p, 2) # Must use pickle protocol >= 2
21 p2 = pickle.loads(data)
22 assert p2.value() == p.value()
23 assert p2.extra1() == p.extra1()
24 assert p2.extra2() == p.extra2()
25
26
27@pytest.mark.xfail("env.PYPY")
28@pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"])
30 cls = getattr(m, cls_name)
31 p = cls("test_value")
32 p.extra = 15
33 p.dynamic = "Attribute"
34
35 data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)
36 p2 = pickle.loads(data)
37 assert p2.value == p.value
38 assert p2.extra == p.extra
39 assert p2.dynamic == p.dynamic
40
41
43 from pybind11_tests import enums as e
44
45 data = pickle.dumps(e.EOne, 2)
46 assert e.EOne == pickle.loads(data)
47
48
49#
50# exercise_trampoline
51#
52class SimplePyDerived(m.SimpleBase):
53 pass
54
55
57 p = SimplePyDerived()
58 p.num = 202
59 p.stored_in_dict = 303
60 data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)
61 p2 = pickle.loads(data)
62 assert isinstance(p2, SimplePyDerived)
63 assert p2.num == 202
64 assert p2.stored_in_dict == 303
65
66
68 p = m.make_SimpleCppDerivedAsBase()
69 assert m.check_dynamic_cast_SimpleCppDerived(p)
70 p.num = 404
71 if not env.PYPY:
72 # To ensure that this unit test is not accidentally invalidated.
73 with pytest.raises(AttributeError):
74 # Mimics the `setstate` C++ implementation.
75 setattr(p, "__dict__", {}) # noqa: B010
76 data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)
77 p2 = pickle.loads(data)
78 assert isinstance(p2, m.SimpleBase)
79 assert p2.num == 404
80 # Issue #3062: pickleable base C++ classes can incur object slicing
81 # if derived typeid is not registered with pybind11
82 assert not m.check_dynamic_cast_SimpleCppDerived(p2)
object getattr(handle obj, handle name)
Definition: pytypes.h:537
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:569
bool isinstance(handle obj)
\rst Return true if obj is an instance of T.
Definition: pytypes.h:489
def test_roundtrip_simple_cpp_derived()
def test_roundtrip_with_dict(cls_name)
def test_roundtrip(cls_name)
def test_roundtrip_simple_py_derived()
def test_enum_pickle()