# 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/decorators.py
# def permissioned_model(cls, perm_type=None, path_fields=None, actions=None):
#     """Function to set up a model for permissioning.  Can either be called
#     directly, passing a class and suitable values for ``perm_type``,
#     ``path_fields`` and ``actions``, or can be used as a class
#     decorator, taking values for ``perm_type``, ``path_fields`` and
#     ``actions`` from the ``TutelaryMeta`` subclass of the decorated
#     class.
# 
#     """
#     if not issubclass(cls, models.Model):
#         raise DecoratorException(
#             'permissioned_model',
#             "class '" + cls.__name__ + "' is not a Django model"
#         )
#     added = False
#     try:
#         if not hasattr(cls, 'TutelaryMeta'):
#             if perm_type is None or path_fields is None or actions is None:
#                 raise DecoratorException(
#                     'permissioned_model',
#                     ("missing argument: all of perm_type, path_fields and " +
#                      "actions must be supplied")
#                 )
#             added = True
#             cls.TutelaryMeta = type('TutelaryMeta', (object,),
#                                     dict(perm_type=perm_type,
#                                          path_fields=path_fields,
#                                          actions=actions))
#         cls.TutelaryMeta.pfs = ([cls.TutelaryMeta.perm_type] +
#                                 get_path_fields(cls))
#         perms_objs = {}
#         for a in cls.TutelaryMeta.actions:
#             an = a
#             ap = {}
#             if isinstance(a, tuple):
#                 an = a[0]
#                 ap = a[1]
#             Action.register(an)
#             if isinstance(ap, dict) and 'permissions_object' in ap:
#                 po = ap['permissions_object']
#                 if po is not None:
#                     try:
#                         t = cls._meta.get_field(po).__class__
#                         if t not in [models.ForeignKey,
#                                      models.OneToOneField]:
#                             raise PermissionObjectException(po)
#                     except:
#                         raise PermissionObjectException(po)
#                 perms_objs[an] = po
#         if len(perms_objs) == 0:
#             cls.get_permissions_object = get_perms_object
#         else:
#             cls.get_permissions_object = make_get_perms_object(perms_objs)
#         return cls
#     except:
#         if added:
#             del cls.TutelaryMeta
#         raise
# 
# Path: tutelary/mixins.py
# class BasePermissionRequiredMixin:
# class PermissionRequiredMixin(BasePermissionRequiredMixin):
# class LoginPermissionRequiredMixin(PermissionRequiredMixin,
#                                    LoginRequiredMixin):
# class PermissionsFilterMixin:
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
#     def get_permission_required(self):
#     def get_permission_denied_message(self, default=None):
#     def get_queryset(self):
#     def perms_filter_queryset(self, objs):
#         def check_one(obj):
#     def has_permission(self):
#     def handle_no_permission(self):
#     def dispatch(self, request, *args, **kwargs):
#     def dispatch(self, request, *args, **kwargs):
#     def dispatch(self, request, *args, **kwargs):
#     def check_permissions(self, request):
#     def initial(self, 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


import pytest
import django.views.generic as generic
from tutelary.engine import Action
from tutelary.decorators import permissioned_model
from tutelary import mixins
from django.db import models
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponseRedirect
from django.http.response import Http404
from django.core.exceptions import PermissionDenied
from .factories import UserFactory, PolicyFactory
from .datadir import datadir  # noqa


@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')

# 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/decorators.py
# def permissioned_model(cls, perm_type=None, path_fields=None, actions=None):
#     """Function to set up a model for permissioning.  Can either be called
#     directly, passing a class and suitable values for ``perm_type``,
#     ``path_fields`` and ``actions``, or can be used as a class
#     decorator, taking values for ``perm_type``, ``path_fields`` and
#     ``actions`` from the ``TutelaryMeta`` subclass of the decorated
#     class.
# 
#     """
#     if not issubclass(cls, models.Model):
#         raise DecoratorException(
#             'permissioned_model',
#             "class '" + cls.__name__ + "' is not a Django model"
#         )
#     added = False
#     try:
#         if not hasattr(cls, 'TutelaryMeta'):
#             if perm_type is None or path_fields is None or actions is None:
#                 raise DecoratorException(
#                     'permissioned_model',
#                     ("missing argument: all of perm_type, path_fields and " +
#                      "actions must be supplied")
#                 )
#             added = True
#             cls.TutelaryMeta = type('TutelaryMeta', (object,),
#                                     dict(perm_type=perm_type,
#                                          path_fields=path_fields,
#                                          actions=actions))
#         cls.TutelaryMeta.pfs = ([cls.TutelaryMeta.perm_type] +
#                                 get_path_fields(cls))
#         perms_objs = {}
#         for a in cls.TutelaryMeta.actions:
#             an = a
#             ap = {}
#             if isinstance(a, tuple):
#                 an = a[0]
#                 ap = a[1]
#             Action.register(an)
#             if isinstance(ap, dict) and 'permissions_object' in ap:
#                 po = ap['permissions_object']
#                 if po is not None:
#                     try:
#                         t = cls._meta.get_field(po).__class__
#                         if t not in [models.ForeignKey,
#                                      models.OneToOneField]:
#                             raise PermissionObjectException(po)
#                     except:
#                         raise PermissionObjectException(po)
#                 perms_objs[an] = po
#         if len(perms_objs) == 0:
#             cls.get_permissions_object = get_perms_object
#         else:
#             cls.get_permissions_object = make_get_perms_object(perms_objs)
#         return cls
#     except:
#         if added:
#             del cls.TutelaryMeta
#         raise
# 
# Path: tutelary/mixins.py
# class BasePermissionRequiredMixin:
# class PermissionRequiredMixin(BasePermissionRequiredMixin):
# class LoginPermissionRequiredMixin(PermissionRequiredMixin,
#                                    LoginRequiredMixin):
# class PermissionsFilterMixin:
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
#     def get_permission_required(self):
#     def get_permission_denied_message(self, default=None):
#     def get_queryset(self):
#     def perms_filter_queryset(self, objs):
#         def check_one(obj):
#     def has_permission(self):
#     def handle_no_permission(self):
#     def dispatch(self, request, *args, **kwargs):
#     def dispatch(self, request, *args, **kwargs):
#     def dispatch(self, request, *args, **kwargs):
#     def check_permissions(self, request):
#     def initial(self, 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/test_permission_required.py
import pytest
import django.views.generic as generic
from tutelary.engine import Action
from tutelary.decorators import permissioned_model
from tutelary import mixins
from django.db import models
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponseRedirect
from django.http.response import Http404
from django.core.exceptions import PermissionDenied
from .factories import UserFactory, PolicyFactory
from .datadir import datadir  # noqa



@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')

    pol3 = PolicyFactory.create(name='pol3', file='policy-3.json')