# Path: tutelary/models.py
# 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)
# 
# 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)
# 
# def user_assigned_policies(user):
#     """Return sequence of policies assigned to a user (or the anonymous
#     user is ``user`` is ``None``).  (Also installed as
#     ``assigned_policies`` method on ``User`` model.
# 
#     """
#     key = user_cache_key(user)
#     cached = cache.get(key)
#     if cached is not None:
#         return cached
# 
#     if user is None:
#         pset = PermissionSet.objects.filter(anonymous_user=True).first()
#     else:
#         pset = user.permissionset.first()
#     if pset is None:
#         return []
# 
#     res = []
#     skip_role_policies = False
#     skip_role = None
#     skip_role_variables = None
#     for pi in pset.policyinstance_set.select_related('policy', 'role'):
#         if skip_role_policies:
#             if pi.role == skip_role and pi.variables == skip_role_variables:
#                 continue
#             else:
#                 skip_role_policies = False
#         if pi.role:
#             res.append(pi.role)
#             skip_role = pi.role
#             skip_role_variables = pi.variables
#             skip_role_policies = True
#         else:
#             if pi.variables != '{}':
#                 res.append((pi.policy, json.loads(pi.variables)))
#             else:
#                 res.append(pi.policy)
#     cache.set(key, res)
#     return res
# 
# 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/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
# 
# class RoleFactory(factory.django.DjangoModelFactory):
#     class Meta:
#         model = Role


from tutelary.models import Role, assign_user_policies, user_assigned_policies
from .datadir import datadir  # noqa
from .factories import UserFactory, PolicyFactory, RoleFactory
import pytest
    users[5].assign_policies(org_admin_1_r, org_admin_2_r)
    users[6].assign_policies(org_admin_1_r, proj_mgr_2_r)
    users[7].assign_policies(proj_mgr_1_r)
    users[8].assign_policies((org_admin_p, {'org': 'Org3'}))
    users[9].assign_policies((org_admin_p, {'org': 'Org3'}),
                             (proj_mgr_p, {'org': 'Org3', 'proj': 'Proj3'}))

    return (users, pols, roles)


def test_role_lookup(datadir, setup):  # noqa
    users, pols, roles = setup
    (sys_admin_r,
     org_admin_1_r, org_admin_2_r,
     proj_mgr_1_r, proj_mgr_2_r) = roles

    assert list(Role.objects.filter(name='sys-admin')) == [sys_admin_r]
    assert (list(Role.objects.filter(name='sys-admin')) == [sys_admin_r])
    assert (set(Role.objects.filter(name='org-admin')) ==
            set([org_admin_1_r, org_admin_2_r]))
    assert (list(Role.objects.filter(name='org-admin',
                                     variables={'org': 'Org1'})) ==
            [org_admin_1_r])
    assert (list(Role.objects.filter(name='org-admin',
                                     variables={'org': 'Org2'})) ==
            [org_admin_2_r])
    assert (list(Role.objects.filter(name='org-admin',
                                     variables={'org': 'Org3'})) == [])
    assert (set(Role.objects.filter(name='proj-mgr')) ==
            set([proj_mgr_1_r, proj_mgr_2_r]))

# Path: tutelary/models.py
# 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)
# 
# 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)
# 
# def user_assigned_policies(user):
#     """Return sequence of policies assigned to a user (or the anonymous
#     user is ``user`` is ``None``).  (Also installed as
#     ``assigned_policies`` method on ``User`` model.
# 
#     """
#     key = user_cache_key(user)
#     cached = cache.get(key)
#     if cached is not None:
#         return cached
# 
#     if user is None:
#         pset = PermissionSet.objects.filter(anonymous_user=True).first()
#     else:
#         pset = user.permissionset.first()
#     if pset is None:
#         return []
# 
#     res = []
#     skip_role_policies = False
#     skip_role = None
#     skip_role_variables = None
#     for pi in pset.policyinstance_set.select_related('policy', 'role'):
#         if skip_role_policies:
#             if pi.role == skip_role and pi.variables == skip_role_variables:
#                 continue
#             else:
#                 skip_role_policies = False
#         if pi.role:
#             res.append(pi.role)
#             skip_role = pi.role
#             skip_role_variables = pi.variables
#             skip_role_policies = True
#         else:
#             if pi.variables != '{}':
#                 res.append((pi.policy, json.loads(pi.variables)))
#             else:
#                 res.append(pi.policy)
#     cache.set(key, res)
#     return res
# 
# 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/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
# 
# class RoleFactory(factory.django.DjangoModelFactory):
#     class Meta:
#         model = Role


# Path: tests/test_queries.py
from tutelary.models import Role, assign_user_policies, user_assigned_policies
from .datadir import datadir  # noqa
from .factories import UserFactory, PolicyFactory, RoleFactory
import pytest

    users[5].assign_policies(org_admin_1_r, org_admin_2_r)
    users[6].assign_policies(org_admin_1_r, proj_mgr_2_r)
    users[7].assign_policies(proj_mgr_1_r)
    users[8].assign_policies((org_admin_p, {'org': 'Org3'}))
    users[9].assign_policies((org_admin_p, {'org': 'Org3'}),
                             (proj_mgr_p, {'org': 'Org3', 'proj': 'Proj3'}))

    return (users, pols, roles)


def test_role_lookup(datadir, setup):  # noqa
    users, pols, roles = setup
    (sys_admin_r,
     org_admin_1_r, org_admin_2_r,
     proj_mgr_1_r, proj_mgr_2_r) = roles

    assert list(Role.objects.filter(name='sys-admin')) == [sys_admin_r]
    assert (list(Role.objects.filter(name='sys-admin')) == [sys_admin_r])
    assert (set(Role.objects.filter(name='org-admin')) ==
            set([org_admin_1_r, org_admin_2_r]))
    assert (list(Role.objects.filter(name='org-admin',
                                     variables={'org': 'Org1'})) ==
            [org_admin_1_r])
    assert (list(Role.objects.filter(name='org-admin',
                                     variables={'org': 'Org2'})) ==
            [org_admin_2_r])
    assert (list(Role.objects.filter(name='org-admin',
                                     variables={'org': 'Org3'})) == [])
    assert (set(Role.objects.filter(name='proj-mgr')) ==
            set([proj_mgr_1_r, proj_mgr_2_r]))

    assert (list(Role.objects.filter(name='proj-mgr',