Example #1
0
    def check_cat_filter(self, params):
        raise SkipTest('until category filtering comes back')
        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))
        eq_(list(r.context['pager'].object_list), list(pager.object_list),
            '%s != %s' % (self.url, urlparams(self.url, **params or {})))

        doc = pq(r.content)('#filter-categories')
        a = pq(r.content)('#filter-categories').children('li').eq(0).find('a')

        # :last will no longer work
        a = doc('li').eq(1).find('a')
        eq_(a.text(), unicode(self.cat.name))
        if cat_selected:
            eq_(a.filter('.sel').length, 1,
                '%r should be selected' % unicode(self.cat.name))
        else:
            eq_(a.filter('.button').length, 1,
                '%r should be selected' % unicode(self.cat.name))

        params.update(cat=self.cat.id)
        eq_(a.attr('href'), urlparams(self.url, **params))

        sorts = pq(r.content)('#filter-sort')
        href = sorts('li:first-child a').attr('href')

        if cat_selected:
            self.assertNotEqual(href.find('sort=popularity'), -1,
                'Category found - first sort option should be Popularity')
        else:
            eq_(href, '/search/?sort=None',
                'Category found - first sort option should be Relevancy')
Example #2
0
    def check_cat_filter(self, params):
        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))
        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,
            "'Any Category' should be selected")
        a = li.children('a')
        eq_(a.length, 1)
        eq_(a.text(), 'Any Category')

        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')),
            {'cat': self.cat.id, 'page': None})
Example #3
0
    def check_cat_filter(self, params):
        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))
        eq_(
            list(r.context["pager"].object_list),
            list(pager.object_list),
            "%s != %s" % (self.url, urlparams(self.url, **params or {})),
        )

        doc = pq(r.content)("#filter-categories")
        a = pq(r.content)("#filter-categories").children("li").eq(0).find("a")

        # :last will no longer work
        a = doc("li").eq(1).find("a")
        eq_(a.text(), unicode(self.cat.name))
        if cat_selected:
            eq_(a.filter(".sel").length, 1, "%r should be selected" % unicode(self.cat.name))
        else:
            eq_(a.filter(".button").length, 1, "%r should be selected" % unicode(self.cat.name))

        params.update(cat=self.cat.id)
        eq_(a.attr("href"), urlparams(self.url, **params))

        sorts = pq(r.content)("#filter-sort")
        href = sorts("li:first-child a").attr("href")

        if cat_selected:
            self.assertNotEqual(
                href.find("sort=popularity"), -1, "Category found - first sort option should be Popularity"
            )
        else:
            eq_(href, "/search/?sort=None", "Category found - first sort option should be Relevancy")
Example #4
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)
Example #5
0
 def test_collection_directory_redirects(self):
     base = reverse("collections.list")
     tests = [
         ("/collections/editors_picks", 301, urlparams(base, sort="featured")),
         ("/collections/popular/", 301, urlparams(base, sort="popular")),
         # These don't work without a login.
         ("/collections/mine", 301, base),
         ("/collections/favorites/", 301, base),
     ]
     for test in tests:
         self.check_response(*test)
Example #6
0
 def test_collection_directory_redirects(self):
     base = reverse('collections.list')
     tests = [
         ('/collections/editors_picks', 301,
          urlparams(base, sort='featured')),
         ('/collections/popular/', 301,
          urlparams(base, sort='popular')),
         # These don't work without a login.
         ('/collections/favorites/', 301, base),
     ]
     for test in tests:
         self.check_response(*test)
Example #7
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)
Example #8
0
    def test_get_featured_apps_no_cat(self):
        request = amo.tests.req_factory_factory(
            urlparams(self.url, category=''),
            user=UserProfile.objects.get(username='******'))
        doc = pq(str(featured_apps_ajax(request)))
        eq_(doc('.featured-app').length, 0)

        FeaturedApp.objects.create(app=self.a1, category=None)
        request = amo.tests.req_factory_factory(
            urlparams(self.url, category=''),
            user=UserProfile.objects.get(username='******'))
        doc = pq(str(featured_apps_ajax(request)))
        eq_(doc('.featured-app').length, 1)
