Esempio n. 1
0
 def get_links(self, obj):
     request = self.context['request']
     return {
         'self': drf_reverse('mimic-detail', kwargs={'pk': obj.pk}, request=request),
         'window': drf_reverse('window-detail', kwargs={'pk': obj.window.pk}, request=request),
         'vars': drf_reverse('var-list', request=request) + '?mimic=%s' % format(obj.pk),
     }
Esempio n. 2
0
 def test_serialized_data(self):
     request = self.client.get(reverse('api:user-list')).wsgi_request
     serializer = UserSerializer(self.user, context={'request': request})
     expected_data = {
         'url':
         drf_reverse('api:user-detail',
                     kwargs={'username': self.user.username},
                     request=request),
         'id':
         str(self.user.id),
         'username':
         self.user.username,
         'email':
         self.user.email,
         'first_name':
         self.user.first_name,
         'last_name':
         self.user.last_name,
         'date_created':
         self.user.date_created.isoformat(),
         'date_updated':
         self.user.date_updated.isoformat(),
         'profile':
         drf_reverse('api:profile-detail',
                     kwargs={'username': self.user.username},
                     request=request),
     }
     self.assertEqual(expected_data, serializer.data)
Esempio n. 3
0
 def test_api_root_returns_correct_links(self):
     expected_data = {
         "simulations": drf_reverse('api:simulations',
                                    request=self.request),
         "simulate": drf_reverse('api:simulate', request=self.request),
     }
     self.assertEqual(expected_data, self.response.data)
Esempio n. 4
0
def api_root(request, format=None):
    # TODO: Add endpoints from addons
    return Response({
        'windows': drf_reverse('window-list', request=request, format=format),
        'devices': drf_reverse('device-list', request=request, format=format),
        'users': drf_reverse('user-list', request=request, format=format),
        'menus': drf_reverse('menuitem-list', request=request, format=format),
    })
Esempio n. 5
0
def api_root(request, format=None):
    # TODO: Add endpoints from addons
    return Response({
        'windows': drf_reverse('window-list', request=request, format=format),
        'devices': drf_reverse('device-list', request=request, format=format),
        'users': drf_reverse('user-list', request=request, format=format),
        'menus': drf_reverse('menuitem-list', request=request, format=format),
    })
Esempio n. 6
0
def api_root(request, format=None):
    return Response({
        'windows':
        drf_reverse('window-list', request=request, format=format),
        'devices':
        drf_reverse('device-list', request=request, format=format),
        'users':
        drf_reverse('user-list', request=request, format=format),
    })
Esempio n. 7
0
def reverse_api_view(viewname, *args, **kwargs):
    # Requires request as a kwarg.
    #
    # Reverse needs to be called with the api namespace when the
    # request is made to perma.cc/api, and cannot be called with
    # a namespace when the request is made to api.perma.cc
    try:
        return drf_reverse('api:' + viewname, *args, **kwargs)
    except NoReverseMatch:
        return drf_reverse(viewname, *args, **kwargs)
Esempio n. 8
0
def reverse_api_view(viewname, *args, **kwargs):
    # Requires request as a kwarg.
    #
    # Reverse needs to be called with the api namespace when the
    # request is made to perma.cc/api, and cannot be called with
    # a namespace when the request is made to api.perma.cc
    try:
        return drf_reverse('api:' + viewname, *args, **kwargs)
    except NoReverseMatch:
        return drf_reverse(viewname, *args, **kwargs)
Esempio n. 9
0
 def get_links(self, obj):
     request = self.context['request']
     return {
         'self':
         drf_reverse('var-detail', kwargs={'pk': obj.pk}, request=request),
         'device':
         drf_reverse('device-detail',
                     kwargs={'pk': obj.device.pk},
                     request=request),
     }
Esempio n. 10
0
 def get_links(self, obj):
     request = self.context['request']
     return {
         'self':
         drf_reverse('device-detail',
                     kwargs={'pk': obj.pk},
                     request=request),
         'vars':
         drf_reverse('var-list', request=request) +
         '?device={}'.format(obj.pk),
     }
