Commits

Jacco Flenter  committed 2fcb2ad Merge

merge changes

  • Participants
  • Parent commits 9b2f570, c028ed9

Comments (0)

Files changed (5)

File scm_core/__init__.py

-__version__ = (0,1,1)
+__version__ = (0, 1, 1)

File scm_core/fields.py

 
 from django.db.models import CharField
-from random import Random
+
 try:
     import uuid
 except ImportError:
 
 from .utils import generate_password
 
+
 class UUIDVersionError(Exception):
     """Exception for UUIDVersion problems
     """
     """ Codefield for django supports random codes of different lengths
     """
 
-    def __init__(self, verbose_name=None, name=None, auto=True, max_length=6, **kwargs):
+    def __init__(self,
+            verbose_name=None,
+            name=None,
+            auto=True,
+            max_length=6,
+            **kwargs):
+
         if auto:
             kwargs['blank'] = True
             kwargs['editable'] = kwargs.get('editable', False)
         self.auto = auto
 
-        CharField.__init__(self, verbose_name, name, max_length=max_length, **kwargs)
+        CharField.__init__(
+                self,
+                verbose_name,
+                name,
+                max_length=max_length,
+                **kwargs
+            )
 
     def generate_code(self, code_length=6, alternate_hands=False):
         """Generate the actual code. Returns the code
         """
 
         return generate_password(code_length, alternate_hands)
-#        rng = Random()
-#
-#        righthand = '23456QWERTASDFGZXCVBqwertasdfgzxcvb~!@#$%^`'
-#        lefthand = '789YUPHJKNMyuphjknm&*()-=_+[]\\{}|;\':",./<>?'
-#        allchars = righthand + lefthand
-#
-#        code = ""
-#        for i in range(code_length):
-#            if not alternate_hands:
-#                code += rng.choice(allchars)
-#            else:
-#                if i % 2:
-#                    code += rng.choice(lefthand)
-#                else:
-#                    code += rng.choice(righthand)
-#
-#        return code
 
     def pre_save(self, model_instance, add):
 
 
             value = unicode(self.generate_code(code_length=self.max_length))
             setattr(model_instance, self.attname, value)
+
             return value
+
         else:
+
             value = super(CodeField, self).pre_save(
                 model_instance,
                 add)
+
             if self.auto and not value:
-                value = unicode(self.generate_code(code_length=self.max_length))
+
+                value = unicode(
+                        self.generate_code(code_length=self.max_length)
+                    )
+
                 setattr(model_instance, self.attname, value)
         return value
 
         suported by the uuid python module.
     """
 
-    def __init__(self, verbose_name=None, name=None, auto=True, version=1, node=None, clock_seq=None, namespace=None, **kwargs):
+    def __init__(
+            self,
+            verbose_name=None,
+            name=None,
+            auto=True,
+            version=1,
+            node=None,
+            clock_seq=None,
+            namespace=None,
+            **kwargs):
+
         kwargs['max_length'] = 36
+
         if auto:
             kwargs['blank'] = True
             kwargs['editable'] = kwargs.get('editable', False)
+
         self.version = version
+
         if version == 1:
             self.node, self.clock_seq = node, clock_seq
+
         elif version == 3 or version == 5:
             self.namespace, self.name = namespace, name
+
         self.auto = auto
+
         CharField.__init__(self, verbose_name, name, **kwargs)
 
     def get_internal_type(self):
         elif self.version == 5:
             return uuid.uuid5(self.namespace, self.name)
         else:
-            raise UUIDVersionError("UUID version %s is not valid." % self.version)
+            raise UUIDVersionError(
+                    "UUID version %s is not valid." % self.version
+                )
 
     def pre_save(self, model_instance, add):
         if self.auto and add:

File scm_core/models.py

     """Live manager, checks for publish_date and state.
 
     .. note::
-       it is not a failsafe way of retrieving data that is published. Keep using
-       common sense while developing!
+       it is not a failsafe way of retrieving data that is published. Keep
+       using common sense while developing!
     """
 
-#    def get_or_create(self, *args, **kwargs):
-#        commit = kwargs.get("commit", 'default_is_true')
-#        if commit == 'default_is_true':
-#            commit = True
-#        else:
-#            del kwargs['commit']
-#
-#        if commit == False:
-#            try:
-#                return (self.get(**kwargs), False)
-#            except self.model.DoesNotExist:
-#                return (self.model(**dict((k, v) \
-#                    for (k, v) in kwargs.items() if '__' not in k)), True)
-#        return super(LiveManager, self).get_or_create(*args, **kwargs)
-#
     def filter(self, *args, **kwargs):
         kwargs['publish_state'] = PUBLISH_STATE_PUBLISHED
         kwargs['publish_date__lte'] = datetime.now
         __class__ = self.__class__
         post_init.connect(
                 ChangeTrackingMixin.handle_post_init,
-                dispatch_uid="track::%s::post_init" % getmodule(__class__).__name__ + "." + __class__.__name__,
+                dispatch_uid="track::%s::post_init" % \
+                        getmodule(__class__).__name__ + \
+                        "." + __class__.__name__,
                 sender=__class__)
 
         if not reversion.is_registered(self.__class__):
     def store_key_hash(self, store_obj, key):
         """Store a hash for a certain key in store_obj[key].
 
