test_pickling.py revision 11986
111986Sandreas.sandberg@arm.comtry:
211986Sandreas.sandberg@arm.com    import cPickle as pickle  # Use cPickle on Python 2.7
311986Sandreas.sandberg@arm.comexcept ImportError:
411986Sandreas.sandberg@arm.com    import pickle
511986Sandreas.sandberg@arm.com
611986Sandreas.sandberg@arm.com
711986Sandreas.sandberg@arm.comdef test_roundtrip():
811986Sandreas.sandberg@arm.com    from pybind11_tests import Pickleable
911986Sandreas.sandberg@arm.com
1011986Sandreas.sandberg@arm.com    p = Pickleable("test_value")
1111986Sandreas.sandberg@arm.com    p.setExtra1(15)
1211986Sandreas.sandberg@arm.com    p.setExtra2(48)
1311986Sandreas.sandberg@arm.com
1411986Sandreas.sandberg@arm.com    data = pickle.dumps(p, 2)  # Must use pickle protocol >= 2
1511986Sandreas.sandberg@arm.com    p2 = pickle.loads(data)
1611986Sandreas.sandberg@arm.com    assert p2.value() == p.value()
1711986Sandreas.sandberg@arm.com    assert p2.extra1() == p.extra1()
1811986Sandreas.sandberg@arm.com    assert p2.extra2() == p.extra2()
1911986Sandreas.sandberg@arm.com
2011986Sandreas.sandberg@arm.com
2111986Sandreas.sandberg@arm.comdef test_roundtrip_with_dict():
2211986Sandreas.sandberg@arm.com    from pybind11_tests import PickleableWithDict
2311986Sandreas.sandberg@arm.com
2411986Sandreas.sandberg@arm.com    p = PickleableWithDict("test_value")
2511986Sandreas.sandberg@arm.com    p.extra = 15
2611986Sandreas.sandberg@arm.com    p.dynamic = "Attribute"
2711986Sandreas.sandberg@arm.com
2811986Sandreas.sandberg@arm.com    data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)
2911986Sandreas.sandberg@arm.com    p2 = pickle.loads(data)
3011986Sandreas.sandberg@arm.com    assert p2.value == p.value
3111986Sandreas.sandberg@arm.com    assert p2.extra == p.extra
3211986Sandreas.sandberg@arm.com    assert p2.dynamic == p.dynamic
33