def test_collaborator_with_read_perms_can_delete_self(self):
        """
        Tests that collaborator with read perms can only
        delete it's own object.
        """
        self.account_owner.is_owner = False
        self.account_owner.save()

        user = User.objects.create_user(
            username='******',
            email='*****@*****.**',
            password=self.password,
            first_name='Other',
            last_name='User'
        )

        self.board_collaborator.permission = 'read'
        self.board_collaborator.user = user
        self.board_collaborator.save()

        request = Request(self.factory.delete('/', self.data, format='json'))
        request.parsers = (JSONParser(), )
        request.user = self.user

        view = mock_view(request)
        has_perm = self.perm_class.has_object_permission(
            request, view, self.board_collaborator)

        self.assertFalse(has_perm)
    def test_multiple_shared_works(self):
        request = RequestFactory().post(
            '/',
            HTTP_AUTHORIZATION='mkt-shared-secret '
            '[email protected],56b6f1a3dd735d962c56'
            'ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb'
            '9c68c31b3371aa8130317815c89e5072e31bb94b4'
            '121c5c165f3515838d4d6c60c4,165d631d3c3045'
            '458b4516242dad7ae')
        drf_request = Request(request)

        # Start with an AnonymousUser on the request, because that's a classic
        # situation: we already went through a middleware, it didn't find a
        # session cookie, if set request.user = AnonymousUser(), and now we
        # are going through the authentication code in the API.
        request.user = AnonymousUser()
        drf_request.authenticators = (
                authentication.RestSharedSecretAuthentication(),
                authentication.RestOAuthAuthentication())

        eq_(drf_request.user, self.profile.user)
        eq_(drf_request._request.user, self.profile.user)
        eq_(drf_request.user.is_authenticated(), True)
        eq_(drf_request._request.user.is_authenticated(), True)
        eq_(drf_request.amo_user.pk, self.profile.pk)
        eq_(drf_request._request.amo_user.pk, self.profile.pk)
    def test_read_write_hyperlinked_collection_property(self):
        request = Request(make_dummy_request())
        request._user = User(username='******', is_superuser=True)

        context = {'request': request}
        serializer = ProjectSerializer(self.project, context=context)

        field = serializer.get_fields()['notes']
        property_serializer = HydraPropertySerializer(
            field, 'notes',
            'projectns:',
            self.project,
            context=context
        )

        supported_operations = property_serializer.data\
            .get('property')\
            .get('hydra:supportedOperation')

        self.assertEqual(len(supported_operations), 2)

        create_operation, = filter(lambda op: op.get('hydra:method') == 'POST',
                                   supported_operations)

        self.assertDictEqual(dict(create_operation), {
            '@id': '_:project_note_create',
            '@type': 'hydra:CreateResourceOperation',
            'label': 'Create a note for this project.',
            'description': None,
            'hydra:method': 'POST',
            'hydra:expects': 'projectns:Note',
            'hydra:returns': 'projectns:Note',
            'hydra:possibleStatus': []
        })
Exemple #4
0
    def test_empty_slug_request_m2m(self):
        class ExampleSerializer(serializers.ModelSerializer):
            my_m2mfield = serializers.SlugRelatedField(many=True, slug_field='username', queryset=User.objects.all())
            class Meta:
                model = models.MyModel

        serializer = ExampleSerializer({'content': 'a','my_m2mfield':[]})
        factory = APIRequestFactory()
        content = json.dumps(serializer.data)
        content_type = 'application/json'
        post_data = {
            api_settings.FORM_CONTENT_OVERRIDE: content,
            api_settings.FORM_CONTENTTYPE_OVERRIDE: content_type
        }
        request = factory.post('/', data=post_data)
        # tbd: try another type of basic request
#        request = urllib2.Request('/', content, {'Content-Type': 'application/json'})
        request = DRFRequest(request)
        request.parsers = (JSONParser(), )
        serializer = ExampleSerializer(data=request.data)
        self.assertTrue(serializer.is_valid())
        self.assertTrue(isinstance(serializer.validated_data['my_m2mfield'],list))
        self.assertEqual(serializer.validated_data, {'content': u'a', 'my_m2mfield': []})
        obj = serializer.create(serializer.validated_data)
        self.assertEqual(obj.content, 'a')
        self.assertEqual(len(obj.my_m2mfield.all()), 0)
