def test_get_resource_name():
    view = APIView()
    context = {'view': view}
    with override_settings(JSON_API_FORMAT_TYPES=None):
        assert 'APIViews' == utils.get_resource_name(context), 'not formatted'

    context = {'view': view}
    with override_settings(JSON_API_FORMAT_TYPES='dasherize'):
        assert 'api-views' == utils.get_resource_name(context), 'derived from view'

    view.model = get_user_model()
    assert 'users' == utils.get_resource_name(context), 'derived from view model'

    view.resource_name = 'custom'
    assert 'custom' == utils.get_resource_name(context), 'manually set on view'

    view.response = Response(status=403)
    assert 'errors' == utils.get_resource_name(context), 'handles 4xx error'

    view.response = Response(status=500)
    assert 'errors' == utils.get_resource_name(context), 'handles 500 error'

    view = GenericAPIView()
    view.serializer_class = ResourceSerializer
    context = {'view': view}
    assert 'users' == utils.get_resource_name(context), 'derived from serializer'

    view.serializer_class.Meta.resource_name = 'rcustom'
    assert 'rcustom' == utils.get_resource_name(context), 'set on serializer'

    view = GenericAPIView()
    view.serializer_class = NonModelResourceSerializer
    context = {'view': view}
    assert 'users' == utils.get_resource_name(context), 'derived from non-model serializer'
Beispiel #2
0
 def test_render(self):
     obj = {
         'recordsTotal': 4,
         'recordsFiltered': 2,
         'data': [{
             'foo': 'bar'
         }, {
             'spam': 'eggs'
         }]
     }
     renderer = DatatablesRenderer()
     view = APIView()
     request = view.initialize_request(
         self.factory.get('/api/foo/?format=datatables&draw=2'))
     content = renderer.render(obj, 'application/json', {
         'request': request,
         'view': view
     })
     expected = {
         'recordsTotal': 4,
         'recordsFiltered': 2,
         'data': [{
             'foo': 'bar'
         }, {
             'spam': 'eggs'
         }],
         'draw': 2
     }
     self.assertEquals(json.loads(content.decode('utf-8')), expected)
Beispiel #3
0
    def test_is_user(self):
        """
        Tests for IserUserOrReadOnly permission class.

        has_object_permission should return True if request is a safe method or
        if the object's user attribute is the request user, or if the requesting
        user is staff.

        Should return false if regular user is attempting to access another
        user's profile
        """
        # normal user on self
        view = UserProfileViewset.as_view({
            'get': 'retrieve',
            'patch': 'partial_update'
        })
        request = self.factory.get(
            reverse('userprofile-detail', args=[self.user.profile.pk]))
        force_authenticate(request, user=self.user)
        perm = IsUserOrReadOnly()
        request = APIView().initialize_request(request)
        self.assertTrue(
            perm.has_object_permission(request, view, self.user.profile))

        # super user on other
        superuser = User.objects.create_superuser(username="******",
                                                  email="*****@*****.**",
                                                  password="******")
        request = self.factory.get(
            reverse('userprofile-detail', args=[self.user.profile.pk]))
        force_authenticate(request, user=superuser)
        request = APIView().initialize_request(request)
        self.assertTrue(
            perm.has_object_permission(request, view, superuser.profile))
Beispiel #4
0
def test_get_resource_name_from_model(settings, format_type, pluralize_type, output):
    settings.JSON_API_FORMAT_TYPES = format_type
    settings.JSON_API_PLURALIZE_TYPES = pluralize_type

    view = APIView()
    view.model = BasicModel
    context = {"view": view}
    assert output == get_resource_name(context)
Beispiel #5
0
 def __init__(self):
     #执行父类初始化方法
     APIView.__init__(self)
     # #获取request对象
     # self.request = request
     # #获取参数
     # self.getParam()
     # #输出
     self.echo = HttpResponse
def test_get_resource_name_from_view_custom_resource_name(
        settings, format_type, pluralize_type):
    settings.JSON_API_FORMAT_TYPES = format_type
    settings.JSON_API_PLURALIZE_TYPES = pluralize_type

    view = APIView()
    view.resource_name = "custom"
    context = {"view": view}
    assert "custom" == get_resource_name(context)
