test_pickling.py revision 14299
1import pytest
2from pybind11_tests import pickling as m
3
4try:
5    import cPickle as pickle  # Use cPickle on Python 2.7
6except ImportError:
7    import pickle
8
9
10@pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"])
11def test_roundtrip(cls_name):
12    cls = getattr(m, cls_name)
13    p = cls("test_value")
14    p.setExtra1(15)
15    p.setExtra2(48)
16
17    data = pickle.dumps(p, 2)  # Must use pickle protocol >= 2
18    p2 = pickle.loads(data)
19    assert p2.value() == p.value()
20    assert p2.extra1() == p.extra1()
21    assert p2.extra2() == p.extra2()
22
23
24@pytest.unsupported_on_pypy
25@pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"])
26def test_roundtrip_with_dict(cls_name):
27    cls = getattr(m, cls_name)
28    p = cls("test_value")
29    p.extra = 15
30    p.dynamic = "Attribute"
31
32    data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)
33    p2 = pickle.loads(data)
34    assert p2.value == p.value
35    assert p2.extra == p.extra
36    assert p2.dynamic == p.dynamic
37
38
39def test_enum_pickle():
40    from pybind11_tests import enums as e
41    data = pickle.dumps(e.EOne, 2)
42    assert e.EOne == pickle.loads(data)
43