Exemple #5
0
class TestFlowEventViewSet(TestCase):

    def setUp(self):
        self.view_set = views.FlowEventViewSet()
        self.view_set.format_kwarg = ''

        self.period = FlowEventFactory()
        FlowEventFactory(timestamp=TIMEZONE.localize(datetime.datetime(2014, 2, 28)))

        self.request = Request(HttpRequest())
        self.request.__setattr__('user', self.period.user)
        self.view_set.request = self.request

    def test_list(self):
        response = self.view_set.list(self.request)

        self.assertEqual(1, len(response.data))
        self.assertEqual(self.period.id, response.data[0]['id'])

    def test_perform_create(self):
        serializer = FlowEventSerializer(data={'timestamp': datetime.datetime(2015, 1, 1)})
        serializer.is_valid()

        self.view_set.perform_create(serializer)

        self.assertEqual(self.request.user, serializer.instance.user)
    def test_multiple_shared_works(self):
        request = RequestFactory().post(
            "/api",
            HTTP_AUTHORIZATION="mkt-shared-secret "
            "[email protected],56b6f1a3dd735d962c56"
            "ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb"
            "9c68c31b3371aa8130317815c89e5072e31bb94b4"
            "121c5c165f3515838d4d6c60c4,165d631d3c3045"
            "458b4516242dad7ae",
        )
        drf_request = Request(request)

        # Start with an AnonymousUser on the request, because that's a classic
        # situation: we already went through a middleware, it didn't find a
        # session cookie, if set request.user = AnonymousUser(), and now we
        # are going through the authentication code in the API.
        request.user = AnonymousUser()

        # Call middleware as they would normally be called.
        RedirectPrefixedURIMiddleware().process_request(request)
        RestSharedSecretMiddleware().process_request(request)
        RestOAuthMiddleware().process_request(request)

        drf_request.authenticators = (
            authentication.RestSharedSecretAuthentication(),
            authentication.RestOAuthAuthentication(),
        )

        eq_(drf_request.user, self.profile.user)
        eq_(drf_request._request.user, self.profile.user)
        eq_(drf_request.user.is_authenticated(), True)
        eq_(drf_request._request.user.is_authenticated(), True)
        eq_(drf_request.amo_user.pk, self.profile.pk)
        eq_(drf_request._request.amo_user.pk, self.profile.pk)
Exemple #7
0
    def test_read_write_hyperlinked_collection_property(self):
        request = Request(make_dummy_request())
        request._user = User(is_superuser=True)

        context = {"request": request}
        serializer = ProjectSerializer(self.project, context=context)

        field = serializer.get_fields()["notes"]
        property_serializer = HydraPropertySerializer(field, "notes", "projectns:", self.project, context=context)

        supported_operations = property_serializer.data.get("property").get("hydra:supportedOperation")

        self.assertEqual(len(supported_operations), 2)

        create_operation, = [op for op in supported_operations if op.get("hydra:method") == "POST"]

        self.assertDictEqual(
            dict(create_operation),
            {
                "@id": "_:project_note_create",
                "@type": "hydra:CreateResourceOperation",
                "label": "Create a note for this project.",
                "description": None,
                "hydra:method": "POST",
                "hydra:expects": "projectns:Note",
                "hydra:returns": "projectns:Note",
                "hydra:possibleStatus": [],
            },
        )
 def test_request_POST_with_form_content(self):
     """
     Ensure request.POST returns content for POST request with form content.
     """
     data = {'qwerty': 'uiop'}
     request = Request(factory.post('/', data))
     request.parsers = (FormParser(), MultiPartParser())
     assert list(request.POST.items()) == list(data.items())
 def test_standard_behaviour_determines_form_content_PUT(self):
     """
     Ensure request.DATA returns content for PUT request with form content.
     """
     data = {'qwerty': 'uiop'}
     request = Request(factory.put('/', data))
     request.parsers = (FormParser(), MultiPartParser())
     self.assertEqual(list(request.DATA.items()), list(data.items()))
 def test_request_DATA_with_form_content(self):
     """
     Ensure request.DATA returns content for POST request with form content.
     """
     data = {'qwerty': 'uiop'}
     request = Request(factory.post('/', data))
     request.parsers = (FormParser(), MultiPartParser())
     self.assertEqual(list(request.DATA.items()), list(data.items()))
Exemple #11
0
 def _make_api_call(self, requesting_user, target_user, course_key):
     """
     Call the `course_detail` api endpoint to get information on the course
     identified by `course_key`.
     """
     request = Request(self.request_factory.get('/'))
     request.user = requesting_user
     return course_detail(request, target_user.username, course_key)
