2014-06-06 11:10:20 +00:00
|
|
|
import pickle
|
|
|
|
|
2015-01-28 12:35:27 +00:00
|
|
|
from django.db import DJANGO_VERSION_PICKLE_KEY, models
|
2018-11-26 19:05:02 +00:00
|
|
|
from django.test import SimpleTestCase
|
2015-04-01 23:15:27 +00:00
|
|
|
from django.utils.version import get_version
|
2014-06-06 11:10:20 +00:00
|
|
|
|
|
|
|
|
2018-11-26 19:05:02 +00:00
|
|
|
class ModelPickleTests(SimpleTestCase):
|
2014-06-06 11:10:20 +00:00
|
|
|
def test_missing_django_version_unpickling(self):
|
|
|
|
"""
|
|
|
|
#21430 -- Verifies a warning is raised for models that are
|
|
|
|
unpickled without a Django version
|
|
|
|
"""
|
|
|
|
class MissingDjangoVersion(models.Model):
|
|
|
|
title = models.CharField(max_length=10)
|
|
|
|
|
|
|
|
def __reduce__(self):
|
2017-01-21 13:13:44 +00:00
|
|
|
reduce_list = super().__reduce__()
|
2014-06-06 11:10:20 +00:00
|
|
|
data = reduce_list[-1]
|
|
|
|
del data[DJANGO_VERSION_PICKLE_KEY]
|
|
|
|
return reduce_list
|
|
|
|
|
|
|
|
p = MissingDjangoVersion(title="FooBar")
|
2015-11-13 20:54:05 +00:00
|
|
|
msg = "Pickled model instance's Django version is not specified."
|
|
|
|
with self.assertRaisesMessage(RuntimeWarning, msg):
|
2014-06-06 11:10:20 +00:00
|
|
|
pickle.loads(pickle.dumps(p))
|
|
|
|
|
|
|
|
def test_unsupported_unpickle(self):
|
|
|
|
"""
|
|
|
|
#21430 -- Verifies a warning is raised for models that are
|
|
|
|
unpickled with a different Django version than the current
|
|
|
|
"""
|
|
|
|
class DifferentDjangoVersion(models.Model):
|
|
|
|
title = models.CharField(max_length=10)
|
|
|
|
|
|
|
|
def __reduce__(self):
|
2017-01-21 13:13:44 +00:00
|
|
|
reduce_list = super().__reduce__()
|
2014-06-06 11:10:20 +00:00
|
|
|
data = reduce_list[-1]
|
2015-04-01 23:15:27 +00:00
|
|
|
data[DJANGO_VERSION_PICKLE_KEY] = '1.0'
|
2014-06-06 11:10:20 +00:00
|
|
|
return reduce_list
|
|
|
|
|
|
|
|
p = DifferentDjangoVersion(title="FooBar")
|
2015-11-13 20:54:05 +00:00
|
|
|
msg = "Pickled model instance's Django version 1.0 does not match the current version %s." % get_version()
|
|
|
|
with self.assertRaisesMessage(RuntimeWarning, msg):
|
2014-06-06 11:10:20 +00:00
|
|
|
pickle.loads(pickle.dumps(p))
|
2017-08-11 19:27:25 +00:00
|
|
|
|
|
|
|
def test_with_getstate(self):
|
|
|
|
"""
|
|
|
|
A model may override __getstate__() to choose the attributes to pickle.
|
|
|
|
"""
|
|
|
|
class PickledModel(models.Model):
|
|
|
|
def __getstate__(self):
|
|
|
|
state = super().__getstate__().copy()
|
|
|
|
del state['dont_pickle']
|
|
|
|
return state
|
|
|
|
|
|
|
|
m = PickledModel()
|
|
|
|
m.dont_pickle = 1
|
|
|
|
dumped = pickle.dumps(m)
|
|
|
|
self.assertEqual(m.dont_pickle, 1)
|
|
|
|
reloaded = pickle.loads(dumped)
|
|
|
|
self.assertFalse(hasattr(reloaded, 'dont_pickle'))
|