requests.HTTPError

Here are the examples of the python api requests.HTTPError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

152 Examples 7

Example 1

Project: softlayer-python
Source File: transport_tests.py
View license
    @mock.patch('requests.request')
    def test_request_exception(self, request):
        # Test Text Error
        e = requests.HTTPError('error')
        e.response = mock.MagicMock()
        e.response.status_code = 404
        e.response.content = 'Error Code'
        request().raise_for_status.side_effect = e

        req = transports.Request()
        req.service = 'SoftLayer_Service'
        req.method = 'getObject'

        self.assertRaises(SoftLayer.TransportError, self.transport, req)

Example 2

Project: lambda-webhook
Source File: hook.py
View license
def relay_github(event, requests_session):
    verified = verify_signature(event['secret'],
                                event['x_hub_signature'],
                                event['payload'])
    print 'Signature verified: ' + str(verified)

    if verified:
        response = requests_session.post(event['jenkins_url'],
                                         headers={
                                            'Content-Type': 'application/json',
                                            'X-GitHub-Delivery': event['x_github_delivery'],
                                            'X-GitHub-Event': event['x_github_event'],
                                            'X-Hub-Signature':  event['x_hub_signature']
                                         },
                                         data=event['payload'])
        response.raise_for_status()
    else:
        raise HTTPError('400 Client Error: Bad Request')

Example 3

Project: balanced-python
Source File: acceptance_suite.py
View license
    def test_fractional_debit(self):
        buyer_account = self._find_buyer_account()
        bad_amount = (3.14, 100.32)
        for amount in bad_amount:
            with self.assertRaises(requests.HTTPError) as exc:
                buyer_account.debit(
                    amount=amount,
                    appears_on_statement_as='pi',
                )
            the_exception = exc.exception
            self.assertEqual(the_exception.status_code, 400)

Example 4

Project: balanced-python
Source File: acceptance_suite.py
View license
    def test_credit_lower_than_escrow(self):
        mp = balanced.Marketplace.query.one()
        escrow_balance = mp.in_escrow
        credit_amount = escrow_balance + 10000
        merchants = mp.accounts
        merchant = merchants[0]
        with self.assertRaises(requests.HTTPError) as exc:
            merchant.credit(amount=credit_amount)
        the_exception = exc.exception
        self.assertEqual(the_exception.status_code, 409)

Example 5

Project: balanced-python
Source File: acceptance_suite.py
View license
    def test_bad_card(self):
        mp = balanced.Marketplace.query.one()
        card_payload = dict(self.us_card_payload)
        card_payload['card_number'] = cards.AUTH_INVALID_CARD
        bad_card = balanced.Card(**card_payload).save()
        bad_card_uri = bad_card.uri
        buyer = mp.create_buyer(
            email_address='[email protected]',
            card_uri=bad_card_uri,
            meta={'foo': 'bar'},
        )
        with self.assertRaises(requests.HTTPError) as exc:
            buyer.debit(777)
        the_exception = exc.exception
        self.assertEqual(the_exception.status_code, 402)
        self.assertEqual(the_exception.category_code, 'card-declined')

Example 6

Project: balanced-python
Source File: acceptance_suite.py
View license
    def test_redirect_on_merchant_failure(self):

        mp = balanced.Marketplace.query.one()
        merchant = copy.deepcopy(merchants.PERSON_MERCHANT)
        merchant['region'] = 'EX'
        merchant['postal_code'] = '99999'
        with self.assertRaises(requests.HTTPError) as ex:
            merchant = mp.create_merchant('[email protected]',
                                          merchant=merchant)
        the_exception = ex.exception
        self.assertEqual(the_exception.status_code, 300)

Example 7