Exemple #12
0
 def _make_api_call(self, requesting_user, specified_user):
     """
     Call the list_courses api endpoint to get information about
     `specified_user` on behalf of `requesting_user`.
     """
     request = Request(self.request_factory.get('/'))
     request.user = requesting_user
     return list_courses(request, specified_user.username)
 def test_request_POST_with_form_content(self):
     """
     Ensure request.POST returns content for POST request with form content.
     """
     data = {"qwerty": "uiop"}
     request = Request(factory.post("/", data))
     request.parsers = (FormParser(), MultiPartParser())
     self.assertEqual(list(request.POST.items()), list(data.items()))
 def test_request_POST_with_files(self):
     """
     Ensure request.POST returns no content for POST request with file content.
     """
     upload = SimpleUploadedFile("file.txt", b"file_content")
     request = Request(factory.post('/', {'upload': upload}))
     request.parsers = (FormParser(), MultiPartParser())
     self.assertEqual(list(request.POST.keys()), [])
     self.assertEqual(list(request.FILES.keys()), ['upload'])
Exemple #15
0
 def __make_sub_request(request, url, resolver):
     wsgi_request = copy(request._request)
     wsgi_request.method = 'GET'
     wsgi_request.path = wsgi_request.path_info = urlsplit(url).path
     wsgi_request.resolver_match = resolver.resolve(wsgi_request.path_info)
     sub_request = Request(wsgi_request)
     sub_request.user = request.user
     sub_request.authenticators = request.authenticators
     return sub_request
Exemple #16
0
 def _make_api_call(self, requesting_user, specified_user, org=None, filter_=None):
     """
     Call the list_courses api endpoint to get information about
     `specified_user` on behalf of `requesting_user`.
     """
     request = Request(self.request_factory.get('/'))
     request.user = requesting_user
     with check_mongo_calls(0):
         return list_courses(request, specified_user.username, org=org, filter_=filter_)
Exemple #17
0
 def _get_request(self, user=None):
     """
     Build a Request object for the specified user.
     """
     if user is None:
         user = self.honor_user
     request = Request(self.request_factory.get('/'))
     request.user = user
     return request
 def test_standard_behaviour_determines_non_form_content_PUT(self):
     """
     Ensure request.data returns content for PUT request with
     non-form content.
     """
     content = b'qwerty'
     content_type = 'text/plain'
     request = Request(factory.put('/', content, content_type=content_type))
     request.parsers = (PlainTextParser(), )
     assert request.data == content
 def test_request_DATA_with_text_content(self):
     """
     Ensure request.data returns content for POST request with
     non-form content.
     """
     content = six.b("qwerty")
     content_type = "text/plain"
     request = Request(factory.post("/", content, content_type=content_type))
     request.parsers = (PlainTextParser(),)
     self.assertEqual(request.data, content)
 def test_standard_behaviour_determines_non_form_content_PUT(self):
     """
     Ensure request.data returns content for PUT request with
     non-form content.
     """
     content = six.b("qwerty")
     content_type = "text/plain"
     request = Request(factory.put("/", content, content_type=content_type))
     request.parsers = (PlainTextParser(),)
     self.assertEqual(request.data, content)
 def test_request_DATA_with_text_content(self):
     """
     Ensure request.data returns content for POST request with
     non-form content.
     """
     content = b'qwerty'
     content_type = 'text/plain'
     request = Request(factory.post('/', content, content_type=content_type))
     request.parsers = (PlainTextParser(),)
     assert request.data == content
Exemple #22
0
    def test_multiple_fail(self):
        request = RequestFactory().post('/')
        drf_request = Request(request)
        request.user = AnonymousUser()
        drf_request.authenticators = (
                authentication.RestSharedSecretAuthentication(),
                authentication.RestOAuthAuthentication())

        eq_(drf_request.user.is_authenticated(), False)
        eq_(drf_request._request.user.is_authenticated(), False)
 def test_request_DATA_with_text_content(self):
     """
     Ensure request.DATA returns content for POST request with
     non-form content.
     """
     content = six.b('qwerty')
     content_type = 'text/plain'
     request = Request(factory.post('/', content, content_type=content_type))
     request.parsers = (PlainTextParser(),)
     self.assertEqual(request.DATA, content)
 def test_standard_behaviour_determines_non_form_content_PUT(self):
     """
     Ensure request.DATA returns content for PUT request with
     non-form content.
     """
     content = six.b('qwerty')
     content_type = 'text/plain'
     request = Request(factory.put('/', content, content_type=content_type))
     request.parsers = (PlainTextParser(), )
     self.assertEqual(request.DATA, content)
    def test_attribute_access_proxy(self):
        http_request = factory.get('/')
        request = Request(http_request)

        inner_sentinel = object()
        http_request.inner_property = inner_sentinel
        assert request.inner_property is inner_sentinel

        outer_sentinel = object()
        request.inner_property = outer_sentinel
        assert request.inner_property is outer_sentinel
    def test_get_cache_key_returns_correct_key_if_user_is_authenticated(self):
        class DummyView:
            throttle_scope = 'user'

        request = Request(HttpRequest())
        user = User.objects.create(username='******')
        force_authenticate(request, user)
        request.user = user
        self.throttle.allow_request(request, DummyView())
        cache_key = self.throttle.get_cache_key(request, view=DummyView())
        assert cache_key == 'throttle_user_%s' % user.pk
 def test_overloaded_behaviour_allows_content_tunnelling(self):
     """
     Ensure request.data returns content for overloaded POST request.
     """
     json_data = {"foobar": "qwerty"}
     content = json.dumps(json_data)
     content_type = "application/json"
     form_data = {api_settings.FORM_CONTENT_OVERRIDE: content, api_settings.FORM_CONTENTTYPE_OVERRIDE: content_type}
     request = Request(factory.post("/", form_data))
     request.parsers = (JSONParser(),)
     self.assertEqual(request.data, json_data)
