From 4e135bb4069f168dc7e1674931608138f5d33115 Mon Sep 17 00:00:00 2001 From: AlanCoding Date: Wed, 4 Jan 2017 14:46:23 -0500 Subject: [PATCH] add unit test to assure permission is checked --- awx/main/tests/unit/api/test_generics.py | 48 +++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/awx/main/tests/unit/api/test_generics.py b/awx/main/tests/unit/api/test_generics.py index b10b1c6c54..579440b201 100644 --- a/awx/main/tests/unit/api/test_generics.py +++ b/awx/main/tests/unit/api/test_generics.py @@ -6,9 +6,16 @@ import mock # DRF from rest_framework import status from rest_framework.response import Response +from rest_framework.exceptions import PermissionDenied # AWX -from awx.api.generics import ParentMixin, SubListCreateAttachDetachAPIView, DeleteLastUnattachLabelMixin +from awx.api.generics import ( + ParentMixin, + SubListCreateAttachDetachAPIView, + DeleteLastUnattachLabelMixin, + ResourceAccessList +) +from awx.main.models import Organization @pytest.fixture @@ -29,6 +36,11 @@ def mock_response_new(mocker): return m +@pytest.fixture +def mock_organization(): + return Organization(pk=4, name="Unsaved Org") + + @pytest.fixture def parent_relationship_factory(mocker): def rf(serializer_class, relationship_name, relationship_value=mocker.Mock()): @@ -178,3 +190,37 @@ class TestParentMixin: get_object_or_404.assert_called_with(parent_mixin.parent_model, **parent_mixin.kwargs) assert get_object_or_404.return_value == return_value + + +class TestResourceAccessList: + + def mock_request(self): + return mock.MagicMock( + user=mock.MagicMock( + is_anonymous=mock.MagicMock(return_value=False), + is_superuser=False + ), method='GET') + + + def mock_view(self): + view = ResourceAccessList() + view.parent_model = Organization + view.kwargs = {'pk': 4} + return view + + + def test_parent_access_check_failed(self, mocker, mock_organization): + with mocker.patch('awx.api.permissions.get_object_or_400', return_value=mock_organization): + mock_access = mocker.MagicMock(__name__='for logger', return_value=False) + with mocker.patch('awx.main.access.BaseAccess.can_read', mock_access): + with pytest.raises(PermissionDenied): + self.mock_view().check_permissions(self.mock_request()) + mock_access.assert_called_once_with(mock_organization) + + + def test_parent_access_check_worked(self, mocker, mock_organization): + with mocker.patch('awx.api.permissions.get_object_or_400', return_value=mock_organization): + mock_access = mocker.MagicMock(__name__='for logger', return_value=True) + with mocker.patch('awx.main.access.BaseAccess.can_read', mock_access): + self.mock_view().check_permissions(self.mock_request()) + mock_access.assert_called_once_with(mock_organization)