Project: balanced-python
Source File: test_suite.py
View license
    def test_credit_a_bank_account(self):
        self.create_marketplace()  # NOTE: fresh mp for escrow checks
        card = balanced.Card(**INTERNATIONAL_CARD).save()
        bank_account = balanced.BankAccount(**BANK_ACCOUNT).save()
        debit = card.debit(amount=10000)
        credit = bank_account.credit(amount=1000)
        self.assertTrue(credit.id.startswith('CR'))
        self.assertEqual(credit.amount, 1000)
        with self.assertRaises(requests.HTTPError) as exc:
            bank_account.credit(amount=(debit.amount - credit.amount) + 1)
        self.assertEqual(exc.exception.status_code, 409)
        self.assertEqual(exc.exception.category_code, 'insufficient-funds')

Example 8

Project: balanced-python
Source File: test_suite.py
View license
    def test_credit_card_limit(self):
        funding_card = balanced.Card(**CARD).save()
        debit = funding_card.debit(amount=250005)
        card = balanced.Card(**CREDITABLE_CARD).save()
        with self.assertRaises(requests.HTTPError) as exc:
            credit = card.credit(amount=250001)
        self.assertEqual(exc.exception.status_code, 409)
        self.assertEqual(exc.exception.category_code, 'amount-exceeds-limit')

Example 9

Project: balanced-python
Source File: test_suite.py
View license
    def test_credit_card_require_name(self):
        funding_card = balanced.Card(**CARD).save()
        debit = funding_card.debit(amount=250005)
        card_payload = CREDITABLE_CARD.copy()
        card_payload.pop("name")
        card = balanced.Card(**card_payload).save()
        with self.assertRaises(requests.HTTPError) as exc:
            credit = card.credit(amount=250001)
        self.assertEqual(exc.exception.status_code, 400)
        self.assertEqual(exc.exception.category_code, 'name-required-to-credit')

Example 10

Project: balanced-python
Source File: test_suite.py
View license
    def test_escrow_limit(self):
        self.create_marketplace()  # NOTE: fresh mp for escrow checks
        bank_account = balanced.BankAccount(**BANK_ACCOUNT).save()
        original_balance = 0
        with self.assertRaises(requests.HTTPError) as exc:
            bank_account.credit(amount=original_balance + 1)
        ex = exc.exception
        self.assertEqual(ex.status_code, 409)
        self.assertEqual(ex.category_code, 'insufficient-funds')

Example 11

Project: glass.py
Source File: user.py
View license
    def request(self, *args, **kwargs):
        """
        Return a request with the user session
        """
        r = self.session.request(*args, **kwargs)
        try:
            r.raise_for_status()
        except requests.HTTPError, e:
            if e.response.status_code == 401:
                raise exceptions.RefreshTokenException()
            else:
                raise e
        return r

Example 12

Project: scalarizr
Source File: queryenv.py
View license
    def _process_request_exception(self, exc):
        if isinstance(exc, requests.HTTPError):
            if exc.response.status_code == 403:
                raise InvalidSignatureError(str(exc))
        msg = 'QueryEnv failed: {}'.format(exc)
        if self.autoretry:
            self._logger.warn(msg)
        else:
            raise QueryEnvError(msg)

Example 13

Project: softlayer-python
Source File: transport_tests.py
View license
    @mock.patch('requests.request')
    def test_error(self, request):
        # Test JSON Error
        e = requests.HTTPError('error')
        e.response = mock.MagicMock()
        e.response.status_code = 404
        e.response.text = '''{
            "error": "description",
            "code": "Error Code"
        }'''
        request().raise_for_status.side_effect = e

        req = transports.Request()
        req.service = 'SoftLayer_Service'
        req.method = 'Resource'
        self.assertRaises(SoftLayer.SoftLayerAPIError, self.transport, req)

Example 14

Project: hammock
Source File: command.py
View license
    def _action(self, parsed_args):
        kwargs = {arg: getattr(parsed_args, arg) for arg in self.spec.all_args}
        if self.spec.keywords:
            kwargs.update(getattr(parsed_args, self.spec.keywords, None) or {})
        try:
            return self.func(**kwargs)
        except requests.HTTPError as exc:
            raise hammock.cli.CLIException(self._format_exception(exc))

