예제 #1
0
    def test_signed_app_response(self, fake_req):
        app_payment = self.payload()

        # Ensure that the JWT sent to the app for payment notification
        # includes the same payment data that the app originally sent.
        def is_valid(payload):
            data = jwt.decode(payload, self.inapp_config.get_private_key(),
                              verify=True)
            eq_(data['iss'], settings.INAPP_MARKET_ID)
            eq_(data['aud'], self.inapp_config.public_key)
            eq_(data['typ'], 'mozilla/payments/pay/postback/v1')
            eq_(data['request']['price'], app_payment['request']['price'])
            eq_(data['request']['currency'],
                app_payment['request']['currency'])
            eq_(data['request']['name'], app_payment['request']['name'])
            eq_(data['request']['description'],
                app_payment['request']['description'])
            eq_(data['request']['productdata'],
                app_payment['request']['productdata'])
            eq_(data['response']['transactionID'], self.contrib.pk)
            assert data['iat'] <= calendar.timegm(time.gmtime()) + 60, (
                                'Expected iat to be about now')
            assert data['exp'] > calendar.timegm(time.gmtime()) + 3500, (
                                'Expected exp to be about an hour from now')
            return True

        (fake_req.expects('post').with_args(arg.any(),
                                            arg.passes_test(is_valid),
                                            timeout=arg.any())
                                 .has_attr(text='<not a valid response>'))
        self.notify()
예제 #2
0
파일: test_views.py 프로젝트: gedex/zamboni
    def test_pay_start_error(self, fetch_prod_im, cef):
        self.inapp_config.addon.support_url = 'http://friendlyapp.org/support'
        self.inapp_config.addon.support_email = '*****@*****.**'
        self.inapp_config.addon.save()

        def inspect_msg(msg):
            assert 'RequestVerificationError' in msg, (
                                    'CEF log should have exception message')
            return True

        cef.expects_call().with_args(arg.any(), 'unknown',
                                     'inapp_pay_error',
                                     arg.passes_test(inspect_msg),
                                     severity=arg.any())

        rp = self.start(req=self.request(app_secret='invalid'))
        eq_(rp.status_code, 200)
        doc = pq(rp.content)
        eq_(doc('h3').text(), 'Payment Error')
        self.assertContains(rp, 'mailto:[email protected]')
        self.assertContains(rp, 'friendlyapp.org/support')

        log = InappPayLog.objects.get()
        eq_(log.action, InappPayLog._actions['EXCEPTION'])
        eq_(log.app_public_key, self.inapp_config.public_key)
        eq_(log.exception, InappPayLog._exceptions['RequestVerificationError'])
        assert log.session_key, 'Unexpected session_key: %r' % log.session_key
        assert not fetch_prod_im.delay.called, (
                    'product image not fetched on error')
예제 #3
0
    def test_prepare_pay(self, api_post):

        def good_data(da):
            da = json.loads(da)
            # TODO(Kumar) fix this when we have default currencies (bug 777747)
            eq_(da['currency'], 'USD')
            eq_(da['amount'], str(self.price.price))
            eq_(da['app_name'], unicode(self.addon.name))
            eq_(da['app_description'], unicode(self.addon.description))
            eq_(da['postback_url'],
                absolutify(reverse('bluevia.postback')))
            eq_(da['chargeback_url'],
                absolutify(reverse('bluevia.chargeback')))
            pd = urlparse.parse_qs(da['product_data'])
            assert 'contrib_uuid' in pd, 'Unexpected: %s' % pd
            eq_(pd['addon_id'][0], str(self.addon.pk))
            return True

        # Sample of BlueVia JWT but not complete.
        bluevia_jwt = {'typ': 'tu.com/payments/inapp/v1'}

        (api_post.expects_call()
                 .with_args(arg.any(), data=arg.passes_test(good_data),
                            timeout=arg.any(), headers=arg.any())
                 .returns(Mock(text=json.dumps(bluevia_jwt),
                               status_code=200)))
        data = self.post(self.prepare_pay)
        cn = Contribution.objects.get(uuid=data['contrib_uuid'])
        eq_(cn.type, amo.CONTRIB_PENDING)
        eq_(cn.user, self.user)
        eq_(cn.price_tier, self.price)
        eq_(data['bluevia_jwt'], bluevia_jwt)