Example #9
0
    def check_price_filter(self, price, selected, type_=None):
        self.setup_paid(type_=type_)
        self.refresh()

        r = self.client.get(self.url, {"price": price})
        eq_(r.status_code, 200)
        links = pq(r.content)("#filter-prices a")
        expected = [
            ("Any Price", 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)
Example #10
0
    def test_locale_switcher(self):
        # Test valid locale redirect.
        from_locale = settings.AMO_LANGUAGES[0]
        to_locale = settings.AMO_LANGUAGES[1]
        from_url = reverse("localizers.locale_dashboard", kwargs=dict(locale_code=from_locale))
        to_url = reverse("localizers.locale_dashboard", kwargs=dict(locale_code=to_locale))
        res = self.client.get(urlparams(from_url, userlang=to_locale), follow=True)
        self.assert3xx(res, to_url, status_code=302)

        # Test invalid locale, which doesn't redirect.
        to_locale = "xx"
        to_url = reverse("localizers.locale_dashboard", kwargs=dict(locale_code=to_locale))
        res = self.client.get(urlparams(from_url, userlang=to_locale), follow=True)
        eq_(res.status_code, 200)
Example #11
0
    def check_price_filter(self, price, selected, type_=None):
        self.setup_paid(type_=type_)
        self.refresh()

        r = self.client.get(self.url, {'price': price})
        eq_(r.status_code, 200)
        links = pq(r.content)('#filter-prices a')
        expected = [
            ('Any Price', 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)
Example #12
0
    def check_device_filter(self, device, selected):
        self.setup_devices()
        self.reindex(Webapp)

        r = self.client.get(self.url, {'device': device})
        eq_(r.status_code, 200)
        links = pq(r.content)('#device-facets a')
        expected = [
            ('Any Device', self.url),
            ('Desktop', urlparams(self.url, device='desktop')),
            ('Mobile', urlparams(self.url, device='mobile')),
            ('Tablet', urlparams(self.url, device='tablet')),
        ]
        amo.tests.check_links(expected, links, selected)
        return sorted(a.id for a in r.context['pager'].object_list)
Example #13
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)
Example #14
0
 def test_updated_sort(self):
     r = self.client.get(urlparams(self.url, sort='updated'))
     sel = pq(r.content)('#sorter ul > li.selected')
     eq_(sel.find('a').attr('class'), 'extra-opt')
     eq_(sel.text(), 'Recently Updated')
     c = r.context['collections'].object_list
     eq_(list(c), sorted(c, key=lambda x: x.modified, reverse=True))
Example #15
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)
Example #16
0
    def test_action_links(self):
        self.create_switch('iarc')
        self.create_switch('comm-dashboard')
        self.create_switch('in-app-payments')
        self.create_switch('view-transactions')
        app = self.get_app()
        app.update(public_stats=True, is_packaged=True,
                   premium_type=amo.ADDON_PREMIUM_INAPP)
        self.make_mine()
        doc = pq(self.client.get(self.url).content)
        expected = [
            ('Edit Listing', app.get_dev_url()),
            ('Add New Version', app.get_dev_url('versions')),
            ('Status & Versions', app.get_dev_url('versions')),
            ('Content Ratings', app.get_dev_url('ratings')),
            ('Compatibility & Payments', app.get_dev_url('payments')),
            ('In-App Payments', app.get_dev_url('in_app_config')),
            ('Team Members', app.get_dev_url('owner')),
            ('View Listing', app.get_url_path()),

            ('Messages', app.get_comm_thread_url()),
            # TODO: Re-enable once Monolith stats are back.
            #('Statistics', app.get_stats_url()),
            ('Transactions', urlparams(
                reverse('mkt.developers.transactions'), app=app.id)),
        ]
        amo.tests.check_links(expected, doc('a.action-link'), verify=False)
Example #17
0
 def test_name_sort(self):
     r = self.client.get(urlparams(self.url, sort='name'))
     sel = pq(r.content)('#sorter ul > li.selected')
     eq_(sel.find('a').attr('class'), 'extra-opt')
     eq_(sel.text(), 'Name')
     c = r.context['collections'].object_list
     eq_(list(c), sorted(c, key=lambda x: x.name))
Example #18
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)
Example #19
0
 def test_sorter(self):
     r = self.client.get(self.url)
     li = pq(r.content)('#sorter li:eq(0)')
     eq_(li.attr('class'), 'selected')
     eq_(li.find('a').attr('href'),
         urlparams(reverse('search.search'), cat=self.cat.id,
                   sort='downloads'))
