def test_post_notification_RequestException(self, mock_post):
     mock_post.return_value.raise_for_status.side_effect = req_exc.Timeout(
         'hello')
     notification_status, notification_error = post_notification(
         None, None, None)
     self.assertEqual(notification_status, Constants.PENDING)
     self.assertEqual(notification_error, 'hello')
Exemplo n.º 2
0
    def test_non_exist_url(self):
        url = 'http://non-exist.com/template'

        requests.get(url, stream=True).AndRaise(exceptions.Timeout())
        self.m.ReplayAll()

        self.assertRaises(urlfetch.URLFetchError, urlfetch.get, url)
        self.m.VerifyAll()
Exemplo n.º 3
0
 def _wait_until_timeout(self, events):
     stime = time.time()
     while (time.time() - stime) <= self._timeout:
         ongoing_events = [a for a in events if self.client.get_event(a).get('status') == "ongoing"]
         if len(ongoing_events) > 0:
             log.info("Waiting for {0}/{1} events to complete ... ".format(len(ongoing_events), len(events)))
             time.sleep(self._event_polling_interval)
         else:
             return
     raise exceptions.Timeout("Storage snapshot event(s) not finished in time ({} seconds)".format(self._timeout))
Exemplo n.º 4
0
 def __exit__(self, type, value, traceback):
     events = self.client.events
     try:
         self._wait_until_timeout(events)
     except exceptions.Timeout as e:
         ongoing_events = [str(a) for a in events if self.client.get_event(a)['status'] == "ongoing"]
         raise exceptions.Timeout("{}\nUnfinished events:\n{}".format(e, ", ".join(ongoing_events)))
     failed_events = [str(a) for a in events if self.client.get_event(a)['status'] == "failed"]
     done_events = [str(a) for a in events if self.client.get_event(a)['status'] == "done"]
     log.info("Failed events: {0}/{2}\nSuccessful events: {1}/{2}".format(len(failed_events), len(done_events), len(events)))
     if len(failed_events) > 0 and self._raise_for_failed_events:
         raise RuntimeError("Snapshot event(s) failed! Failed events: {}".format(", ".join(failed_events)))
Exemplo n.º 5
0
    def test_v2_get_user_by_name_timeout(self, get_mock, post_mock):
        get_mock.side_effect = [
            self._valid_get_response(),
            req_ex.Timeout('Timeout')
        ]
        post_mock.return_value = self._valid_post_response()

        identity = v2.RackspaceIdentity.from_username(
            self.username, self.password, user_domain_id=self.domain_id)

        self.assertRaises(exception.BadGateway, identity.get_user_by_name,
                          self.username)
Exemplo n.º 6
0
def test_request_transport_timeout():
  session = create_autospec(spec=requests.Session, instance=True)
  session.headers = {}
  session.post = Mock(side_effect=request_exceptions.Timeout())
  transport = TRequestsTransport('http://localhost:12345', session_factory=lambda: session)
  protocol = TJSONProtocol.TJSONProtocol(transport)
  client = ReadOnlyScheduler.Client(protocol)

  with pytest.raises(TTransport.TTransportException) as execinfo:
    client.getRoleSummary()

  assert execinfo.value.message == 'Timed out talking to http://localhost:12345'

  transport.close()
Exemplo n.º 7
0
    def send(self, url, method='GET', params={}, data={}, files={}, headers={}, timeout=None):
        headers.update(self.headers)
        prepped = Request(method,
            url,
            params=params,
            data=data,
            files=files,
            headers=headers).prepare()

        try:
            resp = self.session.send(prepped,
                proxies=self.proxies,
                timeout=(self.connect_timeout, timeout),
                )
        except exceptions.Timeout, e:
            raise exceptions.Timeout(e)
 def test_analyze_exception_request(self):
     self.assertEqual(errors.SYSTEM_TRANSIENT,
                      self.apic_handler.analyze_exception(rexc.Timeout()))
     self.assertEqual(
         errors.SYSTEM_TRANSIENT,
         self.apic_handler.analyze_exception(rexc.ConnectionError()))
     self.assertEqual(
         errors.OPERATION_CRITICAL,
         self.apic_handler.analyze_exception(rexc.InvalidURL()))
     self.assertEqual(
         errors.OPERATION_CRITICAL,
         self.apic_handler.analyze_exception(rexc.URLRequired()))
     self.assertEqual(
         errors.OPERATION_TRANSIENT,
         self.apic_handler.analyze_exception(rexc.RequestException()))
     self.assertEqual(errors.UNKNOWN,
                      self.apic_handler.analyze_exception(Exception()))
