예제 #1
0
    def test_redirect(self):
        url = "/developers/"
        res = self.client.get(urlparams(reverse("users.logout"), to=url), follow=True)
        self.assert3xx(res, url, status_code=302)

        # Test that we don't follow domains
        url = urlparams(reverse("users.logout"), to="http://ev.il/developers/")
        res = self.client.get(url, follow=True)
        self.assert3xx(res, "/", status_code=302)
예제 #2
0
    def test_redirect(self):
        url = '/developers/'
        res = self.client.get(urlparams(reverse('users.logout'), to=url),
                              follow=True)
        self.assert3xx(res, url, status_code=302)

        # Test that we don't follow domains
        url = urlparams(reverse('users.logout'), to='http://ev.il/developers/')
        res = self.client.get(url, follow=True)
        self.assert3xx(res, '/', status_code=302)
예제 #3
0
    def test_redirect(self):
        url = '/developers/'
        res = self.client.get(urlparams(reverse('users.logout'), to=url),
                              follow=True)
        self.assert3xx(res, url, status_code=302)

        # Test that we don't follow domains
        url = urlparams(reverse('users.logout'), to='http://ev.il/developers/')
        res = self.client.get(url, follow=True)
        self.assert3xx(res, '/', status_code=302)
예제 #4
0
    def test_compare_revisions_missing_query_param(self):
        """Try to compare two revisions, with a missing query string param."""
        url = reverse('wiki.compare_revisions', args=[self.document.slug])
        query = {'from': self.revision1.id}
        url = urlparams(url, **query)
        response = self.client.get(url)
        eq_(404, response.status_code)

        url = reverse('wiki.compare_revisions', args=[self.document.slug])
        query = {'to': self.revision1.id}
        url = urlparams(url, **query)
        response = self.client.get(url)
        eq_(404, response.status_code)
예제 #5
0
파일: oauth.py 프로젝트: Fjoerfoks/zamboni
def authorize(request):
    if request.method == 'GET' and 'oauth_token' in request.GET:
        try:
            t = Token.objects.get(token_type=REQUEST_TOKEN,
                                  key=request.GET['oauth_token'])
        except Token.DoesNotExist:
            log.error('Invalid OAuth request for obtaining user authorization')
            return HttpResponse(status=401)
        return render(request, 'developers/oauth_authorize.html',
                      {'app_name': t.creds.app_name,
                       'oauth_token': request.GET['oauth_token']})
    elif request.method == 'POST':
        token = request.POST.get('oauth_token')
        try:
            t = Token.objects.get(token_type=REQUEST_TOKEN,
                                  key=token)
        except Token.DoesNotExist:
            return HttpResponse(status=401)
        if 'grant' in request.POST:
            t.user = request.user
            t.save()
            return HttpResponseRedirect(
                urlparams(t.creds.redirect_uri, oauth_token=token,
                          oauth_verifier=t.verifier))
        elif 'deny' in request.POST:
            t.delete()
            return HttpResponse(status=200)
    else:
        log.error('Invalid OAuth request for user access authorization')
        return HttpResponse(status=401)
예제 #6
0
파일: oauth.py 프로젝트: waseem18/zamboni
def authorize(request):
    if request.method == 'GET' and 'oauth_token' in request.GET:
        try:
            t = Token.objects.get(token_type=REQUEST_TOKEN,
                                  key=request.GET['oauth_token'])
        except Token.DoesNotExist:
            log.error('Invalid OAuth request for obtaining user authorization')
            return HttpResponse(status=401)
        return render(
            request, 'developers/oauth_authorize.html', {
                'app_name': t.creds.app_name,
                'oauth_token': request.GET['oauth_token']
            })
    elif request.method == 'POST':
        token = request.POST.get('oauth_token')
        try:
            t = Token.objects.get(token_type=REQUEST_TOKEN, key=token)
        except Token.DoesNotExist:
            return HttpResponse(status=401)
        if 'grant' in request.POST:
            t.user = request.user
            t.save()
            return HttpResponseRedirect(
                urlparams(t.creds.redirect_uri,
                          oauth_token=token,
                          oauth_verifier=t.verifier))
        elif 'deny' in request.POST:
            t.delete()
            return HttpResponse(status=200)
    else:
        log.error('Invalid OAuth request for user access authorization')
        return HttpResponse(status=401)
예제 #7
0
    def test_logout(self):
        data = self._test_login()

        r = self.client.delete(
            urlparams(self.logout_url, _user=data['token']),
            content_type='application/json')
        eq_(r.status_code, 204)
