1
0
mirror of https://github.com/django/django.git synced 2024-11-18 07:26:04 +00:00
django/tests/model_regress/test_pickle.py
Claude Paroz 108b8bf852 Fixed #24007 -- Ensure apps registry's ready before unpickling models
This prevents AppRegistryNotReady errors when unpickling Django
models from an external script.
2014-12-17 18:33:32 +01:00

89 lines
3.2 KiB
Python

import datetime
import pickle
import subprocess
import tempfile
import warnings
from django.db import models, DJANGO_VERSION_PICKLE_KEY
from django.test import TestCase
from django.utils.encoding import force_text
from django.utils.version import get_major_version, get_version
from .models import Article
class ModelPickleTestCase(TestCase):
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):
reduce_list = super(MissingDjangoVersion, self).__reduce__()
data = reduce_list[-1]
del data[DJANGO_VERSION_PICKLE_KEY]
return reduce_list
p = MissingDjangoVersion(title="FooBar")
with warnings.catch_warnings(record=True) as recorded:
pickle.loads(pickle.dumps(p))
msg = force_text(recorded.pop().message)
self.assertEqual(msg,
"Pickled model instance's Django version is not specified.")
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):
reduce_list = super(DifferentDjangoVersion, self).__reduce__()
data = reduce_list[-1]
data[DJANGO_VERSION_PICKLE_KEY] = str(float(get_major_version()) - 0.1)
return reduce_list
p = DifferentDjangoVersion(title="FooBar")
with warnings.catch_warnings(record=True) as recorded:
pickle.loads(pickle.dumps(p))
msg = force_text(recorded.pop().message)
self.assertEqual(msg,
"Pickled model instance's Django version %s does not "
"match the current version %s."
% (str(float(get_major_version()) - 0.1), get_version()))
def test_unpickling_when_appregistrynotready(self):
"""
#24007 -- Verifies that a pickled model can be unpickled without having
to manually setup the apps registry beforehand.
"""
script_template = """#!/usr/bin/env python
import pickle
from django.conf import settings
data = %r
settings.configure(DEBUG=False, INSTALLED_APPS=('model_regress',), SECRET_KEY = "blah")
article = pickle.loads(data)
print(article.headline)"""
a = Article.objects.create(
headline="Some object",
pub_date=datetime.datetime.now(),
article_text="This is an article",
)
with tempfile.NamedTemporaryFile(mode='w+', suffix=".py", dir='.', delete=True) as script:
script.write(script_template % pickle.dumps(a))
script.flush()
try:
result = subprocess.check_output(['python', script.name])
except subprocess.CalledProcessError:
self.fail("Unable to reload model pickled data")
self.assertEqual(result.strip().decode(), "Some object")