Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed #34 -- Added a check for mutable PickledObjectField default. #41

Merged
merged 1 commit into from
Nov 25, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ Changes in version 2.0.0
``.save()``, ``.create()``, etc. raise ``IntegrityError`` if `null` is not
``True`` and no default value was specified like built-in fields do
(thanks to Attila-Mihaly Balazs).
* Added a check for mutable default values to ``PickledObjectField``.

Changes in version 1.1.0
========================
Expand Down
28 changes: 28 additions & 0 deletions picklefield/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from zlib import compress, decompress

import django
from django.core import checks
from django.db import models
from django.utils.encoding import force_text

Expand Down Expand Up @@ -115,6 +116,33 @@ def get_default(self):
# If the field doesn't have a default, then we punt to models.Field.
return super(PickledObjectField, self).get_default()

def _check_default(self):
if self.has_default() and isinstance(self.default, (list, dict, set)):
return [
checks.Warning(
"%s default should be a callable instead of a mutable instance so "
"that it's not shared between all field instances." % (
self.__class__.__name__,
),
hint=(
'Use a callable instead, e.g., use `%s` instead of '
'`%r`.' % (
type(self.default).__name__,
self.default,
)
),
obj=self,
id='picklefield.E001',
)
]
else:
return []

def check(self, **kwargs):
errors = super(PickledObjectField, self).check(**kwargs)
errors.extend(self._check_default())
return errors

def to_python(self, value):
"""
B64decode and unpickle the object, optionally decompressing it.
Expand Down
54 changes: 50 additions & 4 deletions tests/tests.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import json
from datetime import date

from django.core import serializers
from django.db import IntegrityError
from django.test import TestCase
from picklefield.fields import dbsafe_encode, wrap_conflictual_object
from django.core import checks, serializers
from django.db import IntegrityError, models
from django.test import SimpleTestCase, TestCase
from django.test.utils import isolate_apps
from picklefield.fields import (
PickledObjectField, dbsafe_encode, wrap_conflictual_object,
)

from .models import (
D1, D2, L1, S1, T1, MinimalTestingModel, TestCopyDataType,
Expand Down Expand Up @@ -177,3 +180,46 @@ def test_no_copy(self):
def test_empty_strings_not_allowed(self):
with self.assertRaises(IntegrityError):
MinimalTestingModel.objects.create()


@isolate_apps('tests')
class PickledObjectFieldCheckTests(SimpleTestCase):
def test_mutable_default_check(self):
class Model(models.Model):
list_field = PickledObjectField(default=[])
dict_field = PickledObjectField(default={})
set_field = PickledObjectField(default=set())

msg = (
"PickledObjectField default should be a callable instead of a mutable instance so "
"that it's not shared between all field instances."
)

self.assertEqual(Model().check(), [
checks.Warning(
msg=msg,
hint='Use a callable instead, e.g., use `list` instead of `[]`.',
obj=Model._meta.get_field('list_field'),
id='picklefield.E001',
),
checks.Warning(
msg=msg,
hint='Use a callable instead, e.g., use `dict` instead of `{}`.',
obj=Model._meta.get_field('dict_field'),
id='picklefield.E001',
),
checks.Warning(
msg=msg,
hint='Use a callable instead, e.g., use `set` instead of `%s`.' % repr(set()),
obj=Model._meta.get_field('set_field'),
id='picklefield.E001',
)
])

def test_non_mutable_default_check(self):
class Model(models.Model):
list_field = PickledObjectField(default=list)
dict_field = PickledObjectField(default=dict)
set_field = PickledObjectField(default=set)

self.assertEqual(Model().check(), [])