示例#1
0
文件: views.py 项目: LucianU/zamboni
def _get_sorts(request, sort):
    items = []
    url = request.get_full_path()

    sorts = forms.sort_by

    item = MenuItem()
    (item.text, item.url) = (_('Keyword Match'), urlparams(url, sort=None))

    if not sort:
        item.selected = True

    items.append(item)

    for key, val in sorts:
        if key == '':
            continue

        item = MenuItem()
        (item.text, item.url) = (val, urlparams(url, sort=key, page=None))

        if sort == key:
            item.selected = True

        items.append(item)

    return items
示例#2
0
文件: views.py 项目: exezaid/zamboni
def _get_sorts(request, sort):
    items = []
    url = request.get_full_path()

    sorts = forms.sort_by

    item = MenuItem()
    (item.text, item.url) = (_('Keyword Match'), urlparams(url, sort=None))

    if not sort:
        item.selected = True

    items.append(item)

    for key, val in sorts:
        # TODO(davedash): Remove 'name' altogether if nobody complains.
        if key == '' or key == 'name':
            continue

        item = MenuItem()
        (item.text, item.url) = (val, urlparams(url, sort=key, page=None))

        if sort == key:
            item.selected = True

        items.append(item)

    return items
示例#3
0
    def check_cat_filters(self, params, valid=False):
        cat_selected = params.get('cat') == self.cat.id
        r = self.client.get(self.url)
        pager = r.context['pager']

        r = self.client.get(urlparams(self.url, **params))
        if valid:
            eq_(list(r.context['pager'].object_list), list(pager.object_list),
                '%s != %s' % (self.url, urlparams(self.url, **params or {})))

        doc = pq(r.content)('#category-facets')
        li = doc.children('li:first-child')
        # Note: PyQuery's `hasClass` matches children's classes, so yeah.
        eq_(li.attr('class'), 'selected' if not cat_selected else None,
            "'All Apps' should be selected")
        a = li.children('a')
        eq_(a.length, 1)
        eq_(a.text(), 'All Apps')

        li = doc('li:last')
        eq_(li.attr('class'), 'selected' if cat_selected else None,
            '%r should be selected' % unicode(self.cat.name))
        a = li.children('a')
        eq_(a.text(), unicode(self.cat.name))
        params.update(cat=self.cat.id)
        eq_(a.attr('href'), urlparams(self.url, **params))
        eq_(json.loads(a.attr('data-params')),
            dict(cat=self.cat.id, page=None))
示例#4
0
    def check_cat_filters(self, params, valid=False):
        cat_selected = params.get('cat') == self.cat.id
        r = self.client.get(self.url)
        pager = r.context['pager']

        r = self.client.get(urlparams(self.url, **params))
        if valid:
            eq_(list(r.context['pager'].object_list), list(pager.object_list),
                '%s != %s' % (self.url, urlparams(self.url, **params or {})))

        doc = pq(r.content)('#category-facets')
        li = doc.children('li:first-child')
        # Note: PyQuery's `hasClass` matches children's classes, so yeah.
        eq_(li.attr('class'), 'selected' if not cat_selected else None,
            "'All Apps' should be selected")
        a = li.children('a')
        eq_(a.length, 1)
        eq_(a.text(), 'All Apps')

        li = doc('li:last')
        eq_(li.attr('class'), 'selected' if cat_selected else None,
            '%r should be selected' % unicode(self.cat.name))
        a = li.children('a')
        eq_(a.text(), unicode(self.cat.name))
        params.update(cat=self.cat.id)
        eq_(a.attr('href'), urlparams(self.url, **params))
        eq_(json.loads(a.attr('data-params')), dict(cat=self.cat.id,
                                                    page=None))
示例#5
0
def _get_sorts(request, sort):
    items = []
    url = request.get_full_path()

    item = MenuItem()
    (item.text, item.url) = (_('Keyword Match'), urlparams(url, sort=None))

    if not sort:
        item.selected = True

    items.append(item)

    for key, val in sort_by:
        if key == '':
            continue

        item = MenuItem()
        (item.text, item.url) = (val, urlparams(url, sort=key, page=None))

        if sort == key:
            item.selected = True

        items.append(item)

    return items
示例#6
0
    def test_redirect_after_login_evil(self):
        "http://foo.com is a bad value for redirection."
        url = urlparams(self._get_login_url(), to="http://foo.com")
        r = self.client.post(url, {"username": "******", "password": "******"}, follow=True)
        self.assertRedirects(r, "/en-US/firefox/")

        url = urlparams(self._get_login_url(), to="/en-US/firefox", domain="http://evil.com")
        r = self.client.post(url, {"username": "******", "password": "******"}, follow=True)
        self.assertRedirects(r, "/en-US/firefox/")
示例#7
0
    def test_redirect_after_login(self):
        url = urlparams(self._get_login_url(), to="/en-US/firefox/about")
        r = self.client.post(url, {"username": "******", "password": "******"}, follow=True)
        self.assert3xx(r, "/en-US/about")

        url = urlparams(self._get_login_url(), to="/addon/new", domain="builder")
        r = self.client.post(url, {"username": "******", "password": "******"}, follow=True)
        to, code = r.redirect_chain[0]
        self.assertEqual(to, "https://builder.addons.mozilla.org/addon/new")
        self.assertEqual(code, 302)