Beispiel #7
0
 def test_from_request(self):
     request = factory.post('/', json.dumps({'g': _geom}),
                            content_type='application/json')
     view = APIView()
     request = view.initialize_request(request)
     view.initial(request)
     form = forms.RasterQueryForm.from_request(request)
     self.assertTrue(form.is_valid())
     geom = geos.GEOSGeometry(json.dumps(_geom))
     self.assertEqual(form.cleaned_data['g'], geom.ogr)
def test_get_resource_name():
    view = APIView()
    context = {'view': view}
    setattr(settings, 'JSON_API_FORMAT_TYPES', None)
    assert 'APIViews' == utils.get_resource_name(context), 'not formatted'

    context = {'view': view}
    setattr(settings, 'JSON_API_FORMAT_TYPES', 'dasherize')
    assert 'api-views' == utils.get_resource_name(context), 'derived from view'

    view.model = get_user_model()
    assert 'users' == utils.get_resource_name(context), 'derived from view model'

    view.resource_name = 'custom'
    assert 'custom' == utils.get_resource_name(context), 'manually set on view'

    view.response = Response(status=403)
    assert 'errors' == utils.get_resource_name(context), 'handles 4xx error'

    view.response = Response(status=500)
    assert 'errors' == utils.get_resource_name(context), 'handles 500 error'

    view = GenericAPIView()
    view.serializer_class = ResourceSerializer
    context = {'view': view}
    assert 'users' == utils.get_resource_name(context), 'derived from serializer'

    view.serializer_class.Meta.resource_name = 'rcustom'
    assert 'rcustom' == utils.get_resource_name(context), 'set on serializer'

    view = GenericAPIView()
    view.serializer_class = NonModelResourceSerializer
    context = {'view': view}
    assert 'users' == utils.get_resource_name(context), 'derived from non-model serializer'
 def test_from_request(self):
     request = factory.post('/',
                            json.dumps({'g': _geom}),
                            content_type='application/json')
     view = APIView()
     request = view.initialize_request(request)
     view.initial(request)
     form = forms.RasterQueryForm.from_request(request)
     self.assertTrue(form.is_valid())
     geom = geos.GEOSGeometry(json.dumps(_geom))
     self.assertEqual(form.cleaned_data['g'], geom.ogr)
Beispiel #10
0
    def test_has_permission(self):
        view = APIView()

        req = self.factory.get('/')
        req.user = AnonymousUser()

        # no company
        self.assertFalse(self.permission.has_permission(req, view))

        # add company operator
        req.user = self.operator.user
        req.session = self.session

        # no plan/subscription
        self.assertFalse(self.permission.has_permission(req, view))

        # add company subscription
        self.add_subscription(self.operator.company)

        # no subscription features on view defined
        self.assertTrue(self.permission.has_permission(req, view))

        view.subscription_features = ['foo']

        # feature not in plan features
        self.assertFalse(self.permission.has_permission(req, view))

        view.subscription_features = ['shareholders']

        plans = copy.deepcopy(settings.DJSTRIPE_PLANS)
        plans['test']['features']['shareholders'] = {}
        with self.settings(DJSTRIPE_PLANS=plans):
            self.assertTrue(self.permission.has_permission(req, view))

        view.action = 'bar'
        # view action has no validator
        self.assertTrue(self.permission.has_permission(req, view))

        plans['test']['features']['shareholders'] = {
            'max': 2,
            'validators': {
                'bar': [
                    'company.validators.features.'
                    'ShareholderCreateMaxCountValidator'
                ]
            }
        }
        with self.settings(DJSTRIPE_PLANS=plans):
            self.assertTrue(self.permission.has_permission(req, view))

        plans['test']['features']['shareholders']['max'] = 0
        with self.settings(DJSTRIPE_PLANS=plans):
            self.assertFalse(self.permission.has_permission(req, view))
Beispiel #11
0
 def __init__(self):
     """Initialize class"""
     APIView.__init__(self)
     self._file_title = ''
     self._topic = ''
     self._times = []
     self.__workbook = Workbook(encoding='utf-8')
     self._response = HttpResponse(content_type='application/ms-excel')
     self._head_row_style = XFStyle()
     self._data_row_style = XFStyle()
     self.__start_row = 5
     self.__start_column = 5
     self.__message_row = 2
     self.__message_col = 2