Example #20
0
 def test_redirect_free_price_sort(self):
     for url in [self.url, reverse('browse.apps')]:
         # `sort=price` should be changed to `sort=downloads` if
         # `price=free` is in querystring.
         r = self.client.get(url, {'price': 'free', 'sort': 'price'})
         self.assert3xx(r, urlparams(url, price='free', sort='popularity'),
                        302)
Example #21
0
 def test_mostsubscribers_sort(self):
     r = self.client.get(urlparams(self.url, sort='followers'))
     sel = pq(r.content)('#sorter ul > li.selected')
     eq_(sel.find('a').attr('class'), 'opt')
     eq_(sel.text(), 'Most Followers')
     c = r.context['collections'].object_list
     eq_(list(c), sorted(c, key=lambda x: x.subscribers, reverse=True))
Example #22
0
    def check_device_filter(self, device, selected):
        raise SkipTest("See bug 785898")
        self.setup_devices()
        self.reindex(Webapp)

        r = self.client.get(self.url, {"device": device})
        eq_(r.status_code, 200)
        links = pq(r.content)("#device-facets a")
        expected = [
            ("Any Device", self.url),
            ("Desktop", urlparams(self.url, device="desktop")),
            ("Mobile", urlparams(self.url, device="mobile")),
            ("Tablet", urlparams(self.url, device="tablet")),
        ]
        amo.tests.check_links(expected, links, selected)
        return sorted(a.id for a in r.context["pager"].object_list)
Example #23
0
def refund_reason(request, contribution, wizard):
    addon = contribution.addon
    if not 'request' in wizard.get_progress():
        return redirect('users.support', contribution.pk, 'request')

    if contribution.is_instant_refund():
        paypal.refund(contribution.paykey)
        paypal_log.info('Refund issued for contribution %r' % contribution.pk)
        # Note: we have to wait for PayPal to issue an IPN before it's
        # completely refunded.
        messages.success(request, _('Refund is being processed.'))
        return redirect('users.purchases')

    form = forms.ContactForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        url = absolutify(urlparams(addon.get_dev_url('issue_refund'),
                                   transaction_id=contribution.transaction_id))
        template = jingo.render_to_string(request,
            wizard.tpl('emails/refund-request.txt'),
            context={'addon': addon,
                     'form': form,
                     'user': request.amo_user,
                     'contribution': contribution,
                     'refund_url': url})
        log.info('Refund request sent by user: %s for addon: %s' %
                 (request.amo_user.pk, addon.pk))
        # L10n: %s is the addon name.
        send_mail(_(u'New Refund Request for %s' % addon.name),
                  template, settings.NOBODY_EMAIL,
                  [smart_str(addon.support_email)])
        return redirect(reverse('users.support',
                                args=[contribution.pk, 'refund-sent']))

    return wizard.render(request, wizard.tpl('refund.html'), {'form': form})
Example #24
0
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)
Example #25
0
 def test_newest_sort(self):
     r = self.client.get(urlparams(self.url, sort='created'))
     sel = pq(r.content)('#sorter ul > li.selected')
     eq_(sel.find('a').attr('class'), 'opt')
     eq_(sel.text(), 'Newest')
     c = r.context['collections'].object_list
     eq_(list(c), sorted(c, key=lambda x: x.created, reverse=True))
Example #26
0
 def check_results(self, params, expected):
     r = self.client.get(urlparams(self.url, **params), follow=True)
     eq_(r.status_code, 200)
     got = self.get_results(r)
     eq_(got, expected,
         'Got: %s. Expected: %s. Parameters: %s' % (got, expected, params))
     return r
Example #27
0
    def process_request(self, request):
        request.APP = amo.FIREFOX

        path_ = request.get_full_path()
        new_path = None
        new_qs = {}

        lang, app, rest = Prefixer(request).split_path(path_)

        if app:
            # Strip /<app> from URL.
            new_path = rest

        if lang:
            # Strip /<lang> from URL.
            if not new_path:
                new_path = rest
            new_qs['lang'] = lang.lower()

        region, _, rest = path_.lstrip('/').partition('/')
        region = region.lower()

        if region in mkt.regions.REGIONS_DICT:
            # Strip /<region> from URL.
            if not new_path:
                new_path = rest
            new_qs['region'] = region

        if new_path is not None:
            if not new_path or new_path[0] != '/':
                new_path = '/' + new_path
            # TODO: Make this a 301 when we enable region stores in prod.
            return http.HttpResponseRedirect(urlparams(new_path, **new_qs))