示例#8
0
 def test_personas_subnav(self):
     doc = pq(self.client.get(reverse('home')).content)
     base_url = reverse('browse.personas')
     expected = [
         ('Personas', base_url),
         ('Most Popular', urlparams(base_url, sort='popular')),
         ('Top Rated', urlparams(base_url, sort='rating')),
         ('Newest', urlparams(base_url, sort='created')),
     ]
     check_links(expected, doc('#site-nav #personas a'))
示例#9
0
    def test_redirect(self):
        url = '/developers/'
        res = self.client.get(urlparams(reverse('users.logout'), to=url),
                            follow=True)
        self.assertRedirects(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.assertRedirects(res, '/', status_code=302)
示例#10
0
 def test_personas_subnav(self):
     doc = pq(self.client.get(reverse("home")).content)
     base_url = reverse("browse.personas")
     expected = [
         ("Personas", base_url),
         ("Most Popular", urlparams(base_url, sort="popular")),
         ("Top Rated", urlparams(base_url, sort="rating")),
         ("Newest", urlparams(base_url, sort="created")),
     ]
     check_links(expected, doc("#site-nav #personas a"))
示例#11
0
    def test_redirect_after_login(self):
        url = urlparams(self._get_login_url(), to="/en-US/firefox/about")
        r = self.client.post(url, {"username": "******", "password": "******"}, follow=True)
        self.assertRedirects(r, "/en-US/about")

        # Test a valid domain.  Note that assertRedirects doesn't work on
        # external domains
        url = urlparams(self._get_login_url(), to="/addon/new", domain="builder")
        r = self.client.post(url, {"username": "******", "password": "******"}, follow=True)
        to, code = r.redirect_chain[0]
        self.assertEqual(to, "https://builder.addons.mozilla.org/addon/new")
        self.assertEqual(code, 302)
示例#12
0
    def test_redirect_after_login_evil(self):
        "http://foo.com is a bad value for redirection."
        url = urlparams(self._get_login_url(), to="http://foo.com")
        r = self.client.post(url, {'username': '******',
                                   'password': '******'}, follow=True)
        self.assertRedirects(r, '/en-US/firefox/')

        url = urlparams(self._get_login_url(), to="/en-US/firefox",
                domain="http://evil.com")
        r = self.client.post(url, {'username': '******',
                                   'password': '******'}, follow=True)
        self.assertRedirects(r, '/en-US/firefox/')
示例#13
0
def test_login_link():
    request = mock.Mock()
    request.GET = {}
    eq_(reverse('users.login'), get_login_link({'request': request}))

    request.GET = {'to': '/login'}
    eq_(reverse('users.login'), get_login_link({'request': request}))

    request.GET = {'to': 'foo'}
    eq_(urlparams(reverse('users.login'), to='foo'),
        get_login_link({'request': request}))
    eq_(urlparams(reverse('users.login'), to='bar'),
        get_login_link({'request': request}, 'bar'))
示例#14
0
    def check_cat_filters(self, params=None, selected="All Add-ons"):
        if not params:
            params = {}

        r = self.client.get(urlparams(self.url, **params))
        eq_(sorted(a.id for a in self.addons), sorted(a.id for a in r.context["pager"].object_list))

        cat = self.addons[0].all_categories[0]
        links = pq(r.content)("#category-facets li a")
        expected = [
            ("All Add-ons", self.url),
            ("Extensions", urlparams(self.url, atype=amo.ADDON_EXTENSION)),
            (unicode(cat.name), urlparams(self.url, atype=amo.ADDON_EXTENSION, cat=cat.id)),
        ]
        amo.tests.check_links(expected, links, selected, verify=False)
示例#15
0
    def test_redirect_after_login(self):
        url = urlparams(self._get_login_url(), to="/en-US/firefox/about")
        r = self.client.post(url, {'username': '******',
                                   'password': '******'}, follow=True)
        self.assertRedirects(r, '/en-US/about')

        # Test a valid domain.  Note that assertRedirects doesn't work on
        # external domains
        url = urlparams(self._get_login_url(), to="/addon/new",
                        domain="builder")
        r = self.client.post(url, {'username': '******',
                                   'password': '******'}, follow=True)
        to, code = r.redirect_chain[0]
        self.assertEqual(to, 'https://builder.addons.mozilla.org/addon/new')
        self.assertEqual(code, 302)
示例#16
0
    def test_tag_titles(self):
        tag_url = reverse("tags.detail", args=["sky"])

        titles = {
            tag_url: ("sky :: Tag :: Add-ons for Firefox", 'Search Results for tag "sky"'),
            urlparams(tag_url, q="sky"): ("sky :: Search :: Add-ons for Firefox", 'Search Results for "sky"'),
            urlparams(self.url, tag="sky"): ("Search :: Add-ons for Firefox", "Search"),
        }

        for url, titles in titles.iteritems():
            r = self.client.get(url)
            doc = pq(r.content)
            title, heading = titles
            eq_(doc("title").text(), title)
            eq_(doc(".primary h1").text(), heading)
示例#17
0
 def test_redirect(self):
     self.client.login(username='******', password='******')
     self.client.get('/', follow=True)
     url = '/en-US/firefox/about'
     r = self.client.get(urlparams(reverse('users.logout'), to=url),
                         follow=True)
     self.assertRedirects(r, url, status_code=302)
示例#18
0
 def test_known_tag_filter(self):
     for url in (urlparams(self.url,
                           tag='sky'), reverse('tags.detail',
                                               args=['sky'])):
         r = self.client.get(url)
         a = pq(r.content)('#tag-facets li.selected a[data-params]')
         eq_(json.loads(a.attr('data-params')), dict(tag='sky', page=None))
示例#19
0
    def test_results_popularity(self):
        collections = [
            ("Traveler Pack", 2000),
            ("Tools for Developer", 67),
            ("Web Developer", 250),
            ("Web Developer Necessities", 50),
            ("Web Pro", 200),
            ("Web Developer Pack", 242),
        ]
        for name, subscribers in collections:
            amo.tests.collection_factory(name=name, subscribers=subscribers, weekly_subscribers=subscribers)
        self.refresh()

        # "Web Developer Collection" should be the #1 most relevant result.
        expected_name, expected_subscribers = collections[2]
        for sort in ("", "all"):
            r = self.client.get(urlparams(self.url, q="web developer", sort=sort), follow=True)
            eq_(r.status_code, 200)
            results = list(r.context["pager"].object_list)
            first = results[0]
            eq_(unicode(first.name), expected_name, "Was not first result for %r. Results: %s" % (sort, results))
            eq_(
                first.subscribers,
                expected_subscribers,
                "Incorrect subscribers for %r. Got %r. Expected %r." % (sort, first.subscribers, results),
            )
示例#20
0
文件: helpers.py 项目: sunbiz/zamboni
def product_as_dict(request,
                    product,
                    purchased=None,
                    receipt_type=None,
                    src=''):
    # Dev environments might not have authors set.
    author = ''
    author_url = ''
    if product.listed_authors:
        author = product.listed_authors[0].name
        author_url = product.listed_authors[0].get_url_path()

    url = (reverse('receipt.issue', args=[product.app_slug])
           if receipt_type else product.get_detail_url('record'))
    src = src or request.GET.get('src', '')
    reviewer = receipt_type == 'reviewer'

    ret = {
        'id': product.id,
        'name': product.name,
        'categories': [unicode(cat.slug) for cat in product.categories.all()],
        'manifest_url': product.get_manifest_url(reviewer),
        'recordUrl': urlparams(url, src=src),
        'author': author,
        'author_url': author_url,
        'iconUrl': product.get_icon_url(64),
        'is_packaged': product.is_packaged,
        'src': src
    }

    # Add in previews to the dict.
    if product.all_previews:
        previews = []
        for p in product.all_previews:
            preview = {
                'fullUrl': jinja2.escape(p.image_url),
                'type': jinja2.escape(p.filetype),
                'thumbUrl': jinja2.escape(p.thumbnail_url),
                'caption': jinja2.escape(p.caption) if p.caption else ''
            }
            previews.append(preview)
        ret.update({'previews': previews})

    if product.premium:
        ret.update({
            'price':
            product.get_price(region=request.REGION.id),
            'priceLocale':
            product.get_price_locale(region=request.REGION.id),
        })

        if request.amo_user:
            ret['isPurchased'] = purchased

    # Jinja2 escape everything except this whitelist so that bool is retained
    # for the JSON encoding.
    wl = ('categories', 'currencies', 'isPurchased', 'is_packaged', 'previews',
          'price', 'priceLocale')
    return dict([k, jinja2.escape(v) if k not in wl else v]
                for k, v in ret.items())
示例#21
0
 def check_followers_count(self, sort, column):
     # Checks that we show the correct type/number of followers.
     r = self.client.get(urlparams(self.url, sort=sort))
     items = pq(r.content)('.primary .item')
     for idx, c in enumerate(r.context['pager'].object_list):
         eq_(items.eq(idx).find('.followers').text().split()[0],
             numberfmt(getattr(c, column)))
示例#22
0
    def test_results_popularity(self):
        personas = [
            ('Harry Potter', 2000),
            ('Japanese Koi Tattoo', 67),
            ('Japanese Tattoo', 250),
            ('Japanese Tattoo boop', 50),
            ('Japanese Tattoo ballin', 200),
            ('The Japanese Tattooed Girl', 242),
        ]
        for name, popularity in personas:
            self._addons.append(amo.tests.addon_factory(name=name,
                                                        type=amo.ADDON_PERSONA,
                                                        popularity=popularity))
        self.refresh()

        # Japanese Tattoo should be the #1 most relevant result. Obviously.
        expected_name, expected_popularity = personas[2]
        for sort in ('downloads', 'popularity', 'users'):
            r = self.client.get(urlparams(self.url, q='japanese tattoo',
                                          sort=sort), follow=True)
            eq_(r.status_code, 200)
            results = list(r.context['pager'].object_list)
            first = results[0]
            eq_(unicode(first.name), expected_name,
                'Was not first result for %r. Results: %s' % (sort, results))
            eq_(first.persona.popularity, expected_popularity,
                'Incorrect popularity for %r. Got %r. Expected %r.' % (
                sort, first.persona.popularity, results))
            eq_(first.average_daily_users, expected_popularity,
                'Incorrect users for %r. Got %r. Expected %r.' % (
                sort, first.average_daily_users, results))
            eq_(first.weekly_downloads, expected_popularity,
                'Incorrect weekly_downloads for %r. Got %r. Expected %r.' % (
                sort, first.weekly_downloads, results))
示例#23
0
 def test_reviewers(self, check_reviewer):
     check_reviewer.return_value = True
     doc = pq(market_tile(self.context, self.webapp))
     data = json.loads(doc('.mkt-tile').attr('data-product'))
     issue = urlparams(reverse('receipt.issue',
                               args=[self.webapp.app_slug]), src='foo')
     eq_(data['recordUrl'], issue)
示例#24
0
文件: buttons.py 项目: sunbiz/zamboni
    def file_details(self, file):
        platform = file.platform_id
        if self.latest and (self.addon.status == file.status ==
                            amo.STATUS_PUBLIC):
            url = file.latest_xpi_url()
        else:
            url = file.get_url_path(self.src, self.addon)

        if platform == amo.PLATFORM_ALL.id:
            text, os = _('Download Now'), None
        else:
            text, os = _('Download'), amo.PLATFORMS[platform]

        if self.show_eula:
            # L10n: please keep   in the string so → does not wrap.
            text = jinja2.Markup(_('Continue to Download →'))
            self.xpiurl = url
            url = file.eula_url()
        elif self.accept_eula:
            text = _('Accept and Download')
        elif self.show_contrib:
            # The eula doesn't exist or has been hit already.
            # L10n: please keep   in the string so → does not wrap.
            text = jinja2.Markup(_('Continue to Download →'))
            roadblock = reverse('addons.roadblock', args=[self.addon.id])
            url = urlparams(roadblock, eula='', version=self.version.version)

        if self.addon.is_webapp():
            text = _(u'Install App')

        return text, url, os
示例#25
0
    def process_request(self, request):
        carrier = stored_carrier = None
        is_legacy = False
        set_url_prefix(None)
        set_carrier(None)

        # If I have a cookie use that carrier.
        remembered = request.COOKIES.get('carrier')
        if remembered in CARRIER_MAP:
            carrier = stored_carrier = remembered

        choice = request.REQUEST.get('carrier')
        if choice in CARRIER_MAP:
            carrier = choice
        elif 'carrier' in request.GET:
            # We are clearing the carrier.
            carrier = None

        # Legacy /<carrier>/ (don't break Gaia).
        for name in CARRIER_MAP:
            if request.path.startswith('/%s' % name):
                is_legacy = True
                carrier = name
                break

        # Update cookie if value have changed.
        if carrier != stored_carrier:
            request.set_cookie('carrier', carrier)

        if carrier and is_legacy:
            orig_path = request.path_info
            new_path = orig_path[len(carrier) + 1:] or '/'
            return redirect(urlparams(new_path, carrier=carrier))

        set_carrier(carrier)
示例#26
0
def get_preapproval_url(key):
    """
    Returns the URL that you need to bounce user to in order to set up
    pre-approval.
    """
    return urlparams(settings.PAYPAL_CGI_URL, cmd='_ap-preapproval',
                     preapprovalkey=key)
示例#27
0
    def file_details(self, file):
        platform = file.platform_id
        if self.latest and (
            self.addon.status == file.status == amo.STATUS_PUBLIC):
            url = file.latest_xpi_url()
        else:
            url = file.get_url_path(self.src, self.addon)

        if platform == amo.PLATFORM_ALL.id:
            text, os = _('Download Now'), None
        else:
            text, os = _('Download'), amo.PLATFORMS[platform]

        if self.show_eula:
            # L10n: please keep &nbsp; in the string so &rarr; does not wrap.
            text = jinja2.Markup(_('Continue to Download&nbsp;&rarr;'))
            self.xpiurl = url
            url = file.eula_url()
        elif self.accept_eula:
            text = _('Accept and Download')
        elif self.show_contrib:
            # The eula doesn't exist or has been hit already.
            # L10n: please keep &nbsp; in the string so &rarr; does not wrap.
            text = jinja2.Markup(_('Continue to Download&nbsp;&rarr;'))
            roadblock = reverse('addons.roadblock', args=[self.addon.id])
            url = urlparams(roadblock, eula='', version=self.version.version)

        if self.can_be_purchased:
            # TODO(andym): make this faster and less naff
            # L10n: {0} is a price
            text = _('Purchase for {0}').format(self.addon
                                                    .premium.price.price)

        return text, url, os
示例#28
0
 def test_reviewers(self, action_allowed):
     action_allowed.return_value = True
     doc = pq(market_tile(self.context, self.webapp))
     data = json.loads(doc('.mkt-tile').attr('data-product'))
     issue = urlparams(reverse('detail.record',
                               args=[self.webapp.app_slug]), src='foo')
     eq_(data['recordUrl'], issue)
示例#29
0
 def get_url_path(self, app, src):
     # TODO: remove app
     from amo.helpers import urlparams, absolutify
     url = os.path.join(reverse('downloads.file', args=[self.id]),
                        self.filename)
     # Firefox's Add-on Manager needs absolute urls.
     return absolutify(urlparams(url, src=src))
示例#30
0
 def get_url_path(self, app, src):
     # TODO: remove app
     from amo.helpers import urlparams, absolutify
     url = os.path.join(reverse('downloads.file', args=[self.id]),
                        self.filename)
     # Firefox's Add-on Manager needs absolute urls.
     return absolutify(urlparams(url, src=src))
示例#31
0
    def test_results_popularity(self):
        collections = [
            ('Traveler Pack', 2000),
            ('Tools for Developer', 67),
            ('Web Developer', 250),
            ('Web Developer Necessities', 50),
            ('Web Pro', 200),
            ('Web Developer Pack', 242),
        ]
        for name, subscribers in collections:
            amo.tests.collection_factory(name=name,
                                         subscribers=subscribers,
                                         weekly_subscribers=subscribers)
        self.refresh()

        # "Web Developer Collection" should be the #1 most relevant result.
        expected_name, expected_subscribers = collections[2]
        for sort in ('', 'all'):
            r = self.client.get(urlparams(self.url,
                                          q='web developer',
                                          sort=sort),
                                follow=True)
            eq_(r.status_code, 200)
            results = list(r.context['pager'].object_list)
            first = results[0]
            eq_(unicode(first.name), expected_name,
                'Was not first result for %r. Results: %s' % (sort, results))
            eq_(
                first.subscribers, expected_subscribers,
                'Incorrect subscribers for %r. Got %r. Expected %r.' %
                (sort, first.subscribers, results))
示例#32
0
 def check_sort_links(self,
                      key,
                      title=None,
                      sort_by=None,
                      reverse=True,
                      params={}):
     r = self.client.get(urlparams(self.url, sort=key, **params))
     eq_(r.status_code, 200)
     doc = pq(r.content)
     if title:
         if hasattr(self, 'MOBILE'):
             menu = doc('#sort-menu')
             eq_(menu.find('span').text(), title)
             eq_(menu.find('.selected').text(), title)
         else:
             eq_(doc('#sorter .selected').text(), title)
     if sort_by:
         results = r.context['pager'].object_list
         if sort_by == 'name':
             expected = sorted(results, key=lambda x: unicode(x.name))
         else:
             expected = sorted(
                 results,
                 key=lambda x: getattr(x, sort_by),
                 reverse=reverse)
         eq_(list(results), expected)
示例#33
0
文件: tests.py 项目: PinZhang/zamboni
 def test_upandcoming_sort(self):
     r = self.client.get(urlparams(self.url, sort='hotness'))
     sel = pq(r.content)('#sorter ul > li.selected')
     eq_(sel.find('a').attr('class'), 'extra-opt')
     eq_(sel.text(), 'Up & Coming')
     a = r.context['addons'].object_list
     eq_(list(a), sorted(a, key=lambda x: x.hotness, reverse=True))
示例#34
0
def get_preapproval_url(key):
    """
    Returns the URL that you need to bounce user to in order to set up
    pre-approval.
    """
    return urlparams(settings.PAYPAL_CGI_URL, cmd='_ap-preapproval',
                     preapprovalkey=key)
示例#35
0
 def test_updated_timestamp(self):
     self._generate()
     r = self.client.get(urlparams(self.url, sort='updated'))
     items = pq(r.content)('.primary .item')
     for idx, c in enumerate(r.context['pager'].object_list):
         eq_(strip_whitespace(items.eq(idx).find('.modified').text()),
             'Updated %s' % strip_whitespace(datetime_filter(c.modified)))
示例#36
0
 def check_followers_count(self, sort, column):
     # Checks that we show the correct type/number of followers.
     r = self.client.get(urlparams(self.url, sort=sort))
     items = pq(r.content)('.primary .item')
     for idx, c in enumerate(r.context['pager'].object_list):
         eq_(items.eq(idx).find('.followers').text().split()[0],
             numberfmt(getattr(c, column)))
示例#37
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)
示例#38
0
    def _test_price_filter(self, price, selected):
        waffle.models.Switch.objects.create(name='marketplace', active=True)

        self.setup_paid()
        self.refresh()

        r = self.client.get(self.url, {'price': price})
        eq_(r.status_code, 200)
        links = pq(r.content)('#price-facets a')
        expected = [
            ('Free & Premium', self.url),
            ('Free Only', urlparams(self.url, price='free')),
            ('Premium Only', urlparams(self.url, price='paid')),
        ]
        amo.tests.check_links(expected, links, selected)
        return list(r.context['pager'].object_list)
