def test_sleep(httpbin, mocker): # type: (Httpbin, Mock) -> None seconds = 1 tags = ["testing:sleep"] meta = {"request_category": REQUEST_CATEGORY, "testing": "sleep"} mock_ddtrace = mocker.MagicMock(spec_set=Ddtrace) mock_traced_sleep = mocker.patch( "request_session.request_session.traced_sleep", autospec=True) client = RequestSession(host=httpbin.url, ddtrace=mock_ddtrace) client.sleep(seconds, REQUEST_CATEGORY, tags) mock_traced_sleep.assert_called_once_with(REQUEST_CATEGORY + "_retry", seconds, mock_ddtrace, meta)
def test_close_all_sessions(): # type: () -> None session = RequestSession(host="https://kiwi.com") session.prepare_new_session() assert len(RequestSession.session_instances) >= 2 RequestSession.close_all_sessions() assert not RequestSession.session_instances
def test_get_request_category(httpbin): # type: (Httpbin) -> None client = RequestSession(host=httpbin.url) with pytest.raises(AttributeError, match="`request_category` is required parameter."): client._get_request_category() assert (client._get_request_category( request_category=REQUEST_CATEGORY) == REQUEST_CATEGORY) client.request_category = REQUEST_CATEGORY assert client._get_request_category() == REQUEST_CATEGORY
def test_init(mocker, httpbin): # type: (Mock, Httpbin) -> None """Test initialization of RequestSession.""" mock_ddtrace = mocker.Mock(spec_set=Ddtrace) mock_tracing_config = dict() # type: Dict[Any, Any] mock_ddtrace.config.get_from.return_value = mock_tracing_config session = RequestSession( host=httpbin.url, request_category=REQUEST_CATEGORY, max_retries=3, user_agent="UserAgent", ddtrace=mock_ddtrace, headers={}, auth=("user", "passwd"), ) assert session.host == httpbin.url assert session.request_category == REQUEST_CATEGORY assert session.max_retries == 3 assert session.user_agent == "UserAgent" assert session.headers == {} assert session.auth == ("user", "passwd")
def test_raise_for_status(mocker, httpbin, status_code, raises): # type: (Mock, Httpbin, int, Exception) -> None """Test raising of an exception when rejected with 4xx.""" session = RequestSession(host=httpbin.url, request_category=REQUEST_CATEGORY) mock_sys = mocker.patch("request_session.utils.sys", spec_set=sys) mock_sys.exc_info.return_value = (HTTPError, HTTPError(), "fake_traceback") if raises: with pytest.raises(raises): session.get(path="/status/{status_code}".format( status_code=status_code)) if isinstance(raises, HTTPError): assert mock_sys.exc_info()[1].__sentry_source == "third_party" assert mock_sys.exc_info()[1].__sentry_pd_alert == "disabled" else: session.get(path="/status/{status_code}".format( status_code=status_code))
def test_econnreset_error(httpbin, mocker, exceptions, max_retries, expected_call_count): # type: (Httpbin, Mock, Iterator[Exception], int, int) -> None used_sessions = [] def _prepare_new_session(self): # type: ignore self.session = mocker.Mock(spec=requests.Session) self.session_instances.append(self.session) self.session.request.side_effect = next(exceptions) used_sessions.append(self.session) client = RequestSession(host=httpbin.url, max_retries=max_retries, request_category=REQUEST_CATEGORY) mock_log = mocker.Mock(autospec=True) mock_exception_log_and_metrics = mocker.Mock( spec=RequestSession._exception_log_and_metrics) client.log = mock_log # type: ignore client._exception_log_and_metrics = mock_exception_log_and_metrics # type: ignore mocker.patch.object(RequestSession, "prepare_new_session", new=_prepare_new_session, spec_set=True) _prepare_new_session(client) with pytest.raises(RequestException): client.get("/status/500") actual_call_count = sum(session.request.call_count for session in used_sessions) mock_log.assert_called_with( "info", "{category}.session_replace".format(category=client.request_category)) assert mock_exception_log_and_metrics.call_count == 1 assert actual_call_count == expected_call_count
def inner(*args, **kwargs): # type: (*Any, **Any) -> RequestSession return RequestSession( # type: ignore *args, host=httpbin.url, request_category="test", **kwargs )
def test_is_server_error(exception, status_code, expected): # type: (RequestException, Union[int, None], bool) -> None assert RequestSession.is_server_error(exception, status_code) == expected
def test_get_response_text(mocker): # type: (Mock) -> None mock_response = mocker.Mock(spec_set=requests.Response) mock_response.text = "response_text" assert RequestSession.get_response_text(mock_response) == "response_text" assert RequestSession.get_response_text("not_a_response_obj") == ""
def test_remove_session(request_session): # type: (Callable) -> None session = RequestSession(host="https://kiwi.com") before = len(session.session_instances) session.remove_session() assert len(session.session_instances) == before - 1