예제 #4
0
파일: test_tasks.py 프로젝트: Witia1/webpay
    def test_signed_app_response(self, fake_req, slumber):
        app_payment = self.payload()
        self.set_secret_mock(slumber, 'f')
        slumber.generic.product.get_object_or_404.return_value = {
            'secret': 'f'}

        # Ensure that the JWT sent to the app for payment notification
        # includes the same payment data that the app originally sent.
        def is_valid(payload):
            data = jwt.decode(payload['notice'], 'f',  # secret key
                              verify=True)
            eq_(data['iss'], settings.NOTIFY_ISSUER)
            eq_(data['typ'], TYP_POSTBACK)
            eq_(data['request']['pricePoint'], 1)
            eq_(data['request']['name'], app_payment['request']['name'])
            eq_(data['request']['description'],
                app_payment['request']['description'])
            eq_(data['request']['productdata'],
                app_payment['request']['productdata'])
            eq_(data['request']['postbackURL'], 'http://foo.url/post')
            eq_(data['request']['chargebackURL'], 'http://foo.url/charge')
            eq_(data['response']['transactionID'], 'some:uuid')
            assert data['iat'] <= gmtime() + 60, (
                'Expected iat to be about now')
            assert data['exp'] > gmtime() + 3500, (
                'Expected exp to be about an hour from now')
            return True

        (fake_req.expects('post').with_args(arg.any(),
                                            arg.passes_test(is_valid),
                                            timeout=arg.any())
                                 .returns_fake()
                                 .has_attr(text='some:uuid')
                                 .provides('raise_for_status'))
        self.notify()
예제 #5
0
파일: test_tasks.py 프로젝트: potch/webpay
    def test_signed_app_response(self, fake_req):
        app_payment = self.payload()

        # Ensure that the JWT sent to the app for payment notification
        # includes the same payment data that the app originally sent.
        def is_valid(payload):
            data = jwt.decode(payload, self.iss.get_private_key(), verify=True)
            eq_(data["iss"], settings.NOTIFY_ISSUER)
            eq_(data["aud"], self.iss.issuer_key)
            eq_(data["typ"], "mozilla/payments/pay/postback/v1")
            eq_(data["request"]["pricePoint"], 1)
            eq_(data["request"]["name"], app_payment["request"]["name"])
            eq_(data["request"]["description"], app_payment["request"]["description"])
            eq_(data["request"]["productdata"], app_payment["request"]["productdata"])
            eq_(data["response"]["transactionID"], "some:uuid")
            assert data["iat"] <= calendar.timegm(time.gmtime()) + 60, "Expected iat to be about now"
            assert data["exp"] > calendar.timegm(time.gmtime()) + 3500, "Expected exp to be about an hour from now"
            return True

        (
            fake_req.expects("post")
            .with_args(arg.any(), arg.passes_test(is_valid), timeout=arg.any())
            .returns_fake()
            .has_attr(text="<not a valid response>")
            .provides("raise_for_status")
        )
        self.notify()
예제 #6
0
파일: test_tasks.py 프로젝트: potch/webpay
 def test_configurable_http(self, fake_req):
     self.iss_update(is_https=False)
     url = self.url(self.postback, protocol="http")
     (fake_req.expects("post").with_args(url, arg.any(), timeout=arg.any()).returns_fake().is_a_stub())
     self.notify()
     notice = Notice.objects.get()
     eq_(notice.last_error, "")
예제 #7
0
 def test_configurable_http(self, urlopen):
     self.inapp_config.update(is_https=False)
     url = self.url(self.postback, protocol="http")
     (urlopen.expects_call().with_args(url, arg.any(), timeout=arg.any()).returns_fake().is_a_stub())
     self.notify()
     notice = InappPayNotice.objects.get()
     eq_(notice.last_error, "")
예제 #8
0
    def test_signed_app_response(self, urlopen):
        app_payment = self.payload()

        # Ensure that the JWT sent to the app for payment notification
        # includes the same payment data that the app originally sent.
        def is_valid(payload):
            data = jwt.decode(payload, self.inapp_config.private_key, verify=True)
            eq_(data["iss"], settings.INAPP_MARKET_ID)
            eq_(data["aud"], self.inapp_config.public_key)
            eq_(data["typ"], "mozilla/payments/pay/postback/v1")
            eq_(data["request"]["price"], app_payment["request"]["price"])
            eq_(data["request"]["currency"], app_payment["request"]["currency"])
            eq_(data["request"]["name"], app_payment["request"]["name"])
            eq_(data["request"]["description"], app_payment["request"]["description"])
            eq_(data["request"]["productdata"], app_payment["request"]["productdata"])
            eq_(data["response"]["transactionID"], self.contrib.pk)
            assert data["iat"] <= calendar.timegm(time.gmtime()) + 60, "Expected iat to be about now"
            assert data["exp"] > calendar.timegm(time.gmtime()) + 3500, "Expected exp to be about an hour from now"
            return True

        (
            urlopen.expects_call()
            .with_args(arg.any(), arg.passes_test(is_valid), timeout=arg.any())
            .returns_fake()
            .expects("read")
            .returns("<not a valid response>")
            .expects("close")
        )
        self.notify()