Example 15

Project: flit
Source File: upload.py
View license
def do_upload(file:Path, metadata:Metadata, repo_name='pypi'):
    """Upload a wheel, registering a new package if necessary.
    """
    repo = get_repository(repo_name)
    try:
        upload_wheel(file, metadata, repo)
    except requests.HTTPError as e:
        if e.response.status_code == 403:
            # 403 can happens if the package is not already on PyPI - try
            # registering it and uploading again.
            log.warning('Uploading forbidden; trying to register and upload again')
            register(metadata, repo)
            upload_wheel(file, metadata, repo)
        else:
            raise

    log.info("Package is at %s/%s", repo['url'], metadata.name)

Example 16

Project: hug
Source File: use.py
View license
    def request(self, method, url, url_params=empty.dict, headers=empty.dict, timeout=None, **params):
        url = "{0}/{1}".format(self.version, url.lstrip('/')) if self.version else url
        kwargs = {'json' if self.json_transport else 'params': params}
        response = self.session.request(method, self.endpoint + url.format(url_params), headers=headers, **kwargs)

        data = BytesIO(response.content)
        content_type, content_params = parse_content_type(response.headers.get('content-type', ''))
        if content_type in input_format:
            data = input_format[content_type](data, **content_params)

        if response.status_code in self.raise_on:
            raise requests.HTTPError('{0} {1} occured for url: {2}'.format(response.status_code, response.reason, url))

        return Response(data, response.status_code, response.headers)

Example 17

Project: hug
Source File: test_use.py
View license
    def test_request(self):
        """Test so ensure the HTTP service can successfully be used to pull data from an external service"""
        response = self.url_service.request('GET', 'search', query='api')
        assert response
        assert response.data

        with pytest.raises(requests.HTTPError):
            response = self.service.request('GET', 'search', query='api')

        with pytest.raises(requests.HTTPError):
            self.url_service.request('GET', 'not_found', query='api')

Example 18

Project: hug
Source File: test_use.py
View license
    def test_request(self):
        """Test to ensure requesting data from a local service works as expected"""
        assert self.service.get('hello_world').data == 'Hi!'
        assert self.service.get('not_there').status_code == 404
        assert self.service.get('validation_error').status_code == 400

        self.service.raise_on = (404, 500)
        with pytest.raises(requests.HTTPError):
            assert self.service.get('not_there')

        with pytest.raises(requests.HTTPError):
            assert self.service.get('exception')

Example 19

Project: pep438
Source File: test_pep438.py
View license
    def test_valid_package_raises_HTTPError(self):
        from requests import HTTPError
        from pep438.core import valid_package
        response = Mock(status_code=500)
        response.raise_for_status = Mock(side_effect=HTTPError())
        config = {'return_value': response}
        with patch('pep438.core.requests.head', **config):
            self.assertRaises(HTTPError, valid_package, 'dummy_package')

Example 20

Project: python-cloudant
Source File: document.py
View license
    def _update_field(self, action, field, value, max_tries, tries=0):
        """
        Private update_field method. Wrapped by Document.update_field.
        Tracks a "tries" var to help limit recursion.
        """
        # Refresh our view of the document.
        self.fetch()

        # Update the field.
        action(self, field, value)

        # Attempt to save, retrying conflicts up to max_tries.
        try:
            self.save()
        except requests.HTTPError as ex:
            if tries < max_tries and ex.response.status_code == 409:
                return self._update_field(
                    action, field, value, max_tries, tries=tries+1)
            raise

Example 21

Project: python-cloudant
Source File: document_test.py
View license
    def test_delete(self):
        with cloudant(self.user, self.passwd, account=self.user) as c:
            db = c.create_database(self.dbname)

            doc1 = db.create_document({"_id": "doc1", "testing": "document 1"})

            doc1.save()
            doc1.fetch()

            doc1.delete()

            self.assertRaises(requests.HTTPError, doc1.fetch)

