# Path: tutelary/engine.py
# class Action(SimpleSeparated):
#     """Actions are represented by period-separated sequences of elements
#     (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
#     elements indicated by ``*`` (e.g. ``party.*``).  A list of
#     *registered* actions is maintained to support permissions set
#     queries to find the set of actions that are permitted on a
#     specified object pattern.
# 
#     """
#     separator = '.'
# 
#     registered = set()
# 
#     def register(action):
#         """Action registration is used to support generating lists of
#         permitted actions from a permission set and an object pattern.
#         Only registered actions will be returned by such queries.
# 
#         """
#         if isinstance(action, str):
#             Action.register(Action(action))
#         elif isinstance(action, Action):
#             Action.registered.add(action)
#         else:
#             for a in action:
#                 Action.register(a)
# 
# 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)
# 
# 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/check_models.py
# class CheckModel1(models.Model):
#     name = models.CharField(max_length=100)
# 
#     class TutelaryMeta:
#         perm_type = 'check'
#         path_fields = ('name',)
#         actions = [('check.list', {'permissions_object': None}),
#                    ('check.create', {'permissions_object': None}),
#                    ('check.detail',
#                     {'error_message': 'detail view not allowed'}),
#                    'check.delete']
# 
#     def __str__(self):
#         return self.name
# 
# class CheckModel2(models.Model):
#     name = models.CharField(max_length=100)
#     container = models.ForeignKey(CheckModel1)
# 
#     def __str__(self):
#         return self.name
# 
# class CheckModel4(models.Model):
#     name = models.CharField(max_length=100)
# 
#     def __str__(self):
#         return self.name
# 
#     class TutelaryMeta:
#         perm_type = 'check4'
#         path_fields = ('name',)
#         actions = [('check4.list', {'permissions_object': None}),
#                    ('check4.create', {'permissions_object': None}),
#                    'check4.detail',
#                    'check4.delete']
# 
# class CheckModel5(models.Model):
#     name = models.CharField(max_length=100)
# 
#     def __str__(self):
#         return self.name
# 
#     class TutelaryMeta:
#         perm_type = 'check5'
#         path_fields = ('name',)
#         actions = ['check5.detail', 'check5.delete']


from django.core.exceptions import ImproperlyConfigured
from django.http.response import Http404
from rest_framework.exceptions import PermissionDenied
from rest_framework.test import APIRequestFactory, force_authenticate
from tutelary.engine import Action
from tutelary.mixins import APIPermissionRequiredMixin
from .factories import UserFactory, PolicyFactory
from .datadir import datadir  # noqa
from .check_models import CheckModel1, CheckModel2, CheckModel4, CheckModel5
import rest_framework.generics as generic
import pytest





@pytest.fixture(scope="function")  # noqa
def setup(datadir, db):
    user1 = UserFactory.create(username='user1')
    user2 = UserFactory.create(username='user2')

    PolicyFactory.set_directory(str(datadir))
    pol1 = PolicyFactory.create(name='pol1', file='policy-1.json')

# Path: tutelary/engine.py
# class Action(SimpleSeparated):
#     """Actions are represented by period-separated sequences of elements
#     (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
#     elements indicated by ``*`` (e.g. ``party.*``).  A list of
#     *registered* actions is maintained to support permissions set
#     queries to find the set of actions that are permitted on a
#     specified object pattern.
# 
#     """
#     separator = '.'
# 
#     registered = set()
# 
#     def register(action):
#         """Action registration is used to support generating lists of
#         permitted actions from a permission set and an object pattern.
#         Only registered actions will be returned by such queries.
# 
#         """
#         if isinstance(action, str):
#             Action.register(Action(action))
#         elif isinstance(action, Action):
#             Action.registered.add(action)
#         else:
#             for a in action:
#                 Action.register(a)
# 
# 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)
# 
# 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/check_models.py
# class CheckModel1(models.Model):
#     name = models.CharField(max_length=100)
# 
#     class TutelaryMeta:
#         perm_type = 'check'
#         path_fields = ('name',)
#         actions = [('check.list', {'permissions_object': None}),
#                    ('check.create', {'permissions_object': None}),
#                    ('check.detail',
#                     {'error_message': 'detail view not allowed'}),
#                    'check.delete']
# 
#     def __str__(self):
#         return self.name
# 
# class CheckModel2(models.Model):
#     name = models.CharField(max_length=100)
#     container = models.ForeignKey(CheckModel1)
# 
#     def __str__(self):
#         return self.name
# 
# class CheckModel4(models.Model):
#     name = models.CharField(max_length=100)
# 
#     def __str__(self):
#         return self.name
# 
#     class TutelaryMeta:
#         perm_type = 'check4'
#         path_fields = ('name',)
#         actions = [('check4.list', {'permissions_object': None}),
#                    ('check4.create', {'permissions_object': None}),
#                    'check4.detail',
#                    'check4.delete']
# 
# class CheckModel5(models.Model):
#     name = models.CharField(max_length=100)
# 
#     def __str__(self):
#         return self.name
# 
#     class TutelaryMeta:
#         perm_type = 'check5'
#         path_fields = ('name',)
#         actions = ['check5.detail', 'check5.delete']


# Path: tests/test_drf_interface.py
from django.core.exceptions import ImproperlyConfigured
from django.http.response import Http404
from rest_framework.exceptions import PermissionDenied
from rest_framework.test import APIRequestFactory, force_authenticate
from tutelary.engine import Action
from tutelary.mixins import APIPermissionRequiredMixin
from .factories import UserFactory, PolicyFactory
from .datadir import datadir  # noqa
from .check_models import CheckModel1, CheckModel2, CheckModel4, CheckModel5
import rest_framework.generics as generic
import pytest






@pytest.fixture(scope="function")  # noqa
def setup(datadir, db):
    user1 = UserFactory.create(username='user1')
    user2 = UserFactory.create(username='user2')

    PolicyFactory.set_directory(str(datadir))
    pol1 = PolicyFactory.create(name='pol1', file='policy-1.json')

    pol2 = PolicyFactory.create(name='pol2', file='policy-2.json')