test_pickling.py 993 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import pytest
  2. from pybind11_tests import pickling as m
  3. try:
  4. import cPickle as pickle # Use cPickle on Python 2.7
  5. except ImportError:
  6. import pickle
  7. @pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"])
  8. def test_roundtrip(cls_name):
  9. cls = getattr(m, cls_name)
  10. p = cls("test_value")
  11. p.setExtra1(15)
  12. p.setExtra2(48)
  13. data = pickle.dumps(p, 2) # Must use pickle protocol >= 2
  14. p2 = pickle.loads(data)
  15. assert p2.value() == p.value()
  16. assert p2.extra1() == p.extra1()
  17. assert p2.extra2() == p.extra2()
  18. @pytest.unsupported_on_pypy
  19. @pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"])
  20. def test_roundtrip_with_dict(cls_name):
  21. cls = getattr(m, cls_name)
  22. p = cls("test_value")
  23. p.extra = 15
  24. p.dynamic = "Attribute"
  25. data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)
  26. p2 = pickle.loads(data)
  27. assert p2.value == p.value
  28. assert p2.extra == p.extra
  29. assert p2.dynamic == p.dynamic