Esempio n. 11
0
 def get_url(self, obj):
     if obj.endpoint == 'search':
         api = drf_reverse('addon-search',
                           request=self.context.get('request'))
         url = api + obj.criteria
     elif obj.endpoint == 'collections':
         url = drf_reverse('collection-addon-list',
                           request=self.context.get('request'),
                           kwargs={
                               'user_pk': settings.TASK_USER_ID,
                               'collection_slug': obj.criteria
                           })
     return url
Esempio n. 12
0
 def get_links(self, obj):
     request = self.context['request']
     return {
         'self':
         drf_reverse('window-detail',
                     kwargs={'pk': obj.pk},
                     request=request),
         'mimics':
         drf_reverse('mimic-list', request=request) +
         '?window={}'.format(obj.pk),
         'vars':
         drf_reverse('var-list', request=request) +
         '?mimic__window={}'.format(obj.pk),
     }
Esempio n. 13
0
    def clean(self):
        data = self.cleaned_data

        endpoint = data.get('endpoint')
        criteria = data.get('criteria')

        if criteria is None:
            return

        try:
            if endpoint in ('search', 'search-themes'):
                if not criteria.startswith('?') or criteria.count('?') > 1:
                    raise forms.ValidationError('Check criteria field.')
                params = criteria[1:].split('&')
                if endpoint == 'search' and 'type=statictheme' in params:
                    raise forms.ValidationError(
                        'Use "search-themes" endpoint for type=statictheme.'
                    )
                elif endpoint == 'search-themes' and 'type=statictheme' not in params:
                    raise forms.ValidationError(
                        'Don`t use "search-themes" endpoint for non themes. '
                        'Use "search".'
                    )
                url = drf_reverse('addon-search', request=self.request) + criteria
            elif endpoint == 'collections':
                url = drf_reverse(
                    'collection-addon-list',
                    request=self.request,
                    kwargs={
                        'user_pk': settings.TASK_USER_ID,
                        'collection_slug': criteria,
                    },
                )
            else:
                return

        except NoReverseMatch:
            raise forms.ValidationError('No data found - check criteria parameters.')

        try:
            response = requests.get(url)
            if response.status_code == 404:
                raise forms.ValidationError('Check criteria - No data found')
            if response.status_code != 200:
                raise forms.ValidationError('Check criteria - %s' % response.json()[0])
            if response.json().get('count', 0) == 0:
                raise forms.ValidationError('Check criteria parameters - e.g., "type"')

        except requests.exceptions.ConnectionError:
            raise forms.ValidationError('Connection Error')
Esempio n. 14
0
 def get_url(self, instance):
     return absolutify(
         drf_reverse(
             'addon-upload-detail',
             request=self.context.get('request'),
             args=[instance.uuid.hex],
         ))
Esempio n. 15
0
 def to_representation(self, value):
     # Get the parameters we need for reversing
     request = self.context['request']
     format = self.context.get('format', None)
     if format and self.format and self.format != format:
         format = self.format
     reverse = lambda view_name, kwargs: drf_reverse(
         view_name, kwargs=kwargs, request=request, format=format)
     # Always start with the self link
     links = dict(
         self=reverse("{}-detail".format(self.basename), dict(pk=value.pk)))
     # Add links to the related objects
     links.update({
         name: reverse(view_name, dict(pk=getattr(value, attr)))
         for name, view_name, attr in (self.related_object_links or [])
     })
     # Add the related list links
     links.update({
         name: reverse(view_name, {self.basename + '_pk': value.pk})
         for name, view_name in (self.related_list_links or [])
     })
     # Add extra actions to the links
     links.update({
         name: reverse(view_name, dict(pk=value.pk))
         for name, view_name in (self.action_links or [])
     })
     return links
