# Path: shared_schema_tenants/serializers.py
# class TenantSerializer(serializers.ModelSerializer):
#     extra_data = serializers.JSONField()
# 
#     class Meta:
#         model = Tenant
#         fields = ['name', 'slug', 'extra_data']
# 
#     def validate_extra_data(self, extra_data):
#         extra_data_helper = TenantExtraDataHelper()
#         try:
#             validated_extra_data = extra_data_helper.validate_fields(
#                 self.context, extra_data, partial=self.partial)
#         except ValidationError as e:
#             raise serializers.ValidationError(e.message_dict)
#         else:
#             return validated_extra_data
# 
#     def create(self, validated_data):
#         return create_tenant(user=self.context['request'].user, **validated_data)
# 
#     def update(self, instance, validated_data):
#         return update_tenant(instance, **validated_data)
# 
# class TenantSettingsSerializer(serializers.Serializer):
# 
#     def is_valid(self, raise_exception=False):
#         settings_helper = TenantSettingsHelper()
#         try:
#             self._validated_data = settings_helper.validate_fields(
#                 self.context, self.initial_data, self.partial)
#         except ValidationError as exc:
#             self._validated_data = {}
#             self._errors = exc.detail
#         else:
#             self._errors = {}
# 
#         if self._errors and raise_exception:
#             raise ValidationError(self.errors)
# 
#         return not bool(self._errors)
# 
#     def create(self, validated_data):
#         settings_helper = TenantSettingsHelper()
#         instance = settings_helper.update_fields(self.validated_data, partial=self.partial)
#         return instance
# 
#     def to_representation(self, obj):
#         return obj.settings
# 
# class TenantSiteSerializer(serializers.Serializer):
#     id = serializers.IntegerField(read_only=True)
#     domain = serializers.CharField(required=True)
# 
#     def to_representation(self, instance):
#         if instance:
#             return {'id': instance.id, 'domain': instance.site.domain}
#         return None
# 
#     def validate_domain(self, domain):
#         if Site.objects.filter(domain=domain).exists():
#             raise ValidationError(_((
#                 'This domain is already being used '
#                 'by another organization')))
# 
#         return domain
# 
#     def create(self, validated_data):
#         tenant = get_current_tenant()
#         domain = validated_data['domain']
# 
#         with transaction.atomic():
#             site = Site.objects.create(name=domain, domain=domain)
#             return TenantSite.objects.create(tenant=tenant, site=site)
# 
# 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
# 
# 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)


from django.test import TestCase, RequestFactory
from django.contrib.auth.models import User
from model_mommy import mommy
from shared_schema_tenants.serializers import (
    TenantSerializer, TenantSettingsSerializer, TenantSiteSerializer)
from shared_schema_tenants.models import Tenant
from shared_schema_tenants.helpers.tenants import set_current_tenant
    from django.urls import reverse
    from django.core.urlresolvers import reverse
        self.assertEqual(tenant.extra_data['number_of_employees'], 10)


class TenantSiteSerializerTests(TestCase):

    def setUp(self):
        self.tenant = mommy.make('shared_schema_tenants.Tenant')
        self.user = User.objects.create_user(
            first_name='test', last_name='test',
            username='test', email='test@sharedschematenants.com',
            password='test')
        self.tenant_site = mommy.make('shared_schema_tenants.TenantSite',
                                      tenant=self.tenant)

        self.params = {
            'domain': 'sharedschematenants.com'
        }
        set_current_tenant(self.tenant.slug)

    def test_serialize(self):
        data = TenantSiteSerializer(self.tenant_site).data
        keys = ['id', 'domain']
        try:
            self.assertCountEqual(data.keys(), keys)
        except AttributeError:
            self.assertEqual(len(data.keys()), len(keys))
            for key in keys:
                self.assertTrue(key in data.keys())

    def test_create(self):