예제 #9
0
    def test_pay_start_error(self, fetch_prod_im, cef):
        self.inapp_config.addon.support_url = 'http://friendlyapp.org/support'
        self.inapp_config.addon.support_email = '*****@*****.**'
        self.inapp_config.addon.save()

        def inspect_msg(msg):
            assert 'RequestVerificationError' in msg, (
                'CEF log should have exception message')
            return True

        cef.expects_call().with_args(arg.any(),
                                     'unknown',
                                     'inapp_pay_error',
                                     arg.passes_test(inspect_msg),
                                     severity=arg.any())

        rp = self.start(req=self.request(app_secret='invalid'))
        eq_(rp.status_code, 200)
        doc = pq(rp.content)
        eq_(doc('h3').text(), 'Payment Error')
        self.assertContains(rp, 'mailto:[email protected]')
        self.assertContains(rp, 'friendlyapp.org/support')

        log = InappPayLog.objects.get()
        eq_(log.action, InappPayLog._actions['EXCEPTION'])
        eq_(log.app_public_key, self.inapp_config.public_key)
        eq_(log.exception, InappPayLog._exceptions['RequestVerificationError'])
        assert log.session_key, 'Unexpected session_key: %r' % log.session_key
        assert not fetch_prod_im.delay.called, (
            'product image not fetched on error')
예제 #10
0
 def test_invalid_contrib_uuid(self, cef):
     cef.expects_call().with_args(arg.any(),
                                  self.inapp_config.addon,
                                  'inapp_pay_status',
                                  arg.any(),
                                  severity=arg.any())
     res = self.client.get(self.complete_url, {'uuid': 'invalid-uuid'})
     self.assertContains(res, 'Payment Error')
예제 #11
0
    def test_adds_is_test_to_api_class_api_if_in_testing_mode(self):
        api_class = fudge.Fake().expects_call().with_args(arg.any(), arg.any(),
                delimiter=arg.any(), is_test=True)

        backend = backends.AuthorizeNetBackend(testing=True)
        with fudge.patched_context(backend, "api_class", api_class):
            backend.get_api()
        fudge.verify()
예제 #12
0
 def test_configurable_http(self, fake_req):
     self.inapp_config.update(is_https=False)
     url = self.url(self.postback, protocol='http')
     (fake_req.expects('post').with_args(
         url, arg.any(), timeout=arg.any()).returns_fake().is_a_stub())
     self.notify()
     notice = InappPayNotice.objects.get()
     eq_(notice.last_error, '')
예제 #13
0
    def test_is_test_is_false_for_api_class_api_by_default(self):
        api_class = fudge.Fake().expects_call().with_args(arg.any(), arg.any(),
                delimiter=arg.any(), is_test=False)

        backend = backends.AuthorizeNetBackend()
        with fudge.patched_context(backend, "api_class", api_class):
            backend.get_api()
        fudge.verify()
예제 #14
0
    def test_adds_is_test_to_recurring_api_class_api_if_in_testing_mode(self):
        recurring_api_class = fudge.Fake().expects_call().with_args(
            arg.any(), arg.any(), is_test=True)

        backend = backends.AuthorizeNetBackend(testing=True)
        with fudge.patched_context(backend, "recurring_api_class",
                                   recurring_api_class):
            backend.get_recurring_api()
        fudge.verify()
예제 #15
0
    def test_is_test_is_false_for_recurring_api_class_api_by_default(self):
        recurring_api_class = fudge.Fake().expects_call().with_args(
            arg.any(), arg.any(), is_test=False)

        backend = backends.AuthorizeNetBackend()
        with fudge.patched_context(backend, "recurring_api_class",
                                   recurring_api_class):
            backend.get_recurring_api()
        fudge.verify()
예제 #16
0
파일: test_tasks.py 프로젝트: lonnen/webpay
 def test_force_https(self, fake_req):
     self.iss_update(is_https=False)
     url = self.url(self.postback, protocol='https')
     (fake_req.expects('post').with_args(url, arg.any(), timeout=arg.any())
                              .returns_fake()
                              .is_a_stub())
     self.notify()
     notice = Notice.objects.get()
     eq_(notice.last_error, '')