예제 #8
0
파일: test_views.py 프로젝트: zullkay/kuma
    def test_intermediate(self):
        """
        Test that the intermediate DocumentAttachment gets created
        correctly when adding an Attachment with a document_id.

        """
        doc = document(locale='en', slug='attachment-test-intermediate')
        doc.save()
        rev = revision(document=doc, is_approved=True)
        rev.save()

        file_for_upload = make_test_file(
            content='A file for testing intermediate attachment model.')

        post_data = {
            'title': 'Intermediate test file',
            'description': 'Intermediate test file',
            'comment': 'Initial upload',
            'file': file_for_upload,
        }

        add_url = urlparams(reverse('attachments.new_attachment'),
                            document_id=doc.id)
        resp = self.client.post(add_url, data=post_data)
        eq_(302, resp.status_code)

        eq_(1, doc.files.count())

        intermediates = DocumentAttachment.objects.filter(document__pk=doc.id)
        eq_(1, intermediates.count())

        intermediate = intermediates[0]
        eq_('admin', intermediate.attached_by.username)
        eq_(file_for_upload.name.split('/')[-1], intermediate.name)
예제 #9
0
    def process_request(self, request):
        prefixer = Prefixer(request)
        set_url_prefixer(prefixer)
        full_path = prefixer.fix(prefixer.shortened_path)

        if 'lang' in request.GET:
            # Blank out the locale so that we can set a new one. Remove lang
            # from the query params so we don't have an infinite loop.
            prefixer.locale = ''
            new_path = prefixer.fix(prefixer.shortened_path)
            query = dict((smart_str(k), v) for
                         k, v in request.GET.iteritems() if k != 'lang')
            return HttpResponsePermanentRedirect(urlparams(new_path, **query))

        if full_path != request.path:
            query_string = request.META.get('QUERY_STRING', '')
            full_path = urllib.quote(full_path.encode('utf-8'))

            if query_string:
                full_path = '%s?%s' % (full_path, query_string)

            response = HttpResponsePermanentRedirect(full_path)

            # Vary on Accept-Language if we changed the locale
            old_locale = prefixer.locale
            new_locale, _ = split_path(full_path)
            if old_locale != new_locale:
                response['Vary'] = 'Accept-Language'

            return response

        request.path_info = '/' + prefixer.shortened_path
        request.locale = prefixer.locale
        translation.activate(prefixer.locale)
예제 #10
0
    def test_logout(self):
        UserProfile.objects.create(email='*****@*****.**')
        data = self._test_login()

        r = self.client.delete(urlparams(self.logout_url, _user=data['token']),
                               content_type='application/json')
        eq_(r.status_code, 204)
예제 #11
0
 def test_detail_translated(self):
     res = self.anon.get(
         urlparams(reverse('regions-detail', kwargs={'pk': 'br'}),
                   lang='fr'))
     eq_(res.status_code, 200)
     data = json.loads(res.content)
     eq_(data['name'], u'Brésil')
예제 #12
0
def _document_redirect_to_create(document_slug, document_locale, slug_dict):
    """
    When a Document doesn't exist but the user can create it, return
    the creation URL to redirect to.
    """
    url = reverse('wiki.new_document', locale=document_locale)
    if slug_dict['length'] > 1:
        parent_doc = get_object_or_404(Document,
                                       locale=document_locale,
                                       slug=slug_dict['parent'],
                                       is_template=0)
        url = urlparams(url, parent=parent_doc.id, slug=slug_dict['specific'])
    else:
        # This is a "base level" redirect, i.e. no parent
        url = urlparams(url, slug=document_slug)
    return url
예제 #13
0
def _default_locale_fallback(request, document_slug, document_locale):
    """
    If we're falling back to a Document in the default locale, figure
    out why and whether we can redirect to a translation in the
    requested locale.

    """
    fallback_doc = None
    redirect_url = None
    fallback_reason = None

    try:
        fallback_doc = Document.objects.get(
            locale=settings.WIKI_DEFAULT_LANGUAGE, slug=document_slug)

        # If there's a translation to the requested locale, take it:
        translation = fallback_doc.translated_to(document_locale)

        if translation and translation.current_revision:
            url = translation.get_absolute_url()
            redirect_url = urlparams(url, query_dict=request.GET)
        elif translation and fallback_doc.current_revision:
            # Found a translation but its current_revision is None
            # and OK to fall back to parent (parent is approved).
            fallback_reason = 'translation_not_approved'
        elif fallback_doc.current_revision:
            # There is no translation
            # and OK to fall back to parent (parent is approved).
            fallback_reason = 'no_translation'
    except Document.DoesNotExist:
        pass

    return fallback_doc, fallback_reason, redirect_url
예제 #14
0
def redirect(request, viewer, key):
    new = Token(data=[viewer.file.id, key])
    new.save()
    url = urljoin(settings.STATIC_URL,
                  reverse('mkt.files.serve', args=[viewer, key]))
    url = urlparams(url, token=new.token)
    return http.HttpResponseRedirect(url)
예제 #15
0
    def test_get_content_ratings_since(self):
        cr = ContentRating.objects.create(addon=self.app, ratings_body=0,
                                          rating=0)
        cr.update(modified=self.days_ago(100))

        res = self.client.get(urlparams(
            reverse('content-ratings-list', args=[self.app.app_slug]),
            since=self.days_ago(5)))
        eq_(res.status_code, 404)

        cr.update(modified=self.days_ago(1))
        res = self.client.get(urlparams(
            reverse('content-ratings-list', args=[self.app.id]),
            since=self.days_ago(5)))
        eq_(res.status_code, 200)
        eq_(len(json.loads(res.content)['objects']), 1)