Exemplo n.º 9
0
    def test_v2_authentication_with_intermittent_failures(
            self, get_mock, post_mock):
        # Requests timeout exception
        timeout_ex = req_ex.Timeout('Timeout')

        get_mock.return_value = self._valid_get_response()
        post_mock.side_effect = [
            self._valid_post_response(), timeout_ex, timeout_ex,
            self._valid_post_response()
        ]

        identity = v2.RackspaceIdentity.from_username(
            self.username, self.password, user_domain_id=self.domain_id)

        self.assertRaises(exception.BadGateway, identity.authenticate)
        self.assertRaises(exception.BadGateway, identity.authenticate)
        self.assertIsNotNone(identity.authenticate())
Exemplo n.º 10
0
def test_request_transport_timeout():
    session = mock.MagicMock(spec=requests.Session)
    session.headers = {}
    session.post = mock.Mock(side_effect=request_exceptions.Timeout())
    transport = TRequestsTransport('http://localhost:12345',
                                   session_factory=lambda: session)
    protocol = TJSONProtocol.TJSONProtocol(transport)
    client = ReadOnlyScheduler.Client(protocol)

    try:
        client.getRoleSummary()
        assert False, 'getRoleSummary should not succeed'
    except TTransport.TTransportException as e:
        assert e.message == 'Timed out talking to http://localhost:12345'
    except Exception as e:
        assert False, 'Only expected TTransportException, got %s' % e

    transport.close()
Exemplo n.º 11
0
 def test_non_exist_url(self):
     url = 'http://non-exist.com/template'
     mock_get = self.patchobject(requests, 'get')
     mock_get.side_effect = exceptions.Timeout()
     self.assertRaises(urlfetch.URLFetchError, urlfetch.get, url)
     mock_get.assert_called_once_with(url, stream=True)
Exemplo n.º 12
0
    def test_non_exist_url(self):
        url = 'http://non-exist.com/somedata'

        self.patchobject(requests, 'get', side_effect=exceptions.Timeout())
        self.assertRaises(utils.URLFetchError, utils.url_fetch, url)
from requests import exceptions
import pytest
from rest_framework import status
from rest_framework.reverse import reverse

from company.data import CompaniesHouseException
from core.tests.helpers import create_response

expected_exceptions = (
    exceptions.RequestException(),
    exceptions.HTTPError(),
    exceptions.ConnectionError(),
    exceptions.ProxyError(),
    exceptions.SSLError(),
    exceptions.Timeout(),
    exceptions.ConnectTimeout(),
    exceptions.ReadTimeout(),
    CompaniesHouseException(404),
)


@pytest.fixture(autouse=True)
def mock_client_get():
    stub = mock.patch('company.data.CompaniesHouseClient.get')
    yield stub.start()
    stub.stop


def test_company_search_view_missing_querystring(api_client):
    url = reverse('api:search-companies')
Exemplo n.º 14
0
 def _simulate_get_timeout(self, request):
     """Will raise exception for any host request to this resource."""
     if URI_HOSTNAME in request.path_url:
         raise r_exc.Timeout()
Exemplo n.º 15
0
 def _simulate_timeout(self, request):
     if URI_HOSTNAME in request.path_uri:
         raise r_exc.Timeout()
Exemplo n.º 16
0
 def _simulate_token_timeout(self, request):
     raise r_exc.Timeout()
Exemplo n.º 17
0
def token_timeout(url, request):
    raise r_exc.Timeout()
Exemplo n.º 18
0
def timeout(url, request):
    """Simulated timeout of a normal request."""

    if not request.headers.get('X-auth-token', None):
        return {'status_code': requests.codes.UNAUTHORIZED}
    raise r_exc.Timeout()