Esempio n. 16
0
 def get_links(self, obj):
     request = self.context['request']
     return {
         'self':
         drf_reverse('group-detail', kwargs={'pk': obj.pk},
                     request=request),
     }
    def test_create_child_on_viewset_with_mixin(self):
        """
        The `ViewSet` that uses `NestedViewSetMixin` automatically sets the
        parent kwarg on the request.{data,query_params} querydict.

        This allows the parent lookup arg to _not_ be provided on the POST
        data, as is already provided as part of the URL.
        """
        resource_url = reverse('child-with-nested-mixin-list',
                               kwargs={'parent_pk': self.root_1.pk})

        response = self.client.post(resource_url,
                                    content_type='application/json',
                                    data=json.dumps({
                                        'name': 'New Child',
                                    }))

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        data = json.loads(response.content.decode())

        self.assertEqual(data['name'], 'New Child')
        parent_url = drf_reverse('root-detail',
                                 kwargs={'pk': self.root_1.pk},
                                 request=response.wsgi_request)
        self.assertEqual(data['parent'], parent_url)
 def validate(self, data):
     qs = self.Meta.model.objects.filter(inchikey=data["inchikey"])
     if self.instance:
         qs = qs.exclude(pk=self.instance.pk)
     if qs.exists() and not self.admin_override:
         matched = []
         req = self.context.get("request", None)
         for obj in qs:
             matched.append(
                 drf_reverse("definedcompound-detail",
                             request=req,
                             kwargs={"pk": obj.pk}))
         raise ValidationError(
             {
                 "detail": {
                     "detail":
                     f"Inchikey conflicts with {[x.id for x in qs]}",
                     "links": matched,
                     "status": "400",
                     "source": {
                         "pointer": "/data/attributes/inchikey"
                     },
                     "code": "invalid",
                 },
             }, )
     return data
Esempio n. 19
0
 def get_validation_url_json(self, obj):
     return absolutify(
         drf_reverse(
             'reviewers-addon-json-file-validation',
             request=self.context.get('request'),
             args=[obj.addon.pk, obj.current_file.id],
         ))
Esempio n. 20
0
    def test_status_create_with_image_and_content(self):
        self.test_user_token()
        url = drf_reverse('home')
        #(w,h)=(800,1280)
        #color = (255,255,255)
        image_item = Image.new('RGB', (800, 1280), (0, 124, 174))
        temp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
        image_item.save(temp_file, format='JPEG')

        with open(temp_file.name, 'rb') as file_obj:

            data = {
                'content': 'some cool test content',
                'image': file_obj,
            }
            response = self.client.post(url, data, format='multipart')
            print(response.data)
            img_data = response.data.get('image')
            self.assertNotEqual(img_data, None)
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)
            self.assertEqual(Status.objects.count(), 2)

        #remove temp img
        temp_img_dir = os.path.join(settings.MEDIA_ROOT, 'status', 'rahi')
        print(temp_img_dir)
        if os.path.exists(temp_img_dir):
            print('yes exists')
            shutil.rmtree(temp_img_dir)
Esempio n. 21
0
 def create_item(self):
     self.test_user_token()
     url = drf_reverse('home')
     data = {'content': 'some cool test content'}
     response = self.client.post(url, data, format='json')
     self.assertEqual(response.status_code, status.HTTP_201_CREATED)
     self.assertEqual(Status.objects.count(), 2)
     return response.data
Esempio n. 22
0
 def _get_download_url(self, file_):
     url = drf_reverse(
         'signing.file',
         request=self._context.get('request'),
         kwargs={'file_id': file_.id},
     )
     url = os.path.join(url, file_.filename)
     return absolutify(url)
Esempio n. 23
0
 def get_links(self, obj):
     request = self.context['request']
     return {
         'self':
         drf_reverse('mimic-detail', kwargs={'pk': obj.pk},
                     request=request),
         'window':
         drf_reverse('window-detail',
                     kwargs={'pk': obj.window.pk},
                     request=request),
         'vars':
         drf_reverse('var-list', request=request) +
         '?mimic=%s' % format(obj.pk),
         'rules':
         drf_reverse('rule-list', request=request) +
         '?mimic=%s' % format(obj.pk),
     }