예제 #16
0
파일: middleware.py 프로젝트: bluemini/kuma
    def process_request(self, request):
        # https://bugzil.la/1189222
        # Don't redirect POST $subscribe requests to GET zone url
        if request.method == 'POST' and '$subscribe' in request.path:
            return None

        remaps = DocumentZoneURLRemapsJob().get(request.locale)
        for original_path, new_path in remaps:

            if (
                request.path_info == original_path or
                request.path_info.startswith(u''.join([original_path, '/']))
            ):
                # Is this a request for the "original" wiki path? Redirect to
                # new URL root, if so.
                new_path = request.path_info.replace(original_path,
                                                     new_path,
                                                     1)
                new_path = '/%s%s' % (request.locale, new_path)

                query = request.GET.copy()
                if 'lang' in query:
                    query.pop('lang')
                new_path = urlparams(new_path, query_dict=query)

                return HttpResponseRedirect(new_path)

            elif request.path_info.startswith(new_path):
                # Is this a request for the relocated wiki path? If so, rewrite
                # the path as a request for the proper wiki view.
                request.path_info = request.path_info.replace(new_path,
                                                              original_path,
                                                              1)
                break
예제 #17
0
    def process_request(self, request):
        # https://bugzil.la/1189222
        # Don't redirect POST $subscribe requests to GET zone url
        if request.method == 'POST' and '$subscribe' in request.path:
            return None

        remaps = DocumentZoneURLRemapsJob().get(request.locale)
        for original_path, new_path in remaps:

            if request.path_info.startswith(original_path):
                # Is this a request for the "original" wiki path? Redirect to
                # new URL root, if so.
                new_path = request.path_info.replace(original_path, new_path,
                                                     1)
                new_path = '/%s%s' % (request.locale, new_path)

                query = request.GET.copy()
                if 'lang' in query:
                    query.pop('lang')
                new_path = urlparams(new_path, query_dict=query)

                return HttpResponseRedirect(new_path)

            elif request.path_info.startswith(new_path):
                # Is this a request for the relocated wiki path? If so, rewrite
                # the path as a request for the proper wiki view.
                request.path_info = request.path_info.replace(
                    new_path, original_path, 1)
                break
예제 #18
0
    def test_logout(self):
        data = self._test_login()

        r = self.client.delete(
            urlparams(self.logout_url, _user=data['token']),
            content_type='application/json')
        eq_(r.status_code, 204)
예제 #19
0
    def process_request(self, request):
        prefixer = Prefixer(request)
        set_url_prefixer(prefixer)
        full_path = prefixer.fix(prefixer.shortened_path)

        if 'lang' in request.GET:
            # Blank out the locale so that we can set a new one. Remove lang
            # from the query params so we don't have an infinite loop.
            prefixer.locale = ''
            new_path = prefixer.fix(prefixer.shortened_path)
            query = dict((smart_str(k), v) for k, v in request.GET.iteritems()
                         if k != 'lang')
            return HttpResponsePermanentRedirect(urlparams(new_path, **query))

        if full_path != request.path:
            query_string = request.META.get('QUERY_STRING', '')
            full_path = urllib.quote(full_path.encode('utf-8'))

            if query_string:
                full_path = '%s?%s' % (full_path, query_string)

            response = HttpResponsePermanentRedirect(full_path)

            # Vary on Accept-Language if we changed the locale
            old_locale = prefixer.locale
            new_locale, _ = split_path(full_path)
            if old_locale != new_locale:
                response['Vary'] = 'Accept-Language'

            return response

        request.path_info = '/' + prefixer.shortened_path
        request.LANGUAGE_CODE = prefixer.locale or settings.LANGUAGE_CODE
        translation.activate(prefixer.locale)
예제 #20
0
 def test_bad_parameters(self):
     """Ensure badly-formed revision parameters do not cause errors"""
     url = reverse('wiki.compare_revisions', args=[self.document.slug])
     query = {'from': '1e309', 'to': u'1e309'}
     url = urlparams(url, **query)
     response = self.client.get(url)
     eq_(404, response.status_code)
예제 #21
0
파일: middleware.py 프로젝트: Osmose/kuma
    def process_request(self, request):
        remaps = DocumentZoneURLRemapsJob().get(request.locale)
        for original_path, new_path in remaps:

            if request.path_info.startswith(original_path):
                # Is this a request for the "original" wiki path? Redirect to
                # new URL root, if so.
                new_path = request.path_info.replace(original_path,
                                                     new_path,
                                                     1)
                new_path = '/%s%s' % (request.locale, new_path)

                query = request.GET.copy()
                if 'lang' in query:
                    query.pop('lang')
                new_path = urlparams(new_path, query_dict=query)

                return HttpResponseRedirect(new_path)

            elif request.path_info.startswith(new_path):
                # Is this a request for the relocated wiki path? If so, rewrite
                # the path as a request for the proper wiki view.
                request.path_info = request.path_info.replace(new_path,
                                                              original_path,
                                                              1)
                break