# Path: shared_schema_tenants/serializers.py
# class TenantSerializer(serializers.ModelSerializer):
#     extra_data = serializers.JSONField()
# 
#     class Meta:
#         model = Tenant
#         fields = ['name', 'slug', 'extra_data']
# 
#     def validate_extra_data(self, extra_data):
#         extra_data_helper = TenantExtraDataHelper()
#         try:
#             validated_extra_data = extra_data_helper.validate_fields(
#                 self.context, extra_data, partial=self.partial)
#         except ValidationError as e:
#             raise serializers.ValidationError(e.message_dict)
#         else:
#             return validated_extra_data
# 
#     def create(self, validated_data):
#         return create_tenant(user=self.context['request'].user, **validated_data)
# 
#     def update(self, instance, validated_data):
#         return update_tenant(instance, **validated_data)
# 
# class TenantSettingsSerializer(serializers.Serializer):
# 
#     def is_valid(self, raise_exception=False):
#         settings_helper = TenantSettingsHelper()
#         try:
#             self._validated_data = settings_helper.validate_fields(
#                 self.context, self.initial_data, self.partial)
#         except ValidationError as exc:
#             self._validated_data = {}
#             self._errors = exc.detail
#         else:
#             self._errors = {}
# 
#         if self._errors and raise_exception:
#             raise ValidationError(self.errors)
# 
#         return not bool(self._errors)
# 
#     def create(self, validated_data):
#         settings_helper = TenantSettingsHelper()
#         instance = settings_helper.update_fields(self.validated_data, partial=self.partial)
#         return instance
# 
#     def to_representation(self, obj):
#         return obj.settings
# 
# class TenantSiteSerializer(serializers.Serializer):
#     id = serializers.IntegerField(read_only=True)
#     domain = serializers.CharField(required=True)
# 
#     def to_representation(self, instance):
#         if instance:
#             return {'id': instance.id, 'domain': instance.site.domain}
#         return None
# 
#     def validate_domain(self, domain):
#         if Site.objects.filter(domain=domain).exists():
#             raise ValidationError(_((
#                 'This domain is already being used '
#                 'by another organization')))
# 
#         return domain
# 
#     def create(self, validated_data):
#         tenant = get_current_tenant()
#         domain = validated_data['domain']
# 
#         with transaction.atomic():
#             site = Site.objects.create(name=domain, domain=domain)
#             return TenantSite.objects.create(tenant=tenant, site=site)
# 
# 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
# 
# 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)


# Path: shared_schema_tenants/tests/test_serializers.py
from django.test import TestCase, RequestFactory
from django.contrib.auth.models import User
from model_mommy import mommy
from shared_schema_tenants.serializers import (
    TenantSerializer, TenantSettingsSerializer, TenantSiteSerializer)
from shared_schema_tenants.models import Tenant
from shared_schema_tenants.helpers.tenants import set_current_tenant
    from django.urls import reverse
    from django.core.urlresolvers import reverse

        self.assertEqual(tenant.extra_data['number_of_employees'], 10)


class TenantSiteSerializerTests(TestCase):

    def setUp(self):
        self.tenant = mommy.make('shared_schema_tenants.Tenant')
        self.user = User.objects.create_user(
            first_name='test', last_name='test',
            username='test', email='test@sharedschematenants.com',
            password='test')
        self.tenant_site = mommy.make('shared_schema_tenants.TenantSite',
                                      tenant=self.tenant)

        self.params = {
            'domain': 'sharedschematenants.com'
        }
        set_current_tenant(self.tenant.slug)

    def test_serialize(self):
        data = TenantSiteSerializer(self.tenant_site).data
        keys = ['id', 'domain']
        try:
            self.assertCountEqual(data.keys(), keys)
        except AttributeError:
            self.assertEqual(len(data.keys()), len(keys))
            for key in keys:
                self.assertTrue(key in data.keys())

    def test_create(self):

        serializer = TenantSiteSerializer(data=self.params)