# Path: shared_schema_tenants/models.py
# class Tenant(TimeStampedModel):
#     name = models.CharField(max_length=255)
#     slug = models.CharField(max_length=255, primary_key=True)
# 
#     if 'postgresql' in django_settings.DATABASES['default']['ENGINE']:
#         from django.contrib.postgres.fields import JSONField
#         extra_data = JSONField(blank=True, null=True,
#                                default=get_setting('DEFAULT_TENANT_EXTRA_DATA'))
#         settings = JSONField(blank=True, null=True,
#                              default=get_setting('DEFAULT_TENANT_SETTINGS'))
#     else:
#         _extra_data = models.TextField(blank=True, null=True,
#                                        validators=[validate_json],
#                                        default=json.dumps(get_setting('DEFAULT_TENANT_EXTRA_DATA')))
#         _settings = models.TextField(blank=True, null=True,
#                                      validators=[validate_json],
#                                      default=json.dumps(get_setting('DEFAULT_TENANT_SETTINGS')))
# 
#         @property
#         def extra_data(self):
#             import json
#             return json.loads(self._extra_data)
# 
#         @extra_data.setter
#         def extra_data(self, value):
#             import json
#             self._extra_data = json.dumps(value)
# 
#         @property
#         def settings(self):
#             import json
#             return json.loads(self._settings)
# 
#         @settings.setter
#         def settings(self, value):
#             import json
#             self._settings = json.dumps(value)
# 
#     def __str__(self):
#         return self.name
# 
# class TenantSite(TimeStampedModel, SingleTenantModelMixin):
#     tenant = models.ForeignKey('Tenant', related_name="tenant_sites")
#     site = models.OneToOneField(Site, related_name="tenant_site")
# 
#     def __str__(self):
#         return '%s - %s' % (self.tenant.name, self.site.domain)
# 
# Path: shared_schema_tenants/helpers/tenants.py
# def set_current_tenant(tenant_slug):
#     from shared_schema_tenants.middleware import TenantMiddleware
#     return TenantMiddleware.set_tenant(tenant_slug)
# 
# def create_default_tenant_groups():
#     with transaction.atomic():
#         group, created = Group.objects.get_or_create(name='tenant_owner')
# 
#         if created:
#             for perm in get_setting('DEFAULT_TENANT_OWNER_PERMISSIONS'):
#                 try:
#                     group.permissions.add(Permission.objects.get(
#                         content_type__app_label=perm.split('.')[0],
#                         codename=perm.split('.')[1]))
#                 except Permission.DoesNotExist:
#                     pass
# 
#         return [group]
# 
# Path: shared_schema_tenants/helpers/tenant_relationships.py
# def create_relationship(tenant, user, groups=[], permissions=[]):
#     with transaction.atomic():
#         relationship = TenantRelationship.objects.create(user=user, tenant=tenant)
#         for group in groups:
#             relationship.groups.add(group)
#         for perm in permissions:
#             relationship.permissions.add(perm)
# 
#         return relationship


from rest_framework.test import APITestCase
from rest_framework import status
from django.contrib.auth.models import User
from model_mommy import mommy
from shared_schema_tenants.models import Tenant, TenantSite
from shared_schema_tenants.helpers.tenants import set_current_tenant, create_default_tenant_groups
from shared_schema_tenants.helpers.tenant_relationships import create_relationship
    from django.urls import reverse
    from django.core.urlresolvers import reverse

    def test_list(self):
        response = self.client.get(self.view_url, HTTP_TENANT_SLUG=self.tenants[0].slug)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_create(self):
        response = self.client.post(self.view_url, self.params, HTTP_TENANT_SLUG=self.tenants[0].slug)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_create_invalid_extra_data(self):
        self.params['extra_data']['logo'] = 'test'
        response = self.client.post(self.view_url, self.params, HTTP_TENANT_SLUG=self.tenants[0].slug)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_create_empty_extra_data(self):
        self.params['extra_data'] = {}
        response = self.client.post(self.view_url, self.params, HTTP_TENANT_SLUG=self.tenants[0].slug)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)


class TenantDetailsViewTests(APITestCase):

    def setUp(self):
        self.tenants = mommy.make('shared_schema_tenants.Tenant', _quantity=10)
        set_current_tenant(self.tenants[0].slug)
        self.user = User.objects.create_user(
            first_name='test', last_name='test',
            username='test', email='test@sharedschematenants.com',
            password='test')
        groups = create_default_tenant_groups()