Example 22

Project: python-cloudant
Source File: document_tests.py
View license
    def test_create_existing_document(self):
        """
        Test creating an already existing document
        """
        doc = Document(self.db, 'julia006')
        doc.create()
        with self.assertRaises(requests.HTTPError) as cm:
            doc.create()
        err = cm.exception
        self.assertEqual(
            err.response.status_code,
            409
        )

Example 23

Project: python-cloudant
Source File: document_tests.py
View license
    def test_fetch_non_existing_document(self):
        """
        Test fetching document content from a non-existing document
        """
        doc = Document(self.db, 'julia006')
        try:
            doc.fetch()
            self.fail('Above statement should raise an Exception')
        except requests.HTTPError as err:
            self.assertEqual(err.response.status_code, 404)

Example 24

Project: python-cloudant
Source File: index_tests.py
View license
    def test_deleting_non_existing_index(self):
        """
        Tests how deleting a non-existing index is handled.
        """
        ddoc = DesignDocument(self.db, '_design/ddoc001')
        index = Index(self.db, 'ddoc001', 'index001', fields=['name', 'age'])
        self.assertFalse(ddoc.exists())
        with self.assertRaises(requests.HTTPError) as cm:
            index.delete()
        err = cm.exception
        self.assertEqual(err.response.status_code, 404)

Example 25

Project: python-cloudant
Source File: replicator_tests.py
View license
    def test_stop_replication(self):
        """
        Test that a replication can be stopped.
        """
        self.populate_db_with_documents(3)
        repl_id = "test-repl-{}".format(unicode_(uuid.uuid4()))
        repl_doc = self.replicator.create_replication(
            self.db,
            self.target_db,
            repl_id
        )
        self.replicator.stop_replication(repl_id)
        try:
            # The .fetch() will fail since the replication has been stopped
            # and the replication document has been removed from the db.
            repl_doc.fetch()
            self.fail('Above statement should raise a CloudantException')
        except requests.HTTPError as err:
            self.assertEqual(err.response.status_code, 404)

Example 26

Project: python-cloudant
Source File: view_tests.py
View license
    def test_view_callable_with_non_existing_view(self):
        """
        Test error condition when view used does not exist remotely.
        """
        self.populate_db_with_documents()
        # The view "missing-view" does not exist in the remote database
        view = View(
            DesignDocument(self.db, 'ddoc001'),
            'missing-view',
            'function (doc) {\n  emit(doc._id, 1);\n}'
        )
        self.assertIsInstance(view, View)
        try:
            for row in view.result:
                self.fail('Above statement should raise an Exception')
        except requests.HTTPError as err:
            self.assertEqual(err.response.status_code, 404)

Example 27

Project: kpm
Source File: test_kpmcli.py
View license
@pytest.mark.cli
@pytest.mark.last
def test_push_1_existing(package_home, parser, monkeypatch, pkgname, api_stg, capsys):
    os.chdir(package_home)
    cmd = "push"
    args = parser.parse_args(cmd.split(" ") + api_stg)
    with pytest.raises(requests.HTTPError):
        args.func(args)

Example 28

Project: kpm
Source File: test_registry.py
View license
def test_signup_existing():
    r = Registry()
    with requests_mock.mock() as m:
        response = '{"email": "[email protected]", "token": "signup_token"}'
        m.post(DEFAULT_REGISTRY + "/api/v1/users", complete_qs=True, text=response, status_code=401)
        with pytest.raises(requests.HTTPError):
            sign_r = r.signup("ant31", "plop", "plop", "[email protected]")

Example 29

Project: kpm
Source File: test_registry.py
View license
def test_login_failed():
    r = Registry()
    with requests_mock.mock() as m:
        response = '{"email": "[email protected]", "token": "login_token"}'
        m.post(DEFAULT_REGISTRY + "/api/v1/users/login",
              complete_qs=True,
              text=response, status_code=401)
        with pytest.raises(requests.HTTPError):
            login_r = r.login("ant31", "plop")