Example #28
0
    def test_url(self, url, app_is_mobile=True, browser_is_mobile=False):
        """
        Test a view to make sure that it excludes mobile-incompatible apps
        from its listings.
        """
        url = urlparams(url, mobile="true" if browser_is_mobile else "false")

        if app_is_mobile:
            # If the app is supposed to be mobile and we haven't created the
            # AddonDeviceType object yet, create it.
            self.mcompat = AddonDeviceType.objects.create(addon=self.webapp, device_type=amo.DEVICE_MOBILE.id)
            self.mcompat.save()
            self.reindex(Webapp)

        self.refresh()
        r = self.client.get(url, follow=True)
        eq_(r.status_code, 200)

        # If the browser is mobile and the app is not mobile compatible, assert
        # that the app doesn't show up in the listing.
        if browser_is_mobile and not app_is_mobile:
            assert self.app_name not in r.content, "Found non-mobile app for %s" % url
        else:
            # Otherwise assert that it does.
            assert self.app_name in r.content, "Couldn't find mobile app for %s" % url

        # Cleanup
        if app_is_mobile:
            # If the app is not mobile and we haven't destroyed the
            # AddonDeviceType from a previous test, destroy it now.
            self.mcompat.delete()
            self.reindex(Webapp)
            self.mcompat = None
Example #29
0
def download_file(request, file_id, type=None):
    file = get_object_or_404(File.objects, pk=file_id)
    addon = get_object_or_404(Addon.with_unlisted, pk=file.version.addon_id)

    # General case: addon is listed.
    if addon.is_listed:
        if addon.is_disabled or file.status == amo.STATUS_DISABLED:
            if (acl.check_addon_ownership(request, addon, viewer=True,
                                          ignore_disabled=True) or
                    acl.check_addons_reviewer(request)):
                return HttpResponseSendFile(
                    request, file.guarded_file_path,
                    content_type='application/xp-install')
            else:
                raise http.Http404()
    else:
        if not owner_or_unlisted_reviewer(request, addon):
            raise http.Http404  # Not listed, not owner or admin.

    attachment = (type == 'attachment' or not request.APP.browser)

    loc = urlparams(file.get_mirror(addon, attachment=attachment),
                    filehash=file.hash)
    response = http.HttpResponseRedirect(loc)
    response['X-Target-Digest'] = file.hash
    return response
Example #30
0
def queue_apps(request):
    qs = (Webapp.objects.pending().filter(disabled_by_user=False)
                        .order_by('created'))

    review_num = request.GET.get('num', None)
    if review_num:
        try:
            review_num = int(review_num)
        except ValueError:
            pass
        else:
            try:
                # Force a limit query for efficiency:
                start = review_num - 1
                row = qs[start:start + 1][0]
                return redirect(
                    urlparams(reverse('reviewers.apps.review',
                                      args=[row.app_slug]),
                              num=review_num))
            except IndexError:
                pass

    per_page = request.GET.get('per_page', QUEUE_PER_PAGE)
    pager = paginate(request, qs, per_page)

    return jingo.render(request, 'reviewers/queue.html', {'pager': pager})
Example #31
0
    def check_results(self, expected):
        """Make sure the expected addons are listed in a standard search."""
        response = self.client.get(urlparams(self.url, sort='downloads'))
        eq_(response.status_code, 200, str(response.content))
        got = self.get_results(response)

        for addon in expected:
            assert addon.pk in got, '%s is not in %s' % (addon.pk, got)
        return response
Example #32
0
def _find_version_page(qs, addon, version_num):
    ids = list(qs.values_list('version', flat=True))
    url = reverse('addons.versions', args=[addon.slug])
    if version_num in ids:
        page = 1 + ids.index(version_num) / PER_PAGE
        to = urlparams(url, 'version-%s' % version_num, page=page)
        return http.HttpResponseRedirect(to)
    else:
        raise http.Http404()
Example #33
0
    def check_price_filter(self, price, selected, type_=None):
        self.setup_paid(type_=type_)
        self.refresh()

        r = self.client.get(self.url, {'price': price})
        eq_(r.status_code, 200)
        doc = pq(r.content)
        links = doc('#filter-prices a')
        expected = [
            ('Any Price', self.url),
            ('Free Only', urlparams(self.url, price='free')),
            ('Premium Only', urlparams(self.url, price='paid')),
        ]
        amo.tests.check_links(expected, links, selected)

        eq_(doc('#filters-body input[name=price]').attr('value'), price)

        return list(r.context['pager'].object_list)