示例#39
0
    def test_results_popularity(self):
        personas = [
            ('Harry Potter', 2000),
            ('Japanese Koi Tattoo', 67),
            ('Japanese Tattoo', 250),
            ('Japanese Tattoo boop', 50),
            ('Japanese Tattoo ballin', 200),
            ('The Japanese Tattooed Girl', 242),
        ]
        for name, popularity in personas:
            amo.tests.addon_factory(name=name, type=amo.ADDON_PERSONA,
                                    popularity=popularity)
        self.refresh()

        # Japanese Tattoo should be the #1 most relevant result. Obviously.
        expected_name, expected_popularity = personas[2]
        for sort in ('downloads', 'popularity', 'users'):
            r = self.client.get(urlparams(self.url, q='japanese tattoo',
                                          sort=sort), follow=True)
            eq_(r.status_code, 200)
            results = list(r.context['pager'].object_list)
            first = results[0]
            eq_(unicode(first.name), expected_name,
                'Was not first result for %r. Results: %s' % (sort, results))
            eq_(first.persona.popularity, expected_popularity,
                'Incorrect popularity for %r. Got %r. Expected %r.' % (
                sort, first.persona.popularity, results))
            eq_(first.average_daily_users, expected_popularity,
                'Incorrect users for %r. Got %r. Expected %r.' % (
                sort, first.average_daily_users, results))
            eq_(first.weekly_downloads, expected_popularity,
                'Incorrect weekly_downloads for %r. Got %r. Expected %r.' % (
                sort, first.weekly_downloads, results))
