pax_global_header00006660000000000000000000000064150307055070014514gustar00rootroot0000000000000052 comment=feb50478c549d4da66dc319f333f7c1c9e3dc991 django-rest-framework-guardian-0.4.0/000077500000000000000000000000001503070550700175155ustar00rootroot00000000000000django-rest-framework-guardian-0.4.0/.github/000077500000000000000000000000001503070550700210555ustar00rootroot00000000000000django-rest-framework-guardian-0.4.0/.github/workflows/000077500000000000000000000000001503070550700231125ustar00rootroot00000000000000django-rest-framework-guardian-0.4.0/.github/workflows/main.yml000066400000000000000000000025671503070550700245730ustar00rootroot00000000000000name: CI on: push: branches: - master pull_request: jobs: checks: name: Run ${{ matrix.toxenv }} check runs-on: ubuntu-latest strategy: matrix: python-version: ["3.13"] toxenv: ["lint", "dist"] steps: - uses: actions/checkout@v4 - name: Setup Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: 'pip' - name: Install tox run: python -m pip install tox - name: Run check (${{ matrix.toxenv }}) run: tox -e ${{ matrix.toxenv }} tests: name: Test on Python ${{ matrix.python-version }} runs-on: ubuntu-latest strategy: matrix: python-version: ["3.10", "3.11", "3.12", "3.13"] steps: - uses: actions/checkout@v4 - name: Setup Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: 'pip' - name: Install job dependencies run: python -m pip install tox "coverage[toml]" - name: Run tests (${{ matrix.python-version }}) run: tox run -f $(echo py${{ matrix.python-version }} | tr -d .) - name: Upload coverage uses: codecov/codecov-action@v5 with: token: ${{ secrets.CODECOV_TOKEN }} django-rest-framework-guardian-0.4.0/.gitignore000066400000000000000000000022631503070550700215100ustar00rootroot00000000000000# 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.4.0/CHANGELOG000066400000000000000000000015121503070550700207260ustar00rootroot00000000000000Unreleased ========== - Set Python version support to 3.10 through 3.13 - Set Django version support to 4.2 through 5.2 - Modernize packaging to use `pyproject.toml` - Remove deprecated `DjangoObjectPermissionsFilter` - Fix tox py310 build issue 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.4.0/LICENSE000066400000000000000000000027501503070550700205260ustar00rootroot00000000000000BSD 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.4.0/README.md000066400000000000000000000112271503070550700207770ustar00rootroot00000000000000# django-rest-framework-guardian [![build-status](https://github.com/rpkilby/django-rest-framework-guardian/actions/workflows/main.yml/badge.svg)](https://github.com/rpkilby/django-rest-framework-guardian/actions/workflows/main.yml) [![codecov](https://codecov.io/gh/rpkilby/django-rest-framework-guardian/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. ## 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 setuptools build twine $ rm -rf dist/ $ python -m build $ twine upload -r test dist/* $ twine upload dist/* ``` ## License See: [LICENSE](https://github.com/rpkilby/django-rest-framework-guardian/blob/master/LICENSE) django-rest-framework-guardian-0.4.0/manage.py000066400000000000000000000010401503070550700213120ustar00rootroot00000000000000#!/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.4.0/pyproject.toml000066400000000000000000000033031503070550700224300ustar00rootroot00000000000000[build-system] requires = ["setuptools>=77"] build-backend = "setuptools.build_meta" [project] name = "djangorestframework-guardian" version = "0.4.0" dependencies = [ "django", "djangorestframework", "django-guardian", ] requires-python = ">=3.10" authors = [{name = "Ryan P Kilby", email = "kilbyr@gmail.com"}] description = "django-guardian support for Django REST Framework" readme = "README.md" license = "BSD-3-Clause" classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Django", "Framework :: Django :: 4.2", "Framework :: Django :: 5.0", "Framework :: Django :: 5.1", "Framework :: Django :: 5.2", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", ] [project.urls] Repository = "https://github.com/rpkilby/django-rest-framework-guardian" Issues = "https://github.com/rpkilby/django-rest-framework-guardian/issues" Changelog = "https://github.com/rpkilby/django-rest-framework-guardian/CHANGELOG" [tool.setuptools.packages.find] where = ["src"] [tool.coverage.paths] source = ["src/"] [tool.coverage.run] branch = true [tool.coverage.report] show_missing = true [tool.flake8] max-line-length = 88 max-complexity = 10 [tool.isort] profile = "black" atomic = true combine_as_imports = true lines_after_imports = 2 known_first_party = ["rest_framework_guardian", "tests"] known_third_party = ["django", "rest_framework"] src_paths = ["src", "tests"] django-rest-framework-guardian-0.4.0/src/000077500000000000000000000000001503070550700203045ustar00rootroot00000000000000django-rest-framework-guardian-0.4.0/src/rest_framework_guardian/000077500000000000000000000000001503070550700252105ustar00rootroot00000000000000django-rest-framework-guardian-0.4.0/src/rest_framework_guardian/__init__.py000066400000000000000000000000001503070550700273070ustar00rootroot00000000000000django-rest-framework-guardian-0.4.0/src/rest_framework_guardian/filters.py000066400000000000000000000017651503070550700272430ustar00rootroot00000000000000from 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) django-rest-framework-guardian-0.4.0/src/rest_framework_guardian/serializers.py000066400000000000000000000042211503070550700301150ustar00rootroot00000000000000from 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.4.0/tests/000077500000000000000000000000001503070550700206575ustar00rootroot00000000000000django-rest-framework-guardian-0.4.0/tests/__init__.py000066400000000000000000000000001503070550700227560ustar00rootroot00000000000000django-rest-framework-guardian-0.4.0/tests/models.py000066400000000000000000000005031503070550700225120ustar00rootroot00000000000000from django.db import models from django.utils.translation import gettext_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.4.0/tests/settings.py000066400000000000000000000017231503070550700230740ustar00rootroot00000000000000import 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:', }, } DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True django-rest-framework-guardian-0.4.0/tests/test_permissions.py000066400000000000000000000116771503070550700246570ustar00rootroot00000000000000from 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 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(): auth = basic_auth_header(user.username, 'password') self.credentials[user.username] = auth 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, []) django-rest-framework-guardian-0.4.0/tests/test_serializers.py000066400000000000000000000072251503070550700246320ustar00rootroot00000000000000from 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): class TestSerializer(BasicSerializer): def get_permissions_map(self, created): return dict() 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.4.0/tests/utils.py000066400000000000000000000004651503070550700223760ustar00rootroot00000000000000from 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.4.0/tox.ini000066400000000000000000000014661503070550700210370ustar00rootroot00000000000000[tox] envlist = py310-django{42,50,51,52}, py311-django{42,50,51,52}, py312-django{42,50,51,52}, py313-django{51,52}, dist,lint [testenv] commands = coverage run manage.py test {posargs: --no-input -v 2} usedevelop = True setenv = PYTHONDONTWRITEBYTECODE = 1 deps = coverage[toml] django42: Django~=4.2.0 django50: Django~=5.0.0 django51: Django~=5.1.0 django52: Django~=5.2.0 [testenv:dist] commands = python manage.py test {posargs: --no-input -v 2} python -m build twine check dist/* usedevelop = False setenv = PYTHONDONTWRITEBYTECODE = deps = build twine [testenv:lint] commands = isort src tests --check-only --diff flake8 src tests deps = isort flake8 flake8-pyproject flake8-bugbear flake8-commas flake8-quotes