Exemple #28
0
    def test_list_with_min_timestamp(self):
        http_request = HttpRequest()
        http_request.GET = QueryDict(u'min_timestamp=2014-01-05')
        request = Request(http_request)
        request.__setattr__('user', self.period.user)
        self.view_set.kwargs = {'pk': self.request.user.statistics.pk}

        response = self.view_set.list(request)

        self.assertEqual(4, len(response.data))
        self.assertEqual(28, response.data['average_cycle_length'])
        self.assertEqual(self.period.timestamp.date(), response.data['first_date'])
        self.assertEqual(1, response.data['first_day'])
    def test_has_permission_should_return_true(self):
        """
        Tests that `.has_permission` returns `True`.
        """
        request = Request(self.factory.get('/'))
        request.parsers = (JSONParser(), )
        request.user = self.user

        view = mock_view(request)
        view.action = 'list'

        has_perm = self.perm_class.has_permission(request, view)

        self.assertTrue(has_perm)
    def test_authentication_is_required(self):
        """
        Tests that `.has_permission` returns `False`
        if user is not authenticated.
        """
        request = Request(self.factory.post('/', self.data, format='json'))
        request.parsers = (JSONParser(), )

        view = mock_view(request)
        view.action = 'create'

        has_perm = self.perm_class.has_permission(request, view)

        self.assertFalse(has_perm)
Exemple #31
0
    def post(self, request: Request, project_id) -> Response:
        """Create a deep-link.

        The request user must not be anonymous and must have annotate
        permissions.
        ---
        serializer: DeepLinkSerializer
        """
        if request.user == get_anonymous_user(
        ) or not request.user.is_authenticated:
            raise PermissionError('Unauthenticated or anonymous users ' \
                                   'can not create persistent deep links.')

        project_id = int(project_id)

        alias = request.POST.get('alias')
        if alias:
            if not re.match(r'^[a-zA-Z0-9-_\.]+$', alias):
                raise ValueError(
                    "Only alphanumeric characters, '-', '_' and '.' allowed")
        else:
            n_links = DeepLink.objects.filter(project_id=project_id).count()
            alias = make_unique_id()

        params = {
            'project_id': project_id,
            'user': request.user,
            'alias': alias,
        }

        if 'is_public' in request.POST:
            params['is_public'] = get_request_bool(request.POST, 'is_public')

        if 'location_x' in request.POST:
            params['location_x'] = float(request.POST['location_x'])

        if 'location_y' in request.POST:
            params['location_y'] = float(request.POST['location_y'])

        if 'location_z' in request.POST:
            params['location_z'] = float(request.POST['location_z'])

        if 'active_treenode_id' in request.POST:
            params['active_treenode_id'] = int(
                request.POST['active_treenode_id'])

        if 'active_connector_id' in request.POST:
            params['active_connector_id'] = int(
                request.POST['active_connector_id'])

        if 'active_skeleton_id' in request.POST:
            params['active_skeleton_id'] = int(
                request.POST['active_skeleton_id'])

        if 'closest_node_to_location' in request.POST:
            params['closest_node_to_location'] = get_request_bool(
                request.POST, 'closest_node_to_location')

        if 'follow_id_history' in request.POST:
            params['follow_id_history'] = get_request_bool(
                request.POST, 'follow_id_history')

        if 'layered_stacks' in request.POST:
            params['layered_stacks'] = get_request_bool(
                request.POST, 'layered_stacks')

        if 'layout' in request.POST:
            params['layout'] = request.POST['layout']

        if 'tool' in request.POST:
            params['tool'] = request.POST['tool']

        if 'show_help' in request.POST:
            params['show_help'] = get_request_bool(request.POST, 'show_help')

        if 'password' in request.POST:
            params['password'] = make_password(request.POST('password'))

        if 'message' in request.POST:
            params['message'] = request.POST['message']

        # TBA: data_view

        deeplink = DeepLink(**params)
        deeplink.save()
        serializer = DeepLinkSerializer(deeplink)

        # Stacks
        stacks = get_request_list(request.POST, 'stacks', map_fn=float)
        if stacks:
            # Nested lists of 2-tuples: [[stack_id, scale_level]]
            for s in stacks:
                stack_link = DeepLinkStack(
                    **{
                        'project_id': project_id,
                        'user_id': request.user.id,
                        'deep_link': deeplink,
                        'stack_id': int(s[0]),
                        'zoom_level': s[1],
                    })
                stack_link.save()

        # Stack groups
        if 'stack_group' in request.POST:
            sg_id = int(request.POST['stack_group'])
            sg_zoom_levels = get_request_list(request.POST,
                                              'stack_group_scale_levels',
                                              map_fn=float)
            sg_link = DeepLinkStackGroup(
                **{
                    'project_id': project_id,
                    'user_id': request.user.id,
                    'deeplink': deeplink,
                    'stack_group_id': sg_id,
                    'zoom_levels': sg_zoom_levels,
                })
            sg_link.save()

        return Response(serializer.data)
 def test_default_secure_true(self):
     request = Request(factory.get('/', secure=True))
     self.assertEqual(request.scheme, 'https')
 def test_failed_session_auth_query(self):
     req = RequestFactory().post('/api/?_user=bogus')
     for m in self.middlewares:
         m().process_request(req)
     ok_(not self.auth.authenticate(Request(req)))
     assert not getattr(req, 'amo_user', None)
 def test_default_secure_true(self):
     request = Request(factory.get('/', secure=True))
     assert request.scheme == 'https'
 def test_auth_can_be_set(self):
     request = Request(factory.get('/'))
     request.auth = 'DUMMY'
     assert request.auth == 'DUMMY'