Example #34
0
 def test_popular_sort(self):
     r = self.client.get(urlparams(self.url, sort='popular'))
     sel = pq(r.content)('#sorter ul > li.selected')
     eq_(sel.find('a').attr('class'), 'extra-opt')
     eq_(sel.text(), 'Recently Popular')
     c = r.context['collections'].object_list
     eq_(list(c), sorted(c,
                         key=lambda x: x.weekly_subscribers,
                         reverse=True))
Example #35
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)
Example #36
0
 def test_results_item(self):
     r = self.client.get(self.url)
     item = pq(r.content)('.listing .item')
     eq_(item.length, 1)
     a = item.find('a')
     eq_(a.find('h3').text(), unicode(self.webapp.name))
     # Testing the correct download source like a bawse!
     eq_(a.attr('href'),
         urlparams(self.webapp.get_url_path(), src='mkt-search'))
Example #37
0
def media(context, url, key='MEDIA_URL'):
    """Get a MEDIA_URL link with a cache buster querystring."""
    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 context[key] + utils.urlparams(url, b=build)
Example #38
0
    def test_get_featured_apps(self):
        r = self.client.get(urlparams(self.url, category=self.c1.id))
        assert not r.content

        FeaturedApp.objects.create(app=self.a1, category=self.c1)
        FeaturedApp.objects.create(app=self.s1, category=self.c2,
                                   is_sponsor=True)
        r = self.client.get(urlparams(self.url, category=self.c1.id))
        doc = pq(r.content)
        eq_(len(doc), 1)
        eq_(doc('table td').eq(1).text(), 'awesome app 1')
        eq_(doc('table td').eq(4).text(), 'Not sponsored')

        r = self.client.get(urlparams(self.url, category=self.c2.id))
        doc = pq(r.content)
        eq_(len(doc), 1)
        eq_(doc('table td').eq(1).text(), 'splendid app 1')
        eq_(doc('table td').eq(4).text(), 'Sponsored')
Example #39
0
    def test_get_featured_apps(self):
        r = self.client.get(urlparams(self.url, category=self.c1.slug))
        assert not r.content

        FeaturedApp.objects.create(app=self.a1, category=self.c1)
        FeaturedApp.objects.create(app=self.s1,
                                   category=self.c2,
                                   is_sponsor=True)
        r = self.client.get(urlparams(self.url, category=self.c1.slug))
        doc = pq(r.content)
        eq_(len(doc), 1)
        eq_(doc('h2').text(), 'awesome app 1')

        r = self.client.get(urlparams(self.url, category=self.c2.slug))
        doc = pq(r.content)
        eq_(len(doc), 1)
        eq_(doc('h2').text(), 'splendid app 1')
        eq_(doc('em.sponsored').attr('title'), 'Sponsored')
Example #40
0
 def test_sorter(self):
     # TODO(dspasovski): Fix this.
     raise SkipTest
     r = self.client.get(self.url)
     li = pq(r.content)('#sorter li:eq(0)')
     eq_(li.filter('.selected').length, 1)
     eq_(li.find('a').attr('href'),
         urlparams(reverse('search.search'), cat=self.cat.id,
                   sort='downloads'))
Example #41
0
    def test_header_links(self):
        browse = reverse('apps.list')
        cat = Category.objects.create(name='Games',
                                      slug='games',
                                      type=amo.ADDON_WEBAPP)
        expected = [
            ('Most Popular', urlparams(browse, sort='downloads')),
            ('Top Free', urlparams(browse, sort='free')),
            ('Top Paid', urlparams(browse, sort='paid')),
            ('Highest Rated', urlparams(browse, sort='rating')),
            ('Games', cat.get_url_path()),
        ]

        r = self.client.get(self.url)
        doc = pq(r.content)('#site-nav')

        amo.tests.check_links(expected, doc('#explore-cats li a'))
        eq_(doc('#my-apps a').attr('href'), reverse('users.purchases'))
        eq_(doc('#submit-app a').attr('href'), reverse('devhub.submit_apps.1'))
