# Path: tutelary/mixins.py
# class PermissionRequiredMixin(BasePermissionRequiredMixin):
#     """Permission checking mixin -- works just like the
#     ``PermissionRequiredMixin`` in the default Django authentication
#     system.
# 
#     """
#     def has_permission(self):
#         """Permission checking for "normal" Django."""
#         objs = [None]
#         if hasattr(self, 'get_perms_objects'):
#             objs = self.get_perms_objects()
#         else:
#             if hasattr(self, 'get_object'):
#                 try:
#                     objs = [self.get_object()]
#                 except Http404:
#                     raise
#                 except:
#                     pass
#             if objs == [None]:
#                 objs = self.get_queryset()
# 
#         if (hasattr(self, 'permission_filter_queryset') and
#            self.permission_filter_queryset is not False and
#            self.request.method == 'GET'):
#             if objs != [None]:
#                 self.perms_filter_queryset(objs)
#             return True
#         else:
#             return check_perms(self.request.user,
#                                self.get_permission_required(),
#                                objs, self.request.method)
# 
#     def handle_no_permission(self):
#         msg = self.get_permission_denied_message()
#         if hasattr(self, 'raise_exception') and self.raise_exception:
#             raise PermissionDenied(*msg)
#         return msg
# 
#     def dispatch(self, request, *args, **kwargs):
#         if not self.has_permission():
#             return self.handle_no_permission()
#         return super().dispatch(request, *args, **kwargs)
# 
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
#     class Meta:
#         model = User
# 
# class PolicyFactory(factory.django.DjangoModelFactory):
#     class Meta:
#         model = Policy
# 
#     @classmethod
#     def set_directory(cls, dir):
#         cls.directory = dir
# 
#     @classmethod
#     def _adjust_kwargs(cls, **kwargs):
#         body_file = os.path.join(cls.directory, kwargs.pop('file', None))
#         kwargs['body'] = open(body_file).read()
#         return kwargs
# 
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
#     """
#     Fixture responsible for searching a folder with the same name of test
#     module and, if available, moving all contents to a temporary directory so
#     tests can use them freely.
# 
#     Adapted from http://stackoverflow.com/questions/29627341
#     """
#     test_dir = py.path.local(request.module.__file__).new(ext='')
#     try:
#         for f in test_dir.listdir():
#             f.copy(tmpdir)
#     except:
#         pass
#     return tmpdir
# 
# Path: tests/filter_models.py
# class Org(models.Model):
#     name = models.CharField(max_length=100)
# 
#     class TutelaryMeta:
#         perm_type = 'org'
#         path_fields = ('name',)
#         actions = [('org.list', {'permissions_object': None})]
# 
# class Proj(models.Model):
#     name = models.CharField(max_length=100)
#     org = models.ForeignKey(Org)
#     public = models.BooleanField(default=True)
# 
#     class TutelaryMeta:
#         perm_type = 'proj'
#         path_fields = ('org', 'name',)
#         actions = [('proj.list', {'permissions_object': 'org'}),
#                    'proj.detail',
#                    'proj.detail_private',
#                    'proj.delete']


from django.core.exceptions import PermissionDenied
from tutelary.mixins import PermissionRequiredMixin
from django.test import RequestFactory
from .factories import UserFactory, PolicyFactory
from .datadir import datadir  # noqa
from .filter_models import Org, Proj
import django.views.generic as generic
import pytest
#   org1/proj1       X  X
#   org1/proj2       X
#   org1/proj3       X
#   org1/proj4       X
#   org1/proj5       X
#   org1/proj6       X
#   org1/proj7       X
#   org2/proj8       X     X
#   org2/proj9       X     X
#   org2/proj10      X

@pytest.fixture(scope="function")  # noqa
def setup(datadir, db):
    users = []
    pols = []
    PolicyFactory.set_directory(str(datadir))
    for i in range(1, 6):
        user = UserFactory.create(username='user{}'.format(i))
        pol = PolicyFactory.create(name='pol{}'.format(i),
                                   file='policy-{}.json'.format(i))
        user.assign_policies(pol)
        users.append(user)
        pols.append(pol)

    orgs = []
    for i in range(1, 3):
        orgs.append(Org(pk=i, name='org{}'.format(i)))

    projs = []
    for i in range(1, 11):