Exemple #36
0
 def _mock_get_request(self, url):
     return Request(self.request_factory.get(url))
Exemple #37
0
 def test_client_overspecifies_accept_use_client(self):
     request = Request(
         factory.get('/', HTTP_ACCEPT='application/json; indent=8'))
     accepted_renderer, accepted_media_type = self.select_renderer(request)
     self.assertEquals(accepted_media_type, 'application/json; indent=8')
    def test_schema_for_regular_views(self):
        """
        Ensure that schema generation works for ViewSet classes
        with method limitation by Django CBV's http_method_names attribute
        """
        generator = SchemaGenerator(title='Example API',
                                    patterns=self.patterns)
        request = factory.get('/example1/')
        schema = generator.get_schema(Request(request))

        expected = coreapi.Document(
            url='http://testserver/example1/',
            title='Example API',
            content={
                'example1': {
                    'list':
                    coreapi.Link(
                        url='/example1/',
                        action='get',
                        fields=[
                            coreapi.Field(
                                'page',
                                required=False,
                                location='query',
                                schema=coreschema.Integer(
                                    title='Page',
                                    description=
                                    'A page number within the paginated result set.'
                                )),
                            coreapi.Field(
                                'page_size',
                                required=False,
                                location='query',
                                schema=coreschema.Integer(
                                    title='Page size',
                                    description=
                                    'Number of results to return per page.')),
                            coreapi.Field(
                                'ordering',
                                required=False,
                                location='query',
                                schema=coreschema.String(
                                    title='Ordering',
                                    description=
                                    'Which field to use when ordering the results.'
                                ))
                        ]),
                    'custom_list_action':
                    coreapi.Link(url='/example1/custom_list_action/',
                                 action='get'),
                    'custom_list_action_multiple_methods': {
                        'read':
                        coreapi.Link(
                            url=
                            '/example1/custom_list_action_multiple_methods/',
                            action='get')
                    },
                    'read':
                    coreapi.Link(url='/example1/{id}/',
                                 action='get',
                                 fields=[
                                     coreapi.Field('id',
                                                   required=True,
                                                   location='path',
                                                   schema=coreschema.String())
                                 ])
                }
            })
        assert schema == expected