Example 30

Project: kpm
Source File: test_registry.py
View license
def test_delete_package_unauthorized():
    r = Registry()
    with requests_mock.mock() as m:
        response = '{"packages": "true"}'
        m.delete(DEFAULT_REGISTRY + "/api/v1/packages/ant31/kube-ui",
                 complete_qs=True,
                 text=response,
                 status_code=401)
        with pytest.raises(requests.HTTPError):
            r.delete_package(name="ant31/kube-ui")

Example 31

Project: kpm
Source File: test_registry.py
View license
def test_push_unauthorized(kubeui_blob):
    r = Registry()
    with requests_mock.mock() as m:
        body = {"blob": b64encode(kubeui_blob)}
        response = '{"packages": "true"}'
        m.post(DEFAULT_REGISTRY + "/api/v1/packages/ant31/kube-ui?force=false",
                 complete_qs=True,
                 text=response,
                 status_code=401)
        with pytest.raises(requests.HTTPError):
            r.push(name="ant31/kube-ui", body=body)

Example 32

Project: orochi
Source File: api.py
View license
    def _post(self, resource, params={}, **kwargs):
        r = self.s.post(self.base_url + resource, params=params, **kwargs)
        try:
            r.raise_for_status()
        except requests.HTTPError as e:
            e.args = e.args + (r.json(),)
            raise e
        data = r.json()
        if 'errors' in data and data['errors'] is not None:
            raise APIError(data['errors'], data)
        return data

Example 33

Project: subliminal
Source File: test_tvdb.py
View license
@pytest.mark.integration
@vcr.use_cassette
def test_login_error():
    client = TVDBClient('1234', headers={'User-Agent': 'Subliminal/%s' % __short_version__})
    with pytest.raises(requests.HTTPError):
        client.login()

Example 34

Project: amqpstorm
Source File: http_client_tests.py
View license
    def test_api_http_standard_http_error(self):
        fake_payload = {
            'error': 'travis-ci'
        }

        self.assertRaisesRegexp(
            ApiError, 'travis-ci',
            HTTPClient._check_for_errors,
            FakeResponse(raises=requests.HTTPError('travis-ci')),
            fake_payload
        )

Example 35

View license
    def test_get_internal_server_error(self):
        self.prepare_for_token_request()
        httpretty.register_uri('GET', FAKE_RESOURCE_URL, body='Server Error', status=500)

        with self.assertRaises(requests.HTTPError):
            list(self.client.paginated_get(FAKE_RESOURCE_URL))

Example 36

Project: lifter
Source File: http.py
View license
    def parse_response(self, response):
        try:
            response.raise_for_status()
        except requests.HTTPError as e:
            if response.status_code >= 400 and response.status_code < 500:
                raise exceptions.BadQuery(str(e))
            if response.status_code >= 500:
                raise exceptions.StoreError(str(e))
        parser = self.get_parser(response)
        return parser.parse(response.content.decode('utf-8'))

Example 37

Project: f5-common-python
Source File: test_pool.py
View license
    def test_non_404_response__v12_1(self, fakeicontrolsession_v12):
        r1, r2, = self.set_subcoll_pool(fakeicontrolsession_v12)
        memc = Members_s(r1)
        memc._meta_data['uri'] = 'mock://URI'
        memres = memc.member
        memres._meta_data['bigip']._meta_data['tmos_version'] = '12.1.0'
        mock_response = mock.MagicMock()
        mock_response.status_code = 500
        mock_response.text = 'Internal Server Error'
        error = HTTPError(response=mock_response)
        session = mock.MagicMock(name='mock_session')
        session.post.side_effect = error
        memres._meta_data['bigip']._meta_data['icr_session'] = session
        with pytest.raises(HTTPError) as err:
                memres.create(name='fake', partition='fakepart')
        assert err.value.response.status_code == 500

