def session(self): """ Creates and returns new circuit breaker session """ _session = CircuitBreakerSession(internal=True, circuit_breaker=self.CIRCUIT_BREAKER) _session.request = partial(_session.request, headers=self._headers(), timeout=self.timeout) return _session
def session(self): """ Persistence service returns HTTP 404 if there is no skill data available To workaround this behaviour, make 404 a non-failure code """ _session = CircuitBreakerSession(internal=True, circuit_breaker=self.CIRCUIT_BREAKER, good_codes=(range(200, 400), 404)) _session.request = partial(_session.request, headers=self._headers(), timeout=self.timeout) return _session
def test_request_proxy_on_service(self, req_mock): requests.USE_LOCAL_SERVICES = True with CircuitBreakerSession() as session: session.get('http://service-test-service') self.assertEqual(req_mock.call_args_list[0][1]['proxies'], {'http': 'http://localhost:8888'}) requests.USE_LOCAL_SERVICES = False
def test_http_error_500(self, tracer_mock, req_mock): req_mock.get('http://localhost/', status_code=500) with self.assertRaises(BadHttpResponseCodeException): with CircuitBreakerSession() as s: s.get('http://localhost/') tracer_mock().start_span().__enter__().log_kv.assert_called_once_with( {'error': 'BadHttpResponseCodeException 500'})
def test_request_timeout_from_config(self, request_mock): with CircuitBreakerSession() as s: s.get('http://localhost/') request_mock.assert_called_once_with(s, 'GET', 'http://localhost/', allow_redirects=True, timeout=10)
def test_check_status_code_range_and_int(self): response = Mock() response.status_code = 404 try: CircuitBreakerSession(good_codes=(range(200, 400), 404), bad_codes=range( 400, 600))._check_status_code(response) except BadHttpResponseCodeException: self.fail('BadHttpResponseCodeException should not be raised')
def test_request_timeout_to_default(self, request_mock): with CircuitBreakerSession() as s: s.get('http://localhost/') request_mock.assert_called_once_with( s, 'GET', 'http://localhost/', allow_redirects=True, timeout=DEFAULT_REQUEST_TIMEOUT)
def _pre_check(): """ Startup probe: check if Rasa is answering at `server_url` and return "OK" """ server_url = config.get('rasa', 'server_url', fallback=DEFAULT_SERVER_URL) try: return CircuitBreakerSession().get(server_url).ok and 'ok' except RequestException: return skill.HTTPResponse('Not ready', 503)
def handler(stt: str, user_id: str): stt = stt.lower() try: if stt.lower() == 'spiel beenden': with CircuitBreakerSession() as session: session.delete( 'https://n3i39w6xtc.execute-api.eu-west-1.amazonaws.com/prod/delsession?id=' + user_id) return tell("Auf Wiedersehen. bis bald") logger = logging.getLogger(__name__) logger.info("**** CVI Context = " + str(context)) with CircuitBreakerSession() as session: logger.info("**** user_hash = " + str(user_id)) response = session.get( 'https://hi4m6llff6.execute-api.eu-west-1.amazonaws.com/prod/a?id=' + user_id + '&stt=' + stt) return ask_freetext(response.text) except Exception as e: logger.info("**** Exception = " + str(e)) return ask_freetext("Es ist ein Fehler aufgetreten!")
def test_request_headers_propagation(self, request_mock, *mocks): from skill_sdk.requests import CircuitBreakerSession with CircuitBreakerSession(internal=True) as s: s.get('http://localhost/') request_mock.assert_any_call(s, 'GET', 'http://localhost/', timeout=5, allow_redirects=True, headers={ 'X-B3-TraceId': '430ee1c3e2deccfc', 'X-B3-SpanId': 'd4aeec01e3c43fac' })
def send_message_receive_block(server_url, sender_id, message) -> List[Dict[Text, Any]]: """ Send message to Rasa webhook :param server_url: :param sender_id: :param message: :return: """ payload = {"sender": sender_id, "message": message} url = f"{server_url}/webhooks/rest/webhook" with CircuitBreakerSession() as session: with session.post(url, json=payload) as resp: return resp.json()
def test_init(self): zcbs = CircuitBreakerSession(cache=LocalFIFOCache()) self.assertEqual(zcbs.internal, False) self.assertEqual(zcbs.circuit_breaker, DEFAULT_CIRCUIT_BREAKER) self.assertTrue(isinstance(zcbs, Session))
def test_deprecation_warning(self, warn): from skill_sdk.requests import CircuitBreakerSession with CircuitBreakerSession() as s: self.assertEqual(1, warn.call_count)
def test_check_status_code_default_500(self): response = Mock() response.status_code = 500 with self.assertRaises(Exception): CircuitBreakerSession()._check_status_code(response)
def test_check_status_code_int_range_ok(self): response = Mock() response.status_code = 200 self.assertEqual( CircuitBreakerSession( good_codes=(200, 300))._check_status_code(response), None)
def test_check_status_code_int_range_found(self): response = Mock() response.status_code = 302 self.assertEqual( CircuitBreakerSession( good_codes=range(300, 400))._check_status_code(response), None)
def test_check_status_code_string(self): response = Mock() response.status_code = 500 with self.assertRaises(Exception): CircuitBreakerSession( good_codes='200')._check_status_code(response)
def test_check_status_code_int_range_500(self): response = Mock() response.status_code = 500 with self.assertRaises(Exception): CircuitBreakerSession( good_codes=range(200, 400))._check_status_code(response)
def test_request_proxy_off_no_service(self, req_mock): requests.USE_LOCAL_SERVICES = False with CircuitBreakerSession() as session: session.get('http://test') self.assertEqual(req_mock.call_args_list[0][1].get('proxies'), None) requests.USE_LOCAL_SERVICES = False
def test_init_with_internal_true(self): zcbs = CircuitBreakerSession(internal=True) self.assertEqual(zcbs.internal, True) self.assertEqual(zcbs.circuit_breaker, DEFAULT_CIRCUIT_BREAKER) self.assertTrue(isinstance(zcbs, Session))
def test_init_with_circuit_breaker(self): cb = CircuitBreaker() zcbs = CircuitBreakerSession(circuit_breaker=cb) self.assertEqual(zcbs.internal, False) self.assertEqual(zcbs.circuit_breaker, cb) self.assertTrue(isinstance(zcbs, Session))
def test_check_status_code_default_ok(self): response = Mock() response.status_code = 200 self.assertEqual(CircuitBreakerSession()._check_status_code(response), None)
def test_cache_class_can_validate(self): with CircuitBreakerSession() as session: for url in ('http://example.com/', 'https://example.com/'): adapter = session.get_adapter(url) self.assertTrue(hasattr(adapter.cache, 'validate'))