Exemplo n.º 1
0
 def test_bad_access_token(self):
     url = absolutify(reverse('app-list'))
     Token.generate_new(ACCESS_TOKEN, creds=self.access, user=self.user2)
     url, auth_header = self._oauth_request_info(
         url,
         client_key=self.access.key,
         client_secret=self.access.secret,
         resource_owner_key=generate(),
         resource_owner_secret=generate())
     auth = authentication.RestOAuthAuthentication()
     req = RequestFactory().get(url,
                                HTTP_HOST='testserver',
                                HTTP_AUTHORIZATION=auth_header)
     assert not auth.is_authenticated(req)
Exemplo n.º 2
0
 def test_bad_access_token(self):
     url = get_absolute_url(('api_dispatch_list', {'resource_name': 'app'}))
     Token.generate_new(ACCESS_TOKEN, creds=self.access, user=self.user2)
     url, auth_header = self._oauth_request_info(
         url,
         client_key=self.access.key,
         client_secret=self.access.secret,
         resource_owner_key=generate(),
         resource_owner_secret=generate())
     auth = authentication.OAuthAuthentication()
     req = RequestFactory().get(url,
                                HTTP_HOST='testserver',
                                HTTP_AUTHORIZATION=auth_header)
     eq_(auth.is_authenticated(req).status_code, 401)
Exemplo n.º 3
0
 def test_session_auth(self):
     req = RequestFactory().post('/api/',
                                 HTTP_AUTHORIZATION='mkt-shared-secret '
                                 '[email protected],56b6f1a3dd735d962c56'
                                 'ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb'
                                 '9c68c31b3371aa8130317815c89e5072e31bb94b4'
                                 '121c5c165f3515838d4d6c60c4,165d631d3c3045'
                                 '458b4516242dad7ae')
     req.user = AnonymousUser()
     for m in self.middlewares:
         m().process_request(req)
     ok_(self.auth.authenticate(Request(req)))
     ok_(req.user.is_authenticated())
     eq_(self.profile.pk, req.user.pk)
Exemplo n.º 4
0
    def test_waffle_fallback(self):
        self.make_premium(self.app, price='0.99')
        flag = waffle.models.Flag.objects.get(name='allow-paid-app-search')
        flag.everyone = None
        flag.users.add(self.profile.user)
        flag.save()

        req = RequestFactory().get('/')
        req.user = self.profile.user
        with self.settings(PURCHASE_ENABLED_REGIONS=[]):
            res = app_to_dict(self.app, region=regions.US.id, request=req)
        eq_(res['price'], Decimal('0.99'))
        eq_(res['price_locale'], '$0.99')
        eq_(res['payment_required'], True)
Exemplo n.º 5
0
 def process(self,
             authenticated,
             view=None,
             url='/',
             lang='en-US',
             app='firefox'):
     if not view:
         view = normal_view
     request = RequestFactory().get(url, HTTP_X_PJAX=True)
     request.user = Mock()
     request.APP = amo.APPS[app]
     request.LANG = lang
     request.user.is_authenticated.return_value = authenticated
     return LoginRequiredMiddleware().process_view(request, view, [], {})
Exemplo n.º 6
0
def req_factory_factory(url, user=None, post=False, data=None):
    """Creates a request factory, logged in with the user."""
    req = RequestFactory()
    if post:
        req = req.post(url, data or {})
    else:
        req = req.get(url, data or {})
    if user:
        req.amo_user = RequestUser.objects.get(id=user.id)
        req.user = user.user
        req.groups = req.user.get_profile().groups.all()
    req.APP = None
    req.check_ownership = partial(check_ownership, req)
    return req
Exemplo n.º 7
0
    def test_button(self, format='large'):
        rf = RequestFactory()
        get_request = rf.get('/fake')
        get_request.locale = 'fr'
        doc = pq(render("{{ download_button('button', '%s') }}" % format,
                        {'request': get_request}))

        eq_(doc.attr('id'), 'button')

        self.check_dumb_button(doc('noscript'))
        self.check_dumb_button(doc('.unrecognized-download'))
        self.check_dumb_button(doc('.download-list'))

        eq_(doc('.download-other a').length, 3)
Exemplo n.º 8
0
    def test_waffle_fallback(self):
        self.make_premium(self.app, price='0.99')
        flag = waffle.models.Flag.objects.get(name='override-app-purchase')
        flag.everyone = None
        flag.users.add(self.profile.user)
        flag.save()

        req = RequestFactory().get('/')
        req.user = self.profile.user
        with self.settings(PURCHASE_LIMITED=True):
            res = self.serialize(self.app, region=regions.US.id, request=req)
        eq_(res['price'], Decimal('0.99'))
        eq_(res['price_locale'], '$0.99')
        eq_(res['payment_required'], True)