예제 #17
0
파일: test_tasks.py 프로젝트: gedex/zamboni
 def test_configurable_http(self, fake_req):
     self.inapp_config.update(is_https=False)
     url = self.url(self.postback, protocol='http')
     (fake_req.expects('post').with_args(url, arg.any(), timeout=arg.any())
                              .returns_fake()
                              .is_a_stub())
     self.notify()
     notice = InappPayNotice.objects.get()
     eq_(notice.last_error, '')
예제 #18
0
    def test_mail_contains_text_for_claiming_via_url(self, mock_send_mail):
        user = mommy.make(settings.AUTH_USER_MODEL)
        self.bid1.ask_match_sent = timezone.now()
        self.bid1.save()

        mock_send_mail.expects_call().with_args(arg.any(),
                                                arg.contains(self.bid1.url),
                                                arg.any(), ['*****@*****.**'])

        mommy.make(Bid, offer=100, user=user, ask=1000, url=self.url)
 def test_post_key_to_api_uses_requests_json(self, request):
     pa = mommy.make(PushApplication, vapid_key_status='valid')
     request.expects_call().with_args(
         'post',
         arg.any(),
         json={'public-key': pa.vapid_key},
         timeout=arg.any()
     ).returns(
         MESSAGES_API_POST_RESPONSE
     )
     pa.post_key_to_api()
예제 #20
0
    def test_create(self, fetch):
        recent = fetch.expects_call().with_args(self.recent_url,
                                                deadline=arg.any())
        recent.returns_fake().has_attr(status_code=200)
        now = recent.next_call().with_args(self.now_url,
                                           deadline=arg.any())
        now.returns_fake().has_attr(status_code=200)

        resp = self.client.post(reverse('playlists.send_track_to_live_site'), {
            'id': self.track.key()
        })
예제 #21
0
    def test_create(self, fetch):
        recent = fetch.expects_call().with_args(self.recent_url,
                                                deadline=arg.any())
        recent.returns_fake().has_attr(status_code=200)
        now = recent.next_call().with_args(self.now_url,
                                           deadline=arg.any())
        now.returns_fake().has_attr(status_code=200)

        resp = self.client.post(reverse('playlists.send_track_to_live_site'), {
            'id': self.track.key()
        })
    def test_delete_key_from_messages_api_204(self, request):
        pa = mommy.make(PushApplication, vapid_key_status='recording')
        request.expects_call().with_args(
            'delete',
            arg.any(),
            json=arg.any(),
            timeout=arg.any()
        ).returns(
            fudge.Fake().has_attr(status_code=204)
        )

        delete_key_from_messages_api(PushApplication, pa)
예제 #23
0
 def test_post_key_to_api_uses_requests_json(self, request):
     pa = mommy.make(PushApplication, vapid_key_status='valid')
     request.expects_call().with_args(
         'post',
         arg.any(),
         json={
             'public-key': pa.vapid_key
         },
         timeout=arg.any()).returns(
             fudge.Fake().has_attr(status_code=200).expects('json').returns(
                 self.fake_post_response_json))
     pa.post_key_to_api()
예제 #24
0
 def test_post_key_to_api_uses_requests_json(self, request):
     pa = mommy.make(PushApplication, vapid_key_status='valid')
     request.expects_call().with_args(
         'post',
         arg.any(),
         json={'public-key': pa.vapid_key},
         timeout=arg.any()
     ).returns(
         fudge.Fake().has_attr(status_code=200).expects('json').returns(
             self.fake_post_response_json
         )
     )
     pa.post_key_to_api()
    def test_delete_key_from_messages_api_404(self, request):
        # TODO: Decide what to do with 404 responses to DELETE
        # https://github.com/mozilla-services/push-dev-dashboard/issues/205#issuecomment-217182142
        pa = mommy.make(PushApplication, vapid_key_status='recording')
        request.expects_call().with_args(
            'delete',
            arg.any(),
            json=arg.any(),
            timeout=arg.any()
        ).returns(
            fudge.Fake().has_attr(status_code=404)
        )

        with self.assertRaises(MessagesAPIError):
            delete_key_from_messages_api(PushApplication, pa)
예제 #26
0
    def test_only_send_mail_to_unsent_matching_askers(self, mock_send_mail):
        user = mommy.make(settings.AUTH_USER_MODEL)
        self.bid1.ask_match_sent = timezone.now()
        self.bid1.save()
        subject = "[codesy] There's $100 waiting for you!"

        mock_send_mail.expects_call().with_args(subject, arg.any(), arg.any(),
                                                ['*****@*****.**'])

        offer_bid = mommy.make(Bid,
                               offer=100,
                               user=user,
                               ask=1000,
                               url=self.url)
        offer_bid.save()