Exemple #39
0
    def setUp(self):
        self.feira1 = Feira.objects.create(
            id=FIXTURES['feira1']['id'],
            longi=FIXTURES['feira1']['longi'],
            lat=FIXTURES['feira1']['lat'],
            setcens=FIXTURES['feira1']['setcens'],
            areap=FIXTURES['feira1']['areap'],
            coddist=FIXTURES['feira1']['coddist'],
            distrito=FIXTURES['feira1']['distrito'],
            codsubpref=FIXTURES['feira1']['codsubpref'],
            subprefe=FIXTURES['feira1']['subprefe'],
            regiao5=FIXTURES['feira1']['regiao5'],
            regiao8=FIXTURES['feira1']['regiao8'],
            nome_feira=FIXTURES['feira1']['nome_feira'],
            registro=FIXTURES['feira1']['registro'],
            logradouro=FIXTURES['feira1']['logradouro'],
            numero=FIXTURES['feira1']['numero'],
            bairro=FIXTURES['feira1']['bairro'],
            referencia=FIXTURES['feira1']['referencia'])

        self.feira2 = Feira.objects.create(
            id=FIXTURES['feira2']['id'],
            longi=FIXTURES['feira2']['longi'],
            lat=FIXTURES['feira2']['lat'],
            setcens=FIXTURES['feira2']['setcens'],
            areap=FIXTURES['feira2']['areap'],
            coddist=FIXTURES['feira2']['coddist'],
            distrito=FIXTURES['feira2']['distrito'],
            codsubpref=FIXTURES['feira2']['codsubpref'],
            subprefe=FIXTURES['feira2']['subprefe'],
            regiao5=FIXTURES['feira2']['regiao5'],
            regiao8=FIXTURES['feira2']['regiao8'],
            nome_feira=FIXTURES['feira2']['nome_feira'],
            registro=FIXTURES['feira2']['registro'],
            logradouro=FIXTURES['feira2']['logradouro'],
            numero=FIXTURES['feira2']['numero'],
            bairro=FIXTURES['feira2']['bairro'],
            referencia=FIXTURES['feira2']['referencia'])
        '''
        Eu tive que adicionar o código abaixo setando o serializer em um
        contexto explícito porque caso contrário o serializador terá problemas
        quando houver listado a "url" em sua lista de campos Meta.
        O erro apontado antes de definir explicitamente o contexto do serializador,
        foi semelhante à este:

        AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context.
        Add `context={'request': request}` when instantiating the serializer

        Este thread stackoverflow ajudou a resolvê-lo:
        Http://stackoverflow.com/questions/34438290/assertionerror-hyperlinkedidentityfield-requires-the-request-in-the-serialize
        '''
        factory = APIRequestFactory()
        request = factory.get('/')
        serializer_context = {'request': Request(request)}

        # Serializer aqui produz um dict
        self.feira1_data = FeiraSerializer(self.feira1,
                                           context=serializer_context).data
        # Abaixo nós atualizamos este dict definindo os valores que queremos mudar (nome_feira)
        self.feira1_data.update({'nome_feira': 'GENERICA SP 1 *** CHANGED'})

        # Abaixo funciona exatamente como o caso de "self.feira1_data"
        self.feira2_data = FeiraSerializer(self.feira2,
                                           context=serializer_context).data
        self.feira2_data.update({'nome_feira': 'GENERICA SP 2 *** CHANGED'})
Exemple #40
0
    def paginate_queryset(
        self,
        queryset: QuerySet,
        request: Request,
        view: APIView = None,
    ) -> OptionalList:
        serializer_class = self.get_request_serializer_class()
        serializer = serializer_class(data=request.query_params,
                                      max_per_page=self.max_page_size)
        serializer.is_valid(raise_exception=True)

        self.per_page = serializer.validated_data.get(
            self.page_size_query_param)

        if not self.per_page:
            return None

        after_uuid = serializer.validated_data.get(self.after_query_param)
        before_uuid = serializer.validated_data.get(self.before_query_param)

        order = get_order(self.default_order, serializer.validated_data.keys())
        self.cursor_obj, self.order = get_cursor(queryset, after_uuid,
                                                 before_uuid, order)

        lookup = self.get_lookup()
        if lookup:
            queryset = queryset.filter(**lookup)

        order_sign = '-' if self.order == 'before' else ''
        order_keyword = f'{order_sign}{self.order_by_field}'
        queryset = queryset.order_by(order_keyword)

        base_url = request.build_absolute_uri()
        self.base_url = replace_query_param(base_url,
                                            self.page_size_query_param,
                                            self.per_page)
        self.request = request
        self.has_next = False

        start_offset = 0
        stop_offset = start_offset + self.per_page + 1

        if self.use_count:
            self.total = queryset.count()

        paginated = list(queryset[:stop_offset])

        if len(paginated) > self.per_page:
            self.has_next = True
            del paginated[-1]

        if paginated:
            self.page_boundaries = (
                paginated[0].uuid,
                paginated[-1].uuid,
            )
        elif self.cursor_obj:
            self.page_boundaries = (self.cursor_obj.uuid, self.cursor_obj.uuid)
        else:
            self.page_boundaries = (None, None)

        return paginated
    def test_with_request(self):
        factory = APIRequestFactory()
        request = Request(factory.get('/?q=1'))

        assert get_query_param(request, 'q') == 1
 def test_invalid_cursor(self):
     request = Request(factory.get('/', {'cursor': '123'}))
     with pytest.raises(exceptions.NotFound):
         self.pagination.paginate_queryset(self.queryset, request)
 def test_invalid_page(self):
     request = Request(factory.get('/', {'page': 'invalid'}))
     with pytest.raises(exceptions.NotFound):
         self.paginate_queryset(request)