示例#40
0
 def test_redirect(self):
     self.client.login(username='******', password='******')
     self.client.get('/', follow=True)
     url = '/en-US/firefox/about'
     r = self.client.get(urlparams(reverse('users.logout'), to=url),
                         follow=True)
     self.assertRedirects(r, url, status_code=302)
示例#41
0
 def test_reviewers(self, check_reviewer):
     check_reviewer.return_value = True
     doc = pq(market_tile(self.context, self.webapp))
     data = json.loads(doc('.mkt-tile').attr('data-product'))
     issue = urlparams(reverse('receipt.issue',
                               args=[self.webapp.app_slug]), src='foo')
     eq_(data['recordUrl'], issue)
示例#42
0
 def test_reviewers(self):
     doc = pq(market_button(self.context, self.webapp, 'reviewer'))
     data = json.loads(doc('a').attr('data-product'))
     issue = urlparams(reverse('reviewers.receipt.issue',
                               args=[self.webapp.app_slug]),
                       src='foo')
     eq_(data['recordUrl'], issue)
示例#43
0
文件: views.py 项目: petercpg/zamboni
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)
示例#44
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'))
示例#45
0
 def test_mobile_results(self):
     r = self.client.get(self.url)
     item = pq(r.content)('#content .item')
     eq_(item.length, 1)
     eq_(item.find('h3').text(), unicode(self.webapp.name))
     eq_(item.find('.info').children('a').attr('href'),
         urlparams(self.webapp.get_url_path(), src='search'))