예제 #27
0
    def test_send_mail_to_matching_askers(self, mock_send_mail):
        user = mommy.make(settings.AUTH_USER_MODEL)
        bid1_subject = "[codesy] There's $50 waiting for you!"
        bid2_subject = "[codesy] There's $100 waiting for you!"
        mock_send_mail.expects_call().with_args(bid1_subject, arg.any(),
                                                arg.any(), ['*****@*****.**'])
        mock_send_mail.next_call().with_args(bid2_subject, arg.any(),
                                             arg.any(), ['*****@*****.**'])

        offer_bid = mommy.make(Bid,
                               offer=100,
                               user=user,
                               ask=1000,
                               url=self.url)
        offer_bid.save()
예제 #28
0
    def test_mail_contains_text_for_claiming_via_url(self, mock_send_mail):
        user = mommy.make(settings.AUTH_USER_MODEL)
        self.bid1.ask_match_sent = timezone.now()
        self.bid1.save()

        mock_send_mail.expects_call().with_args(
            arg.any(),
            arg.contains(self.bid1.url),
            arg.any(),
            ['*****@*****.**']
        )

        mommy.make(
            Bid, offer=100, user=user, ask=1000, url=self.url
        )
예제 #29
0
 def test_with_kwargs_with_object_that_is_never_equal_to_anything(self):
     class NeverEqual(object):
         def __eq__(self, other):
             return False
     obj = NeverEqual()
     self.fake.expects('save').with_args(foo=arg.any())
     self.fake.save(foo=obj) # this should pass but was failing prior to issue 9
예제 #30
0
def test_context_manager(fake):
    fudge.patch_object(statsd.StatsClient, 'timing', mock_statsd_method)
    k = kruxstatsd.StatsClient('js', env='prod')
    fake.expects_call().with_args('prod.js.mytimer.%s' % (hostname, ),
                                  arg.any(), 1)
    with k.timer('mytimer'):
        assert True
예제 #31
0
파일: test_tasks.py 프로젝트: ferjm/webpay
    def test_postback(self, slumber, fake_req):
        self.set_secret_mock(slumber, 'f')
        payload = self.payload(typ=TYP_POSTBACK,
                               extra_req={'simulate': {
                                   'result': 'postback'
                               }})
        url = payload['request']['postbackURL']

        def req_ok(req):
            dd = jwt.decode(req['notice'], verify=False)
            eq_(dd['request'], payload['request'])
            eq_(dd['typ'], payload['typ'])
            jwt.decode(req['notice'], 'f', verify=True)
            return True

        (fake_req.expects('post').with_args(
            url, arg.passes_test(req_ok),
            timeout=arg.any()).returns_fake().has_attr(
                text=self.trans_uuid).expects('raise_for_status'))
        self.notify(payload)
        notice = Notice.objects.get()
        assert notice.transaction_uuid, notice
        eq_(notice.success, True)
        eq_(notice.url, url)
        eq_(notice.simulated, SIMULATED_POSTBACK)
예제 #32
0
    def test_only_send_mail_to_unsent_matching_askers(self, mock_send_mail):
        user = mommy.make(settings.AUTH_USER_MODEL)
        self.bid1.ask_match_sent = datetime.now()
        self.bid1.save()

        mock_send_mail.expects_call().with_args(
            self._add_url('[codesy] Your ask for 100 for {url} has been met'),
            arg.any(),
            arg.any(),
            ['*****@*****.**']
        )

        offer_bid = mommy.prepare(
            Bid, offer=100, user=user, ask=1000, url=self.url
        )
        offer_bid.save()
예제 #33
0
    def test_chargeback(self, slumber, fake_req):
        self.set_secret_mock(slumber, 'f')
        req = {'simulate': {'result': 'chargeback'}}
        payload = self.payload(typ=TYP_CHARGEBACK,
                               extra_req=req)
        url = payload['request']['chargebackURL']

        def req_ok(req):
            dd = jwt.decode(req['notice'], verify=False)
            eq_(dd['request'], payload['request'])
            eq_(dd['typ'], payload['typ'])
            jwt.decode(req['notice'], 'f', verify=True)
            return True

        (fake_req.expects('post').with_args(url, arg.passes_test(req_ok),
                                            timeout=arg.any())
                                 .returns_fake()
                                 .has_attr(text=self.trans_uuid)
                                 .expects('raise_for_status'))
        self.notify(payload)
        notice = Notice.objects.get()
        assert notice.transaction_uuid, notice
        eq_(notice.success, True)
        eq_(notice.url, url)
        eq_(notice.simulated, SIMULATED_CHARGEBACK)
