# Path: tutelary/mixins.py
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
#     """Permission checking mixin for Django Rest Framework -- works just
#     like the ``PermissionRequiredMixin`` in the default Django
#     authentication system.
# 
#     """
#     def check_permissions(self, request):
#         """Permission checking for DRF."""
#         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 len(objs) == 0:
#                 objs = [None]
# 
#         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)
#         else:
#             has_perm = check_perms(self.request.user,
#                                    self.get_permission_required(),
#                                    objs, self.request.method)
# 
#             if not has_perm:
#                 msg = self.get_permission_denied_message(
#                     default="Permission denied."
#                 )
#                 if isinstance(msg, Sequence):
#                     msg = msg[0]
#                 self.permission_denied(request, message=msg)
# 
#     def initial(self, request, *args, **kwargs):
#         self.check_permissions(request)
#         return super().initial(request, *args, **kwargs)
# 
# class PermissionsFilterMixin:
#     def dispatch(self, request, *args, **kwargs):
#         permissions = request.GET.get('permissions', None)
#         if permissions:
#             actions = tuple(permissions.split(','))
# 
#             if (hasattr(self, 'permission_filter_queryset') and
#                     isinstance(self.permission_filter_queryset, Sequence)):
#                 actions += tuple(self.permission_filter_queryset)
# 
#             self.permission_filter_queryset = actions
# 
#         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 rest_framework import serializers
from tutelary.mixins import APIPermissionRequiredMixin, PermissionsFilterMixin
from rest_framework.test import APIRequestFactory, force_authenticate
from .factories import UserFactory, PolicyFactory
from .datadir import datadir  # noqa
from .filter_models import Org, Proj
import rest_framework.generics as generics
import pytest
    assert project_count(view(r2).render()) == 1
    assert project_count(view(r3).render()) == 2
    assert project_count(view(r4).render()) == 0
    assert project_count(view(r5).render()) == 0


def test_detail_delete_filter_listing(datadir, setup):  # noqa
    users, pols, orgs, projs = setup
    r1, r2, r3, r4, r5 = map(lambda u: api_get('/projs', u), users)

    view = DetailDeleteProjList().as_view(objects=projs)
    assert project_count(view(r1).render()) == 10
    assert project_count(view(r2).render()) == 1
    assert project_count(view(r3).render()) == 2
    assert project_count(view(r4).render()) == 0
    assert project_count(view(r5).render()) == 0


def test_detail_with_private_filter_listing(datadir, setup):  # noqa
    users, pols, orgs, projs = setup
    r1, r2, r3, r4, r5 = map(lambda u: api_get('/projs', u), users)

    view = DetailWithPrivateProjList().as_view(objects=projs)
    assert project_count(view(r1).render()) == 8
    assert project_count(view(r2).render()) == 3
    assert project_count(view(r3).render()) == 2
    assert project_count(view(r4).render()) == 0
    assert project_count(view(r5).render()) == 6



# Path: tutelary/mixins.py
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
#     """Permission checking mixin for Django Rest Framework -- works just
#     like the ``PermissionRequiredMixin`` in the default Django
#     authentication system.
# 
#     """
#     def check_permissions(self, request):
#         """Permission checking for DRF."""
#         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 len(objs) == 0:
#                 objs = [None]
# 
#         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)
#         else:
#             has_perm = check_perms(self.request.user,
#                                    self.get_permission_required(),
#                                    objs, self.request.method)
# 
#             if not has_perm:
#                 msg = self.get_permission_denied_message(
#                     default="Permission denied."
#                 )
#                 if isinstance(msg, Sequence):
#                     msg = msg[0]
#                 self.permission_denied(request, message=msg)
# 
#     def initial(self, request, *args, **kwargs):
#         self.check_permissions(request)
#         return super().initial(request, *args, **kwargs)
# 
# class PermissionsFilterMixin:
#     def dispatch(self, request, *args, **kwargs):
#         permissions = request.GET.get('permissions', None)
#         if permissions:
#             actions = tuple(permissions.split(','))
# 
#             if (hasattr(self, 'permission_filter_queryset') and
#                     isinstance(self.permission_filter_queryset, Sequence)):
#                 actions += tuple(self.permission_filter_queryset)
# 
#             self.permission_filter_queryset = actions
# 
#         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_drf_filtering.py
from rest_framework import serializers
from tutelary.mixins import APIPermissionRequiredMixin, PermissionsFilterMixin
from rest_framework.test import APIRequestFactory, force_authenticate
from .factories import UserFactory, PolicyFactory
from .datadir import datadir  # noqa
from .filter_models import Org, Proj
import rest_framework.generics as generics
import pytest

    assert project_count(view(r2).render()) == 1
    assert project_count(view(r3).render()) == 2
    assert project_count(view(r4).render()) == 0
    assert project_count(view(r5).render()) == 0


def test_detail_delete_filter_listing(datadir, setup):  # noqa
    users, pols, orgs, projs = setup
    r1, r2, r3, r4, r5 = map(lambda u: api_get('/projs', u), users)

    view = DetailDeleteProjList().as_view(objects=projs)
    assert project_count(view(r1).render()) == 10
    assert project_count(view(r2).render()) == 1
    assert project_count(view(r3).render()) == 2
    assert project_count(view(r4).render()) == 0
    assert project_count(view(r5).render()) == 0


def test_detail_with_private_filter_listing(datadir, setup):  # noqa
    users, pols, orgs, projs = setup
    r1, r2, r3, r4, r5 = map(lambda u: api_get('/projs', u), users)

    view = DetailWithPrivateProjList().as_view(objects=projs)
    assert project_count(view(r1).render()) == 8
    assert project_count(view(r2).render()) == 3
    assert project_count(view(r3).render()) == 2
    assert project_count(view(r4).render()) == 0
    assert project_count(view(r5).render()) == 6



def test_permission_normal_listing_without_filter(datadir, setup):  # noqa