示例#46
0
    def _test_price_filter(self, price, selected):
        waffle.models.Switch.objects.create(name='marketplace', active=True)

        self.setup_paid()
        self.refresh()

        r = self.client.get(self.url, {'price': price})
        eq_(r.status_code, 200)
        links = pq(r.content)('#price-facets a')
        expected = [
            ('Free & Premium', self.url),
            ('Free Only', urlparams(self.url, price='free')),
            ('Premium Only', urlparams(self.url, price='paid')),
        ]
        amo.tests.check_links(expected, links, selected)
        return list(r.context['pager'].object_list)
示例#47
0
def get_permission_url(addon, dest, scope):
    """
    Send permissions request to PayPal for privileges on
    this PayPal account. Returns URL on PayPal site to visit.
    Documentation: http://bit.ly/zlhXlT
    """
    # This is set in settings_test so we don't start calling PayPal
    # by accident. Explicitly set this in your tests.
    if not settings.PAYPAL_PERMISSIONS_URL:
        return ''

    paypal_log.debug('Getting refund permission URL for addon: %s' % addon.pk)

    with statsd.timer('paypal.permissions.url'):
        url = urlparams(addon.get_dev_url('acquire_refund_permission'),
                        dest=dest)
        try:
            r = _call(settings.PAYPAL_PERMISSIONS_URL + 'RequestPermissions',
                      {'scope': scope, 'callback': absolutify(url)})
        except PaypalError, e:
            paypal_log.debug('Error on refund permission URL addon: %s, %s' %
                             (addon.pk, e))
            if e.id == '580028':
                # PayPal is very picky about where they redirect users to.
                # If you try and create a PayPal permissions URL on a
                # zamboni that has a non-standard port number or a
                # non-standard TLD, it will blow up with an error. We need
                # to be able to at least visit these pages and alter them
                # in dev, so this will give you a broken token that doesn't
                # work, but at least the page will function.
                r = {'token': 'wont-work-paypal-doesnt-like-your-domain'}
            else:
                raise
