pax_global_header00006660000000000000000000000064135207052600014512gustar00rootroot0000000000000052 comment=e98671892238a89327766e2f6ec38a5a30157f12 django-rest-framework-guardian-0.3.0/000077500000000000000000000000001352070526000175125ustar00rootroot00000000000000django-rest-framework-guardian-0.3.0/.circleci/000077500000000000000000000000001352070526000213455ustar00rootroot00000000000000django-rest-framework-guardian-0.3.0/.circleci/config.yml000066400000000000000000000035011352070526000233340ustar00rootroot00000000000000version: 2.1 aliases: - &environ run: name: setup virtual environment # The below ensures the venv is activated for every subsequent step command: | virtualenv venv echo "source /home/circleci/project/venv/bin/activate" >> $BASH_ENV - &install run: name: install dependencies command: | pip install -U pip setuptools wheel tox codecov - &test-steps steps: - checkout - *environ - *install - run: tox - run: coverage report - run: codecov jobs: lint: steps: - checkout - *environ - *install - run: tox -e isort,lint,readme docker: - image: circleci/python:3.7 dist: steps: - checkout - *environ - *install - run: | python setup.py bdist_wheel tox -e dist --installpkg ./dist/djangorestframework_guardian-*.whl tox -e dist docker: - image: circleci/python:3.7 test-py37: <<: *test-steps docker: - image: circleci/python:3.7 environment: TOXENV: py37 test-py36: <<: *test-steps docker: - image: circleci/python:3.6 environment: TOXENV: py36 test-py35: <<: *test-steps docker: - image: circleci/python:3.5 environment: TOXENV: py35 workflows: version: 2 commit: &test-workflow jobs: - lint - dist: requires: - lint - test-py37: requires: - lint - test-py36: requires: - lint - test-py35: requires: - lint weekly: <<: *test-workflow triggers: - schedule: # 8/9 AM PST/PDT every Monday cron: "0 16 * * 1" filters: branches: only: - master django-rest-framework-guardian-0.3.0/.gitignore000066400000000000000000000022631352070526000215050ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ django-rest-framework-guardian-0.3.0/CHANGELOG000066400000000000000000000011511352070526000207220ustar00rootroot00000000000000Unreleased ========== 0.3.0 (2019-08-01) ================== - Add `ObjectPermissionsAssignmentMixin` serializer mixin, which facilitates the assigment of object permissions. - Rename `DjangoObjectPermissionsFilter` to `ObjectPermissionsFilter`. 0.2.0 (2019-07-19) ================== - Add Django 2.2 support - Drop Django 1.1 & 2.1 support - Drop Python 2.7 & 3.4 support 0.1.1 (2018-11-02) ================== - Allow `get_objects_for_user` keyword arguments to be overridden. - Ensure Python 3.7 compatibility 0.1.0 (2018-07-09) ================== - Port initial implementation from Django REST Framework. django-rest-framework-guardian-0.3.0/LICENSE000066400000000000000000000027501352070526000205230ustar00rootroot00000000000000BSD 3-Clause License Copyright (c) 2018, Ryan P Kilby All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. django-rest-framework-guardian-0.3.0/README.md000066400000000000000000000112601352070526000207710ustar00rootroot00000000000000# django-rest-framework-guardian [![CircleCI](https://circleci.com/gh/rpkilby/django-rest-framework-guardian.svg?style=shield)](https://circleci.com/gh/rpkilby/django-rest-framework-guardian) [![Codecov](https://codecov.io/gh/rpkilby/django-rest-framework-guardian/branch/master/graph/badge.svg)](https://codecov.io/gh/rpkilby/django-rest-framework-guardian) [![License](https://img.shields.io/pypi/l/djangorestframework-guardian.svg)](https://pypi.org/project/djangorestframework-guardian) [![Version](https://img.shields.io/pypi/v/djangorestframework-guardian.svg)](https://pypi.org/project/djangorestframework-guardian) [![Python](https://img.shields.io/pypi/pyversions/djangorestframework-guardian.svg)](https://pypi.org/project/djangorestframework-guardian/) django-rest-framework-guardian provides django-guardian integrations for Django REST Framework. Currently, this only includes the `ObjectPermissionsFilter`. ## Installation & Setup To use django-rest-framework-guardian, install it into your environment. ```sh $ pip install djangorestframework-guardian ``` Ensure both Django REST Framework and django-guardian are configured and added to your `INSTALLED_APPS` setting. ```python INSTALLED_APPS = [ 'rest_framework', 'guardian', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'guardian.backends.ObjectPermissionBackend', ] ``` ## ObjectPermissionsFilter The filter will ensure that querysets only returns objects for which the user has the appropriate view permission. If you're using `ObjectPermissionsFilter`, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass `DjangoObjectPermissions` and add `'view'` permissions to the `perms_map` attribute. An example using both `ObjectPermissionsFilter` and `DjangoObjectPermissions` might look like the following: **permissions.py**: ```python from rest_framework import permissions class CustomObjectPermissions(permissions.DjangoObjectPermissions): """ Similar to `DjangoObjectPermissions`, but adding 'view' permissions. """ perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': ['%(app_label)s.view_%(model_name)s'], 'HEAD': ['%(app_label)s.view_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } ``` **views.py**: ```python from rest_framework import viewsets from rest_framework_guardian import filters from myapp.models import Event from myapp.permissions import CustomObjectPermissions from myapp.serializers import EventSerializer class EventViewSet(viewsets.ModelViewSet): """ Viewset that only lists events if user has 'view' permissions, and only allows operations on individual events if user has appropriate 'view', 'add', 'change' or 'delete' permissions. """ queryset = Event.objects.all() serializer_class = EventSerializer permission_classes = [CustomObjectPermissions] filter_backends = [filters.ObjectPermissionsFilter] ``` ## ObjectPermissionsAssignmentMixin A serializer mixin that allows permissions to be easily assigned to users and/or groups. So each time an object is created or updated, the `permissions_map` returned by `Serializer.get_permissions_map` will be used to assign permission(s) to that object. Please note that the existing permissions will remain intact. A usage example might look like the following: ```python from rest_framework_guardian.serializers import ObjectPermissionsAssignmentMixin from blog.models import Post class PostSerializer(ObjectPermissionsAssignmentMixin, serializers.ModelSerializer): class Meta: model = Post fields = '__all__' def get_permissions_map(self, created): current_user = self.context['request'].user readers = Group.objects.get(name='readers') supervisors = Group.objects.get(name='supervisors') return { 'view_post': [current_user, readers], 'change_post': [current_user], 'delete_post': [current_user, supervisors] } ``` ## Release Process - Update changelog - Update package version in setup.py - Create git tag for version - Build & upload release to PyPI ```bash $ pip install -U pip setuptools wheel twine $ rm -rf dist/ build/ $ python setup.py bdist_wheel $ twine upload dist/* ``` ## License See: [LICENSE](https://github.com/rpkilby/django-rest-framework-guardian/blob/master/LICENSE) django-rest-framework-guardian-0.3.0/manage.py000066400000000000000000000010401352070526000213070ustar00rootroot00000000000000#!/usr/bin/env python import os import sys if __name__ == '__main__': sys.path.append('tests') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') try: from django.core.management import execute_from_command_line except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) execute_from_command_line(sys.argv) django-rest-framework-guardian-0.3.0/setup.cfg000066400000000000000000000031241352070526000213330ustar00rootroot00000000000000[bdist_wheel] universal = 1 [coverage:run] branch = true source = src [coverage:report] show_missing = true [flake8] max_line_length = 90 max_complexity = 10 [isort] atomic = true line_length = 90 lines_after_imports = 2 multi_line_output = 4 known_third_party = django,rest_framework known_first_party = rest_framework_guardian,tests [metadata] name = djangorestframework-guardian version = 0.3.0 description = django-guardian support for Django REST Framework long_description = file: README.md, LICENSE long_description_content_type = text/markdown license = BSD license_file = LICENSE author = Ryan P Kilby author_email=kilbyr@gmail.com url = https://github.com/rpkilby/django-rest-framework-guardian project_urls = Source=https://github.com/rpkilby/django-rest-framework-guardian Tracker=https://github.com/rpkilby/django-rest-framework-guardian/issues classifiers = Development Status :: 5 - Production/Stable Environment :: Web Environment Framework :: Django Framework :: Django :: 2.1 Framework :: Django :: 2.2 Intended Audience :: Developers License :: OSI Approved :: BSD License Operating System :: OS Independent Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Topic :: Internet :: WWW/HTTP [options] install_requires = django djangorestframework django-guardian include_package_data = true package_dir = =src packages = find: zip_safe = false [options.packages.find] where = src django-rest-framework-guardian-0.3.0/setup.py000066400000000000000000000000471352070526000212250ustar00rootroot00000000000000from setuptools import setup setup() django-rest-framework-guardian-0.3.0/src/000077500000000000000000000000001352070526000203015ustar00rootroot00000000000000django-rest-framework-guardian-0.3.0/src/rest_framework_guardian/000077500000000000000000000000001352070526000252055ustar00rootroot00000000000000django-rest-framework-guardian-0.3.0/src/rest_framework_guardian/__init__.py000066400000000000000000000000001352070526000273040ustar00rootroot00000000000000django-rest-framework-guardian-0.3.0/src/rest_framework_guardian/filters.py000066400000000000000000000025671352070526000272410ustar00rootroot00000000000000import warnings from rest_framework.filters import BaseFilterBackend class ObjectPermissionsFilter(BaseFilterBackend): """ A filter backend that limits results to those where the requesting user has read object level permissions. """ perm_format = '%(app_label)s.view_%(model_name)s' shortcut_kwargs = { 'accept_global_perms': False, } def filter_queryset(self, request, queryset, view): # We want to defer this import until runtime, rather than import-time. # See https://github.com/encode/django-rest-framework/issues/4608 # (Also see #1624 for why we need to make this import explicitly) from guardian.shortcuts import get_objects_for_user user = request.user permission = self.perm_format % { 'app_label': queryset.model._meta.app_label, 'model_name': queryset.model._meta.model_name, } return get_objects_for_user( user, permission, queryset, **self.shortcut_kwargs) class DjangoObjectPermissionsFilter(ObjectPermissionsFilter): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) warnings.warn( '`DjangoObjectPermissionsFilter` has been renamed to ' '`ObjectPermissionsFilter` and will be removed in the future.', DeprecationWarning, stacklevel=2, ) django-rest-framework-guardian-0.3.0/src/rest_framework_guardian/serializers.py000066400000000000000000000042211352070526000301120ustar00rootroot00000000000000from collections.abc import Mapping from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.db import transaction from rest_framework.serializers import Serializer User = get_user_model() class ObjectPermissionsAssignmentMixin(Serializer): """ A serializer mixin that provides an easy way to assign permissions to given users and/or group when an object is created or updated. """ def save(self, **kwargs): created = self.instance is not None result = super().save(**kwargs) permissions_map = self.get_permissions_map(created) self.assign_permissions(permissions_map) return result def get_permissions_map(self, created): """ Return a map where keys are permissions and values are list of users and/or groups """ raise NotImplementedError def assign_permissions(self, permissions_map): """ Assign the permissions to their associated users/groups. """ # Import at runtime (see: DjangoObjectPermissionsFilter.filter_queryset) from guardian.shortcuts import assign_perm assert isinstance(permissions_map, Mapping), ( 'Expected %s.get_permissions_map to return a dict, got %s instead.' % (self.__class__.__name__, type(permissions_map).__name__) ) with transaction.atomic(): for permission, assignees in permissions_map.items(): users = [u for u in assignees if isinstance(u, User)] groups = [g for g in assignees if isinstance(g, Group)] # TODO: support Django Guardian bulk permission assigning # Currently, trying to assign a permission to multiple # users or groups can result uniqueness constraint error # in database level due to `assign_perm` not checking # the existance of a permission before inserting for user in users: assign_perm(permission, user, self.instance) for group in groups: assign_perm(permission, group, self.instance) django-rest-framework-guardian-0.3.0/tests/000077500000000000000000000000001352070526000206545ustar00rootroot00000000000000django-rest-framework-guardian-0.3.0/tests/__init__.py000066400000000000000000000000001352070526000227530ustar00rootroot00000000000000django-rest-framework-guardian-0.3.0/tests/models.py000066400000000000000000000005041352070526000225100ustar00rootroot00000000000000from django.db import models from django.utils.translation import ugettext_lazy as _ class BasicModel(models.Model): text = models.CharField(max_length=100, help_text=_('Text description.')) class BasicPermModel(models.Model): text = models.CharField(max_length=100) class Meta: app_label = 'tests' django-rest-framework-guardian-0.3.0/tests/settings.py000066400000000000000000000016601352070526000230710ustar00rootroot00000000000000import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'not-a-secret' DEBUG = True ANONYMOUS_USER_ID = -1 AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'guardian.backends.ObjectPermissionBackend', ] INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'rest_framework', 'guardian', 'tests', ] MIDDLEWARE = [ 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ] ROOT_URLCONF = [] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True django-rest-framework-guardian-0.3.0/tests/test_permissions.py000066400000000000000000000127771352070526000246560ustar00rootroot00000000000000import warnings from django.contrib.auth.models import Group, User from django.test import TestCase from rest_framework import authentication, generics, permissions, serializers, status from rest_framework.test import APIRequestFactory from rest_framework_guardian.filters import ( DjangoObjectPermissionsFilter, ObjectPermissionsFilter) from tests.models import BasicModel, BasicPermModel from tests.utils import basic_auth_header factory = APIRequestFactory() class BasicSerializer(serializers.ModelSerializer): class Meta: model = BasicModel fields = '__all__' class BasicPermSerializer(serializers.ModelSerializer): class Meta: model = BasicPermModel fields = '__all__' # Custom object-level permission, that includes 'view' permissions class ViewObjectPermissions(permissions.DjangoObjectPermissions): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': ['%(app_label)s.view_%(model_name)s'], 'HEAD': ['%(app_label)s.view_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } class ObjectPermissionInstanceView(generics.RetrieveUpdateDestroyAPIView): queryset = BasicPermModel.objects.all() serializer_class = BasicPermSerializer authentication_classes = [authentication.BasicAuthentication] permission_classes = [ViewObjectPermissions] object_permissions_view = ObjectPermissionInstanceView.as_view() class ObjectPermissionListView(generics.ListAPIView): queryset = BasicPermModel.objects.all() serializer_class = BasicPermSerializer authentication_classes = [authentication.BasicAuthentication] permission_classes = [ViewObjectPermissions] filter_backends = [ObjectPermissionsFilter] object_permissions_list_view = ObjectPermissionListView.as_view() class GetQuerysetObjectPermissionInstanceView(generics.RetrieveUpdateDestroyAPIView): serializer_class = BasicPermSerializer authentication_classes = [authentication.BasicAuthentication] permission_classes = [ViewObjectPermissions] def get_queryset(self): return BasicPermModel.objects.all() get_queryset_object_permissions_view = GetQuerysetObjectPermissionInstanceView.as_view() class ObjectPermissionsIntegrationTests(TestCase): """ Integration tests for the object level permissions API. """ def setUp(self): from guardian.shortcuts import assign_perm # create users create = User.objects.create_user users = { 'fullaccess': create('fullaccess', 'fullaccess@example.com', 'password'), 'readonly': create('readonly', 'readonly@example.com', 'password'), 'writeonly': create('writeonly', 'writeonly@example.com', 'password'), 'deleteonly': create('deleteonly', 'deleteonly@example.com', 'password'), } # give everyone model level permissions, as we are not testing those everyone = Group.objects.create(name='everyone') model_name = BasicPermModel._meta.model_name app_label = BasicPermModel._meta.app_label perms = { 'view': '{0}_{1}'.format('view', model_name), 'change': '{0}_{1}'.format('change', model_name), 'delete': '{0}_{1}'.format('delete', model_name), } for perm in perms.values(): perm = '{0}.{1}'.format(app_label, perm) assign_perm(perm, everyone) everyone.user_set.add(*users.values()) # appropriate object level permissions readers = Group.objects.create(name='readers') writers = Group.objects.create(name='writers') deleters = Group.objects.create(name='deleters') model = BasicPermModel.objects.create(text='foo') assign_perm(perms['view'], readers, model) assign_perm(perms['change'], writers, model) assign_perm(perms['delete'], deleters, model) readers.user_set.add(users['fullaccess'], users['readonly']) writers.user_set.add(users['fullaccess'], users['writeonly']) deleters.user_set.add(users['fullaccess'], users['deleteonly']) self.credentials = {} for user in users.values(): self.credentials[user.username] = basic_auth_header(user.username, 'password') def test_can_read_list_permissions(self): request = factory.get('/', HTTP_AUTHORIZATION=self.credentials['readonly']) response = object_permissions_list_view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data[0].get('id'), 1) def test_cannot_read_list_permissions(self): request = factory.get('/', HTTP_AUTHORIZATION=self.credentials['writeonly']) response = object_permissions_list_view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertListEqual(response.data, []) def test_deprecation_warning(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') DjangoObjectPermissionsFilter() self.assertEqual(len(w), 1) self.assertIs(w[0].category, DeprecationWarning) self.assertEqual(str(w[0].message), '`DjangoObjectPermissionsFilter` has been renamed ' 'to `ObjectPermissionsFilter` and will be removed ' 'in the future.') django-rest-framework-guardian-0.3.0/tests/test_serializers.py000066400000000000000000000074151352070526000246300ustar00rootroot00000000000000from collections import OrderedDict from django.contrib.auth.models import Group, User from django.test import TestCase from rest_framework import serializers from rest_framework.test import APIRequestFactory from rest_framework_guardian.serializers import ObjectPermissionsAssignmentMixin from tests.models import BasicModel factory = APIRequestFactory() class BasicSerializer(ObjectPermissionsAssignmentMixin, serializers.ModelSerializer): class Meta: model = BasicModel fields = '__all__' def get_permissions_map(self, created): current_user = self.context['request'].user readers = Group.objects.get(name='readers') return { 'view_%s' % BasicModel._meta.model_name: [current_user, readers], 'change_%s' % BasicModel._meta.model_name: [current_user], } class ObjectPermissionsAssignmentIntegrationTests(TestCase): """ Integration tests for the object level permissions assignment API. """ def setUp(self): create = User.objects.create_user self.writer = create('writer', password='password') self.reader = create('reader', password='password') self.no_perms = create('no_perms', password='password') # Add readers to our reader group reader_group = Group.objects.create(name='readers') reader_group.user_set.add(self.reader) def create_object(self): request = factory.post('/') request.user = self.writer serializer = BasicSerializer( data={'text': 'test'}, context={'request': request}, ) serializer.is_valid(raise_exception=True) instance = serializer.save() return instance def test_read_permissions(self): instance = self.create_object() # Reader is indirectly assigned via its group permissions self.assertTrue(self.writer.has_perm('view_basicmodel', instance)) self.assertTrue(self.reader.has_perm('view_basicmodel', instance)) self.assertFalse(self.no_perms.has_perm('view_basicmodel', instance)) def test_change_permissions(self): instance = self.create_object() self.assertTrue(self.writer.has_perm('change_basicmodel', instance)) self.assertFalse(self.reader.has_perm('change_basicmodel', instance)) self.assertFalse(self.no_perms.has_perm('change_basicmodel', instance)) def test_delete_permissions(self): instance = self.create_object() # No user should be assigned delete permissions self.assertFalse(self.writer.has_perm('delete_basicmodel', instance)) self.assertFalse(self.reader.has_perm('delete_basicmodel', instance)) self.assertFalse(self.no_perms.has_perm('delete_basicmodel', instance)) class ObjectPermissionsAssignmentImplementationTests(TestCase): def test_get_permissions_map_should_return_a_mapping(self): for return_value in [dict(), OrderedDict()]: class TestSerializer(BasicSerializer): def get_permissions_map(self, created): return return_value serializer = TestSerializer(data={'text': 'test'}) serializer.is_valid(raise_exception=True) self.assertIsInstance(serializer.save(), BasicModel) def test_get_permissions_map_error_message(self): error_message = ( 'Expected InvalidSerializer.get_permissions_map ' 'to return a dict, got list instead.' ) class InvalidSerializer(BasicSerializer): def get_permissions_map(self, created): return [] serializer = InvalidSerializer(data={'text': 'test'}) serializer.is_valid(raise_exception=True) with self.assertRaisesMessage(AssertionError, error_message): serializer.save() django-rest-framework-guardian-0.3.0/tests/utils.py000066400000000000000000000004651352070526000223730ustar00rootroot00000000000000from base64 import b64encode from rest_framework import HTTP_HEADER_ENCODING def basic_auth_header(username, password): credentials = ('%s:%s' % (username, password)) credentials = credentials.encode(HTTP_HEADER_ENCODING) return 'Basic %s' % b64encode(credentials).decode(HTTP_HEADER_ENCODING) django-rest-framework-guardian-0.3.0/tox.ini000066400000000000000000000014451352070526000210310ustar00rootroot00000000000000[tox] envlist = {py35,py36,py37}-django21, {py35,py36,py37}-django22, dist,isort,lint,readme [testenv] commands = coverage run manage.py test {posargs: --no-input -v 2} usedevelop = True envdir={toxworkdir}/v/{envname} setenv = PYTHONDONTWRITEBYTECODE = 1 deps = coverage django21: Django~=2.1 django22: Django~=2.2 [testenv:dist] commands = python manage.py test {posargs: --no-input -v 2} usedevelop = False [testenv:isort] commands = isort --check-only --recursive src tests {posargs:--diff} deps = isort [testenv:lint] commands = flake8 src tests {posargs} deps = flake8 flake8-bugbear flake8-commas flake8-quotes [testenv:readme] commands = python setup.py sdist bdist_wheel twine check dist/* usedevelop = False deps = twine