Exemple #44
0
	def retrieve (self,request,pk):
		event = Event.objects.get(pk=pk)
		serializer_context={'request':Request(request._request)}
		return Response(EventByIdSerializer(event,context=serializer_context).data)
Exemple #45
0
 def test_client_without_accept_use_renderer(self):
     request = Request(factory.get('/'))
     accepted_renderer, accepted_media_type = self.select_renderer(request)
     self.assertEquals(accepted_media_type, 'application/json')
def test_not(backend, view, rf, monkeypatch):
    request = Request(rf.get('/aaa/?id__not=1'))
    monkeypatch.setattr(view, 'filter_fields', ['id'])

    qs = backend.filter_queryset(request, view.queryset, view)
    assert not qs.filter(id=1)
Exemple #47
0
 def setUp(self):
     self.request = Request(RequestFactory().get('/'))
def view(rf):
    request = Request(rf.get(''))
    return DemoModelView(request=request,
                         queryset=DemoModel.objects.all(),
                         format_kwarg=None)
Exemple #49
0
from __future__ import unicode_literals

from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.test import TestCase

from rest_framework import (exceptions, metadata, serializers, status,
                            versioning, views)
from rest_framework.renderers import BrowsableAPIRenderer
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory

request = Request(APIRequestFactory().options('/'))