示例#48
0
def product_as_dict(request, product, purchased=None, receipt_type=None,
                    src=''):
    # Dev environments might not have authors set.
    author = ''
    author_url = ''
    if product.listed_authors:
        author = product.listed_authors[0].name
        author_url = product.listed_authors[0].get_url_path()

    url = (reverse('receipt.issue', args=[product.app_slug])
           if receipt_type else product.get_detail_url('record'))
    src = src or request.GET.get('src', '')
    reviewer = receipt_type == 'reviewer'

    ret = {
        'id': product.id,
        'name': product.name,
        'categories': [unicode(cat.name) for cat in
                       product.categories.all()],
        'manifest_url': product.get_manifest_url(reviewer),
        'recordUrl': urlparams(url, src=src),
        'author': author,
        'author_url': author_url,
        'iconUrl': product.get_icon_url(64),
        'is_packaged': product.is_packaged,
        'src': src
    }

    # Add in previews to the dict.
    if product.all_previews:
        previews = []
        for p in product.all_previews:
            preview = {
                'fullUrl': jinja2.escape(p.image_url),
                'type': jinja2.escape(p.filetype),
                'thumbUrl': jinja2.escape(p.thumbnail_url),
                'caption': jinja2.escape(p.caption) if p.caption else ''
            }
            previews.append(preview)
        ret.update({'previews': previews})

    if product.has_price():
        ret.update({
            'price': product.premium.get_price() or '0',
            'priceLocale': product.premium.get_price_locale(),
        })
        currencies = product.premium.supported_currencies()
        if len(currencies) > 1 and waffle.switch_is_active('currencies'):
            currencies_dict = dict([(k, v.get_price_locale())
                                    for k, v in currencies])
            ret['currencies'] = json.dumps(currencies_dict, cls=JSONEncoder)
        if request.amo_user:
            ret['isPurchased'] = purchased

    # Jinja2 escape everything except this whitelist so that bool is retained
    # for the JSON encoding.
    wl = ('isPurchased', 'price', 'currencies', 'categories', 'previews',
          'is_packaged')
    return dict([k, jinja2.escape(v) if k not in wl else v]
                for k, v in ret.items())