Example 38

Project: f5-common-python
Source File: test_pool.py
View license
    def test_404_response_v12_1(self, fakeicontrolsession_v12):
        r1, r2, = self.set_subcoll_pool(fakeicontrolsession_v12)
        memc = Members_s(r1)
        memres = memc.member
        memres._meta_data['bigip']._meta_data['tmos_version'] = '12.1.0'
        mock_response = mock.MagicMock()
        mock_response.status_code = 404
        error = HTTPError(response=mock_response)
        MRO = MockResponse({u"kind": self.memkinds[self.urielementname()],
                            u"selfLink":
                                u".../~Common~testpool/members/~Common~fake"})
        session = mock.MagicMock(name='mock_session')
        session.post.side_effect = error
        session.get.return_value = MRO
        memres._meta_data['bigip']._meta_data['icr_session'] = session
        a = memres.create(name='fake', partition='Common')
        assert a.selfLink == '.../~Common~testpool/members/~Common~fake'
        assert a.kind == self.memkinds[self.urielementname()]

Example 39

Project: home-assistant
Source File: automatic.py
View license
def setup_scanner(hass, config: dict, see):
    """Validate the configuration and return an Automatic scanner."""
    try:
        AutomaticDeviceScanner(hass, config, see)
    except requests.HTTPError as err:
        _LOGGER.error(str(err))
        return False

    return True

Example 40

Project: nbviewer
Source File: base.py
View license
@contextmanager
def assert_http_error(status, msg=None):
    try:
        yield
    except requests.HTTPError as e:
        real_status = e.response.status_code
        assert real_status == status, \
                    "Expected status %d, got %d" % (real_status, status)
        if msg:
            assert msg in str(e), e
    else:
        assert False, "Expected HTTP error status"

Example 41

Project: nbviewer
Source File: base.py
View license
@contextmanager
def assert_http_error(status, msg=None):
    try:
        yield
    except requests.HTTPError as e:
        real_status = e.response.status_code
        assert real_status == status, \
                    "Expected status %d, got %d" % (real_status, status)
        if msg:
            assert msg in str(e), e
    else:
        assert False, "Expected HTTP error status"

Example 42

Project: Tardis
Source File: RemoteDB.py
View license
def reconnect(func):
    #print "Decorating ", str(func)
    @functools.wraps(func)
    def doit(self, *args, **kwargs):
        try:
            # Try the original function
            return func(self, *args, **kwargs)
        except requests.HTTPError as e:
            # Got an exception.  If it's ' 401 (not authorized)
            # reconnecton, and try it again
            logger=logging.getLogger('Reconnect')
            logger.info("Got HTTPError: %s", e)
            if e.response.status_code == 401:
                logger.info("Reconnecting")
                self.connect()
                logger.info("Retrying %s(%s %s)", str(func), str(args), str(kwargs))
                return func(self, *args, **kwargs)
            raise e
    return doit

Example 43

Project: Tardis
Source File: RemoteDB.py
View license
def reconnect(func):
    #print "Decorating ", str(func)
    @functools.wraps(func)
    def doit(self, *args, **kwargs):
        try:
            # Try the original function
            return func(self, *args, **kwargs)
        except requests.HTTPError as e:
            # Got an exception.  If it's ' 401 (not authorized)
            # reconnecton, and try it again
            logger=logging.getLogger('Reconnect')
            logger.info("Got HTTPError: %s", e)
            if e.response.status_code == 401:
                logger.info("Reconnecting")
                self.connect()
                logger.info("Retrying %s(%s %s)", str(func), str(args), str(kwargs))
                return func(self, *args, **kwargs)
            raise e
    return doit

Example 44