Exemplo n.º 9
0
    def _test_auth(self, pk, is_authenticated, two_legged=True):
        request = RequestFactory().get('/en-US/firefox/2/api/2/user/',
                                       data={'authenticate_as': pk})
        request.user = None

        def alter_request(*args, **kw):
            request.user = self.admin
            return True
        is_authenticated.return_value = True
        is_authenticated.side_effect = alter_request

        auth = AMOOAuthAuthentication()
        auth.two_legged = two_legged
        auth.is_authenticated(request)
        return request
Exemplo n.º 10
0
    def test_release_notes(self):
        res = self.serialize()
        eq_(res['release_notes'], None)
        version = self.app.current_version
        version.releasenotes = u'These are nötes.'
        version.save()
        self.app.save()
        self.refresh('webapp')
        res = self.serialize()
        eq_(res['release_notes'], {u'en-US': unicode(version.releasenotes)})

        self.request = RequestFactory().get('/?lang=whatever')
        self.request.REGION = mkt.regions.US
        res = self.serialize()
        eq_(res['release_notes'], unicode(version.releasenotes))
Exemplo n.º 11
0
 def test_use_access_token(self):
     url = absolutify(reverse('app-list'))
     t = Token.generate_new(ACCESS_TOKEN, creds=self.access,
                            user=self.user2)
     url, auth_header = self._oauth_request_info(
         url, client_key=self.access.key, client_secret=self.access.secret,
         resource_owner_key=t.key, resource_owner_secret=t.secret)
     auth = authentication.RestOAuthAuthentication()
     req = RequestFactory().get(
         url, HTTP_HOST='testserver',
         HTTP_AUTHORIZATION=auth_header)
     req.API = True
     RestOAuthMiddleware().process_request(req)
     assert auth.authenticate(Request(req))
     eq_(req.user, self.user2)
Exemplo n.º 12
0
 def test_unknown_error_responses(self):
     # Create a scenario where the proxied API raises an HTTP error.
     data = {'unknown_error': 'something went wrong'}
     proxy_res = HttpResponse(data,
                              content_type='application/json',
                              status=403)
     proxy_res.json = data
     proxy_res.request = RequestFactory().get('http://api/some/endpoint')
     exc = HttpClientError(proxy_res.content, response=proxy_res)
     self.api.products.get.side_effect = exc
     res = self.request('get', '/reference/products?foo=bar', 'products')
     eq_(res.status_code, 403)
     eq_(json.loads(res.content),
         {u'error_message': {
             u'unknown_error': u'something went wrong'
         }})
Exemplo n.º 13
0
    def test_button(self, small=False):
        rf = RequestFactory()
        get_request = rf.get('/fake')
        get_request.locale = 'fr'
        doc = pq(
            render(
                "{{ download_firefox(small=%s, "
                "dom_id='button') }}" % small, {'request': get_request}))

        eq_(doc.attr('id'), 'button')

        self.check_dumb_button(doc('noscript'))
        self.check_dumb_button(doc('.unrecognized-download'))
        self.check_dumb_button(doc('.download-list'))

        eq_(doc('.download-other a').length, 6)
Exemplo n.º 14
0
    def test_post_reply(self):
        # Create a Tweet to reply to.
        Tweet.objects.create(pk=1,
                             raw_json='{}',
                             locale='en',
                             created=datetime.now())

        # Create a request and mock all the required properties and methods.
        request = RequestFactory().post(
            reverse('customercare.twitter_post'), {
                'reply_to': 1,
                'content': '@foobar try Aurora! #fxhelp'
            })
        request.session = {}
        request.twitter = Mock()
        request.twitter.authed = True
        request.twitter.api = Mock()
        return_value = {
            'id':
            123456790,
            'text':
            '@foobar try Aurora! #fxhelp',
            'created_at':
            datetime.strftime(datetime.utcnow(), '%a %b %d %H:%M:%S +0000 %Y'),
            'user': {
                'lang': 'en',
                'id': 42,
                'screen_name': 'r1cky',
                'profile_image_url': 'http://example.com/profile.jpg',
                'profile_image_url_https': 'https://example.com/profile.jpg',
            }
        }
        request.twitter.api.update_status.return_value = return_value
        credentials = {'screen_name': 'r1cky'}
        request.twitter.api.verify_credentials.return_value = credentials
        request.user = Mock()
        request.user.is_authenticated.return_value = False

        # Pass the request to the view and verify response.
        response = twitter_post(request)
        eq_(200, response.status_code)

        # Verify the reply was inserted with the right data.
        reply = Reply.objects.all()[0]
        eq_('r1cky', reply.twitter_username)
        eq_(1, reply.reply_to_tweet_id)
        eq_('@foobar try Aurora! #fxhelp', json.loads(reply.raw_json)['text'])