示例#49
0
def product_as_dict(request, product, purchased=None, receipt_type=None):

    # Dev environments might not have authors set.
    author = ''
    author_url = ''
    if product.listed_authors:
        author = product.listed_authors[0].name
        author_url = product.listed_authors[0].get_url_path()

    url = (reverse('receipt.issue', args=[product.app_slug])
           if receipt_type else product.get_detail_url('record'))
    src = request.GET.get('src', '')

    ret = {
        'id': product.id,
        'name': product.name,
        'categories': [unicode(cat.name) for cat in
                       product.categories.all()],
        'manifest_url': product.get_manifest_url(),
        'preapprovalUrl': reverse('detail.purchase.preapproval',
                                  args=[product.app_slug]),
        'recordUrl': urlparams(url, src=src),
        'author': author,
        'author_url': author_url,
        'iconUrl': product.get_icon_url(64),
        'is_packaged': product.is_packaged,
    }

    # Add in previews to the dict.
    if product.all_previews:
        previews = []
        for p in product.all_previews:
            previews.append({
                'fullUrl': jinja2.escape(p.image_url),
                'type': jinja2.escape(p.filetype),
                'caption': jinja2.escape(p.caption),
                'thumbUrl': jinja2.escape(p.thumbnail_url),
            })
        ret.update({'previews': previews})

    if product.is_premium() and product.premium:
        ret.update({
            'price': product.premium.get_price() or '0',
            'priceLocale': product.premium.get_price_locale(),
            'purchase': product.get_purchase_url(),
        })
        currencies = product.premium.supported_currencies()
        if len(currencies) > 1 and waffle.switch_is_active('currencies'):
            currencies_dict = dict([(k, v.get_price_locale())
                                    for k, v in currencies])
            ret['currencies'] = json.dumps(currencies_dict, cls=JSONEncoder)
        if request.amo_user:
            ret['isPurchased'] = purchased

    # Jinja2 escape everything except this whitelist so that bool is retained
    # for the JSON encoding.
    wl = ('isPurchased', 'price', 'currencies', 'categories', 'previews',
          'is_packaged')
    return dict([k, jinja2.escape(v) if k not in wl else v]
                for k, v in ret.items())
示例#50
0
    def file_details(self, file):
        platform = file.platform_id
        if self.latest and (
            self.addon.status == file.status == amo.STATUS_PUBLIC):
            url = file.latest_xpi_url()
        else:
            url = file.get_url_path(self.src)

        if platform == amo.PLATFORM_ALL.id:
            text, os = _('Download Now'), None
        else:
            text, os = _('Download'), amo.PLATFORMS[platform]

        if self.show_eula:
            # L10n: please keep &nbsp; in the string so &rarr; does not wrap.
            text = jinja2.Markup(_('Continue to Download&nbsp;&rarr;'))
            url = file.eula_url()
        elif self.accept_eula:
            text = _('Accept and Download')
        elif self.show_contrib:
            # The eula doesn't exist or has been hit already.
            # L10n: please keep &nbsp; in the string so &rarr; does not wrap.
            text = jinja2.Markup(_('Continue to Download&nbsp;&rarr;'))
            roadblock = reverse('addons.roadblock', args=[self.addon.id])
            url = urlparams(roadblock, eula='', version=self.version.version)

        return text, url, os
示例#51
0
 def test_updated_timestamp(self):
     self._generate()
     r = self.client.get(urlparams(self.url, sort='updated'))
     items = pq(r.content)('.primary .item')
     for idx, c in enumerate(r.context['pager'].object_list):
         eq_(strip_whitespace(items.eq(idx).find('.modified').text()),
             'Updated %s' % strip_whitespace(datetime_filter(c.modified)))
