test_pickle.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import pickle
  2. from django.db import DJANGO_VERSION_PICKLE_KEY, models
  3. from django.test import SimpleTestCase
  4. from django.utils.version import get_version
  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 = "Pickled model instance's Django version 1.0 does not match the current version %s." % get_version()
  36. with self.assertRaisesMessage(RuntimeWarning, msg):
  37. pickle.loads(pickle.dumps(p))
  38. def test_with_getstate(self):
  39. """
  40. A model may override __getstate__() to choose the attributes to pickle.
  41. """
  42. class PickledModel(models.Model):
  43. def __getstate__(self):
  44. state = super().__getstate__().copy()
  45. del state['dont_pickle']
  46. return state
  47. m = PickledModel()
  48. m.dont_pickle = 1
  49. dumped = pickle.dumps(m)
  50. self.assertEqual(m.dont_pickle, 1)
  51. reloaded = pickle.loads(dumped)
  52. self.assertFalse(hasattr(reloaded, 'dont_pickle'))