Exemplo n.º 15
0
 def setUp(self):
     self.profile = UserProfile.objects.get(pk=2519)
     self.request = RequestFactory().get('/')
     self.request.REGION = mkt.regions.US
     self.request.user = self.profile
     self.app = Webapp.objects.get(pk=337141)
     self.version = self.app.current_version
     self.app.update(categories=['books', 'social'])
     Preview.objects.all().delete()
     self.preview = Preview.objects.create(filetype='image/png',
                                           addon=self.app, position=0)
     self.app.description = {
         'en-US': u'XSS attempt <script>alert(1)</script>',
         'fr': u'Déscriptîon in frènch'
     }
     self.app.save()
     self.refresh('webapp')
Exemplo n.º 16
0
    def test_multiple_fails(self):
        client = OAuthClient(Mock(key='foo', secret='bar'))
        req = RequestFactory().get('/',
                                   HTTP_HOST='api',
                                   HTTP_AUTHORIZATION=client.header(
                                       'GET', 'http://foo/'))
        req.user = AnonymousUser()
        next_auth = Mock()
        self.resource._meta.authentication = (
            # OAuth fails because there are bogus auth headers.
            authentication.OAuthAuthentication(),
            next_auth)

        with self.assertRaises(ImmediateHttpResponse):
            eq_(self.resource.is_authenticated(req), None)
        # This never even got called.
        ok_(not next_auth.is_authenticated.called)
Exemplo n.º 17
0
    def setUp(self):
        self.request = RequestFactory()
        self.request.POST = {'toggle-paid': ''}

        self.addon = Addon.objects.get(pk=337141)
        AddonDeviceType.objects.create(
            addon=self.addon, device_type=amo.DEVICE_GAIA.id)
        self.platforms = {'free_platforms': ['free-firefoxos'],
                          'paid_platforms': ['paid-firefoxos']}

        self.price = Price.objects.create(price='0.99')
        self.user = UserProfile.objects.get(email='*****@*****.**')

        self.kwargs = {
            'request': self.request,
            'addon': self.addon,
            'user': self.user,
        }
Exemplo n.º 18
0
    def test_button_has_data_attr_if_not_direct(self):
        """
        If the button points to the thank you page, it should have a
        `data-direct-link` attribute that contains the direct url.
        """
        rf = RequestFactory()
        get_request = rf.get('/fake')
        get_request.locale = 'fr'
        doc = pq(render("{{ download_button('button') }}",
                        {'request': get_request}))

        # The first 3 links should be for desktop.
        links = doc('.download-list a')
        for link in links[:3]:
            ok_(pq(link).attr('data-direct-link')
                .startswith('https://download.mozilla.org'))
        # The fourth link is mobile and should not have the attr
        ok_(pq(links[3]).attr('data-direct-link') is None)
Exemplo n.º 19
0
class RedirectToTestcase(TestCase):
    rf = RequestFactory()

    def test_redirect_to(self):
        resp = redirect_to(self.rf.get('/'), url='home', permanent=False)
        assert isinstance(resp, HttpResponseRedirect)
        eq_(reverse('home'), resp['location'])

    def test_redirect_permanent(self):
        resp = redirect_to(self.rf.get('/'), url='home')
        assert isinstance(resp, HttpResponsePermanentRedirect)
        eq_(reverse('home'), resp['location'])

    def test_redirect_kwargs(self):
        resp = redirect_to(self.rf.get('/'),
                           url='users.confirm_email',
                           activation_key='1234')
        eq_(reverse('users.confirm_email', args=['1234']), resp['location'])
Exemplo n.º 20
0
    def test_basic_with_lang(self):
        # Check that when ?lang is passed, we get the right language and we get
        # empty strings instead of None if the strings don't exist.
        self.request = RequestFactory().get('/?lang=es')
        self.request.REGION = mkt.regions.US
        res = self.serialize()
        expected = {
            'id': 337141,
            'description': u'XSS attempt &lt;script&gt;alert(1)&lt;/script&gt;',
            'homepage': None,
            'name': u'Algo Algo Steamcube!',
            'support_email': None,
            'support_url': None,
        }

        for k, v in expected.items():
            eq_(res[k], v,
                u'Expected value "%s" for field "%s", got "%s"' %
                (v, k, res[k]))