示例#52
0
 def check_sort_links(self,
                      key,
                      title=None,
                      sort_by=None,
                      reverse=True,
                      params={}):
     r = self.client.get(urlparams(self.url, sort=key, **params))
     eq_(r.status_code, 200)
     doc = pq(r.content)
     if title:
         if hasattr(self, 'MOBILE'):
             menu = doc('#sort-menu')
             eq_(menu.find('span').text(), title)
             eq_(menu.find('.selected').text(), title)
         else:
             eq_(doc('#sorter .selected').text(), title)
     if sort_by:
         results = r.context['pager'].object_list
         if sort_by == 'name':
             expected = sorted(results, key=lambda x: unicode(x.name))
         else:
             expected = sorted(results,
                               key=lambda x: getattr(x, sort_by),
                               reverse=reverse)
         eq_(list(results), expected)
示例#53
0
def refund_permission_url(addon, dest='payments'):
    """
    Send permissions request to PayPal for refund privileges on
    this addon's paypal account. Returns URL on PayPal site to visit.
    """
    # This is set in settings_test so we don't start calling PayPal
    # by accident. Explicitly set this in your tests.
    if not settings.PAYPAL_PERMISSIONS_URL:
        return ''
    paypal_log.debug('Getting refund permission URL for addon: %s' % addon.pk)

    with statsd.timer('paypal.permissions.url'):
        url = urlparams(reverse('devhub.addons.acquire_refund_permission',
                                args=[addon.slug]),
                        dest=dest)
        try:
            r = _call(settings.PAYPAL_PERMISSIONS_URL + 'RequestPermissions', {
                'scope': 'REFUND',
                'callback': absolutify(url)
            })
        except PaypalError, e:
            paypal_log.debug('Error on refund permission URL addon: %s, %s' %
                             (addon.pk, e))
            if 'malformed' in str(e):
                # PayPal is very picky about where they redirect users to.
                # If you try and create a PayPal permissions URL on a
                # zamboni that has a non-standard port number or a
                # non-standard TLD, it will blow up with an error. We need
                # to be able to at least visit these pages and alter them
                # in dev, so this will give you a broken token that doesn't
                # work, but at least the page will function.
                r = {'token': 'wont-work-paypal-doesnt-like-your-domain'}
            else:
                raise
示例#54
0
 def test_reviewers(self, action_allowed):
     action_allowed.return_value = True
     doc = pq(market_tile(self.context, self.webapp))
     data = json.loads(doc('.mkt-tile').attr('data-product'))
     issue = urlparams(reverse('detail.record',
                               args=[self.webapp.app_slug]), src='foo')
     eq_(data['recordUrl'], issue)
示例#55
0
 def test_redirect_after_login(self):
     url = urlparams(self._get_login_url(), to="en-US/firefox/about")
     r = self.client.post(url, {
         'username': '******',
         'password': '******'
     },
                          follow=True)
     self.assertRedirects(r, '/en-US/firefox/about')
示例#56
0
    def test_results_popularity(self):
        collections = [
            ('Traveler Pack', 2000),
        ]
        webdev_collections = [
            ('Tools for Developer', 67),
            ('Web Developer', 250),
            ('Web Developer Necessities', 50),
            ('Web Pro', 200),
            ('Web Developer Pack', 242),
        ]
        sorted_webdev_collections = sorted(webdev_collections,
                                           key=lambda x: x[1],
                                           reverse=True)

        # Create collections, in "random" order, with an additional collection
        # that isn't relevant to our query.
        for name, subscribers in (collections + webdev_collections):
            self._collections.append(
                amo.tests.collection_factory(name=name,
                                             subscribers=subscribers,
                                             weekly_subscribers=subscribers))
        self.refresh()

        # No sort = sort by weekly subscribers, 'all' = sort by subscribers.
        for sort in ('', 'all'):
            if sort:
                r = self.client.get(urlparams(self.url,
                                              q='web developer',
                                              sort=sort),
                                    follow=True)
            else:
                r = self.client.get(urlparams(self.url, q='web developer'),
                                    follow=True)
            eq_(r.status_code, 200)
            results = list(r.context['pager'].object_list)
            eq_(len(results), len(webdev_collections))
            for coll, expected in zip(results, sorted_webdev_collections):
                eq_(
                    unicode(coll.name), expected[0],
                    'Wrong order for sort %r. Got: %s, expected: %s' %
                    (sort, results, sorted_webdev_collections))
                eq_(
                    coll.subscribers, expected[1],
                    'Incorrect subscribers for %r. Got %s. Expected %s.' %
                    (sort, coll.subscribers, expected[1]))
示例#57
0
    def check_cat_filters(self, params=None, selected='All Add-ons'):
        if not params:
            params = {}

        r = self.client.get(urlparams(self.url, **params))
        eq_(sorted(a.id for a in self.addons),
            sorted(a.id for a in r.context['pager'].object_list))

        cat = self.addons[0].all_categories[0]
        links = pq(r.content)('#category-facets li a')
        expected = [
            ('All Add-ons', self.url),
            ('Extensions', urlparams(self.url, atype=amo.ADDON_EXTENSION)),
            (unicode(cat.name),
             urlparams(self.url, atype=amo.ADDON_EXTENSION, cat=cat.id)),
        ]
        amo.tests.check_links(expected, links, selected, verify=False)
示例#58
0
 def test_redirect_after_login_evil(self):
     url = urlparams(self._get_login_url(), to='http://foo.com')
     r = self.client.post(url, {
         'username': '******',
         'password': '******'
     },
                          follow=True)
     self.assertRedirects(r, '/en-US/firefox/')