class TestMetadata:
    def test_metadata(self):
        """
        OPTIONS requests to views should return a valid 200 response.
        """
        class ExampleView(views.APIView):
            """Example view."""
            pass

        view = ExampleView.as_view()
        response = view(request=request)
        expected = {
            'name':
            'Example',
            'description':
            'Example view.',
def test_invalid_filter(backend, view, rf):
    request = Request(rf.get('/aaa/?a=1'))

    with pytest.raises(InvalidFilterError):
        backend.filter_queryset(request, view.queryset, view)
 def test_default_secure_false(self):
     request = Request(factory.get('/', secure=False))
     assert request.scheme == 'http'
 def test_standard_behaviour_determines_no_content_GET(self):
     """
     Ensure request.data returns empty QueryDict for GET request.
     """
     request = Request(factory.get('/'))
     self.assertEqual(request.data, {})
 def test_standard_behaviour_determines_no_content_HEAD(self):
     """
     Ensure request.data returns empty QueryDict for HEAD request.
     """
     request = Request(factory.head('/'))
     assert request.data == {}
 def test_default_secure_false(self):
     request = Request(factory.get('/', secure=False))
     self.assertEqual(request.scheme, 'http')
Exemple #55
0
 def setUp(self):
     # Create a mock incoming request and view
     self.request = Request(HttpRequest())
     self.view = HasScopesTest.MockView()
     self.perm = permissions.HasScopesPermission()
Exemple #56
0
	def list (self, request):
		events= Event.objects.all()
		serializer_context = {'request': Request(request._request)}
		return Response(EventSerializer(events, many=True, context=serializer_context).data)
Exemple #57
0
    def dispatch(self, request: Request, *args, **kwargs) -> Response:
        """
        Identical to rest framework's dispatch except we add the ability
        to convert arguments (for common URL params).
        """
        with sentry_sdk.start_span(op="base.dispatch.setup", description=type(self).__name__):
            self.args = args
            self.kwargs = kwargs
            request = self.initialize_request(request, *args, **kwargs)
            self.load_json_body(request)
            self.request = request
            self.headers = self.default_response_headers  # deprecate?

        # Tags that will ultimately flow into the metrics backend at the end of
        # the request (happens via middleware/stats.py).
        request._metric_tags = {}

        start_time = time.time()

        origin = request.META.get("HTTP_ORIGIN", "null")
        # A "null" value should be treated as no Origin for us.
        # See RFC6454 for more information on this behavior.
        if origin == "null":
            origin = None

        try:
            with sentry_sdk.start_span(op="base.dispatch.request", description=type(self).__name__):
                if origin:
                    if request.auth:
                        allowed_origins = request.auth.get_allowed_origins()
                    else:
                        allowed_origins = None
                    if not is_valid_origin(origin, allowed=allowed_origins):
                        response = Response(f"Invalid origin: {origin}", status=400)
                        self.response = self.finalize_response(request, response, *args, **kwargs)
                        return self.response

                self.initial(request, *args, **kwargs)

                # Get the appropriate handler method
                if request.method.lower() in self.http_method_names:
                    handler = getattr(self, request.method.lower(), self.http_method_not_allowed)

                    (args, kwargs) = self.convert_args(request, *args, **kwargs)
                    self.args = args
                    self.kwargs = kwargs
                else:
                    handler = self.http_method_not_allowed

                if getattr(request, "access", None) is None:
                    # setup default access
                    request.access = access.from_request(request)

            with sentry_sdk.start_span(
                op="base.dispatch.execute",
                description=f"{type(self).__name__}.{handler.__name__}",
            ):
                response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(request, exc)

        if origin:
            self.add_cors_headers(request, response)

        self.response = self.finalize_response(request, response, *args, **kwargs)

        if settings.SENTRY_API_RESPONSE_DELAY:
            duration = time.time() - start_time

            if duration < (settings.SENTRY_API_RESPONSE_DELAY / 1000.0):
                with sentry_sdk.start_span(
                    op="base.dispatch.sleep",
                    description=type(self).__name__,
                ) as span:
                    span.set_data("SENTRY_API_RESPONSE_DELAY", settings.SENTRY_API_RESPONSE_DELAY)
                    time.sleep(settings.SENTRY_API_RESPONSE_DELAY / 1000.0 - duration)

        return self.response
Exemple #58
0
    def post(self, request: Request, name=None):
        check_captcha = grecaptcha_verify(request)
        if not check_captcha["status"]:
            return HttpResponseForbidden(text=check_captcha["message"])

        request.session["file_guid"] = None
        #############################################################
        #  Adding different pdf form logic: Jul 3, 2020
        data = request.data
        name = request.query_params.get("name")

        template = "{}.html".format(name)

        # These are the current allowed forms (whitelist)
        possibleTemplates = [
            "notice-to-disputant-response",
            "violation-ticket-statement-and-written-reasons",
        ]

        # If not one of our two forms... reject.
        if name not in possibleTemplates:
            return HttpResponseBadRequest("No valid form specified")

        transformed_data = transform(data)

        template = get_template(template)
        html_content = template.render(transformed_data)
        #############################################################

        disputant = data.get("disputantName", {})
        email = data.get("disputantEmail")

        result_bin = json.dumps(data).encode("ascii")
        (key_id, result_enc) = settings.ENCRYPTOR.encrypt(result_bin)

        response = TicketResponse(
            first_name=disputant.get("first"),
            middle_name=disputant.get("middle"),
            last_name=disputant.get("last"),
            result=result_enc,
            key_id=key_id,
            ticket_number=data.get("ticketNumber"),
            ticket_date=data.get("ticketDate"),
            hearing_location_id=data.get("hearingLocation"),
            hearing_attendance=data.get("hearingAttendance"),
            dispute_type=data.get("disputeType"),
        )

        check_required = [
            "first_name",
            "last_name",
            "ticket_number",
            "ticket_date",
            "hearing_location_id",
        ]

        for fname in check_required:
            if not getattr(response, fname):
                return HttpResponseBadRequest("Missing: " + fname)

        # Generate/Save the pdf to DB and generate email with pdf attached
        email_sent = False
        pdf_response = None

        try:
            pdf_content = render_pdf(html_content)

            pdf_response = PreparedPdf(data=pdf_content)
            pdf_response.save()
            response.prepared_pdf_id = pdf_response.pk
            response.printed_date = timezone.now()

            if pdf_content:
                (pdf_key_id,
                 pdf_content_enc) = settings.ENCRYPTOR.encrypt(pdf_content)
                pdf_response = PreparedPdf(data=pdf_content_enc,
                                           key_id=pdf_key_id)
                pdf_response.save()
                response.prepared_pdf_id = pdf_response.pk
                response.save()
                request.session["file_guid"] = str(response.file_guid)

            if email and pdf_content:
                send_email(email, pdf_content, name)
                response.emailed_date = timezone.now()
                email_sent = True
                response.save()

        except Exception as exception:
            LOGGER.exception("Pdf / Email generation error", exception)

        return Response({"id": response.pk, "email-sent": email_sent})
Exemple #59
0
 def setUp(self):
     fact = APIRequestFactory()
     request = fact.get("/")
     req = Request(request)
     self.definition_serializer = NiftiInputDefinitionSerializer(
         instance=self.definition, context={"request": req})
 def test_auth_can_be_set(self):
     request = Request(factory.get('/'))
     request.auth = 'DUMMY'
     self.assertEqual(request.auth, 'DUMMY')