Beispiel #12
0
 def test_render_no_pagination1_1(self):
     obj = [{'foo': 'bar'}]
     renderer = DatatablesRenderer()
     view = APIView()
     request = view.initialize_request(
         self.factory.get('/api/foo.datatables?draw=1')
     )
     content = renderer.render(obj, 'application/json', {'request': request, 'view': view})
     expected = {
         'recordsTotal': 1,
         'recordsFiltered': 1,
         'data': [{'foo': 'bar'}],
         'draw': 1
     }
     self.assertEquals(json.loads(content.decode('utf-8')), expected)
Beispiel #13
0
 def handle_exception(self, exc):
     if isinstance(exc, InvalidRequestException):
         return project_api_response.Response(
             self.request_form_errors, status=status.HTTP_400_BAD_REQUEST)
     base_response = APIView.handle_exception(self, exc)
     return project_api_response.Response(base_response.data,
                                          status=base_response.status_code)
Beispiel #14
0
async def authenticate(request, handler):
    """Authenticates the request to the content app using the DRF authentication classes"""
    django_request = convert_request(request)
    fake_view = APIView()

    def _authenticate_blocking():
        drf_request = fake_view.initialize_request(django_request)
        try:
            try:
                fake_view.perform_authentication(drf_request)
            except (InterfaceError, OperationalError):
                Handler._reset_db_connection()
                fake_view.perform_authentication(drf_request)
        except APIException as e:
            log.warning(
                _('"{} {}" "{}": {}').format(request.method, request.path,
                                             request.host, e))

        return drf_request

    auth_request = await sync_to_async(_authenticate_blocking)()
    request["user"] = auth_request.user
    request["auth"] = auth_request.auth
    request["drf_request"] = auth_request

    return await handler(request)
 def test_set_custom_inspector_class_via_settings(self):
     with override_settings(REST_FRAMEWORK={
             'DEFAULT_SCHEMA_CLASS':
             'tests.test_schemas.CustomViewInspector'
     }):
         view = APIView()
         assert isinstance(view.schema, CustomViewInspector)
Beispiel #16
0
def test_authenticate_existing_user_existing_same_data_source(
    api_client, data_source, signed_auth_key_factory, user_factory, user_origin_factory
):
    signed_auth_key = signed_auth_key_factory(data_source=data_source)

    user = user_factory()
    user_origin_factory(user=user, data_source=data_source)

    now = datetime.datetime.utcnow()

    data = {
        "hsa_source": data_source.id,
        "hsa_username": user.username,
        "hsa_created_at": now.isoformat() + "Z",
        "hsa_valid_until": (now + datetime.timedelta(minutes=10)).isoformat() + "Z",
    }

    source_string = join_params(data)
    signature = calculate_signature(signed_auth_key.signing_key, source_string)

    params = {**data, "hsa_signature": signature}

    # Create a fake DRF request
    request_factory = APIRequestFactory()
    http_request = request_factory.get("/", params)
    request = APIView().initialize_request(http_request)

    auth = HaukiSignedAuthentication()
    authenticated_user = auth.authenticate(request)[0]

    assert authenticated_user.id == user.id
    assert authenticated_user.username == user.username
Beispiel #17
0
 def setUp(self):
     factory = APIRequestFactory()
     self.request = factory.get("/foo", format="json")
     self.request.user = AnonymousUser()
     self.request = APIView().initialize_request(self.request)
     self.endpoint = PostcodeViewSet()
     self.endpoint.get_ee_wrapper = lambda x: EEMockWithElection()
Beispiel #18
0
def test_auth_data_resource(
    api_client,
    data_source,
    resource_factory,
    resource_origin_factory,
    hsa_params_factory,
):
    resource = resource_factory()
    resource_origin_factory(resource=resource, data_source=data_source)

    hsa_params = {
        "username": "******",
        "data_source": data_source,
        "resource": resource,
    }
    params = hsa_params_factory(**hsa_params)

    # Create a fake DRF request
    request_factory = APIRequestFactory()
    http_request = request_factory.get("/", params)
    request = APIView().initialize_request(http_request)

    auth = HaukiSignedAuthentication()
    (authenticated_user, auth) = auth.authenticate(request)

    assert authenticated_user.id is not None
    assert authenticated_user.username == "test_user"

    assert auth.user == authenticated_user
    assert auth.user_origin.data_source == data_source
    assert auth.has_organization_rights is False
    assert auth.organization is None
    assert auth.resource == resource
 def test_filters_query(self):
     backend = Filter()
     request = Request(factory.get('/', {'text': 'txt'}))
     qs = BasicModel.objects.all()
     view = APIView()
     filtered_qs = backend.filter_queryset(request, qs, view)
     assert qs.query != filtered_qs.query