Example #42
0
    def test_locale_switcher(self):
        # Test valid locale redirect.
        from_locale = settings.AMO_LANGUAGES[0]
        to_locale = settings.AMO_LANGUAGES[1]
        from_url = reverse('localizers.locale_dashboard',
                           kwargs=dict(locale_code=from_locale))
        to_url = reverse('localizers.locale_dashboard',
                         kwargs=dict(locale_code=to_locale))
        res = self.client.get(urlparams(from_url, userlang=to_locale),
                              follow=True)
        self.assertRedirects(res, to_url, status_code=302)

        # Test invalid locale, which doesn't redirect.
        to_locale = 'xx'
        to_url = reverse('localizers.locale_dashboard',
                         kwargs=dict(locale_code=to_locale))
        res = self.client.get(urlparams(from_url, userlang=to_locale),
                              follow=True)
        eq_(res.status_code, 200)
Example #43
0
def cache_buster(context, url):
    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 utils.urlparams(url, b=build)
Example #44
0
    def check_results(self, params, expected, sorted=True):
        r = self.client.get(urlparams(self.url, **params), follow=True)
        eq_(r.status_code, 200, str(r.content))
        got = self.get_results(r)
        if sorted:
            got.sort()
            expected.sort()

        eq_(got, expected,
            'Got: %s. Expected: %s. Parameters: %s' % (got, expected, params))
        return r
Example #45
0
 def get_url_path(self, src=None):
     """
     We use <username> as the slug, unless it contains gross
     characters - in which case use <id> as the slug.
     """
     from amo.utils import urlparams
     chars = '/<>"\''
     slug = self.username
     if not self.username or any(x in chars for x in self.username):
         slug = self.id
     url = reverse('users.profile', args=[slug])
     return urlparams(url, src=src)
Example #46
0
def collection_listing(request, base=None):
    sort = request.GET.get('sort')
    # We turn users into followers.
    if sort == 'users':
        return redirect(urlparams(reverse('collections.list'),
                                  sort='followers'), permanent=True)
    filter = get_filter(request, base)
    collections = paginate(request, filter.qs)
    return render(request, 'bandwagon/impala/collection_listing.html',
                  dict(collections=collections, src='co-hc-sidebar',
                       dl_src='co-dp-sidebar', filter=filter, sort=sort,
                       sorting=filter.field))
Example #47
0
def legacy_directory_redirects(request, page):
    sorts = {'editors_picks': 'featured', 'popular': 'popular',
             'users': 'followers'}
    loc = base = reverse('collections.list')
    if page in sorts:
        loc = urlparams(base, sort=sorts[page])
    elif request.user.is_authenticated():
        if page == 'mine':
            loc = reverse('collections.user', args=[request.amo_user.username])
        elif page == 'favorites':
            loc = reverse('collections.following')
    return http.HttpResponseRedirect(loc)
Example #48
0
    def check_sort_links(self, key, title=None, sort_by=None, reverse=True,
                         params=None):
        if not params:
            params = {}
        r = self.client.get(urlparams(self.url, sort=key, **params))
        eq_(r.status_code, 200)

        if sort_by:
            results = r.context['pager'].object_list
            expected = sorted(results, key=lambda x: getattr(x, sort_by),
                              reverse=reverse)
            eq_(list(results), expected)
Example #49
0
def purchase_complete(request, addon, status):
    result = ''
    if status == 'complete':
        uuid_ = request.GET.get('uuid')
        log.debug('Looking up contrib for uuid: %s' % uuid_)

        # The IPN may, or may not have come through. Which means looking for
        # a for pre or post IPN contributions. If both fail, then we've not
        # got a matching contribution.
        lookup = (Q(uuid=uuid_, type=amo.CONTRIB_PENDING)
                  | Q(transaction_id=uuid_, type=amo.CONTRIB_PURCHASE))
        con = get_object_or_404(Contribution, lookup)

        log.debug('Check purchase paypal addon: %s, user: %s, paykey: %s' %
                  (addon.pk, request.amo_user.pk, con.paykey[:10]))
        try:
            result = paypal.check_purchase(con.paykey)
            if result == 'ERROR':
                paypal.paypal_log_cef(
                    request, addon, uuid_, 'Purchase Fail', 'PURCHASEFAIL',
                    'Checking purchase state returned error')
                raise
        except:
            paypal.paypal_log_cef(
                request, addon, uuid_, 'Purchase Fail', 'PURCHASEFAIL',
                'There was an error checking purchase state')
            log.error('Check purchase paypal addon: %s, user: %s, paykey: %s' %
                      (addon.pk, request.amo_user.pk, con.paykey[:10]),
                      exc_info=True)
            result = 'ERROR'
            status = 'error'

        log.debug('Paypal returned: %s for paykey: %s' %
                  (result, con.paykey[:10]))
        if result == 'COMPLETED' and con.type == amo.CONTRIB_PENDING:
            con.update(type=amo.CONTRIB_PURCHASE)

    context = {
        'realurl': request.GET.get('realurl', ''),
        'status': status,
        'result': result
    }

    # For mobile, bounce back to the details page.
    if request.MOBILE:
        url = urlparams(shared_url('detail', addon), **context)
        return http.HttpResponseRedirect(url)

    context.update({'addon': addon})
    response = jingo.render(request, 'addons/paypal_result.html', context)
    response['x-frame-options'] = 'allow'
    return response
