Skip to content

Commit

Permalink
Fixed some flake8 warnings and uncovered a non-running test.
Browse files Browse the repository at this point in the history
  • Loading branch information
charettes committed Dec 2, 2014
1 parent f22d983 commit 1b22260
Show file tree
Hide file tree
Showing 29 changed files with 172 additions and 140 deletions.
6 changes: 6 additions & 0 deletions setup.cfg
@@ -0,0 +1,6 @@
[flake8]
exclude=.tox,.git
max-line-length = 119

[wheel]
universal = 1
8 changes: 2 additions & 6 deletions tenancy/management/__init__.py
Expand Up @@ -7,16 +7,12 @@
from django.utils.datastructures import SortedDict as OrderedDict
import logging

import django
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured
from django.core.management.color import no_style
from django.db import connections, models, router, transaction
from django.dispatch.dispatcher import receiver
from django.db import connections, router, transaction

from .. import signals
from ..utils import (allow_migrate, disconnect_signals, receivers_for_model,
remove_from_app_cache)
from ..utils import allow_migrate


def create_tenant_schema(tenant, using=None):
Expand Down
2 changes: 2 additions & 0 deletions tenancy/management/commands/createsuperuser.py
Expand Up @@ -15,6 +15,8 @@ def get_tenant_by_natural_key(option, opt, value, parser):


class Command(Command):
requires_model_validation = False

