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