Example #50
0
 def check_results(self, q, expected):
     res = self.client.get(urlparams(self.url, q=q))
     eq_(res.status_code, 200)
     content = json.loads(res.content)
     eq_(len(content), len(expected))
     ids = [int(c['value']) for c in content]
     emails = [u'%s' % c['label'] for c in content]
     for d in expected:
         id = d['value']
         email = u'%s' % d['label']
         assert id in ids, ('Expected user ID "%s" not found' % id)
         assert email in emails, ('Expected username "%s" not found' %
                                  email)
Example #51
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_(row['default_currency'], region.default_currency)
         eq_(row['default_language'], region.default_language)
     eq_(len(data['objects']), len(mkt.regions.REGIONS_DICT))
     eq_(data['meta']['total_count'], len(mkt.regions.REGIONS_DICT))
Example #52
0
    def test_lookup_app(self, index_webapps_mock):
        # Load the Webapp fixture here, as loading it in the
        # TestAddonSearch.fixtures would trigger the reindex, and fail, as
        # this is an AMO test.
        management.call_command('loaddata', 'base/337141-steamcube')
        index_webapps_mock.assert_called()

        res = self.client.get(urlparams(self.url, q='steamcube'))
        eq_(res.status_code, 200)
        links = pq(res.content)('form + h3 + ul li a')
        eq_(len(links), 0)
        if any(li.text().contains('Steamcube') for li in links):
            raise AssertionError('Did not expect webapp in results.')
Example #53
0
def index(request, version=None):
    template = 'compat/index.html'
    COMPAT = [v for v in amo.COMPAT if v['app'] == request.APP.id]
    compat_dict = dict((v['main'], v) for v in COMPAT)
    if not COMPAT:
        return jingo.render(request, template, {'results': False})
    if version not in compat_dict:
        return http.HttpResponseRedirect(
            reverse('compat.index', args=[COMPAT[0]['main']]))
    qs = AppCompat.search()
    binary = None

    initial = {'appver': '%s-%s' % (request.APP.id, version), 'type': 'all'}
    initial.update(request.GET.items())
    form = CompatForm(initial)
    if request.GET and form.is_valid():
        if form.cleaned_data['appver']:
            app, ver = form.cleaned_data['appver'].split('-')
            if int(app) != request.APP.id or ver != version:
                new = reverse('compat.index', args=[ver], add_prefix=False)
                url = '/%s%s' % (amo.APP_IDS[int(app)].short, new)
                type_ = form.cleaned_data['type'] or None
                return http.HttpResponseRedirect(urlparams(url, type=type_))

        if form.cleaned_data['type'] != 'all':
            binary = form.cleaned_data['type'] == 'binary'

    compat, app = compat_dict[version], str(request.APP.id)
    compat_queries = (
        ('prev',
         qs.query(
             **{
                 'top_95.%s.%s' % (app, vint(compat['previous'])): True,
                 'support.%s.max__gte' % app: vint(compat['previous'])
             })),
        ('top_95', qs.query(**{'top_95_all.%s' % app: True})),
        ('all', qs),
    )
    compat_levels = [(key, version_compat(qs, compat, app, binary))
                     for key, qs in compat_queries]
    usage_addons, usage_total = usage_stats(request, compat, app, binary)
    return jingo.render(
        request, template, {
            'version': version,
            'usage_addons': usage_addons,
            'usage_total': usage_total,
            'compat_levels': compat_levels,
            'form': form,
            'results': True,
            'show_previous': request.GET.get('previous')
        })
