test_pickling.py 993 Bytes
Newer Older
Wenzel Jakob's avatar
Wenzel Jakob committed
1
import pytest
2
from pybind11_tests import pickling as m
Wenzel Jakob's avatar
Wenzel Jakob committed
3

Dean Moldovan's avatar
Dean Moldovan committed
4
5
6
7
8
9
try:
    import cPickle as pickle  # Use cPickle on Python 2.7
except ImportError:
    import pickle


10
11
12
13
@pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"])
def test_roundtrip(cls_name):
    cls = getattr(m, cls_name)
    p = cls("test_value")
Dean Moldovan's avatar
Dean Moldovan committed
14
15
16
17
18
19
20
21
    p.setExtra1(15)
    p.setExtra2(48)

    data = pickle.dumps(p, 2)  # Must use pickle protocol >= 2
    p2 = pickle.loads(data)
    assert p2.value() == p.value()
    assert p2.extra1() == p.extra1()
    assert p2.extra2() == p.extra2()
Dean Moldovan's avatar
Dean Moldovan committed
22
23


Wenzel Jakob's avatar
Wenzel Jakob committed
24
@pytest.unsupported_on_pypy
25
26
27
28
@pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"])
def test_roundtrip_with_dict(cls_name):
    cls = getattr(m, cls_name)
    p = cls("test_value")
Dean Moldovan's avatar
Dean Moldovan committed
29
30
31
32
33
34
35
36
    p.extra = 15
    p.dynamic = "Attribute"

    data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)
    p2 = pickle.loads(data)
    assert p2.value == p.value
    assert p2.extra == p.extra
    assert p2.dynamic == p.dynamic