# Path: shared_schema_tenants/models.py
# class Tenant(TimeStampedModel):
#     name = models.CharField(max_length=255)
#     slug = models.CharField(max_length=255, primary_key=True)
# 
#     if 'postgresql' in django_settings.DATABASES['default']['ENGINE']:
#         from django.contrib.postgres.fields import JSONField
#         extra_data = JSONField(blank=True, null=True,
#                                default=get_setting('DEFAULT_TENANT_EXTRA_DATA'))
#         settings = JSONField(blank=True, null=True,
#                              default=get_setting('DEFAULT_TENANT_SETTINGS'))
#     else:
#         _extra_data = models.TextField(blank=True, null=True,
#                                        validators=[validate_json],
#                                        default=json.dumps(get_setting('DEFAULT_TENANT_EXTRA_DATA')))
#         _settings = models.TextField(blank=True, null=True,
#                                      validators=[validate_json],
#                                      default=json.dumps(get_setting('DEFAULT_TENANT_SETTINGS')))
# 
#         @property
#         def extra_data(self):
#             import json
#             return json.loads(self._extra_data)
# 
#         @extra_data.setter
#         def extra_data(self, value):
#             import json
#             self._extra_data = json.dumps(value)
# 
#         @property
#         def settings(self):
#             import json
#             return json.loads(self._settings)
# 
#         @settings.setter
#         def settings(self, value):
#             import json
#             self._settings = json.dumps(value)
# 
#     def __str__(self):
#         return self.name
# 
# class TenantSite(TimeStampedModel, SingleTenantModelMixin):
#     tenant = models.ForeignKey('Tenant', related_name="tenant_sites")
#     site = models.OneToOneField(Site, related_name="tenant_site")
# 
#     def __str__(self):
#         return '%s - %s' % (self.tenant.name, self.site.domain)
# 
# Path: shared_schema_tenants/helpers/tenants.py
# def set_current_tenant(tenant_slug):
#     from shared_schema_tenants.middleware import TenantMiddleware
#     return TenantMiddleware.set_tenant(tenant_slug)
# 
# def create_default_tenant_groups():
#     with transaction.atomic():
#         group, created = Group.objects.get_or_create(name='tenant_owner')
# 
#         if created:
#             for perm in get_setting('DEFAULT_TENANT_OWNER_PERMISSIONS'):
#                 try:
#                     group.permissions.add(Permission.objects.get(
#                         content_type__app_label=perm.split('.')[0],
#                         codename=perm.split('.')[1]))
#                 except Permission.DoesNotExist:
#                     pass
# 
#         return [group]
# 
# Path: shared_schema_tenants/helpers/tenant_relationships.py
# def create_relationship(tenant, user, groups=[], permissions=[]):
#     with transaction.atomic():
#         relationship = TenantRelationship.objects.create(user=user, tenant=tenant)
#         for group in groups:
#             relationship.groups.add(group)
#         for perm in permissions:
#             relationship.permissions.add(perm)
# 
#         return relationship


# Path: shared_schema_tenants/tests/test_views.py
from rest_framework.test import APITestCase
from rest_framework import status
from django.contrib.auth.models import User
from model_mommy import mommy
from shared_schema_tenants.models import Tenant, TenantSite
from shared_schema_tenants.helpers.tenants import set_current_tenant, create_default_tenant_groups
from shared_schema_tenants.helpers.tenant_relationships import create_relationship
    from django.urls import reverse
    from django.core.urlresolvers import reverse


    def test_list(self):
        response = self.client.get(self.view_url, HTTP_TENANT_SLUG=self.tenants[0].slug)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_create(self):
        response = self.client.post(self.view_url, self.params, HTTP_TENANT_SLUG=self.tenants[0].slug)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_create_invalid_extra_data(self):
        self.params['extra_data']['logo'] = 'test'
        response = self.client.post(self.view_url, self.params, HTTP_TENANT_SLUG=self.tenants[0].slug)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_create_empty_extra_data(self):
        self.params['extra_data'] = {}
        response = self.client.post(self.view_url, self.params, HTTP_TENANT_SLUG=self.tenants[0].slug)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)


class TenantDetailsViewTests(APITestCase):

    def setUp(self):
        self.tenants = mommy.make('shared_schema_tenants.Tenant', _quantity=10)
        set_current_tenant(self.tenants[0].slug)
        self.user = User.objects.create_user(
            first_name='test', last_name='test',
            username='test', email='test@sharedschematenants.com',
            password='test')
        groups = create_default_tenant_groups()

        create_relationship(self.tenants[0], self.user, groups)