Dean Moldovan | a0c1ccf | 2016-08-12 13:50:00 +0200 | [diff] [blame] | 1 | try: |
| 2 | import cPickle as pickle # Use cPickle on Python 2.7 |
| 3 | except ImportError: |
| 4 | import pickle |
| 5 | |
Dean Moldovan | a0c1ccf | 2016-08-12 13:50:00 +0200 | [diff] [blame] | 6 | |
| 7 | def test_roundtrip(): |
Dean Moldovan | 6fccf69 | 2016-10-11 01:12:48 +0200 | [diff] [blame] | 8 | from pybind11_tests import Pickleable |
| 9 | |
Dean Moldovan | a0c1ccf | 2016-08-12 13:50:00 +0200 | [diff] [blame] | 10 | p = Pickleable("test_value") |
| 11 | p.setExtra1(15) |
| 12 | p.setExtra2(48) |
| 13 | |
| 14 | data = pickle.dumps(p, 2) # Must use pickle protocol >= 2 |
| 15 | p2 = pickle.loads(data) |
| 16 | assert p2.value() == p.value() |
| 17 | assert p2.extra1() == p.extra1() |
| 18 | assert p2.extra2() == p.extra2() |
Dean Moldovan | 6fccf69 | 2016-10-11 01:12:48 +0200 | [diff] [blame] | 19 | |
| 20 | |
| 21 | def test_roundtrip_with_dict(): |
| 22 | from pybind11_tests import PickleableWithDict |
| 23 | |
| 24 | p = PickleableWithDict("test_value") |
| 25 | p.extra = 15 |
| 26 | p.dynamic = "Attribute" |
| 27 | |
| 28 | data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL) |
| 29 | p2 = pickle.loads(data) |
| 30 | assert p2.value == p.value |
| 31 | assert p2.extra == p.extra |
| 32 | assert p2.dynamic == p.dynamic |