def __init__(self):
super(Command, self).__init__()
from ...settings import TENANT_AUTH_USER_MODEL
Expand Down
11 changes: 4 additions & 7 deletions tenancy/management/commands/createtenant.py
Expand Up @@ -86,10 +86,7 @@ def handle(self, *args, **options):
"any superusers defined.\nWould you like to create one "
"now? (yes/no): "
)
while True:
if confirm not in ('yes', 'no'):
confirm = input('Please enter either "yes" or "no": ')
else:
if confirm == 'yes':
call_command('createsuperuser', tenant=tenant, **options)
break
while confirm not in ('yes', 'no'):
confirm = input('Please enter either "yes" or "no": ')
if confirm == 'yes':
call_command('createsuperuser', tenant=tenant, **options)
5 changes: 3 additions & 2 deletions tenancy/managers.py
Expand Up @@ -55,5 +55,6 @@ def __init__(self, model):
def __get__(self, instance, owner):
raise AttributeError(
"Manager isn't available; %s is tenant specific" % (
self.model._meta.object_name,
))
self.model._meta.object_name,
)
)
2 changes: 1 addition & 1 deletion tenancy/middleware.py
Expand Up @@ -12,7 +12,7 @@
class TenantHostMiddleware(object):
def __init__(self):
try:
import django_hosts
import django_hosts # NOQA
except ImportError:
raise ImproperlyConfigured(
'You must install django-hosts in order to '
Expand Down
34 changes: 19 additions & 15 deletions tenancy/models.py
Expand Up @@ -22,8 +22,9 @@

from . import get_tenant_model
from .management import create_tenant_schema, drop_tenant_schema
from .managers import (AbstractTenantManager, TenantManager,
TenantModelManagerDescriptor)
from .managers import (
AbstractTenantManager, TenantManager, TenantModelManagerDescriptor
)
from .signals import lazy_class_prepared
from .utils import (
clear_opts_related_cache, disconnect_signals, get_model,
Expand Down Expand Up @@ -207,7 +208,7 @@ def __new__(cls, name, bases, attrs):

Meta = attrs.setdefault('Meta', meta())
if (getattr(Meta, 'abstract', False) or
any(issubclass(base, TenantSpecificModel) for base in bases)):
any(issubclass(base, TenantSpecificModel) for base in bases)):
# Abstract model definition and ones subclassing tenant specific
# ones shouldn't get any special treatment.
model = super_new(cls, name, bases, attrs)
Expand Down Expand Up @@ -267,7 +268,7 @@ def __new__(cls, name, bases, attrs):
cls.validate_related_name(m2m, to, model)
through = rel.through
if (not isinstance(through, string_types) and
through._meta.auto_created):
through._meta.auto_created):
# Replace the automatically created intermediary model
# by a TenantModelBase instance.
remove_from_app_cache(through)
Expand Down Expand Up @@ -311,7 +312,7 @@ def validate_related_name(cls, field, rel_to, model):
elif not isinstance(rel_to, TenantModelBase):
related_name = cls.references[model].related_names[field.name]
if (related_name is not None and
not (field.rel.is_hidden() or '%(class)s' in related_name)):
not (field.rel.is_hidden() or '%(class)s' in related_name)):
del cls.references[model]
remove_from_app_cache(model, quiet=True)
raise ImproperlyConfigured(
Expand Down Expand Up @@ -391,7 +392,8 @@ def abstract_tenant_model_factory(self, tenant):
if issubclass(self, TenantSpecificModel):
raise ValueError('Can only be called on non-tenant specific model.')
reference = self.references[self]
model = super(TenantModelBase, self).__new__(self.__class__,
model = super(TenantModelBase, self).__new__(
self.__class__,
str("Abstract%s" % reference.object_name_for_tenant(tenant)),
(self,) + self.tenant_model_bases(tenant, self.__bases__), {
'__module__': self.__module__,
Expand Down Expand Up @@ -482,11 +484,13 @@ def _prepare(self):
# Since our declaration class is not one of our parents we must
# make sure our exceptions extend his.
for exception in self.exceptions:
self.add_to_class(exception, subclass_exception(str(exception),
(getattr(self, exception),
getattr(for_tenant_model, exception)),
self.__module__, self
))
subclass = subclass_exception(
str(exception),
(getattr(self, exception), getattr(for_tenant_model, exception)),
self.__module__,
self,
)
self.add_to_class(exception, subclass)

def for_tenant(self, tenant):
"""
Expand Down Expand Up @@ -524,8 +528,8 @@ def for_tenant(self, tenant):
base = type(
str("Abstract%s" % reference.object_name_for_tenant(tenant)),
(self,), {
'__module__':self.__module__,
'Meta': meta(abstract=True)
'__module__': self.__module__,
'Meta': meta(abstract=True),
}
)
# Remove ourself from the parents chain and our descriptor
Expand Down Expand Up @@ -608,8 +612,8 @@ def attach_signals(signal, sender, **kwargs):
Re-attach signals to tenant models
"""
if issubclass(sender, TenantSpecificModel):
for signal, receiver in receivers_for_model(sender._for_tenant_model):
signal.connect(receiver, sender=sender)
for signal, receiver_ in receivers_for_model(sender._for_tenant_model):
signal.connect(receiver_, sender=sender)


def validate_not_to_tenant_model(field, to, model):
Expand Down
4 changes: 2 additions & 2 deletions tenancy/mutant/models.py
Expand Up @@ -37,8 +37,8 @@ class MutableTenantModelBase(TenantModelBase):
def tenant_model_bases(cls, tenant, bases):
tenant_bases = super(MutableTenantModelBase, cls).tenant_model_bases(tenant, bases)
return tuple(
tenant_base.__get__(None, None) if isinstance(base, cls) and
not base._meta.abstract else tenant_base
tenant_base.__get__(None, None)
if isinstance(base, cls) and not base._meta.abstract else tenant_base
for base, tenant_base in zip(bases, tenant_bases)
)

Expand Down
2 changes: 1 addition & 1 deletion tenancy/signals.py
Expand Up @@ -20,7 +20,7 @@ def lazy_class_prepared(app_label, object_name, callback):
def receiver(sender, **kwargs):
opts = sender._meta
if (opts.app_label == app_label and
opts.object_name == object_name):
opts.object_name == object_name):
class_prepared.disconnect(receiver)
callback(sender)
class_prepared.connect(receiver, weak=False)
Expand Down
12 changes: 0 additions & 12 deletions tenancy/tests/__init__.py
@@ -1,12 +0,0 @@
from __future__ import unicode_literals

from .test_auth import *
from .test_commands import *
from .test_forms import *
from .test_hosts import *
from .test_models import *
from .test_managers import *
from .test_middleware import *
from .test_mutant import *
from .test_signals import *
from .test_views import *
6 changes: 3 additions & 3 deletions tenancy/tests/hosts.py
@@ -1,11 +1,11 @@
from __future__ import unicode_literals

from django_hosts import host, patterns
from django_hosts import host

from ..settings import HOST_NAME


host_patterns = patterns('',
host_patterns = [
host(r'(?P<name>[\w-]+)', 'tenancy.tests.tenant_urls', name=HOST_NAME),
host(r'', 'tenancy.tests.urls', name='default'),
)
]
10 changes: 3 additions & 7 deletions tenancy/tests/models.py
Expand Up @@ -2,8 +2,8 @@

import sys

import django
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.core.exceptions import ImproperlyConfigured
try:
from django.contrib.contenttypes.fields import (
GenericRelation, GenericForeignKey
Expand All @@ -13,7 +13,6 @@
GenericRelation, GenericForeignKey
)
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured
from django.db import models

from ..models import Tenant, TenantModel
Expand Down Expand Up @@ -83,11 +82,8 @@ class PostInitFieldsModel(TenantModel):
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
try:
if django.VERSION >= (1, 6):
from django.utils.image import Image as _
else:
from PIL import Image as _
except (ImportError, ImproperlyConfigured):
from django.utils.image import Image as _ # NOQA
except ImproperlyConfigured:
pass
else:
image = models.ImageField(upload_to='void')
Expand Down
9 changes: 4 additions & 5 deletions tenancy/tests/tenant_urls.py
@@ -1,14 +1,13 @@
from __future__ import unicode_literals

from django.conf.urls import patterns, url
from django.conf.urls import url
from django.http import HttpResponse

from ..models import Tenant


urlpatterns = patterns('',
urlpatterns = [
url(r'^$',
lambda request: HttpResponse(getattr(request, Tenant.ATTR_NAME).name),
name='tenant_name'
),
)
name='tenant_name'),
]
6 changes: 4 additions & 2 deletions tenancy/tests/test_auth.py
Expand Up @@ -11,7 +11,8 @@
class CustomTenantUserBackendTest(TenancyTestCase):
@override_settings(AUTH_USER_MODEL='auth.User')
def test_custom_user_not_tenant(self):
self.assertRaisesMessage(ImproperlyConfigured,
self.assertRaisesMessage(
ImproperlyConfigured,
"The `tenancy.auth.backends.CustomTenantUserBackend` "
"authentification backend can only be used with a custom "
"tenant user model.",
Expand All @@ -20,7 +21,8 @@ def test_custom_user_not_tenant(self):

@override_settings(AUTH_USER_MODEL='tenancy.TenantUser')
def test_missing_connection_tenant(self):
self.assertRaisesMessage(ImproperlyConfigured,
self.assertRaisesMessage(
ImproperlyConfigured,
"The `tenancy.auth.backends.CustomTenantUserBackend` "
"authentification backend requires that a `tenant` attribute "
"be set on the default connection to work properly. The "
Expand Down
15 changes: 10 additions & 5 deletions tenancy/tests/test_commands.py
Expand Up @@ -3,10 +3,11 @@
import sys
# TODO: Remove when support for Python 2.6 is dropped
if sys.version_info >= (2, 7):
from unittest import skipUnless
from unittest import skipIf, skipUnless
else:
from django.utils.unittest import skipUnless
from django.utils.unittest import skipIf, skipUnless

import django
from django.db import connection, connections, router, transaction
from django.db.utils import DatabaseError
from django.core.management import call_command
Expand All @@ -19,8 +20,9 @@
from ..signals import pre_schema_creation, post_schema_deletion
from ..utils import allow_migrate

from .utils import (mock_inputs, setup_custom_tenant_user, skipIfCustomTenant,
TenancyTestCase)
from .utils import (
mock_inputs, setup_custom_tenant_user, skipIfCustomTenant, TenancyTestCase
)


@skipIfCustomTenant
Expand Down Expand Up @@ -62,6 +64,9 @@ def test_verbosity(self):
finally:
tenant.delete()

@skipIf(
django.VERSION >= (1, 7), 'Management commands cannot be overriden on Django >= 1.7'
)
@setup_custom_tenant_user
@mock_inputs((
('\nYou just created a new tenant,', 'yes'),
Expand All @@ -79,7 +84,7 @@ def test_superuser_creation_prompt(self):
@mock_inputs((
('\nYou just created a new tenant,', 'no'),
))
def test_superuser_creation_prompt(self):
def test_superuser_creation_cancelled_prompt(self):
stdout = StringIO()
call_command('createtenant', 'tenant', stdout=stdout, interactive=True)
stdout.seek(0)
Expand Down
12 changes: 8 additions & 4 deletions tenancy/tests/test_forms.py
Expand Up @@ -3,12 +3,16 @@
from django.core.exceptions import ImproperlyConfigured
from django.forms.models import modelform_factory, modelformset_factory

from ..forms import (tenant_inlineformset_factory, tenant_modelform_factory,
tenant_modelformset_factory)
from ..forms import (
tenant_inlineformset_factory, tenant_modelform_factory,
tenant_modelformset_factory
)
from ..models import Tenant

from .forms import (NonTenantInlineFormSet, RelatedInlineFormSet,
RelatedTenantModelForm, SpecificModelForm, SpecificModelFormSet)
from .forms import (
NonTenantInlineFormSet, RelatedInlineFormSet, RelatedTenantModelForm,
SpecificModelForm, SpecificModelFormSet
)
from .models import NonTenantModel, RelatedTenantModel, SpecificModel
from .utils import TenancyTestCase

Expand Down
13 changes: 6 additions & 7 deletions tenancy/tests/test_hosts.py
Expand Up @@ -20,9 +20,7 @@
try:
import django_hosts
except ImportError:
django_hosts_installed = False
else:
django_hosts_installed = True
django_hosts = None


def django_hosts_installed_setup(func):
Expand All @@ -35,7 +33,7 @@ def django_hosts_installed_setup(func):
)
)(func)
return skipUnless(
django_hosts_installed,
django_hosts,
'django-hosts is not installed.'
)(func)

Expand All @@ -47,7 +45,7 @@ def tenant_client(cls, tenant):
domain = "%s.testserver" % tenant.name
return cls.client_class(SERVER_NAME=domain)

@skipIf(django_hosts_installed, 'django-hosts is installed.')
@skipIf(django_hosts, 'django-hosts is installed.')
def test_not_installed(self):
self.assertRaisesMessage(
ImproperlyConfigured,
Expand All @@ -56,15 +54,16 @@ def test_not_installed(self):
TenantHostMiddleware
)

@skipUnless(django_hosts_installed, 'django-hosts is not installed.')
@skipUnless(django_hosts, 'django-hosts is not installed.')
@override_settings(
MIDDLEWARE_CLASSES=(
'tenancy.middleware.TenantHostMiddleware',
'django_hosts.middleware.HostsMiddleware'
)
)
def test_wrong_order(self):
self.assertRaisesMessage(ImproperlyConfigured,
self.assertRaisesMessage(
ImproperlyConfigured,
"Make sure that 'django_hosts.middleware.HostsMiddleware' is "
"placed before 'tenancy.middleware.TenantHostMiddleware' in your "
"`MIDDLEWARE_CLASSES` setting.",
Expand Down

0 comments on commit 1b22260

Please sign in to comment.