diff --git a/django_hstore/apps.py b/django_hstore/apps.py index fcd6136..6e3563e 100755 --- a/django_hstore/apps.py +++ b/django_hstore/apps.py @@ -27,8 +27,7 @@ warnings.warn("""\n DJANGO_HSTORE_GLOBAL_REGISTER setting is deprecated since django-hstore 1.2.5 and will be removed in 1.3.0. Use DJANGO_HSTORE_ADAPTER_REGISTRATION by setting it either to 'global' or 'connection'. - """, - DeprecationWarning) + """, DeprecationWarning) class ConnectionCreateHandler(object): diff --git a/django_hstore/compat.py b/django_hstore/compat.py index 9692d00..3b595b3 100755 --- a/django_hstore/compat.py +++ b/django_hstore/compat.py @@ -6,7 +6,7 @@ class UnicodeMixin(object): Mixin class to handle defining the proper __str__/__unicode__ methods in Python 2 or 3. """ - if sys.version_info[0] >= 3: # Python 3 + if sys.version_info[0] >= 3: # Python 3 def __str__(self): return self.__unicode__() else: # Python 2 diff --git a/django_hstore/descriptors.py b/django_hstore/descriptors.py index f6bcb64..e862630 100755 --- a/django_hstore/descriptors.py +++ b/django_hstore/descriptors.py @@ -1,5 +1,5 @@ from django.db import models -from .dict import * +from .dict import HStoreDict, HStoreReferenceDict __all__ = [ diff --git a/django_hstore/dict.py b/django_hstore/dict.py index 7b298c1..7ca2201 100755 --- a/django_hstore/dict.py +++ b/django_hstore/dict.py @@ -22,7 +22,6 @@ class HStoreDict(UnicodeMixin, dict): """ A dictionary subclass which implements hstore support. """ - schema_mode = False # python2.6 compatibility def __init__(self, value=None, field=None, instance=None, schema_mode=False, **kwargs): @@ -84,7 +83,7 @@ def get(self, *args): key = args[0] try: return self.__getitem__(key) - except KeyError as e: + except KeyError: if len(args) > 1: return args[1] # return default value else: diff --git a/django_hstore/fields.py b/django_hstore/fields.py index 6654e06..9612e20 100755 --- a/django_hstore/fields.py +++ b/django_hstore/fields.py @@ -1,13 +1,13 @@ from __future__ import unicode_literals, absolute_import -from django.db import models, connection +from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.exceptions import ImproperlyConfigured from django import get_version -from .descriptors import * -from .dict import * -from .virtual import * +from .descriptors import HStoreDescriptor, HStoreReferenceDescriptor +from .dict import HStoreDict, HStoreReferenceDict +from .virtual import create_hstore_virtual_field from . import forms, utils @@ -70,7 +70,8 @@ def south_field_triple(self): if get_version() >= '1.7': - from .lookups import * + from .lookups import (HStoreGreaterThan, HStoreGreaterThanOrEqual, HStoreLessThan, + HStoreLessThanOrEqual, HStoreContains, HStoreIContains, HStoreIsNull) HStoreField.register_lookup(HStoreGreaterThan) HStoreField.register_lookup(HStoreGreaterThanOrEqual) diff --git a/django_hstore/hstore.py b/django_hstore/hstore.py index 7720715..fefdc38 100755 --- a/django_hstore/hstore.py +++ b/django_hstore/hstore.py @@ -1,14 +1,13 @@ -from django_hstore.fields import DictionaryField, ReferencesField -from django_hstore.managers import HStoreManager +from django_hstore.fields import DictionaryField, ReferencesField # noqa +from django_hstore.managers import HStoreManager # noqa try: - from django_hstore.managers import HStoreGeoManager + from django_hstore.managers import HStoreGeoManager # noqa except: # django.contrib.gis is not configured properly pass import django if django.get_version() < '1.7': - from . import apps - + from . import apps # noqa diff --git a/django_hstore/models.py b/django_hstore/models.py index 0a1f952..f804d27 100755 --- a/django_hstore/models.py +++ b/django_hstore/models.py @@ -1,9 +1,6 @@ import django -from django.db import models -from django.core.exceptions import ValidationError - -from .fields import DictionaryField +from .fields import DictionaryField # noqa if django.get_version() < '1.7': - from . import apps + from . import apps # noqa diff --git a/django_hstore/virtual.py b/django_hstore/virtual.py index bdd4091..3873fb0 100755 --- a/django_hstore/virtual.py +++ b/django_hstore/virtual.py @@ -94,7 +94,7 @@ def deconstruct(self, *args, **kwargs): specific for django 1.7 and greater (migration framework) """ name, path, args, kwargs = super(VirtualField, self).deconstruct(*args, **kwargs) - return (name, path, args, { 'default': kwargs.get('default')}) + return (name, path, args, {'default': kwargs.get('default')}) # support DateTimeField if BaseField == models.DateTimeField and (kwargs.get('null') or kwargs.get('blank')): @@ -106,7 +106,7 @@ def value_to_string(self, obj): val = self._get_val_from_obj(obj) try: return '' if val is None else val.isoformat() - except AttributeError as e: + except AttributeError: return val VirtualField.value_to_string = value_to_string diff --git a/runtests.py b/runtests.py index 5479c56..1661874 100755 --- a/runtests.py +++ b/runtests.py @@ -2,7 +2,8 @@ # -*- coding: utf-8 -*- -import os, sys +import os +import sys os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") sys.path.insert(0, "tests") diff --git a/tests/django_hstore_tests/admin.py b/tests/django_hstore_tests/admin.py index b70db26..b14ab80 100755 --- a/tests/django_hstore_tests/admin.py +++ b/tests/django_hstore_tests/admin.py @@ -1,6 +1,6 @@ from django.contrib import admin from django import get_version -from .models import * +from .models import * # noqa class DataBagAdmin(admin.ModelAdmin): @@ -18,7 +18,7 @@ class DefaultsModelAdmin(admin.ModelAdmin): class RefsBagAdmin(admin.ModelAdmin): pass - + admin.site.register(DataBag, DataBagAdmin) admin.site.register(DefaultsModel, DefaultsModelAdmin) @@ -28,5 +28,5 @@ class RefsBagAdmin(admin.ModelAdmin): if get_version()[0:3] >= '1.6': class SchemaDataBagAdmin(admin.ModelAdmin): list_display = ['name'] - + admin.site.register(SchemaDataBag, SchemaDataBagAdmin) diff --git a/tests/django_hstore_tests/models.py b/tests/django_hstore_tests/models.py index 16aadbd..6ab23d6 100755 --- a/tests/django_hstore_tests/models.py +++ b/tests/django_hstore_tests/models.py @@ -43,6 +43,7 @@ class NullableDataBag(HStoreModel): name = models.CharField(max_length=32) data = hstore.DictionaryField(null=True) + class RefsBag(HStoreModel): name = models.CharField(max_length=32) refs = hstore.ReferencesField() @@ -65,7 +66,7 @@ class BadDefaultsModel(models.Model): class DefaultsInline(models.Model): parent = models.ForeignKey(DefaultsModel) - d = hstore.DictionaryField(default={ 'default': 'yes' }) + d = hstore.DictionaryField(default={'default': 'yes'}) class NumberedDataBag(HStoreModel): @@ -79,7 +80,7 @@ class UniqueTogetherDataBag(HStoreModel): data = hstore.DictionaryField() class Meta: - unique_together = ("name", "data") + unique_together = ('name', 'data') if get_version()[0:3] >= '1.6': class SchemaDataBag(HStoreModel): @@ -198,6 +199,7 @@ class SchemaDataBag(HStoreModel): # if geodjango is in use define Location model, which contains GIS data if GEODJANGO: from django.contrib.gis.db import models as geo_models + class Location(geo_models.Model): name = geo_models.CharField(max_length=32) data = hstore.DictionaryField() diff --git a/tests/django_hstore_tests/tests.py b/tests/django_hstore_tests/tests.py index 775c715..c2f7542 100755 --- a/tests/django_hstore_tests/tests.py +++ b/tests/django_hstore_tests/tests.py @@ -5,20 +5,17 @@ from decimal import Decimal import datetime -import django - -from django.db import transaction -from django.db import connection +from django import VERSION as DJANGO_VERSION +from django import forms +from django.db import transaction, connection, models from django.db.models.aggregates import Count -from django.db.utils import IntegrityError, DatabaseError -from django import forms, get_version as get_django_version -from django.db import models -from django.core.urlresolvers import reverse +from django.db.utils import IntegrityError from django.core.exceptions import ValidationError, ImproperlyConfigured -from django.test import TestCase -from django.test import SimpleTestCase +from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.utils.encoding import force_text +from django.test import TestCase +from django.test import SimpleTestCase from django_hstore import get_version, hstore from django_hstore.forms import DictionaryFieldWidget, ReferencesFieldWidget @@ -27,7 +24,7 @@ from django_hstore.utils import unserialize_references, serialize_references, acquire_reference from django_hstore.virtual import create_hstore_virtual_field -from django_hstore_tests.models import * +from django_hstore_tests.models import * # noqa class TestDictionaryField(TestCase): @@ -42,7 +39,7 @@ def _create_bags(self): return alpha, beta def _create_bitfield_bags(self): - # create dictionaries with bits as dictionary keys (i.e. bag5 = { 'b0':'1', 'b2':'1'}) + # create dictionaries with bits as dictionary keys (i.e. bag5 = {'b0':'1', 'b2':'1'}) for i in range(10): DataBag.objects.create(name='bag%d' % (i,), data=dict(('b%d' % (bit,), '1') for bit in range(4) if (1 << bit) & i)) @@ -87,16 +84,16 @@ def test_number(self): databag = DataBag.objects.get(name='number') self.assertEqual(databag.data['num'], '1') - databag = DataBag(name='number', data={ 'num': 1 }) + databag = DataBag(name='number', data={'num': 1}) self.assertEqual(databag.data['num'], '1') def test_list(self): - databag = DataBag.objects.create(name='list', data={ 'list': ['a', 'b', 'c'] }) + databag = DataBag.objects.create(name='list', data={'list': ['a', 'b', 'c']}) databag = DataBag.objects.get(name='list') self.assertEqual(json.loads(databag.data['list']), ['a', 'b', 'c']) def test_dictionary(self): - databag = DataBag.objects.create(name='dict', data={ 'dict': {'subkey': 'subvalue'} }) + databag = DataBag.objects.create(name='dict', data={'dict': {'subkey': 'subvalue'}}) databag = DataBag.objects.get(name='dict') self.assertEqual(json.loads(databag.data['dict']), {'subkey': 'subvalue'}) @@ -105,7 +102,7 @@ def test_dictionary(self): self.assertEqual(json.loads(databag.data['dict']), {'subkey': True, 'list': ['a', 'b', False]}) def test_boolean(self): - databag = DataBag.objects.create(name='boolean', data={ 'boolean': True }) + databag = DataBag.objects.create(name='boolean', data={'boolean': True}) databag = DataBag.objects.get(name='boolean') self.assertEqual(json.loads(databag.data['boolean']), True) @@ -339,7 +336,7 @@ def test_single_key_querying(self): def test_simple_text_icontains_querying(self): alpha, beta = self._create_bags() - gamma = DataBag.objects.create(name='gamma', data={'theKey': 'someverySpecialValue', 'v2': '3'}) + DataBag.objects.create(name='gamma', data={'theKey': 'someverySpecialValue', 'v2': '3'}) self.assertEqual(DataBag.objects.filter(data__contains='very').count(), 1) self.assertEqual(DataBag.objects.filter(data__contains='very')[0].name, 'gamma') @@ -363,19 +360,19 @@ def test_invalid_containment_lookup_values(self): def test_invalid_comparison_lookup_values(self): alpha, beta = self._create_bags() with self.assertRaises(ValueError): - DataBag.objects.filter(data__lt=[1,2])[0] + DataBag.objects.filter(data__lt=[1, 2])[0] with self.assertRaises(ValueError): DataBag.objects.filter(data__lt=99)[0] with self.assertRaises(ValueError): - DataBag.objects.filter(data__lte=[1,2])[0] + DataBag.objects.filter(data__lte=[1, 2])[0] with self.assertRaises(ValueError): DataBag.objects.filter(data__lte=99)[0] with self.assertRaises(ValueError): - DataBag.objects.filter(data__gt=[1,2])[0] + DataBag.objects.filter(data__gt=[1, 2])[0] with self.assertRaises(ValueError): DataBag.objects.filter(data__gt=99)[0] with self.assertRaises(ValueError): - DataBag.objects.filter(data__gte=[1,2])[0] + DataBag.objects.filter(data__gte=[1, 2])[0] with self.assertRaises(ValueError): DataBag.objects.filter(data__gte=99)[0] @@ -458,7 +455,7 @@ def test_hstoredictionaryexception(self): HStoreDict(3) def test_hstoredictionary_unicoce_vs_str(self): - d = HStoreDict({ 'test': 'test' }) + d = HStoreDict({'test': 'test'}) self.assertEqual(d.__str__(), d.__unicode__()) def test_hstore_model_field_validation(self): @@ -486,7 +483,7 @@ def test_hstore_model_field_validation(self): 'a': 1, 'b': 2.2, 'c': ['a', 'b'], - 'd': { 'test': 'test' } + 'd': {'test': 'test'} } with self.assertRaises(ValidationError): @@ -559,13 +556,13 @@ def test_get_version(self): def test_unique_together(self): d = UniqueTogetherDataBag() d.name = 'test' - d.data = { 'test': 'test '} + d.data = {'test': 'test '} d.full_clean() d.save() d = UniqueTogetherDataBag() d.name = 'test' - d.data = { 'test': 'test '} + d.data = {'test': 'test '} with self.assertRaises(ValidationError): d.full_clean() @@ -576,9 +573,9 @@ def test_properties_hstore(self): from django_hstore.fields import HStoreDict instance = DataBag() - test_props = {'foo':'bar', 'size': '3'} + test_props = {'foo': 'bar', 'size': '3'} - instance.name = "foo" + instance.name = 'foo' instance.data = test_props instance.save() @@ -611,7 +608,7 @@ def test_str(self): class SchemaTests(TestCase): - if get_django_version()[0:3] >= '1.6': + if DJANGO_VERSION[:2] >= (1, 6): def _login_as_admin(self): # create admin user admin = User.objects.create(username='admin', password='tester', is_staff=True, is_superuser=True, is_active=True) @@ -712,7 +709,7 @@ def test_admin_add(self): response = self.client.get(url) self.assertEqual(response.status_code, 200) - response = self.client.post(url, { 'name': 'test_add', 'number': 3, 'float': 2.4 }) + response = self.client.post(url, {'name': 'test_add', 'number': 3, 'float': 2.4}) d = SchemaDataBag.objects.all()[0] self.assertEqual(d.name, 'test_add') self.assertEqual(d.number, 3) @@ -724,7 +721,7 @@ def test_admin_add_utf8(self): response = self.client.get(url) self.assertEqual(response.status_code, 200) - response = self.client.post(url, { 'name': 'test_add', 'number': 3, 'float': 2.4, 'char': 'è' }) + response = self.client.post(url, {'name': 'test_add', 'number': 3, 'float': 2.4, 'char': 'è'}) d = SchemaDataBag.objects.all()[0] self.assertEqual(d.name, 'test_add') self.assertEqual(d.number, 3) @@ -741,7 +738,7 @@ def test_admin_change(self): response = self.client.get(url) self.assertEqual(response.status_code, 200) - response = self.client.post(url, { 'name': 'test_change', 'number': 6, 'float': 2.6 }) + response = self.client.post(url, {'name': 'test_change', 'number': 6, 'float': 2.6}) d = SchemaDataBag.objects.get(pk=d.id) self.assertEqual(d.name, 'test_change') self.assertEqual(d.number, 6) @@ -750,29 +747,29 @@ def test_admin_change(self): self.assertEqual(d.data['float'], 2.6) def test_create_hstore_virtual_field(self): - integer = create_hstore_virtual_field('IntegerField', { 'default': 0 }, 'data') + integer = create_hstore_virtual_field('IntegerField', {'default': 0}, 'data') self.assertIsInstance(integer, models.IntegerField) - char = create_hstore_virtual_field('CharField', { 'default': 'test', 'blank': True, 'max_length': 10 }, 'data') + char = create_hstore_virtual_field('CharField', {'default': 'test', 'blank': True, 'max_length': 10}, 'data') self.assertIsInstance(char, models.CharField) - text = create_hstore_virtual_field('TextField', { 'blank': True }, 'data') + text = create_hstore_virtual_field('TextField', {'blank': True}, 'data') self.assertIsInstance(text, models.TextField) def test_create_hstore_virtual_field_wrong_class(self): with self.assertRaises(ValueError): - create_hstore_virtual_field(float, { 'blank': True }, 'data') + create_hstore_virtual_field(float, {'blank': True}, 'data') def test_create_hstore_virtual_field_wrong_class_string(self): with self.assertRaises(ValueError): - create_hstore_virtual_field('IdoNotExist', { 'blank': True }, 'data') + create_hstore_virtual_field('IdoNotExist', {'blank': True}, 'data') def test_create_hstore_virtual_field_concrete_class(self): - integer = create_hstore_virtual_field(models.IntegerField, { 'default': 0 }, 'data') - url = create_hstore_virtual_field(models.URLField, { 'blank': True }, 'data') + integer = create_hstore_virtual_field(models.IntegerField, {'default': 0}, 'data') + url = create_hstore_virtual_field(models.URLField, {'blank': True}, 'data') self.assertTrue(isinstance(integer, models.IntegerField)) self.assertTrue(isinstance(url, models.URLField)) def test_DictionaryField_with_schema(self): - data = hstore.DictionaryField(schema=[ + hstore.DictionaryField(schema=[ { 'name': 'number', 'class': 'IntegerField', @@ -785,27 +782,27 @@ def test_DictionaryField_with_schema(self): def test_schema_validation_string(self): with self.assertRaises(ValueError): - data = hstore.DictionaryField(schema='') + hstore.DictionaryField(schema='') with self.assertRaises(ValueError): - data = hstore.DictionaryField(schema='WRONG') + hstore.DictionaryField(schema='WRONG') def test_schema_validation_wrong_list(self): with self.assertRaises(ValueError): - data = hstore.DictionaryField(schema=[]) + hstore.DictionaryField(schema=[]) with self.assertRaises(ValueError): - data = hstore.DictionaryField(schema=['i am teasing you']) + hstore.DictionaryField(schema=['i am teasing you']) def test_schema_validation_wrong_dict(self): with self.assertRaises(ValueError): - data = hstore.DictionaryField(schema=[ - { 'wrong': 'wrong' } + hstore.DictionaryField(schema=[ + {'wrong': 'wrong'} ]) with self.assertRaises(ValueError): - data = hstore.DictionaryField(schema=[ - { 'name': 'test' } + hstore.DictionaryField(schema=[ + {'name': 'test'} ]) def test_utf8(self): @@ -882,8 +879,8 @@ def test_reload_schema(self): d = SchemaDataBag() self.assertTrue(d.data.schema_mode) self.assertEqual(len(SchemaDataBag._meta.virtual_fields), len(original_schema)) - self.assertEqual(len(SchemaDataBag._meta.fields), len(original_schema)+concrete_fields_length) - self.assertEqual(len(SchemaDataBag._meta.local_fields), len(original_schema)+concrete_fields_length) + self.assertEqual(len(SchemaDataBag._meta.fields), len(original_schema) + concrete_fields_length) + self.assertEqual(len(SchemaDataBag._meta.local_fields), len(original_schema) + concrete_fields_length) self.assertTrue(hasattr(SchemaDataBag, '_hstore_virtual_fields')) for key in hstore_virtual_fields_keys: self.assertTrue(hasattr(d, key)) @@ -907,8 +904,8 @@ def test_reload_schema(self): d = SchemaDataBag() self.assertTrue(d.data.schema_mode) self.assertEqual(len(SchemaDataBag._meta.virtual_fields), len(original_schema)) - self.assertEqual(len(SchemaDataBag._meta.fields), len(original_schema)+concrete_fields_length) - self.assertEqual(len(SchemaDataBag._meta.local_fields), len(original_schema)+concrete_fields_length) + self.assertEqual(len(SchemaDataBag._meta.fields), len(original_schema) + concrete_fields_length) + self.assertEqual(len(SchemaDataBag._meta.local_fields), len(original_schema) + concrete_fields_length) self.assertTrue(hasattr(SchemaDataBag, '_hstore_virtual_fields')) for key in hstore_virtual_fields_keys: self.assertTrue(hasattr(d, key)) @@ -923,7 +920,7 @@ def test_datetime_is_none(self): d = SchemaDataBag.objects.get(name='datetime') self.assertIsNone(d.datetime, None) - if django.VERSION[:2] >= (1, 7): + if DJANGO_VERSION[:2] >= (1, 7): def test_migration_datetime(self): """ issue #82 https://github.com/djangonauts/django-hstore/issues/82 """ from django.core.management import call_command @@ -968,37 +965,29 @@ class SchemaDataBag(models.Model): class NotTransactionalTests(SimpleTestCase): - if django.VERSION[:2] >= (1,6): + if DJANGO_VERSION[:2] >= (1, 6): def test_hstore_registring_in_transaction_block(self): obj1 = DataBag.objects.create(name='alpha1', data={'v': '1', 'v2': '3'}) obj2 = DataBag.objects.create(name='alpha2', data={'v': '1', 'v2': '3'}) - # Close any existing connection previously do anything connection.close() - with transaction.atomic(): qs = DataBag.objects.filter(name__in=["alpha2", "alpha1"]) self.assertIsInstance(qs[0].data, HStoreDict) - obj1.delete() obj2.delete() - connection.close() else: def test_hstore_registring_in_transaction_block(self): obj1 = DataBag.objects.create(name='alpha1', data={'v': '1', 'v2': '3'}) obj2 = DataBag.objects.create(name='alpha2', data={'v': '1', 'v2': '3'}) - # Close any existing connection previously do anything connection.close() - with transaction.commit_on_success(): qs = DataBag.objects.filter(name__in=["alpha2", "alpha1"]) self.assertIsInstance(qs[0].data, HStoreDict) - obj1.delete() obj2.delete() - connection.close() @@ -1139,7 +1128,7 @@ def test_unserialize_references_edge_cases(self): def test_serialize_references_edge_cases(self): self.assertEqual(serialize_references(None), {}) - self.assertEqual(serialize_references({ 'test': 'test' }), { 'test': 'test' }) + self.assertEqual(serialize_references({'test': 'test'}), {'test': 'test'}) def test_acquire_references_edge_cases(self): with self.assertRaises(ValueError): @@ -1272,7 +1261,7 @@ def test_location_geomanager(self): d1 = Location.objects.filter(point__distance_lte=(self.pnt1, 70000)) self.assertEqual(d1.count(), 2) - + # noqa class TestReferencesFieldPlusGIS(TestDictionaryFieldPlusGIS): """ Test ReferenceField with gis backend """ diff --git a/tests/settings.py b/tests/settings.py index 38db4e0..b956689 100755 --- a/tests/settings.py +++ b/tests/settings.py @@ -64,7 +64,7 @@ # local settings must be imported before test runner otherwise they'll be ignored try: - from local_settings import * + from local_settings import * # noqa except ImportError: pass @@ -72,7 +72,7 @@ TEST_RUNNER = 'django.test.runner.DiscoverRunner' else: try: - import discover_runner + import discover_runner # noqa TEST_RUNNER = "discover_runner.DiscoverRunner" except ImportError: print("For run tests with django <= 1.5 you should install " diff --git a/tests/urls.py b/tests/urls.py index 575dc4c..0560b4d 100755 --- a/tests/urls.py +++ b/tests/urls.py @@ -4,13 +4,12 @@ admin.autodiscover() -urlpatterns = patterns('', - # Uncomment the next line to enable the admin: +urlpatterns = patterns('', # noqa url(r'^admin/', include(admin.site.urls)), ) if 'grappelli' in settings.INSTALLED_APPS: - urlpatterns = urlpatterns + patterns('', + urlpatterns = urlpatterns + patterns('', # noqa url(r'^grappelli/', include('grappelli.urls')), - ) \ No newline at end of file + )