예제 #22
0
def manifest(request):
    ctx = RequestContext(request)
    data = {
        "name": getattr(settings, "WEBAPP_MANIFEST_NAME", "Firefox Marketplace"),
        "description": "The Firefox Marketplace",
        "developer": {"name": "Mozilla", "url": "http://mozilla.org"},
        "icons": {
            # Using the default addon image until we get a marketplace logo.
            "128": media(ctx, "img/mkt/logos/128.png"),
            "64": media(ctx, "img/mkt/logos/64.png"),
            "32": media(ctx, "img/mkt/logos/32.png"),
        },
        "activities": {
            "marketplace-app": {"href": "/"},
            "marketplace-app-rating": {"href": "/"},
            "marketplace-category": {"href": "/"},
            "marketplace-search": {"href": "/"},
        },
    }
    if get_carrier():
        data["launch_path"] = urlparams("/", carrier=get_carrier())

    manifest_content = json.dumps(data)
    manifest_etag = hashlib.sha256(manifest_content).hexdigest()

    @etag(lambda r: manifest_etag)
    def _inner_view(request):
        response = HttpResponse(manifest_content, content_type="application/x-web-app-manifest+json")
        return response

    return _inner_view(request)
예제 #23
0
파일: oauth.py 프로젝트: ujdhesa/zamboni
def authorize(request):
    if request.method == "GET" and "oauth_token" in request.GET:
        try:
            t = Token.objects.get(token_type=REQUEST_TOKEN, key=request.GET["oauth_token"])
        except Token.DoesNotExist:
            log.error("Invalid OAuth request for obtaining user authorization")
            return HttpResponse(status=401)
        return render(
            request,
            "developers/oauth_authorize.html",
            {"app_name": t.creds.app_name, "oauth_token": request.GET["oauth_token"]},
        )
    elif request.method == "POST":
        token = request.POST.get("oauth_token")
        try:
            t = Token.objects.get(token_type=REQUEST_TOKEN, key=token)
        except Token.DoesNotExist:
            return HttpResponse(status=401)
        if "grant" in request.POST:
            t.user = request.user
            t.save()
            return HttpResponseRedirect(urlparams(t.creds.redirect_uri, oauth_token=token, oauth_verifier=t.verifier))
        elif "deny" in request.POST:
            t.delete()
            return HttpResponse(status=200)
    else:
        log.error("Invalid OAuth request for user access authorization")
        return HttpResponse(status=401)
예제 #24
0
def _mini_manifest(addon, version_id, token=None):
    if not addon.is_packaged:
        raise http.Http404

    version = get_object_or_404(addon.versions, pk=version_id)
    file_ = version.all_files[0]
    manifest = addon.get_manifest_json(file_)

    package_path = absolutify(
        reverse('reviewers.signed', args=[addon.app_slug, version.id]))

    if token:
        # Generate a fresh token.
        token = Token(data={'app_id': addon.id})
        token.save()
        package_path = urlparams(package_path, token=token.token)

    data = {
        'name': manifest['name'],
        'version': version.version,
        'size': file_.size,
        'release_notes': version.releasenotes,
        'package_path': package_path,
    }
    for key in ['developer', 'icons', 'locales']:
        if key in manifest:
            data[key] = manifest[key]

    return json.dumps(data, cls=JSONEncoder)
예제 #25
0
파일: helpers.py 프로젝트: waseem18/zamboni
def fxa_auth_info(context=None):
    state = uuid.uuid4().hex
    return (state,
            urlparams(fxa_oauth_api('authorization'),
                      client_id=settings.FXA_CLIENT_ID,
                      state=state,
                      scope='profile'))
예제 #26
0
파일: admin.py 프로젝트: anaran/kuma
 def revisions(self, obj):
     """HTML link to user's revisions with count"""
     link = urlparams(reverse('dashboards.revisions'),
                      user=obj.username)
     count = obj.created_revisions.count()
     return ('<a href="%(link)s"><strong>%(count)s</strong></a>' %
             {'link': link, 'count': count})
예제 #27
0
 def test_compare_revisions_invalid_from_int(self):
     """Provide invalid 'from' int for revision ids."""
     url = reverse('wiki.compare_revisions', args=[self.document.slug])
     query = {'from': 'invalid', 'to': ''}
     url = urlparams(url, **query)
     response = self.client.get(url)
     eq_(404, response.status_code)
예제 #28
0
def _mini_manifest(addon, version_id, token=None):
    if not addon.is_packaged:
        raise http.Http404

    version = get_object_or_404(addon.versions, pk=version_id)
    file_ = version.all_files[0]
    manifest = addon.get_manifest_json(file_)

    package_path = absolutify(
        reverse('reviewers.signed', args=[addon.app_slug, version.id]))

    if token:
        # Generate a fresh token.
        token = Token(data={'app_id': addon.id})
        token.save()
        package_path = urlparams(package_path, token=token.token)

    data = {
        'name': manifest['name'],
        'version': version.version,
        'size': file_.size,
        'release_notes': version.releasenotes,
        'package_path': package_path,
    }
    for key in ['developer', 'icons', 'locales']:
        if key in manifest:
            data[key] = manifest[key]

    return json.dumps(data, cls=JSONEncoder)