Exemplo n.º 21
0
def req_factory_factory(url='', user=None, post=False, data=None, **kwargs):
    """Creates a request factory, logged in with the user."""
    req = RequestFactory()
    if post:
        req = req.post(url, data or {})
    else:
        req = req.get(url, data or {})
    if user:
        req.user = UserProfile.objects.get(id=user.id)
        req.groups = user.groups.all()
    else:
        req.user = AnonymousUser()
    req.check_ownership = partial(check_ownership, req)
    req.REGION = kwargs.pop('region', mkt.regions.REGIONS_CHOICES[0][1])
    req.API_VERSION = 2

    for key in kwargs:
        setattr(req, key, kwargs[key])
    return req
Exemplo n.º 22
0
class PlusToSpaceTestCase(TestCase):

    rf = RequestFactory()
    ptsm = PlusToSpaceMiddleware()

    def test_plus_to_space(self):
        """Pluses should be converted to %20."""
        request = self.rf.get('/url+with+plus')
        response = self.ptsm.process_request(request)
        assert isinstance(response, HttpResponsePermanentRedirect)
        eq_('/url%20with%20plus', response['location'])

    def test_query_string(self):
        """Query strings should be maintained."""
        request = self.rf.get('/pa+th', {'a': 'b'})
        response = self.ptsm.process_request(request)
        eq_('/pa%20th?a=b', response['location'])

    def test_query_string_unaffected(self):
        """Pluses in query strings are not affected."""
        request = self.rf.get('/pa+th?var=a+b')
        response = self.ptsm.process_request(request)
        eq_('/pa%20th?var=a+b', response['location'])

    def test_pass_through(self):
        """URLs without a + should be left alone."""
        request = self.rf.get('/path')
        assert not self.ptsm.process_request(request)

    def test_with_locale(self):
        """URLs with a locale should keep it."""
        request = self.rf.get('/pa+th', {'a': 'b'})
        request.LANGUAGE_CODE = 'ru'
        response = self.ptsm.process_request(request)
        eq_('/ru/pa%20th?a=b', response['location'])

    def test_smart_query_string(self):
        """The request QUERY_STRING might not be unicode."""
        request = self.rf.get(u'/pa+th')
        request.LANGUAGE_CODE = 'ja'
        request.META['QUERY_STRING'] = 's=\xe3\x82\xa2'
        response = self.ptsm.process_request(request)
        eq_('/ja/pa%20th?s=%E3%82%A2', response['location'])
Exemplo n.º 23
0
 def setUp(self):
     self.create_switch('iarc')
     self.profile = UserProfile.objects.get(pk=2519)
     self.request = RequestFactory().get('/')
     self.request.REGION = mkt.regions.US
     self.request.amo_user = self.profile
     self.app = Webapp.objects.get(pk=337141)
     self.version = self.app.current_version
     self.category = Category.objects.create(name='cattest', slug='testcat',
                                             type=amo.ADDON_WEBAPP)
     AddonCategory.objects.create(addon=self.app, category=self.category)
     self.preview = Preview.objects.create(filetype='image/png',
                                           addon=self.app, position=0)
     self.app.description = {
         'en-US': u'XSS attempt <script>alert(1)</script>',
         'fr': u'Déscriptîon in frènch'
     }
     self.app.save()
     self.refresh('webapp')
Exemplo n.º 24
0
    def test_button_force_direct(self):
        """
        If the force_direct parameter is True, all download links must be
        directly to https://download.mozilla.org.
        """
        rf = RequestFactory()
        get_request = rf.get('/fake')
        get_request.locale = 'fr'
        doc = pq(render("{{ download_button('button', force_direct=true) }}",
                        {'request': get_request}))

        # Check that the first 3 links are direct.
        links = doc('.download-list a')
        for link in links[:3]:
            link = pq(link)
            ok_(link.attr('href')
                .startswith('https://download.mozilla.org'))
            # direct links should not have the data attr.
            ok_(link.attr('data-direct-link') is None)