Esempio n. 24
0
    def test_api_root_get_routes(self, user: settings.AUTH_USER_MODEL,
                                 request_factory: RequestFactory):
        """Ensure the api root view produces the required hyperlinks."""

        view = APIRootView()
        url = drf_reverse("accounts-api:api-root")
        request = request_factory.get(url)
        request.user = user

        view.request = request
        routes = view.get_routes(request)

        assert isinstance(routes, dict)
        assert routes["users"] == drf_reverse("accounts-api:user-list",
                                              request=request)
        assert routes["check-username-availability"] == drf_reverse(
            "accounts-api:user-check-username-availability", request=request)
Esempio n. 25
0
 def get_url(self, instance):
     return absolutify(
         drf_reverse('signing.version',
                     request=self._context.get('request'),
                     args=[
                         instance.addon.guid, instance.version,
                         instance.uuid.hex
                     ]))
Esempio n. 26
0
    def test_token_register_user_api(self):
        url = drf_reverse('login')
        data = {'username': '******', 'password': '******'}

        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        token = response.data.get('token', None)
        self.client.credentials(HTTP_AUTHORIZATION=f'JWT {token}')

        url2 = drf_reverse('register')
        data2 = {
            'username': '******',
            'email': '*****@*****.**',
            'password': '******',
            'password2': 'rahirahi'
        }
        response = self.client.post(url2, data2, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Esempio n. 27
0
 def get_links(self, obj):
     request = self.context['request']
     username = obj.get_username()
     return {
         'self':
         drf_reverse('user-detail',
                     kwargs={User.USERNAME_FIELD: username},
                     request=request),
     }
Esempio n. 28
0
    def test_status_create_and_get(self):
        data = self.create_item()
        data_id = data.get('id')
        rud_url = drf_reverse('status-detail', kwargs={'pk': data_id})
        rud_data = {'content': 'updated cool data'}

        #get method/ retrieve
        get_response = self.client.get(rud_url, foramt='json')
        self.assertEqual(get_response.status_code, status.HTTP_200_OK)
def drf_url(context, viewname, *args, **kwargs):
    """Helper for DjangoRestFramework's ``reverse`` in templates."""
    request = context.get('request')
    if request:
        if not hasattr(request, 'versioning_scheme'):
            request.versioning_scheme = api_settings.DEFAULT_VERSIONING_CLASS()
        request.version = request.versioning_scheme.determine_version(
            request, *args, **kwargs)
    return drf_reverse(viewname, request=request, args=args, kwargs=kwargs)
Esempio n. 30
0
 def test_empty_create_item(self):
     self.test_user_token()
     url = drf_reverse('home')
     data = {
         #'content':'some cool test content'
     }
     response = self.client.post(url, data, format='json')
     self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
     return response.data
Esempio n. 31
0
    def get_url(self, obj):
        if obj.endpoint in (Shelf.Endpoints.SEARCH, Shelf.Endpoints.RANDOM_TAG):
            api = drf_reverse('addon-search', request=self.context.get('request'))
            params = obj.get_param_dict()
            url = f'{api}?{"&".join(f"{key}={value}" for key, value in params.items())}'
        elif obj.endpoint == Shelf.Endpoints.COLLECTIONS:
            url = drf_reverse(
                'collection-addon-list',
                request=self.context.get('request'),
                kwargs={
                    'user_pk': str(settings.TASK_USER_ID),
                    'collection_slug': obj.criteria,
                },
            )
        else:
            url = None

        return url
def drf_url(context, viewname, *args, **kwargs):
    """Helper for DjangoRestFramework's ``reverse`` in templates."""
    request = context.get('request')
    if request:
        if not hasattr(request, 'versioning_scheme'):
            request.versioning_scheme = api_settings.DEFAULT_VERSIONING_CLASS()
        request.version = request.versioning_scheme.determine_version(
            request, *args, **kwargs)
    return drf_reverse(viewname, request=request, args=args, kwargs=kwargs)
Esempio n. 33
0
    def get_url(self, obj):
        if obj.endpoint in ('search', 'search-themes'):
            api = drf_reverse('addon-search',
                              request=self.context.get('request'))
            url = api + obj.criteria
        elif obj.endpoint == 'collections':
            url = drf_reverse(
                'collection-addon-list',
                request=self.context.get('request'),
                kwargs={
                    'user_pk': str(settings.TASK_USER_ID),
                    'collection_slug': obj.criteria,
                },
            )
        else:
            url = None

        return url
Esempio n. 34
0
    def clean(self):
        data = self.cleaned_data
        baseUrl = settings.INTERNAL_SITE_URL

        endpoint = data.get('endpoint')
        criteria = data.get('criteria')

        if criteria is None:
            return

        try:
            if endpoint == 'search':
                if not criteria.startswith('?') or criteria.count('?') > 1:
                    raise forms.ValidationError('Check criteria field.')
                else:
                    api = drf_reverse('v4:addon-search')
                    url = baseUrl + api + criteria
            elif endpoint == 'collections':
                api = drf_reverse('v4:collection-addon-list',
                                  kwargs={
                                      'user_pk': settings.TASK_USER_ID,
                                      'collection_slug': criteria
                                  })
                url = baseUrl + api
            else:
                return

        except NoReverseMatch:
            raise forms.ValidationError(
                'No data found - check criteria parameters.')

        try:
            response = requests.get(url)
            if response.status_code == 404:
                raise forms.ValidationError('Check criteria - No data found')
            if response.status_code != 200:
                raise forms.ValidationError('Check criteria - %s' %
                                            response.json()[0])
            if response.json().get('count', 0) == 0:
                raise forms.ValidationError(
                    'Check criteria parameters - e.g., "type"')

        except requests.exceptions.ConnectionError:
            raise forms.ValidationError('Connection Error')
Esempio n. 35
0
    def test_get_all_patient_api(self):
        # this should not be taken as a reason not to do more indepth unit tests!
        # its just a nice sanity check
        patient_lists = PatientList.list()
        request = self.factory.get("/")
        request.user = self.user
        for pl in patient_lists:
            slug = pl.get_slug()
            url = drf_reverse(
                "patientlist-detail", kwargs={"pk": slug}, request=request
            )

            self.assertStatusCode(
                url, 200,
                msg="Failed to load the template for {}".format(slug)
            )
Esempio n. 36
0
 def get_model_data(self, model):
     model_admin = self.registry[model]
     model_options = utils.model_options(model)
     opts = {
         'current_app': model_admin.admin.name,
         'app_label': model_options.app_label,
         'model_name': model_options.object_name.lower(),
     }
     model_url = drf_reverse(
         '%(current_app)s:%(app_label)s_%(model_name)s_api_list' % opts,
         request=self.request,
         format=self.kwargs.get('format'))
     model_options = utils.model_options(model)
     return {
         'url': model_url,
         'verbose_name': force_str(model_options.verbose_name),
         'verbose_name_plural': force_str(model_options.verbose_name_plural),
     }
Esempio n. 37
0
def reverse_ns(viewname, api_version=None, args=None, kwargs=None, **extra):
    """An API namespace aware reverse to be used in DRF API based tests.

    It works by creating a fake request from the API version you need, and
    then setting the version so the un-namespaced viewname from DRF is resolved
    into the namespaced viewname used interally by django.

    Unless overriden with the api_version parameter, the API version used is
    the DEFAULT_VERSION in settings.

    e.g. reverse_ns('addon-detail') is resolved to reverse('v4:addon-detail')
    if the api version is 'v4'.
    """
    api_version = api_version or api_settings.DEFAULT_VERSION
    request = req_factory_factory('/api/%s/' % api_version)
    request.versioning_scheme = api_settings.DEFAULT_VERSIONING_CLASS()
    request.version = api_version
    return drf_reverse(
        viewname, args=args or [], kwargs=kwargs or {}, request=request,
        **extra)
    def test_version_history(self):
        self.client.cookies[API_TOKEN_COOKIE] = 'magicbeans'
        v1 = self.version
        v2, _ = self._extra_version_and_file(amo.STATUS_AWAITING_REVIEW)

        response = self.client.get(self.url)
        assert response.status_code == 200
        doc = pq(response.content)

        show_links = doc('.review-history-show')
        assert show_links.length == 3
        assert show_links[0].attrib['data-div'] == '#%s-review-history' % v1.id
        assert not show_links[1].attrib.get('data-div')
        assert show_links[2].attrib['data-div'] == '#%s-review-history' % v2.id

        # All 3 links will have a 'data-version' attribute.
        assert show_links[0].attrib['data-version'] == str(v1.id)
        # But the 2nd link will point to the latest version in the channel.
        assert show_links[1].attrib['data-version'] == str(v2.id)
        assert show_links[2].attrib['data-version'] == str(v2.id)

        # Test review history
        review_history_td = doc('#%s-review-history' % v1.id)[0]
        assert review_history_td.attrib['data-token'] == 'magicbeans'
        api_url = absolutify(drf_reverse(
            'v4:version-reviewnotes-list',
            args=[self.addon.id, self.version.id]))
        assert review_history_td.attrib['data-api-url'] == api_url
        assert doc('.review-history-hide').length == 2

        pending_activity_count = doc('.review-history-pending-count')
        # No counter, because we don't have any pending activity to show.
        assert pending_activity_count.length == 0

        # Reply box div is there (only one)
        assert doc('.dev-review-reply-form').length == 1
        review_form = doc('.dev-review-reply-form')[0]
        review_form.attrib['action'] == api_url
        review_form.attrib['data-token'] == 'magicbeans'
        review_form.attrib['data-history'] == '#%s-review-history' % v2.id
Esempio n. 39
0
 def url(self):
     from rest_framework.reverse import reverse as drf_reverse
     return drf_reverse('song_file', kwargs={'song_id': self.id, })
Esempio n. 40
0
 def get_links(self, obj):
     request = self.context['request']
     return {
         'self': drf_reverse('device-detail', kwargs={'pk': obj.pk}, request=request),
         'vars': drf_reverse('var-list', request=request) + '?device={}'.format(obj.pk),
     }
Esempio n. 41
0
 def get_links(self, obj):
     request = self.context['request']
     return {
         'self': drf_reverse('group-detail', kwargs={'pk': obj.pk}, request=request),
     }
Esempio n. 42
0
 def get_url(self, instance):
     return absolutify(drf_reverse(
         'signing.version', request=self._context.get('request'),
         args=[instance.addon.guid, instance.version, instance.uuid.hex]))
Esempio n. 43
0
 def _get_download_url(self, file_):
     url = drf_reverse(
         'signing.file', request=self._context.get('request'),
         kwargs={'file_id': file_.id})
     url = os.path.join(url, file_.filename)
     return absolutify(urlparams(url, src='api'))
Esempio n. 44
0
def api_root(request, format=None):
    return Response({
        'windows': drf_reverse('window-list', request=request, format=format),
        'devices': drf_reverse('device-list', request=request, format=format),
        'users': drf_reverse('user-list', request=request, format=format),
    })
Esempio n. 45
0
 def test_get_api_url(self):
     survey = self.factory.create()
     expected_url = drf_reverse('survey-form', kwargs={'pk': survey.pk})
     self.assertEqual(survey.get_api_url(), expected_url)
Esempio n. 46
0
 def get_links(self, obj):
     request = self.context['request']
     return {
         'self': drf_reverse('var-detail', kwargs={'pk': obj.pk}, request=request),
         'device': drf_reverse('device-detail', kwargs={'pk': obj.device.pk}, request=request),
     }
Esempio n. 47
0
 def get_links(self, obj):
     request = self.context['request']
     username = obj.get_username()
     return {
         'self': drf_reverse('user-detail', kwargs={User.USERNAME_FIELD: username}, request=request),
     }