예제 #29
0
파일: document.py 프로젝트: anaran/kuma
def _default_locale_fallback(request, document_slug, document_locale):
    """
    If we're falling back to a Document in the default locale, figure
    out why and whether we can redirect to a translation in the
    requested locale.

    """
    fallback_doc = None
    redirect_url = None
    fallback_reason = None

    try:
        fallback_doc = Document.objects.get(locale=settings.WIKI_DEFAULT_LANGUAGE,
                                            slug=document_slug)

        # If there's a translation to the requested locale, take it:
        translation = fallback_doc.translated_to(document_locale)

        if translation and translation.current_revision:
            url = translation.get_absolute_url()
            redirect_url = urlparams(url, query_dict=request.GET)
        elif translation and fallback_doc.current_revision:
            # Found a translation but its current_revision is None
            # and OK to fall back to parent (parent is approved).
            fallback_reason = 'translation_not_approved'
        elif fallback_doc.current_revision:
            # There is no translation
            # and OK to fall back to parent (parent is approved).
            fallback_reason = 'no_translation'
    except Document.DoesNotExist:
        pass

    return fallback_doc, fallback_reason, redirect_url
예제 #30
0
파일: views.py 프로젝트: shahbaz17/zamboni
def redirect(request, viewer, key):
    new = Token(data=[viewer.file.id, key])
    new.save()
    url = urljoin(settings.STATIC_URL,
                  reverse('mkt.files.serve', args=[viewer, key]))
    url = urlparams(url, token=new.token)
    return http.HttpResponseRedirect(url)
예제 #31
0
    def process_request(self, request):
        prefixer = Prefixer(request)
        set_url_prefixer(prefixer)
        full_path = prefixer.fix(prefixer.shortened_path)

        if "lang" in request.GET:
            # Blank out the locale so that we can set a new one. Remove lang
            # from the query params so we don't have an infinite loop.
            prefixer.locale = ""
            new_path = prefixer.fix(prefixer.shortened_path)
            query = dict((smart_str(k), v) for k, v in request.GET.iteritems() if k != "lang")
            return HttpResponsePermanentRedirect(urlparams(new_path, **query))

        if full_path != request.path:
            query_string = request.META.get("QUERY_STRING", "")
            full_path = urllib.quote(full_path.encode("utf-8"))

            if query_string:
                full_path = "%s?%s" % (full_path, query_string)

            response = HttpResponsePermanentRedirect(full_path)

            # Vary on Accept-Language if we changed the locale
            old_locale = prefixer.locale
            new_locale, _ = split_path(full_path)
            if old_locale != new_locale:
                response["Vary"] = "Accept-Language"

            return response

        request.path_info = "/" + prefixer.shortened_path
        request.LANGUAGE_CODE = prefixer.locale or settings.LANGUAGE_CODE
        translation.activate(prefixer.locale)
예제 #32
0
파일: admin.py 프로젝트: KinaMarie/kuma
 def revisions(self, obj):
     """HTML link to user's revisions with count"""
     link = urlparams(reverse('dashboards.revisions'), user=obj.username)
     count = obj.created_revisions.count()
     return ('<a href="%(link)s"><strong>%(count)s</strong></a>' % {
         'link': link,
         'count': count
     })
예제 #33
0
파일: document.py 프로젝트: anaran/kuma
def _document_redirect_to_create(document_slug, document_locale, slug_dict):
    """
    When a Document doesn't exist but the user can create it, return
    the creation URL to redirect to.
    """
    url = reverse('wiki.create', locale=document_locale)
    if slug_dict['length'] > 1:
        parent_doc = get_object_or_404(Document,
                                       locale=document_locale,
                                       slug=slug_dict['parent'],
                                       is_template=0)
        url = urlparams(url, parent=parent_doc.id,
                        slug=slug_dict['specific'])
    else:
        # This is a "base level" redirect, i.e. no parent
        url = urlparams(url, slug=document_slug)
    return url
예제 #34
0
def url(viewname, *args, **kwargs):
    """Helper for Django's ``reverse`` in templates."""
    host = kwargs.pop('host', '')
    src = kwargs.pop('src', '')
    url = '%s%s' % (host, reverse(viewname, args=args, kwargs=kwargs))
    if src:
        url = helpers.urlparams(url, src=src)
    return url
예제 #35
0
def fxa_auth_info(context=None):
    state = uuid.uuid4().hex
    return (state,
            urlparams(
                fxa_oauth_api('authorization'),
                client_id=settings.FXA_CLIENT_ID,
                state=state,
                scope='profile'))