# Path: tutelary/mixins.py
# class PermissionRequiredMixin(BasePermissionRequiredMixin):
#     """Permission checking mixin -- works just like the
#     ``PermissionRequiredMixin`` in the default Django authentication
#     system.
# 
#     """
#     def has_permission(self):
#         """Permission checking for "normal" Django."""
#         objs = [None]
#         if hasattr(self, 'get_perms_objects'):
#             objs = self.get_perms_objects()
#         else:
#             if hasattr(self, 'get_object'):
#                 try:
#                     objs = [self.get_object()]
#                 except Http404:
#                     raise
#                 except:
#                     pass
#             if objs == [None]:
#                 objs = self.get_queryset()
# 
#         if (hasattr(self, 'permission_filter_queryset') and
#            self.permission_filter_queryset is not False and
#            self.request.method == 'GET'):
#             if objs != [None]:
#                 self.perms_filter_queryset(objs)
#             return True
#         else:
#             return check_perms(self.request.user,
#                                self.get_permission_required(),
#                                objs, self.request.method)
# 
#     def handle_no_permission(self):
#         msg = self.get_permission_denied_message()
#         if hasattr(self, 'raise_exception') and self.raise_exception:
#             raise PermissionDenied(*msg)
#         return msg
# 
#     def dispatch(self, request, *args, **kwargs):
#         if not self.has_permission():
#             return self.handle_no_permission()
#         return super().dispatch(request, *args, **kwargs)
# 
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
#     class Meta:
#         model = User
# 
# class PolicyFactory(factory.django.DjangoModelFactory):
#     class Meta:
#         model = Policy
# 
#     @classmethod
#     def set_directory(cls, dir):
#         cls.directory = dir
# 
#     @classmethod
#     def _adjust_kwargs(cls, **kwargs):
#         body_file = os.path.join(cls.directory, kwargs.pop('file', None))
#         kwargs['body'] = open(body_file).read()
#         return kwargs
# 
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
#     """
#     Fixture responsible for searching a folder with the same name of test
#     module and, if available, moving all contents to a temporary directory so
#     tests can use them freely.
# 
#     Adapted from http://stackoverflow.com/questions/29627341
#     """
#     test_dir = py.path.local(request.module.__file__).new(ext='')
#     try:
#         for f in test_dir.listdir():
#             f.copy(tmpdir)
#     except:
#         pass
#     return tmpdir
# 
# Path: tests/filter_models.py
# class Org(models.Model):
#     name = models.CharField(max_length=100)
# 
#     class TutelaryMeta:
#         perm_type = 'org'
#         path_fields = ('name',)
#         actions = [('org.list', {'permissions_object': None})]
# 
# class Proj(models.Model):
#     name = models.CharField(max_length=100)
#     org = models.ForeignKey(Org)
#     public = models.BooleanField(default=True)
# 
#     class TutelaryMeta:
#         perm_type = 'proj'
#         path_fields = ('org', 'name',)
#         actions = [('proj.list', {'permissions_object': 'org'}),
#                    'proj.detail',
#                    'proj.detail_private',
#                    'proj.delete']


# Path: tests/test_filtering.py
from django.core.exceptions import PermissionDenied
from tutelary.mixins import PermissionRequiredMixin
from django.test import RequestFactory
from .factories import UserFactory, PolicyFactory
from .datadir import datadir  # noqa
from .filter_models import Org, Proj
import django.views.generic as generic
import pytest

#   org1/proj1       X  X
#   org1/proj2       X
#   org1/proj3       X
#   org1/proj4       X
#   org1/proj5       X
#   org1/proj6       X
#   org1/proj7       X
#   org2/proj8       X     X
#   org2/proj9       X     X
#   org2/proj10      X

@pytest.fixture(scope="function")  # noqa
def setup(datadir, db):
    users = []
    pols = []
    PolicyFactory.set_directory(str(datadir))
    for i in range(1, 6):
        user = UserFactory.create(username='user{}'.format(i))
        pol = PolicyFactory.create(name='pol{}'.format(i),
                                   file='policy-{}.json'.format(i))
        user.assign_policies(pol)
        users.append(user)
        pols.append(pol)

    orgs = []
    for i in range(1, 3):
        orgs.append(Org(pk=i, name='org{}'.format(i)))

    projs = []
    for i in range(1, 11):

        projs.append(Proj(pk=i, name='proj{}'.format(i),