Example #54
0
    def check_cat_filter(self, params):
        raise SkipTest('until category filtering comes back')
        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))
        eq_(list(r.context['pager'].object_list), list(pager.object_list),
            '%s != %s' % (self.url, urlparams(self.url, **params or {})))

        doc = pq(r.content)('#filter-categories')
        a = pq(r.content)('#filter-categories').children('li').eq(0).find('a')

        # :last will no longer work
        a = doc('li').eq(1).find('a')
        eq_(a.text(), unicode(self.cat.name))
        if cat_selected:
            eq_(
                a.filter('.sel').length, 1,
                '%r should be selected' % unicode(self.cat.name))
        else:
            eq_(
                a.filter('.button').length, 1,
                '%r should be selected' % unicode(self.cat.name))

        params.update(cat=self.cat.id)
        eq_(a.attr('href'), urlparams(self.url, **params))

        sorts = pq(r.content)('#filter-sort')
        href = sorts('li:first-child a').attr('href')

        if cat_selected:
            self.assertNotEqual(
                href.find('sort=popularity'), -1,
                'Category found - first sort option should be Popularity')
        else:
            eq_(href, '/search/?sort=None',
                'Category found - first sort option should be Relevancy')
Example #55
0
    def add_root_elements(self, handler):
        # set feed_url to current page
        page = None if self.page.number == 1 else self.page.number
        self.feed['feed_url'] = urlparams(self.feed['feed_url'], page=page)
        DefaultFeed.add_root_elements(self, handler)

        # http://tools.ietf.org/html/rfc5005#section-3
        self.add_page_relation(handler, 'first', 1)
        if self.page.has_previous():
            self.add_page_relation(handler, 'previous',
                                   self.page.previous_page_number())
        if self.page.has_next():
            self.add_page_relation(handler, 'next',
                                   self.page.next_page_number())
        self.add_page_relation(handler, 'last', self.page.paginator.num_pages)
Example #56
0
def recalc_hash(request, file_id):

    file = get_object_or_404(File, pk=file_id)
    file.size = int(max(1, round(os.path.getsize(file.file_path) / 1024, 0)))
    file.hash = file.generate_hash()
    file.save()

    log.info('Recalculated hash for file ID %d' % file.id)
    messages.success(request,
                     'File hash and size recalculated for file %d.' % file.id)

    redirect_url = reverse('zadmin.addon_manage',
                           args=[file.version.addon.slug])
    page = request.GET.get('page', 1)
    return redirect(urlparams(redirect_url, page=page))
Example #57
0
def collection_listing(request, base=None):
    sort = request.GET.get('sort')
    # We turn users into followers.
    if sort == 'users':
        return redirect(urlparams(reverse('collections.list'),
                                  sort='followers'), permanent=True)
    filter = get_filter(request, base)
    collections = paginate(request, filter.qs)
    try:
        addon_collector = Addon.objects.get(id=11950)
    except Addon.DoesNotExist:
        addon_collector = None
    return render(request, 'bandwagon/impala/collection_listing.html',
                  dict(collections=collections, src='co-hc-sidebar',
                       dl_src='co-dp-sidebar', filter=filter, sort=sort,
                       sorting=filter.field, addon_collector=addon_collector))
Example #58
0
 def test_mobile_no_flash(self):
     a = amo.tests.app_factory()
     a.name = 'Basta Addendum'
     AddonDeviceType.objects.create(addon=self.webapp,
                                    device_type=amo.DEVICE_MOBILE.id)
     AddonDeviceType.objects.create(addon=a,
                                    device_type=amo.DEVICE_MOBILE.id)
     a.save()
     af = a.get_latest_file()
     af.uses_flash = True
     af.save()
     a.save()
     self.reindex(Webapp)
     r = self.client.get(urlparams(reverse('search.search'), q='Basta'))
     eq_(r.status_code, 200)
     eq_(list(r.context['pager'].object_list), [self.webapp])
Example #59
0
 def get_user_url(self, name='profile', src=None, args=None):
     """
     We use <username> as the slug, unless it contains gross
     characters - in which case use <id> as the slug.
     """
     # TODO: Remove this ASAP (bug 880767).
     if settings.MARKETPLACE and name == 'profile':
         return '#'
     from amo.utils import urlparams
     chars = '/<>"\''
     slug = self.username
     if not self.username or any(x in chars for x in self.username):
         slug = self.id
     args = args or []
     url = reverse('users.%s' % name, args=[slug] + args)
     return urlparams(url, src=src)
Example #60
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': '/'
            },
        },
        'orientation': ['portrait-primary']
    }
    if settings.USE_APPCACHE:
        data['appcache_path'] = reverse('django_appcache.manifest')
    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,
                                mimetype='application/x-web-app-manifest+json')
        return response

    return _inner_view(request)