예제 #36
0
    def test_logout(self):
        UserProfile.objects.create(email='*****@*****.**')
        data = self._test_login()

        r = self.client.delete(
            urlparams(self.logout_url, _user=data['token']),
            content_type='application/json')
        eq_(r.status_code, 204)
예제 #37
0
 def test_compare_unmatched_document_url(self):
     """Comparing two revisions of unlinked document should cause error."""
     unmatched_document = _create_document(title='Invalid document')
     url = reverse('wiki.compare_revisions', args=[unmatched_document.slug])
     query = {'from': self.revision1.id, 'to': self.revision2.id}
     url = urlparams(url, **query)
     response = self.client.get(url)
     eq_(404, response.status_code)
예제 #38
0
파일: helpers.py 프로젝트: waseem18/zamboni
def url(viewname, *args, **kwargs):
    """Helper for Django's ``reverse`` in templates."""
    host = kwargs.pop('host', '')
    src = kwargs.pop('src', '')
    url = '%s%s' % (host, reverse(viewname, args=args, kwargs=kwargs))
    if src:
        url = helpers.urlparams(url, src=src)
    return url
예제 #39
0
def get_absolute_url(url, api_name='apps', absolute=True):
    # Gets an absolute url, except where you don't want that.
    url[1]['api_name'] = api_name
    res = reverse(url[0], kwargs=url[1])
    if absolute:
        res = urlparse.urljoin(settings.SITE_URL, res)
    if len(url) > 2:
        res = urlparams(res, **url[2])
    return res
예제 #40
0
    def test_get_content_ratings_since(self):
        cr = ContentRating.objects.create(addon=self.app,
                                          ratings_body=0,
                                          rating=0)
        cr.update(modified=self.days_ago(100))

        res = self.client.get(
            urlparams(reverse('content-ratings-list',
                              args=[self.app.app_slug]),
                      since=self.days_ago(5)))
        eq_(res.status_code, 404)

        cr.update(modified=self.days_ago(1))
        res = self.client.get(
            urlparams(reverse('content-ratings-list', args=[self.app.id]),
                      since=self.days_ago(5)))
        eq_(res.status_code, 200)
        eq_(len(json.loads(res.content)['objects']), 1)
예제 #41
0
def get_absolute_url(url, api_name='apps', absolute=True):
    # Gets an absolute url, except where you don't want that.
    url[1]['api_name'] = api_name
    res = reverse(url[0], kwargs=url[1])
    if absolute:
        res = urlparse.urljoin(settings.SITE_URL, res)
    if len(url) > 2:
        res = urlparams(res, **url[2])
    return res
예제 #42
0
 def test_compare_revisions(self):
     """Compare two revisions"""
     url = reverse('wiki.compare_revisions', args=[self.document.slug])
     query = {'from': self.revision1.id, 'to': self.revision2.id}
     url = urlparams(url, **query)
     response = self.client.get(url)
     eq_(200, response.status_code)
     doc = pq(response.content)
     eq_('Dolor', doc('span.diff_add').text())
예제 #43
0
파일: test_helpers.py 프로젝트: chiu/jingo
def _check_query(path, result=None, **query):
    paramed = helpers.urlparams(path, **query)
    if result is None:
        result = query
    for k, v in result.items():
        if not isinstance(v, list):
            result[k] = [v]
    qs = cgi.parse_qs(paramed.split('?')[1])
    for k in query:
        eq_(set(result[k]), set(qs[k]))
예제 #44
0
    def test_get_content_ratings_since(self):
        old_date = self.days_ago(100)
        cr = ContentRating.objects.create(addon=self.app, ratings_body=0,
                                          rating=0)
        # Pass _signal=False to avoid django auto-now on modified.
        cr.update(modified=old_date, _signal=False)
        eq_(cr.modified, old_date)

        res = self.client.get(urlparams(
            reverse('content-ratings-list', args=[self.app.app_slug]),
            since=self.days_ago(5)))
        eq_(res.status_code, 404)

        cr.update(modified=self.days_ago(1))
        res = self.client.get(urlparams(
            reverse('content-ratings-list', args=[self.app.id]),
            since=self.days_ago(5)))
        eq_(res.status_code, 200)
        eq_(len(json.loads(res.content)['objects']), 1)
예제 #45
0
def _check_query(path, result=None, **query):
    paramed = helpers.urlparams(path, **query)
    if result is None:
        result = query
    for k, v in result.items():
        if not isinstance(v, list):
            result[k] = [v]
    qs = cgi.parse_qs(paramed.split('?')[1])
    for k in query:
        eq_(set(result[k]), set(qs[k]))