-        Note: the stored value may be None if the value of the key is None or if a models.exceptions.ObjectDoesNotExist.
-        Also keep in mind that relations are not being traversed. So only simple changes will be detected.
+        Note: the stored value may be None if the value of the key is None or
+        if a models.exceptions.ObjectDoesNotExist. Also keep in mind that
+        relations are not being traversed. So only simple changes will been
+        detected.
         """
         try:
             store_obj[key] = self.generate_hash(smart_str(getattr(self, key)))
 
     @staticmethod
     def generate_hash(value):
-        """Generate a sha1 hexdigest of a specific value (or return None if the value parameter is also None)
+        """Generate a sha1 hexdigest of a specific value (or return None if the
+        value parameter is also None)
         """
         if value:
             return sha1(value).hexdigest()
         # check for possible problems
         if len(self.hash_table.keys()) == 0 or \
                 len(self.__class__.hashable_keys) == 0:
-            raise ValueError("The hash table for changes does not contain any values and/or no hashable keys are defined")
+            raise ValueError("""The hash table for changes does not contain any
+            values and/or no hashable keys are defined""")
 
         for key, value in self.hash_table.items():
             try:
 
     @reversion.revision.create_on_success
     def save_revision(self, changes):
-        reversion.revision.comment = "Storing from stream: " + ','.join(self.get_verbose_names(changes))
+
+        reversion.revision.comment = "Storing from stream: " +\
+                ','.join(self.get_verbose_names(changes))
         self.save()
 
     @reversion.revision.create_on_success
     def save_as_stale(self, changes):
+
         self.publish_state = PUBLISH_STATE_STALE
         self.external_id = ''
-        reversion.revision.comment = "Setting stale and maybe saving other changes: " + ','.join(self.get_verbose_names(changes))
+
+        reversion.revision.comment = \
+                "Setting stale and maybe saving other changes: " + \
+                ','.join(self.get_verbose_names(changes))
+
         self.save()
 
 

File scm_core/tests.py

 from django.test import TestCase
+from django.db import DatabaseError
 
+
+from scm_core.fields import CodeField
+from scm_core.models import ChangeTrackingMixin, PublishItem
+from scm_core.models import PUBLISH_STATE_DRAFT
 from scm_core.models import TestPubjectItem
 
 
         try:
             TestPubjectItem.pubjects.get(id=self.hidden.id)
             # you should not be here, the object is not set to published
+
             self.fail()
         except TestPubjectItem.DoesNotExist:
             pass
 
         TestPubjectItem.pubjects.all()
 
-        self.failUnless(len(TestPubjectItem.objects.all()), len(TestPubjectItem.pubjects.all()))
-        self.failUnless(len(TestPubjectItem.objects.all()), TestPubjectItem.pubjects.all().count())
-        self.failIfEqual(TestPubjectItem.objects.all().count(), TestPubjectItem.pubjects.all().count())
-        self.failIfEqual(TestPubjectItem.objects.count(), TestPubjectItem.pubjects.count())
-        self.failIfEqual(TestPubjectItem.objects.filter(id=self.hidden.id), TestPubjectItem.pubjects.filter(id=self.hidden.id))
+        self.failUnless(
+                len(TestPubjectItem.objects.all()),
+                len(TestPubjectItem.pubjects.all())
+            )
+
+        self.failUnless(
+                len(TestPubjectItem.objects.all()),
+                TestPubjectItem.pubjects.all().count()
+            )
+
+        self.failIfEqual(
+                TestPubjectItem.objects.all().count(),
+                TestPubjectItem.pubjects.all().count()
+            )
+
+        self.failIfEqual(
+                TestPubjectItem.objects.count(),
+                TestPubjectItem.pubjects.count()
+            )
+
+        self.failIfEqual(
+                TestPubjectItem.objects.filter(id=self.hidden.id),
+                TestPubjectItem.pubjects.filter(id=self.hidden.id)
+            )
 
     def test_visible_object(self):
+
         TestPubjectItem.pubjects.get(id=self.published.id)
 
-        self.failIfEqual(len(TestPubjectItem.pubjects.all()), len(TestPubjectItem.objects.all()))
-        self.failUnless(len(TestPubjectItem.pubjects.filter(id=self.published.id)), len(TestPubjectItem.objects.filter(id=self.published.id)))
+        self.failIfEqual(
+                len(TestPubjectItem.pubjects.all()),
+                len(TestPubjectItem.objects.all())
+            )
 