예제 #34
0
 def test_with_kwargs_with_object_that_is_never_equal_to_anything(self):
     class NeverEqual(object):
         def __eq__(self, other):
             return False
     obj = NeverEqual()
     self.fake.expects('save').with_args(foo=arg.any())
     self.fake.save(foo=obj) # this should pass but was failing prior to issue 9
예제 #35
0
    def test_reset(self, cef):
        cfg = self.config(public_key='old-key',
                          private_key='old-secret')

        def inspect_msg(msg):
            assert 'old-key' in msg, 'CEF should log old key'
            return True

        cef.expects_call().with_args(arg.any(),
                                     cfg.addon,
                                     'inapp_reset',
                                     arg.passes_test(inspect_msg),
                                     severity=6)
        res = self.client.post(self.get_url(cfg.pk))
        self.assertRedirects(res, self.webapp.get_dev_url('in_app_config'))
        old_cfg = InappConfig.objects.get(pk=cfg.pk)
        eq_(old_cfg.status, amo.INAPP_STATUS_REVOKED)
        inapp = InappConfig.objects.get(addon=self.webapp,
                                        status=amo.INAPP_STATUS_ACTIVE)
        eq_(inapp.chargeback_url, cfg.chargeback_url)
        eq_(inapp.postback_url, cfg.postback_url)
        assert inapp.public_key != cfg.public_key, (
                                    'Unexpected: %s' % inapp.public_key)
        pk = inapp.get_private_key()
        assert pk != cfg.get_private_key, ('Unexpected: %s' % pk)
예제 #36
0
def test_context_manager(fake):
    fudge.patch_object(statsd.StatsClient, 'timing', mock_statsd_method)
    k = kruxstatsd.StatsClient('js', env='prod')
    fake.expects_call().with_args(
        'prod.js.mytimer.%s' % (hostname,), arg.any(), 1)
    with k.timer('mytimer'):
        assert True
예제 #37
0
 def test_postback(self, fake_req):
     (fake_req.expects('post').with_args(self.purchase_url,
                                         self.signed_jwt,
                                         timeout=arg.any())
                              .returns_fake()
                              .has_attr(text=str(self.contrib.pk))
                              .expects('raise_for_status'))
     self.purchase_notify()
예제 #38
0
    def test_only_send_mail_to_unsent_matching_askers(self, mock_send_mail):
        user = mommy.make(settings.AUTH_USER_MODEL)
        self.bid1.ask_match_sent = timezone.now()
        self.bid1.save()
        subject = "[codesy] There's $100 waiting for you!"

        mock_send_mail.expects_call().with_args(
            subject,
            arg.any(),
            arg.any(),
            ['*****@*****.**']
        )

        offer_bid = mommy.make(
            Bid, offer=100, user=user, ask=1000, url=self.url
        )
        offer_bid.save()
예제 #39
0
 def test_absolute_url(self, fake_req):
     url = 'http://mycdn-somewhere.com/media/my.jpg'
     (fake_req.expects('get')
              .with_args(url, timeout=arg.any())
              .returns_fake()
              .has_attr(raw=self.open_img())
              .expects('raise_for_status'))
     self.fetch(url=url)
예제 #40
0
 def test_postback(self, fake_req):
     (fake_req.expects('post').with_args(self.purchase_url,
                                         self.signed_jwt,
                                         timeout=arg.any())
                              .returns_fake()
                              .has_attr(text=str(self.contrib.pk))
                              .expects('raise_for_status'))
     self.purchase_notify()
예제 #41
0
 def test_paykey_pre_approval_empty(self, _call, check_purchase):
     check_purchase.return_value = 'COMPLETED'
     PreApprovalUser.objects.create(user=self.user, paypal_key='')
     r = lambda s: 'receiverList.receiver(0).email' in s
     (_call.expects_call()
           .with_matching_args(arg.any(), arg.passes_test(r))
           .returns({'payKey': 'some-pay-key',
                     'paymentExecStatus': 'COMPLETED'}))
     self.client.post_ajax(self.purchase_url)
예제 #42
0
    def test_updates_config(self):
        # first assert signatures of the functions we are going to mock did not change.
        assert_spec(self.sqlite_db.set_config_value, ['self', 'group', 'key', 'value'])

        self.sqlite_db.set_config_value = fudge.Fake('set_config_value')\
            .expects_call()\
            .with_args('activity', 'change', arg.any())

        self.sqlite_db._mark_update()
        fudge.verify()