예제 #46
0
    def test_persona_signup_copy(self):
        """
        After a new user signs up with Persona, their username, an
        indication that Persona was used to log in, and a logout link
        appear in the auth tools section of the page.
        """
        persona_signup_email = '*****@*****.**'
        persona_signup_username = '******'
        add_persona_verify_response({
            'status': 'okay',
            'email': persona_signup_email,
        })

        self.client.post(reverse('persona_login'), follow=True)
        data = {
            'website': '',
            'username': persona_signup_username,
            'email': persona_signup_email,
            'terms': True
        }
        response = self.client.post(reverse(
            'socialaccount_signup', locale=settings.WIKI_DEFAULT_LANGUAGE),
                                    data=data,
                                    follow=True)

        user_url = reverse('users.user_detail',
                           kwargs={'username': persona_signup_username},
                           locale=settings.WIKI_DEFAULT_LANGUAGE)
        signout_url = urlparams(reverse('account_logout',
                                        locale=settings.WIKI_DEFAULT_LANGUAGE),
                                next=reverse(
                                    'home',
                                    locale=settings.WIKI_DEFAULT_LANGUAGE))
        parsed = pq(response.content)

        login_info = parsed.find('.oauth-logged-in')
        ok_(len(login_info.children()))

        signed_in_message = login_info.children()[0]
        ok_('title' in signed_in_message.attrib)
        eq_('Signed in with Persona', signed_in_message.attrib['title'])

        auth_links = login_info.children()[1].getchildren()
        ok_(len(auth_links))

        user_link = auth_links[0].getchildren()[0]
        ok_('href' in user_link.attrib)
        eq_(user_url, user_link.attrib['href'])

        signout_link = auth_links[1].getchildren()[0]
        ok_('href' in signout_link.attrib)
        eq_(
            signout_url.replace('%2F', '/'),  # urlparams() encodes slashes
            signout_link.attrib['href'])
예제 #47
0
    def test_persona_signup_copy(self):
        """
        After a new user signs up with Persona, their username, an
        indication that Persona was used to log in, and a logout link
        appear in the auth tools section of the page.
        """
        persona_signup_email = '*****@*****.**'
        persona_signup_username = '******'

        with mock.patch('requests.post') as requests_mock:
            requests_mock.return_value.json.return_value = {
                'status': 'okay',
                'email': persona_signup_email,
            }
            self.client.post(reverse('persona_login'), follow=True)
            data = {'website': '',
                    'username': persona_signup_username,
                    'email': persona_signup_email,
                    'terms': True}
            response = self.client.post(
                reverse('socialaccount_signup',
                        locale=settings.WIKI_DEFAULT_LANGUAGE),
                data=data, follow=True)

            user_url = reverse(
                'users.user_detail',
                kwargs={'username': persona_signup_username},
                locale=settings.WIKI_DEFAULT_LANGUAGE)
            signout_url = urlparams(
                reverse('account_logout',
                        locale=settings.WIKI_DEFAULT_LANGUAGE),
                next=reverse('home',
                             locale=settings.WIKI_DEFAULT_LANGUAGE))
            parsed = pq(response.content)

            login_info = parsed.find('.oauth-logged-in')
            ok_(len(login_info.children()))

            signed_in_message = login_info.children()[0]
            ok_('title' in signed_in_message.attrib)
            eq_('Signed in with Persona',
                signed_in_message.attrib['title'])

            auth_links = login_info.children()[1].getchildren()
            ok_(len(auth_links))

            user_link = auth_links[0].getchildren()[0]
            ok_('href' in user_link.attrib)
            eq_(user_url, user_link.attrib['href'])

            signout_link = auth_links[1].getchildren()[0]
            ok_('href' in signout_link.attrib)
            eq_(signout_url.replace('%2F', '/'),  # urlparams() encodes slashes
                signout_link.attrib['href'])
예제 #48
0
파일: helpers.py 프로젝트: waseem18/zamboni
def media(context, url, key='MEDIA_URL'):
    """Get a MEDIA_URL link with a cache buster querystring."""
    if 'BUILD_ID' in context:
        build = context['BUILD_ID']
    else:
        if url.endswith('.js'):
            build = context['BUILD_ID_JS']
        elif url.endswith('.css'):
            build = context['BUILD_ID_CSS']
        else:
            build = context['BUILD_ID_IMG']
    return urljoin(context[key], helpers.urlparams(url, b=build))
예제 #49
0
    def test_get_content_ratings_since(self):
        old_date = self.days_ago(100)
        cr = ContentRating.objects.create(addon=self.app,
                                          ratings_body=0,
                                          rating=0)
        # Pass _signal=False to avoid django auto-now on modified.
        cr.update(modified=old_date, _signal=False)
        eq_(cr.modified, old_date)

        res = self.client.get(
            urlparams(reverse('content-ratings-list',
                              args=[self.app.app_slug]),
                      since=self.days_ago(5)))
        eq_(res.status_code, 404)

        cr.update(modified=self.days_ago(1))
        res = self.client.get(
            urlparams(reverse('content-ratings-list', args=[self.app.id]),
                      since=self.days_ago(5)))
        eq_(res.status_code, 200)
        eq_(len(json.loads(res.content)['objects']), 1)
예제 #50
0
def media(context, url, key='MEDIA_URL'):
    """Get a MEDIA_URL link with a cache buster querystring."""
    if 'BUILD_ID' in context:
        build = context['BUILD_ID']
    else:
        if url.endswith('.js'):
            build = context['BUILD_ID_JS']
        elif url.endswith('.css'):
            build = context['BUILD_ID_CSS']
        else:
            build = context['BUILD_ID_IMG']
    return urljoin(context[key], helpers.urlparams(url, b=build))
