# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
#     """Assign a sequence of policies to a user (or the anonymous user is
#     ``user`` is ``None``).  (Also installed as ``assign_policies``
#     method on ``User`` model.
# 
#     """
#     clear_user_policies(user)
#     pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
#     pset.refresh()
#     if user is None:
#         pset.anonymous_user = True
#     else:
#         pset.users.add(user)
#     pset.save()
#     cache.set(user_cache_key(user), None)
# 
# class Role(models.Model):
#     """A policy role has a name, a sequence of policies and a set of
#     variable assignments.  Changes to roles are audited.
# 
#     """
# 
#     name = models.CharField(max_length=200)
#     """Role name field."""
# 
#     policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
# 
#     variables = models.TextField()
#     """JSON dump of dictionary giving variable assignments for role.
# 
#     """
# 
#     audit_log = AuditLog()
# 
#     objects = RoleManager()
# 
#     def __str__(self):
#         return self.name
# 
#     def variable_names(self):
#         return set().union(*[p.variable_names() for p in self.policies.all()])
# 
#     def delete(self, *args, **kwargs):
#         RolePolicyAssign.objects.filter(role=self).delete()
#         super().delete(*args, **kwargs)
# 
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
#     """Objects are represented by slash-separated sequences of elements
#     (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
#     wildcard elements indicated by ``*``
#     (e.g. ``Cadasta/*/parcel/*``).  Slashes can be backslash-escaped,
#     as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
# 
#     """
#     separator = '/'
# 
# 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/exceptions.py
# class RoleVariableException(TutelaryException):
#     """Exception raised for missing or illegal variable substitutions for
#     permissions roles.
# 
#     """
#     def __init__(self, msg):
#         super().__init__("illegal role variables: " + msg)
# 
# 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


from tutelary.models import (assign_user_policies, Role)
from tutelary.engine import Object, Action
from tutelary.exceptions import RoleVariableException
from .factories import UserFactory, PolicyFactory
from .datadir import datadir  # noqa
import pytest


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

# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
#     """Assign a sequence of policies to a user (or the anonymous user is
#     ``user`` is ``None``).  (Also installed as ``assign_policies``
#     method on ``User`` model.
# 
#     """
#     clear_user_policies(user)
#     pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
#     pset.refresh()
#     if user is None:
#         pset.anonymous_user = True
#     else:
#         pset.users.add(user)
#     pset.save()
#     cache.set(user_cache_key(user), None)
# 
# class Role(models.Model):
#     """A policy role has a name, a sequence of policies and a set of
#     variable assignments.  Changes to roles are audited.
# 
#     """
# 
#     name = models.CharField(max_length=200)
#     """Role name field."""
# 
#     policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
# 
#     variables = models.TextField()
#     """JSON dump of dictionary giving variable assignments for role.
# 
#     """
# 
#     audit_log = AuditLog()
# 
#     objects = RoleManager()
# 
#     def __str__(self):
#         return self.name
# 
#     def variable_names(self):
#         return set().union(*[p.variable_names() for p in self.policies.all()])
# 
#     def delete(self, *args, **kwargs):
#         RolePolicyAssign.objects.filter(role=self).delete()
#         super().delete(*args, **kwargs)
# 
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
#     """Objects are represented by slash-separated sequences of elements
#     (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
#     wildcard elements indicated by ``*``
#     (e.g. ``Cadasta/*/parcel/*``).  Slashes can be backslash-escaped,
#     as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
# 
#     """
#     separator = '/'
# 
# 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/exceptions.py
# class RoleVariableException(TutelaryException):
#     """Exception raised for missing or illegal variable substitutions for
#     permissions roles.
# 
#     """
#     def __init__(self, msg):
#         super().__init__("illegal role variables: " + msg)
# 
# 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_roles.py
from tutelary.models import (assign_user_policies, Role)
from tutelary.engine import Object, Action
from tutelary.exceptions import RoleVariableException
from .factories import UserFactory, PolicyFactory
from .datadir import datadir  # noqa
import pytest



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

    user4 = UserFactory.create(username='user4')