예제 #43
0
 def test_process_mp3(self, store, album_art):
     store.expects_call().with_args(arg.any(), self.session_key)
     album_art.expects('delay')
     tasks.process_file('*****@*****.**', self.sample_path, self.session_key)
     tr = Track.objects.get()
     eq_(tr.email.email, '*****@*****.**')
     eq_(tr.artist, 'Gescom')
     eq_(tr.album, 'Minidisc')
     eq_(tr.track, 'Horse')
     eq_(tr.session.pk, self.session_key)
     eq_(tr.track_num, 53)
예제 #44
0
 def test_fetch_ok(self, fake_req):
     url = '/media/my.jpg'
     (fake_req.expects('get').with_args(
         self.url(url), timeout=arg.any()).returns_fake().has_attr(
             raw=self.open_img()).expects('raise_for_status'))
     self.fetch(url=url)
     prod = InappImage.objects.get()
     assert os.path.exists(prod.path()), 'Image not created'
     eq_(prod.valid, True)
     eq_(prod.processed, True)
     eq_(prod.config.pk, self.inapp_config.pk)
예제 #45
0
 def test_fetch_ok(self, urlopen):
     url = '/media/my.jpg'
     (urlopen.expects_call()
             .with_args(self.url(url), timeout=arg.any())
             .returns(self.open_img()))
     self.fetch(url=url)
     prod = InappImage.objects.get()
     assert os.path.exists(prod.path()), 'Image not created'
     eq_(prod.valid, True)
     eq_(prod.processed, True)
     eq_(prod.config.pk, self.inapp_config.pk)
예제 #46
0
 def test_fetch_ok(self, fake_req):
     url = 'http://site/media/my.jpg'
     ext_size = 512
     size = 64
     (fake_req.expects('get').with_args(
         url,
         timeout=arg.any()).returns_fake().expects('iter_content').returns(
             self.open_img()).expects('raise_for_status'))
     self.fetch(url, ext_size, size)
     prod = ProductIcon.objects.get()
     eq_(prod.ext_size, ext_size)
     eq_(prod.size, size)
     assert public_storage.exists(prod.storage_path()), 'Image not created'
예제 #47
0
    def test_preauth_ok(self, check_purchase, get_paykey, payment_notify):
        payload = self.payload()

        get_paykey.expects_call().returns(['some-pay-key', 'COMPLETED'])
        check_purchase.expects_call().returns('COMPLETED')
        payment_notify.expects('delay').with_args(arg.any())  # pay ID to-be

        req = self.request(payload=json.dumps(payload))
        self.client.post(reverse('inapp_pay.pay'), dict(req=req))

        logs = InappPayLog.objects.all().order_by('created')
        eq_(logs[0].action, InappPayLog._actions['PAY'])
        eq_(logs[1].action, InappPayLog._actions['PAY_COMPLETE'])
예제 #48
0
파일: test_tasks.py 프로젝트: ralic/webpay
    def test_signed_app_response(self, fake_req, slumber):
        app_payment = self.payload()
        self.set_secret_mock(slumber, 'f')
        slumber.generic.product.get_object_or_404.return_value = {
            'secret': 'f'
        }

        # Ensure that the JWT sent to the app for payment notification
        # includes the same payment data that the app originally sent.
        def is_valid(payload):
            data = jwt.decode(
                payload['notice'],
                'f',  # secret key
                verify=True,
                audience=self.payment_issuer)
            eq_(data['iss'], settings.NOTIFY_ISSUER)
            eq_(data['typ'], TYP_POSTBACK)
            eq_(data['request']['pricePoint'], 1)
            eq_(data['request']['name'], app_payment['request']['name'])
            eq_(data['request']['description'],
                app_payment['request']['description'])
            eq_(data['request']['productdata'],
                app_payment['request']['productdata'])
            eq_(data['request']['postbackURL'], 'http://foo.url/post')
            eq_(data['request']['chargebackURL'], 'http://foo.url/charge')
            eq_(data['response']['transactionID'], 'some:uuid')
            assert data['iat'] <= gmtime() + 60, (
                'Expected iat to be about now')
            assert data['exp'] > gmtime() + 3500, (
                'Expected exp to be about an hour from now')
            return True

        (fake_req.expects('post').with_args(
            arg.any(), arg.passes_test(is_valid),
            timeout=arg.any()).returns_fake().has_attr(
                text='some:uuid').provides('raise_for_status'))

        self.notify(payload=app_payment)