예제 #51
0
 def test_list_translation(self):
     res = self.anon.get(urlparams(reverse('regions-list'), lang='fr'))
     eq_(res.status_code, 200)
     data = json.loads(res.content)
     for row in data['objects']:
         region = mkt.regions.REGIONS_DICT.get(row['slug'])
         eq_(row['name'], region.name)
         eq_(row['slug'], region.slug)
         eq_(row['id'], region.id)
     eq_(len(data['objects']), len(mkt.regions.REGIONS_DICT))
     eq_(data['meta']['total_count'], len(mkt.regions.REGIONS_DICT))
     eq_(data['objects'][1]['name'], 'Afrique du Sud')
     eq_(data['objects'][-1]['name'], 'Reste du monde')
예제 #52
0
 def test_list(self):
     res = self.anon.get(urlparams(reverse('regions-list')))
     eq_(res.status_code, 200)
     data = json.loads(res.content)
     for row in data['objects']:
         region = mkt.regions.REGIONS_DICT.get(row['slug'])
         eq_(row['name'], region.name)
         eq_(row['slug'], region.slug)
         eq_(row['id'], region.id)
     eq_(len(data['objects']), len(mkt.regions.REGIONS_DICT))
     eq_(data['meta']['total_count'], len(mkt.regions.REGIONS_DICT))
     eq_(data['objects'][0]['name'],
         mkt.regions.REGIONS_LIST_SORTED_BY_NAME()[0].name)
     eq_(data['objects'][-1]['name'],
         unicode(mkt.regions.REGIONS_LIST_SORTED_BY_NAME()[-1].name))
예제 #53
0
    def test_persona_signin_copy(self):
        """
        After an existing user successfully authenticates with
        Persona, their username, an indication that Persona was used
        to log in, and a logout link appear in the auth tools section
        of the page.
        """
        with mock.patch('requests.post') as requests_mock:
            requests_mock.return_value.json.return_value = {
                'status': 'okay',
                'email': self.existing_persona_email,
            }
            response = self.client.post(reverse('persona_login'),
                                        follow=True)
            eq_(response.status_code, 200)

            profile_url = reverse(
                'users.profile',
                kwargs={
                    'username': self.existing_persona_username
                },
                locale=settings.WIKI_DEFAULT_LANGUAGE)
            signout_url = urlparams(
                reverse('account_logout',
                        locale=settings.WIKI_DEFAULT_LANGUAGE),
                next=reverse('home',
                             locale=settings.WIKI_DEFAULT_LANGUAGE))
            parsed = pq(response.content)

            login_info = parsed.find('.header-login .user-state')
            ok_(len(login_info.children()))

            signed_in_message = login_info.children()[0]
            ok_('title' in signed_in_message.attrib)
            eq_('Signed in with Persona',
                signed_in_message.attrib['title'])

            auth_links = login_info.children()[1].getchildren()
            ok_(len(auth_links))

            profile_link = auth_links[0].getchildren()[0]
            ok_('href' in profile_link.attrib)
            eq_(profile_url, profile_link.attrib['href'])

            signout_link = auth_links[1].getchildren()[0]
            ok_('href' in signout_link.attrib)
            eq_(signout_url.replace('%2F', '/'),  # urlparams() encodes slashes
                signout_link.attrib['href'])
예제 #54
0
파일: test_views.py 프로젝트: zullkay/kuma
    def test_files_dict(self):
        doc = document(locale='en', slug='attachment-test-files-dict')
        doc.save()
        rev = revision(document=doc, is_approved=True)
        rev.save()

        test_file_1 = make_test_file(
            content='A file for testing the files dict')

        post_data = {
            'title': 'Files dict test file',
            'description': 'Files dict test file',
            'comment': 'Initial upload',
            'file': test_file_1,
        }

        add_url = urlparams(reverse('attachments.new_attachment'),
                            document_id=doc.id)
        self.client.post(add_url, data=post_data)

        test_file_2 = make_test_file(
            content='Another file for testing the files dict')

        post_data = {
            'title': 'Files dict test file 2',
            'description': 'Files dict test file 2',
            'comment': 'Initial upload',
            'file': test_file_2,
        }

        self.client.post(add_url, data=post_data)

        doc = Document.objects.get(pk=doc.id)

        files_dict = doc.files_dict()

        file1 = files_dict[test_file_1.name.split('/')[-1]]
        eq_('admin', file1['attached_by'])
        eq_('Files dict test file', file1['description'])
        eq_('text/plain', file1['mime_type'])
        ok_(test_file_1.name.split('/')[-1] in file1['url'])

        file2 = files_dict[test_file_2.name.split('/')[-1]]
        eq_('admin', file2['attached_by'])
        eq_('Files dict test file 2', file2['description'])
        eq_('text/plain', file2['mime_type'])
        ok_(test_file_2.name.split('/')[-1] in file2['url'])