# Path: shared_schema_tenants/middleware.py
# class TenantMiddleware(object):
#     _threadmap = {}
# 
#     def __init__(self, get_response):
#         self.get_response = get_response
#         # One-time configuration and initialization.
# 
#     @classmethod
#     def get_current_tenant(cls):
#         try:
#             return cls._threadmap[threading.get_ident()]
#         except KeyError:
#             return None
# 
#     @classmethod
#     def set_tenant(cls, tenant_slug):
#         cls._threadmap[threading.get_ident()] = SimpleLazyObject(
#             lambda: Tenant.objects.filter(slug=tenant_slug).first())
# 
#     @classmethod
#     def clear_tenant(cls):
#         del cls._threadmap[threading.get_ident()]
# 
#     def process_request(self, request):
#         request.tenant = SimpleLazyObject(lambda: get_tenant(request))
#         self._threadmap[threading.get_ident()] = request.tenant
# 
#         return request
# 
#     def process_exception(self, request, exception):
#         try:
#             del self._threadmap[threading.get_ident()]
#         except KeyError:
#             pass
# 
#     def process_response(self, request, response):
#         try:
#             del self._threadmap[threading.get_ident()]
#         except KeyError:
#             pass
#         return response
# 
#     def __call__(self, request):
#         # Code to be executed for each request before
#         # the view (and later middleware) are called.
#         request = self.process_request(request)
#         response = self.get_response(request)
#         return self.process_response(request, response)
# 
# def get_tenant(request):
#     if not hasattr(request, '_cached_tenant'):
#         tenant_retrievers = get_setting('TENANT_RETRIEVERS')
# 
#         for tenant_retriever in tenant_retrievers:
#             tenant = import_from_string(tenant_retriever)(request)
#             if tenant:
#                 request._cached_tenant = tenant
#                 break
# 
#         if not getattr(request, '_cached_tenant', False):
#             lazy_tenant = TenantMiddleware.get_current_tenant()
#             if not lazy_tenant:
#                 return None
# 
#             lazy_tenant._setup()
#             request._cached_tenant = lazy_tenant._wrapped
# 
#         elif get_setting('ADD_TENANT_TO_SESSION'):
#             try:
#                 request.session['tenant_slug'] = request._cached_tenant.slug
#             except AttributeError:
#                 pass
# 
#     return request._cached_tenant
# 
# Path: shared_schema_tenants/helpers/tenants.py
# def create_tenant(name, slug, extra_data, domains=[], user=None):
#     from shared_schema_tenants.models import Tenant
#     with transaction.atomic():
#         tenant = Tenant.objects.create(
#             name=name, slug=slug, extra_data=extra_data)
# 
#         if len(domains) > 0:
#             for domain in domains:
#                 site = Site.objects.create(name=name, domain=domain)
#                 tenant.tenant_sites.create(site=site)
# 
#         if user:
#             rel = tenant.relationships.create(user=user)
#             rel.groups.add(create_default_tenant_groups()[0])
# 
#         return tenant
# 
# def set_current_tenant(tenant_slug):
#     from shared_schema_tenants.middleware import TenantMiddleware
#     return TenantMiddleware.set_tenant(tenant_slug)
# 
# Path: shared_schema_tenants/exceptions.py
# class TenantNotFoundError(Exception):
# 
#     def __init__(self, message="Tenant with this slug couldn't be found", errors=[]):
#         super(TenantNotFoundError, self).__init__(message)


import mock
from django.test import TestCase, RequestFactory
from django.http import HttpResponse
from shared_schema_tenants.middleware import TenantMiddleware, get_tenant
from shared_schema_tenants.helpers.tenants import create_tenant, set_current_tenant
from shared_schema_tenants.exceptions import TenantNotFoundError
    from django.urls import reverse
    from django.core.urlresolvers import reverse
        request = factory.get(reverse('shared_schema_tenants:tenant_list'), HTTP_HOST='test.localhost:8000')
        response = HttpResponse()
        request = TenantMiddleware(lambda r: response).process_request(request)

        self.assertEqual(request.tenant.slug, tenant.slug)
        get_tenant.assert_called_once()

    def test_call_returns_correct_response(self):
        tenant = create_tenant(name='test', slug='test', extra_data={}, domains=['test.localhost:8000'])
        get_tenant.return_value = tenant
        factory = RequestFactory()
        request = factory.get(reverse('shared_schema_tenants:tenant_list'), HTTP_HOST='test.localhost:8000')

        response = HttpResponse()
        processed_response = TenantMiddleware(lambda r: response).__call__(request)

        self.assertEqual(response, processed_response)


class GetTenantTests(TestCase):

    def test_with_correct_domain(self):
        tenant = create_tenant(name='test', slug='test', extra_data={}, domains=['test.localhost:8000'])
        factory = RequestFactory()
        request = factory.get(reverse('shared_schema_tenants:tenant_list'), HTTP_HOST='test.localhost:8000')
        retrieved_tenant = get_tenant(request)

        self.assertEqual(retrieved_tenant, tenant)

    def test_with_http_header(self):