-from scm_core.fields import CodeField
-from scm_core.models import ChangeTrackingMixin, PublishItem, PUBLISH_STATE_DRAFT
-from django.db import DatabaseError
+        self.failUnless(
+                len(TestPubjectItem.pubjects.filter(id=self.published.id)),
+                len(TestPubjectItem.objects.filter(id=self.published.id))
+            )
 
 
 class TestingModel(PublishItem, ChangeTrackingMixin):
-    hashable_keys = ['code',]
+    hashable_keys = ['code', ]
 
     code = CodeField(max_length=10)
 
+
 class TestingModelMixin(object):
 
     def setUp(self):
             from django.core.management.color import no_style
 
             connection = connections[TestingModel.objects.db]
-            raw_sql = connection.creation.sql_create_model(TestingModel, no_style())
+            raw_sql = connection.creation.sql_create_model(
+                    TestingModel,
+                    no_style()
+                )
 
             raw_sql = ''.join(raw_sql[0])
             raw_sql = raw_sql.replace('\n', '')
         except DatabaseError:
             pass
 
+
 class ModelsPublishItemTestCase(TestingModelMixin, TestCase):
 
     def test_is_published(self):
 
         publish_date = datetime.now() + timedelta(days=3)
 
-        model_test = TestingModel(publish_date = publish_date, publish_state=PUBLISH_STATE_DRAFT)
+        model_test = TestingModel(
+                publish_date=publish_date,
+                publish_state=PUBLISH_STATE_DRAFT
+            )
+
         model_test.save()
 
         model_test = TestingModel.objects.get(id=model_test.id)
 
         self.assertEqual(model_test.code, initial_code)
 
+
 class ModelsChangeTrackingMixinTestCase(TestingModelMixin, TestCase):
+
     def test_stuff(self):
 
         model_test = TestingModel(code='standard_value')
 
 class UtilsTestCase(TestCase):
     def test_generate_password(self):
-        from scm_core.utils import generate_password, CHARACTERS_LEFT_HAND, CHARACTERS_RIGHT_HAND
+        from scm_core.utils import generate_password, CHARACTERS_LEFT_HAND
+        from scm_core.utils import CHARACTERS_RIGHT_HAND
 
         code = generate_password()
 
         self.assertEqual(len(code), 8)
 
-        code = generate_password(alternate_hands = True)
+        code = generate_password(alternate_hands=True)
 
         self.assertEqual(len(code), 8)
 
             else:
                 self.assertTrue(code[i] in CHARACTERS_RIGHT_HAND)
 
+
 class UploadToCase(TestCase):
     def test_all_filefields(self):
 
 
         if 'sorl.thumbnail' in settings.INSTALLED_APPS:
             test_with_sorl = True
-        else: 
+        else:
             test_with_sorl = False
 
         for c_type in ContentType.objects.all():
+
             m_class = c_type.model_class()
+
             for field in m_class._meta.fields:
-                if isinstance(field, FileField) and isinstance(field.storage, DefaultStorage):
-                    result = NamedTemporaryFile(suffix=".jpg", dir=field.storage.path(field.upload_to))
+
+                if isinstance(field, FileField) and \
+                    isinstance(field.storage, DefaultStorage):
+
+                    result = NamedTemporaryFile(
+                            suffix=".jpg",
+                            dir=field.storage.path(field.upload_to)
+                        )
+
                     if test_with_sorl:
-                        image = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static','tscm_core','images','2x2.jpg'), 'r')
+                        image = open(
+                                os.path.join(os.path.dirname(
+                                    os.path.realpath(__file__)),
+                                    'static',
+                                    'scm_core',
+                                    'images',
+                                    '2x2.jpg'
+                                ),
+                                'r'
+                            )
+
                         result.write(image.read())
                         result.seek(0)
                         image.close()
 
                         from sorl.thumbnail import get_thumbnail
-                        # test for both jpg and png support by resizing a jpeg to a png
-                        im = get_thumbnail(result.name[len(field.storage.location)+1:], '1x1', format='PNG')
+
+                        # test for both jpg and png support by resizing a
+                        # jpeg to a png
+
+                        im = get_thumbnail(
+                                result.name[len(
+                                    field.storage.location
+                                ) + 1:],
+                                '1x1',
+                                format='PNG'
+                            )
 
                         self.assertTrue(im.exists())
 
                         test_with_sorl = False
 
                     result.close()
-
 
 tests_require = [
     'django',
-    # also requires the disqus fork of haystack
 ]
 
 setup(
     name='django-scm_core',
     version=".".join(map(str, __import__('scm_core').__version__)),
     author='Jacco Flenter / Secretcodemachine',
-    description='Some often used models/fields/utils (like publish/modified enabled meta class & manager)',
+    description='Some often used models/fields/utils \
+            (like publish/modified enabled meta class & manager)',
     url='http://bitbucket.org/flenter/django-scm_core',
     install_requires=[
         'django',