Exemplo n.º 25
0
    def test_version_sidebar(self):
        request = RequestFactory()
        request.GET = {}
        request.APP = amo.FIREFOX

        request.get(reverse('search.search'))
        facets = {
            u'platforms': [{
                u'count': 58,
                u'term': 1
            }],
            u'appversions': [{
                u'count': 58,
                u'term': 5000000200100
            }],
            u'categories': [{
                u'count': 55,
                u'term': 1
            }],
            u'tags': [],
        }
        versions = version_sidebar(request, {}, facets)
        assert versions[0].selected

        versions = version_sidebar(request, {'appver': '5.0'}, facets)
        assert versions[1].selected

        # We're not storing the version in the session anymore: no memories.
        versions = version_sidebar(request, {}, facets)
        assert versions[0].selected

        # We read the appver from the cleaned form data.
        request.GET['appver'] = '123.4'
        # No form data, fallback to default (first entry).
        versions = version_sidebar(request, {}, facets)
        assert versions[0].selected
        # Form data has the proper version, use it.
        versions = version_sidebar(request, {'appver': '5.0'}, facets)
        assert versions[1].selected
        # Form data has the proper version, which is new: add it.
        versions = version_sidebar(request, {'appver': '123.4'}, facets)
        assert versions[1].selected
        eq_(len(versions), 3)
Exemplo n.º 26
0
    def check_appver_filters(self, appver, expected):
        request = RequestFactory()
        request.GET = {}
        request.APP = amo.FIREFOX

        facets = {
            u'platforms': [{u'count': 58, u'term': 1}],
            u'appversions': [{u'count': 58, u'term': 5000000200100}],
            u'categories': [{u'count': 55, u'term': 1}],
            u'tags': []
        }

        versions = version_sidebar(request,
                                   {'appver': floor_version(appver)}, facets)

        all_ = versions.pop(0)
        eq_(all_.text, 'Any %s' % unicode(request.APP.pretty))
        eq_(all_.selected, not expected)

        return [v.__dict__ for v in versions]
Exemplo n.º 27
0
 def request(self,
             verb,
             qs=None,
             content_type='application/json',
             encoder=json.dumps,
             **data):
     if not qs:
         qs = ''
     request = getattr(RequestFactory(), verb.lower())
     request = request('/?' + qs,
                       content_type=content_type,
                       data=encoder(data) if data else '')
     request.user = self.user
     ACLMiddleware().process_request(request)
     return Request(
         request,
         parsers=[
             parser_cls()
             for parser_cls in api_settings.DEFAULT_PARSER_CLASSES
         ])
Exemplo n.º 28
0
    def test_with_request_path_override_existing_params(self):
        self.url = '/api/whatever/?limit=0&offset=xxx&extra&superfluous=yes'
        self.request = RequestFactory().get(self.url)

        data = ['a', 'b', 'c', 'd', 'e', 'f']
        per_page = 2
        page = Paginator(data, per_page).page(2)
        serialized = self.get_serialized_data(page)
        eq_(serialized['offset'], 2)
        eq_(serialized['total_count'], len(data))
        eq_(serialized['limit'], per_page)

        prev = urlparse(serialized['previous'])
        eq_(prev.path, '/api/whatever/')
        eq_(QueryDict(prev.query),
            QueryDict('limit=2&offset=0&extra=&superfluous=yes'))

        next = urlparse(serialized['next'])
        eq_(next.path, '/api/whatever/')
        eq_(QueryDict(next.query),
            QueryDict('limit=2&offset=4&extra=&superfluous=yes'))
Exemplo n.º 29
0
def dump_app(id, **kw):
    # Because @robhudson told me to.
    from mkt.api.resources import AppResource
    # Note: not using storage because all these operations should be local.
    target_dir = os.path.join(settings.DUMPED_APPS_PATH, 'apps',
                              str(id / 1000))
    target_file = os.path.join(target_dir, str(id) + '.json')

    try:
        obj = Webapp.objects.get(pk=id)
    except Webapp.DoesNotExist:
        task_log.info(u'Webapp does not exist: {0}'.format(id))
        return

    req = RequestFactory().get('/')
    req.REGION = WORLDWIDE

    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    task_log.info('Dumping app {0} to {1}'.format(id, target_file))
    res = AppResource().dehydrate_objects([obj], request=req)
    json.dump(res[0], open(target_file, 'w'), cls=JSONEncoder)
    return target_file
Exemplo n.º 30
0
 def setUp(self):
     self.create_switch('iarc')
     self.app = amo.tests.app_factory(version_kw={'version': '1.8'})
     self.profile = UserProfile.objects.get(pk=2519)
     self.request = RequestFactory().get('/')