# Path: shared_schema_tenants/middleware.py
# class TenantMiddleware(object):
#     _threadmap = {}
# 
#     def __init__(self, get_response):
#         self.get_response = get_response
#         # One-time configuration and initialization.
# 
#     @classmethod
#     def get_current_tenant(cls):
#         try:
#             return cls._threadmap[threading.get_ident()]
#         except KeyError:
#             return None
# 
#     @classmethod
#     def set_tenant(cls, tenant_slug):
#         cls._threadmap[threading.get_ident()] = SimpleLazyObject(
#             lambda: Tenant.objects.filter(slug=tenant_slug).first())
# 
#     @classmethod
#     def clear_tenant(cls):
#         del cls._threadmap[threading.get_ident()]
# 
#     def process_request(self, request):
#         request.tenant = SimpleLazyObject(lambda: get_tenant(request))
#         self._threadmap[threading.get_ident()] = request.tenant
# 
#         return request
# 
#     def process_exception(self, request, exception):
#         try:
#             del self._threadmap[threading.get_ident()]
#         except KeyError:
#             pass
# 
#     def process_response(self, request, response):
#         try:
#             del self._threadmap[threading.get_ident()]
#         except KeyError:
#             pass
#         return response
# 
#     def __call__(self, request):
#         # Code to be executed for each request before
#         # the view (and later middleware) are called.
#         request = self.process_request(request)
#         response = self.get_response(request)
#         return self.process_response(request, response)
# 
# def get_tenant(request):
#     if not hasattr(request, '_cached_tenant'):
#         tenant_retrievers = get_setting('TENANT_RETRIEVERS')
# 
#         for tenant_retriever in tenant_retrievers:
#             tenant = import_from_string(tenant_retriever)(request)
#             if tenant:
#                 request._cached_tenant = tenant
#                 break
# 
#         if not getattr(request, '_cached_tenant', False):
#             lazy_tenant = TenantMiddleware.get_current_tenant()
#             if not lazy_tenant:
#                 return None
# 
#             lazy_tenant._setup()
#             request._cached_tenant = lazy_tenant._wrapped
# 
#         elif get_setting('ADD_TENANT_TO_SESSION'):
#             try:
#                 request.session['tenant_slug'] = request._cached_tenant.slug
#             except AttributeError:
#                 pass
# 
#     return request._cached_tenant
# 
# Path: shared_schema_tenants/helpers/tenants.py
# def create_tenant(name, slug, extra_data, domains=[], user=None):
#     from shared_schema_tenants.models import Tenant
#     with transaction.atomic():
#         tenant = Tenant.objects.create(
#             name=name, slug=slug, extra_data=extra_data)
# 
#         if len(domains) > 0:
#             for domain in domains:
#                 site = Site.objects.create(name=name, domain=domain)
#                 tenant.tenant_sites.create(site=site)
# 
#         if user:
#             rel = tenant.relationships.create(user=user)
#             rel.groups.add(create_default_tenant_groups()[0])
# 
#         return tenant
# 
# def set_current_tenant(tenant_slug):
#     from shared_schema_tenants.middleware import TenantMiddleware
#     return TenantMiddleware.set_tenant(tenant_slug)
# 
# Path: shared_schema_tenants/exceptions.py
# class TenantNotFoundError(Exception):
# 
#     def __init__(self, message="Tenant with this slug couldn't be found", errors=[]):
#         super(TenantNotFoundError, self).__init__(message)


# Path: shared_schema_tenants/tests/test_middlewares.py
import mock
from django.test import TestCase, RequestFactory
from django.http import HttpResponse
from shared_schema_tenants.middleware import TenantMiddleware, get_tenant
from shared_schema_tenants.helpers.tenants import create_tenant, set_current_tenant
from shared_schema_tenants.exceptions import TenantNotFoundError
    from django.urls import reverse
    from django.core.urlresolvers import reverse

        request = factory.get(reverse('shared_schema_tenants:tenant_list'), HTTP_HOST='test.localhost:8000')
        response = HttpResponse()
        request = TenantMiddleware(lambda r: response).process_request(request)

        self.assertEqual(request.tenant.slug, tenant.slug)
        get_tenant.assert_called_once()

    def test_call_returns_correct_response(self):
        tenant = create_tenant(name='test', slug='test', extra_data={}, domains=['test.localhost:8000'])
        get_tenant.return_value = tenant
        factory = RequestFactory()
        request = factory.get(reverse('shared_schema_tenants:tenant_list'), HTTP_HOST='test.localhost:8000')

        response = HttpResponse()
        processed_response = TenantMiddleware(lambda r: response).__call__(request)

        self.assertEqual(response, processed_response)


class GetTenantTests(TestCase):

    def test_with_correct_domain(self):
        tenant = create_tenant(name='test', slug='test', extra_data={}, domains=['test.localhost:8000'])
        factory = RequestFactory()
        request = factory.get(reverse('shared_schema_tenants:tenant_list'), HTTP_HOST='test.localhost:8000')
        retrieved_tenant = get_tenant(request)

        self.assertEqual(retrieved_tenant, tenant)

    def test_with_http_header(self):

        tenant = create_tenant(name='test', slug='test', extra_data={}, domains=['test.localhost:8000'])