test_pickle.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import pickle
  2. import django
  3. from django.db import DJANGO_VERSION_PICKLE_KEY, models
  4. from django.test import SimpleTestCase
  5. class ModelPickleTests(SimpleTestCase):
  6. def test_missing_django_version_unpickling(self):
  7. """
  8. #21430 -- Verifies a warning is raised for models that are
  9. unpickled without a Django version
  10. """
  11. class MissingDjangoVersion(models.Model):
  12. title = models.CharField(max_length=10)
  13. def __reduce__(self):
  14. reduce_list = super().__reduce__()
  15. data = reduce_list[-1]
  16. del data[DJANGO_VERSION_PICKLE_KEY]
  17. return reduce_list
  18. p = MissingDjangoVersion(title="FooBar")
  19. msg = "Pickled model instance's Django version is not specified."
  20. with self.assertRaisesMessage(RuntimeWarning, msg):
  21. pickle.loads(pickle.dumps(p))
  22. def test_unsupported_unpickle(self):
  23. """
  24. #21430 -- Verifies a warning is raised for models that are
  25. unpickled with a different Django version than the current
  26. """
  27. class DifferentDjangoVersion(models.Model):
  28. title = models.CharField(max_length=10)
  29. def __reduce__(self):
  30. reduce_list = super().__reduce__()
  31. data = reduce_list[-1]
  32. data[DJANGO_VERSION_PICKLE_KEY] = "1.0"
  33. return reduce_list
  34. p = DifferentDjangoVersion(title="FooBar")
  35. msg = (
  36. "Pickled model instance's Django version 1.0 does not match the "
  37. "current version %s." % django.__version__
  38. )
  39. with self.assertRaisesMessage(RuntimeWarning, msg):
  40. pickle.loads(pickle.dumps(p))
  41. def test_with_getstate(self):
  42. """
  43. A model may override __getstate__() to choose the attributes to pickle.
  44. """
  45. class PickledModel(models.Model):
  46. def __getstate__(self):
  47. state = super().__getstate__().copy()
  48. del state["dont_pickle"]
  49. return state
  50. m = PickledModel()
  51. m.dont_pickle = 1
  52. dumped = pickle.dumps(m)
  53. self.assertEqual(m.dont_pickle, 1)
  54. reloaded = pickle.loads(dumped)
  55. self.assertFalse(hasattr(reloaded, "dont_pickle"))