Beispiel #20
0
 def test_get_request_filters_with_falsey_values(self):
     """ Verify the method does not strip valid falsey values. """
     request = APIRequestFactory().get('/?q=&test=0')
     request = APIView().initialize_request(request)
     filters = HaystackRequestFilterMixin.get_request_filters(request)
     assert 'q' not in filters
     assert filters.get('test') == '0'
 def test_get_request_filters_with_falsey_values(self):
     """ Verify the method does not strip valid falsey values. """
     request = APIRequestFactory().get('/?q=&test=0')
     request = APIView().initialize_request(request)
     filters = HaystackRequestFilterMixin.get_request_filters(request)
     self.assertNotIn('q', filters)
     self.assertEqual(filters.get('test'), '0')
Beispiel #22
0
 def handle_exception(self, exc):
     if isinstance(exc, InvalidRequestException):
         return project_api_response.Response(
             self.request_form_errors, status=status.HTTP_400_BAD_REQUEST)
     base_response = APIView.handle_exception(self, exc)
     return project_api_response.Response(
         base_response.data, status=base_response.status_code)
Beispiel #23
0
 def test_get_request_filters_with_list(self):
     """ Verify the method does not affect list values. """
     request = APIRequestFactory().get(
         '/?q=&content_type=courserun&content_type=program')
     request = APIView().initialize_request(request)
     filters = HaystackRequestFilterMixin.get_request_filters(request)
     assert 'q' not in filters
     assert filters.getlist('content_type') == ['courserun', 'program']
Beispiel #24
0
    def test_authentication_no_user(self):
        """test when user containing token not egzists"""

        request = self.req_factory.get('/', {'token': self.token})
        # trick because of: AttributeError: 'WSGIRequest' object has no attribute 'query_params'
        request = APIView().initialize_request(request)
        with self.assertRaisesMessage(AuthenticationFailed, 'No such user'):
            self.auth_obj.authenticate(request)
Beispiel #25
0
def create_request_context():
    from rest_framework.test import APIRequestFactory
    factory = APIRequestFactory()
    request = factory.get('/')
    from rest_framework.views import APIView
    request = APIView().initialize_request(request)
    context = {'request': request}
    return context
    def get_mock_request(self, url, format, user=None):
        factory = APIRequestFactory()

        request = factory.get(url + '/swagger.' + format)
        if user is not None:
            force_authenticate(request, user=user)
        request = APIView().initialize_request(request)
        return request
Beispiel #27
0
 def setUp(self) -> None:
     self.enterprise_tier = self.create_enterprise_tier()
     self.user = CustomUserFactory(account_tier=self.enterprise_tier)
     self.user_image = UserImageFactory(user=self.user)
     self.permission = HasGenerateLinkPermission()
     self.request = RequestFactory()
     self.request.user = self.user
     self.view = APIView.as_view()
Beispiel #28
0
    def test_authentication(self):
        """test case when everything is ok"""

        user = UserFactory(uuid=self.token)
        request = self.req_factory.get('/', {'token': self.token})
        # trick because of: AttributeError: 'WSGIRequest' object has no attribute 'query_params'
        request = APIView().initialize_request(request)
        result = self.auth_obj.authenticate(request)
        self.assertEqual(result, (user, None))
 def test_has_permission(self, authentication_class, jwt_scopes, required_scopes, expected_result):
     request = RequestFactory().get('/')
     request.successful_authenticator = authentication_class
     request.auth = generate_jwt(self.user, scopes=jwt_scopes)
     if required_scopes is None:
         view = APIView()
     else:
         view = Mock(required_scopes=required_scopes)
     self.assertEqual(permissions.JwtHasScope().has_permission(request, view), expected_result)
Beispiel #30
0
        def construct_response_data(self, obj_id):
            obj = self.model.objects.get(id=obj_id)
            request = APIView().initialize_request(APIRequestFactory().request())
            serialized_obj = self.serializer(context={"request": request}).to_representation(obj)

            for name, transformer in self.field_transformers.items():
                serialized_obj[name] = transformer(serialized_obj[name])

            return serialized_obj