Project: pyscp
Source File: snapshot.py
View license
    @utils.ignore(requests.HTTPError)
    def _save_page(self, page):
        """Download contents, revisions, votes and discussion of the page."""
        orm.Page.create(
            id=page._id, url=page.url, thread=page._thread._id, html=page.html)

        revisions = orm.User.convert_to_id(i._asdict() for i in page.history)
        votes = orm.User.convert_to_id(i._asdict() for i in page.votes)
        tags = [{'tag': t} for t in page.tags]
        tags = orm.Tag.convert_to_id(tags, key='tag')

        def _insert(table, data):
            table.insert_many(dict(i, page=page._id) for i in data)

        _insert(orm.Revision, revisions)
        _insert(orm.Vote, votes)
        _insert(orm.PageTag, tags)

        self._save_thread(page._thread)

Example 45

Project: pyscp
Source File: snapshot.py
View license
    @utils.ignore(requests.HTTPError)
    def _save_page(self, page):
        """Download contents, revisions, votes and discussion of the page."""
        orm.Page.create(
            id=page._id, url=page.url, thread=page._thread._id, html=page.html)

        revisions = orm.User.convert_to_id(i._asdict() for i in page.history)
        votes = orm.User.convert_to_id(i._asdict() for i in page.votes)
        tags = [{'tag': t} for t in page.tags]
        tags = orm.Tag.convert_to_id(tags, key='tag')

        def _insert(table, data):
            table.insert_many(dict(i, page=page._id) for i in data)

        _insert(orm.Revision, revisions)
        _insert(orm.Vote, votes)
        _insert(orm.PageTag, tags)

        self._save_thread(page._thread)

Example 46

Project: python-mediawiki-utilities
Source File: api.py
View license
    def request(self, type, params):
        try:
            result = self.session.request(type, self.uri, params=params,
                                          timeout=self.timeout)
            self.failed = 0
            return result
        except (requests.HTTPError, requests.ConnectionError):
            self.failed += 1

            if self.failed > self.failure_threshold:
                self.failed = 0
                raise
            else:
                self.__sleep()
                self.request(type, params)

Example 47

Project: python-mediawiki-utilities
Source File: api.py
View license
    def request(self, type, params):
        try:
            result = self.session.request(type, self.uri, params=params,
                                          timeout=self.timeout)
            self.failed = 0
            return result
        except (requests.HTTPError, requests.ConnectionError):
            self.failed += 1

            if self.failed > self.failure_threshold:
                self.failed = 0
                raise
            else:
                self.__sleep()
                self.request(type, params)

Example 48

Project: django-payments
Source File: test_paypal.py
View license
    @patch('requests.post')
    def test_provider_handles_captured_payment(self, mocked_post):
        data = MagicMock()
        data.return_value = {
            'name': 'AUTHORIZATION_ALREADY_COMPLETED'}
        response = MagicMock()
        response.json = data
        mocked_post.side_effect = HTTPError(response=response)
        self.provider.capture(self.payment)
        self.assertEqual(self.payment.status, 'confirmed')

Example 49

Project: django-payments
Source File: test_paypal.py
View license
    @patch('requests.post')
    def test_provider_handles_captured_payment(self, mocked_post):
        data = MagicMock()
        data.return_value = {
            'name': 'AUTHORIZATION_ALREADY_COMPLETED'}
        response = MagicMock()
        response.json = data
        mocked_post.side_effect = HTTPError(response=response)
        self.provider.capture(self.payment)
        self.assertEqual(self.payment.status, 'confirmed')

Example 50

Project: django-payments
Source File: test_paypal.py
View license
    def test_form_shows_validation_error_message(self):
        with patch('requests.post') as mocked_post:
            error_message = 'error message'
            data = MagicMock()
            data.return_value = {'details': [{'issue': error_message}]}
            post = MagicMock()
            post.json = data
            post.status_code = 400
            mocked_post.side_effect = HTTPError(response=post)
            form = self.provider.get_form(
                payment=self.payment, data=PROCESS_DATA)
        self.assertEqual(self.payment.status, 'error')
        self.assertEqual(form.errors['__all__'][0], error_message)