예제 #49
0
    def test_api_instantiates_api_class_with_configured_settings(self):
        random_login = "******" % random.randint(100, 200)
        random_key = "some random key %d" % random.randint(100, 200)
        random_return = "some random return %d" % random.randint(100, 200)
        settings = fudge.Fake()
        settings.has_attr(AUTHORIZE={
            "LOGIN": random_login,
            "KEY": random_key,
        })
        api_class = fudge.Fake()

        # Note that delimiter is included here because authorize's code
        # can't even keep track of what deliminter it wants to use!
        (api_class.expects_call().with_args(
            random_login, random_key, delimiter=arg.any(),
            is_test=arg.any()).returns(random_return))
        fudge.clear_calls()

        backend = backends.AuthorizeNetBackend(api_class=api_class,
                                               settings=settings)
        result = backend.get_api()
        self.assertEqual(result, random_return)
        fudge.verify()
예제 #50
0
 def base_setup(self, option_overrides):
     # Create a fake VirtstrapConfig
     config = fudge.Fake()
     config.provides('from_file').returns(config)
     self.config = (config.provides('process_section').with_args(
         'project_name', arg.any()).returns('projdir'))
     # Patch VirtstrapConfig
     self.config_patch = patch_object('virtstrap.project',
                                      'VirtstrapConfig', config)
     base_parser = create_base_parser()
     options = base_parser.parse_args(args=[])
     # Add any overrides
     for name, override in option_overrides.iteritems():
         setattr(options, name, override)
     self._options = options
     self._project = None
예제 #51
0
    def test_run_server_should_pass_xheaders_to_correct_method(
            self, settings, IOLoop, Application):
        settings.has_attr(ROOT_URLS='tests.core.test_server')
        PORT = 1234
        XHEADERS = True

        # Just to prevent the test from hanging
        IOLoop.is_a_stub()

        (Application.is_callable().with_args(
            arg.any(), cookie_secret=None,
            debug=False).returns_fake().expects('listen').with_args(
                PORT, xheaders=XHEADERS))

        torneira_server = server.TorneiraServer(PORT, '/my_media/', XHEADERS)
        torneira_server.run()
예제 #52
0
    def test_fires_donation_complete_on_successful_charge(self):
        donation, form = self.random_donation_and_form
        result = {
            "status": True,
            "random": random.randint(100, 200),
        }
        backend = backends.Backend()
        signal = (fudge.Fake().expects_call().with_args(sender=backend,
                                                        donation=donation,
                                                        signal=arg.any(),
                                                        form=form,
                                                        result=result))
        signals.successful_purchase.connect(signal)
        backend.send_successful_purchase(donation, form, result)

        fudge.verify()
        signals.successful_purchase.disconnect(signal)
예제 #53
0
    def test_password_reset(self, fake_send):
        (fake_send.expects_call().with_args(
            '*****@*****.**', 'forgot', 'Reset Your Draughtcraft Password', {
                'name': 'Ryan',
                'code': arg.any()
            }))

        model.User(first_name=u'Ryan', email=u'*****@*****.**')
        model.commit()

        response = self.post('/forgot/',
                             params={'email': model.User.get(1).email})

        assert model.PasswordResetRequest.query.count() == 1

        assert response.status_int == 302
        assert response.headers['Location'].endswith('/login')
예제 #54
0
파일: test_tasks.py 프로젝트: ralic/webpay
    def test_chargeback_reason(self, slumber, fake_req):
        self.set_secret_mock(slumber, 'f')
        reason = 'something'
        req = {'simulate': {'result': 'chargeback', 'reason': reason}}
        payload = self.payload(typ=TYP_CHARGEBACK, extra_req=req)
        url = payload['request']['chargebackURL']

        def req_ok(req):
            dd = jwt.decode(req['notice'], verify=False)
            eq_(dd['request'], payload['request'])
            eq_(dd['response']['reason'], reason)
            return True

        (fake_req.expects('post').with_args(
            url, arg.passes_test(req_ok),
            timeout=arg.any()).returns_fake().has_attr(
                text=self.trans_uuid).expects('raise_for_status'))
        self.notify(payload)
예제 #55
0
    def test_get_recurring_api_instantiates_with_configured_settings(self):
        random_login = "******" % random.randint(100, 200)
        random_key = "some random key %d" % random.randint(100, 200)
        random_return = "some random return %d" % random.randint(100, 200)
        settings = fudge.Fake().has_attr(AUTHORIZE={
            "LOGIN": random_login,
            "KEY": random_key,
        })

        recurring_api_class = (fudge.Fake().expects_call().with_args(
            random_login, random_key,
            is_test=arg.any()).returns(random_return))
        fudge.clear_calls()

        backend = backends.AuthorizeNetBackend(
            settings=settings, recurring_api_class=recurring_api_class)
        result = backend.get_recurring_api()
        self.assertEqual(result, random_return)
        fudge.verify()