Beispiel #31
0
    def dispatch(self, request, *args, **kwargs):
        """
        `.dispatch()` is pretty much the same as Django's regular dispatch,
        but with extra hooks for startup, finalize, and exception handling.
        """

        response = APIView.dispatch(self, request, *args, **kwargs)
        # response.content = self.add_documentation(request, response.content)
        return response
Beispiel #32
0
def mock_schema_request(db):
    from rest_framework.test import force_authenticate

    factory = APIRequestFactory()
    user = User.objects.get(username="******")
    request = factory.get("/swagger.json")
    force_authenticate(request, user=user)
    request = APIView().initialize_request(request)
    return request
 def test_filters_or_query(self):
     backend = Filter()
     request = Request(factory.get('/', {'text': ['txt', 'axt']}))
     qs = BasicModel.objects.all()
     view = APIView()
     filtered_qs = backend.filter_queryset(request, qs, view)
     assert qs.query != filtered_qs.query
     # check or queries exist
     assert len(filtered_qs.query.where.children[0].children) == 2
Beispiel #34
0
# 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.

"""
URLs API for resources
"""

from django.conf.urls import url
from rest_framework.views import APIView

from ....api.charges import ChargeResourceView, EmailChargeReceiptAPIView
from ....settings import ACCT_REGEX


urlpatterns = [
    url(r'^charges/(?P<charge>%s)/email/' % ACCT_REGEX,
        EmailChargeReceiptAPIView.as_view(),
        name='saas_api_email_charge_receipt'),
    url(r'^charges/(?P<charge>%s)/?' % ACCT_REGEX,
        ChargeResourceView.as_view(), name='saas_api_charge'),
    url(r'^charges/',
        APIView.as_view(), name='saas_api_charge_base'),
]
 def _finalize_response(self, request, response, *args, **kwargs):
     response.request = request
     return APIView.finalize_response(self, request, response, *args, **kwargs)
Beispiel #36
0
 def handle_exception(self, exc):
     resp = handle_proctored_exception(exc, name=self.__class__.__name__)
     if not resp:
         resp = APIView.handle_exception(self, exc)
     return resp
from django.test import override_settings, TestCase
import mock
from rest_framework import exceptions, status
from rest_framework.test import APIClient
from rest_framework.views import APIView
from testfixtures import LogCapture


LOG_NAME = 'programs.apps.api.exception_handler'
LOG_LEVEL = 'INFO'
LOG_MSG_TEMPLATE = "raised_http_401: exc_type=u'{exc_type}', exc_detail=u'{exc_detail}'"


# make "/" map to a dummy view, that we can patch to raise various exceptions.
urlpatterns = [
    url(r'^$', APIView.as_view())
]


class Custom401Exception(exceptions.APIException):  # pylint:disable=missing-docstring
    status_code = status.HTTP_401_UNAUTHORIZED


class Custom400Exception(exceptions.APIException):  # pylint:disable=missing-docstring
    status_code = status.HTTP_400_BAD_REQUEST


@override_settings(ROOT_URLCONF='programs.apps.api.tests.test_exception_handler')
class TestAuthExceptionHandler(TestCase):
    """
    Ensure APIExceptions mapping to 401 responses are logged for diagnostic
from django.conf.urls import url
from django.contrib.auth.models import User
from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from rest_framework.views import APIView


urlpatterns = [
    url(r'^$', APIView.as_view(authentication_classes=(TokenAuthentication,))),
]


class MyMiddleware(object):

    def process_response(self, request, response):
        assert hasattr(request, 'user'), '`user` is not set on request'
        assert request.user.is_authenticated(), '`user` is not authenticated'
        return response


class TestMiddleware(APITestCase):

    urls = 'tests.test_middleware'

    def test_middleware_can_access_user_when_processing_response(self):
        user = User.objects.create_user('john', '*****@*****.**', 'password')
        key = 'abcd1234'
        Token.objects.create(key=key, user=user)
Beispiel #39
0
 def perform_authentication(self, request):
     myview = APIView()
     init_request = myview.initialize_request(request)
     myview.perform_authentication(init_request)
     return init_request.user.username