From 8933e909393ec548291ac7f0a770b0687c28d4a4 Mon Sep 17 00:00:00 2001 From: Nacy Dev Date: Mon, 16 Nov 2026 07:07:22 +0700 Subject: [PATCH 1/2] fix(webdriver): handle HTTP error responses and alert text in MobileErrorHandler --- appium/webdriver/errorhandler.py | 71 ++++++++++++++----- test/unit/webdriver/errorhandler_test.py | 87 ++++++++++++++++++++++++ 2 files changed, 142 insertions(+), 16 deletions(-) diff --git a/appium/webdriver/errorhandler.py b/appium/webdriver/errorhandler.py index 2248f7d6..1837c1d6 100644 --- a/appium/webdriver/errorhandler.py +++ b/appium/webdriver/errorhandler.py @@ -13,6 +13,7 @@ # limitations under the License. import json +from http import HTTPStatus from typing import Any import selenium.common.exceptions as sel_exceptions @@ -23,28 +24,48 @@ class MobileErrorHandler(errorhandler.ErrorHandler): def check_response(self, response: dict[str, Any]) -> None: - """Handle W3C errors, retaining Appium-specific exception mappings.""" + """Handle W3C and HTTP error responses, retaining Appium-specific exception mappings.""" + status = response.get('status') + if status == errorhandler.ErrorCode.SUCCESS and not isinstance(status, bool): + return + + http_error_status = ( + status if isinstance(status, int) and not isinstance(status, bool) and status >= HTTPStatus.BAD_REQUEST else None + ) payload = response.get('value', '') - if isinstance(payload, dict): - payload_dict = payload - else: - try: - payload_dict = json.loads(payload) - except (json.JSONDecodeError, TypeError): - return - if not isinstance(payload_dict, dict): - return + payload_dict = _parse_payload_dict(payload) + + if payload_dict is None: + if http_error_status is not None: + self._raise_http_error(http_error_status, payload if isinstance(payload, str) else '') + return + value = payload_dict.get('value') - if not isinstance(value, dict): + is_jsonwp_dict = 'status' in payload_dict and not isinstance(payload_dict.get('error'), str) + if isinstance(value, dict): + error = value.get('error') + if isinstance(error, str) and error: + self._delegate_w3c_error(error, value) + return + if http_error_status is not None and not is_jsonwp_dict: + self._raise_http_error(http_error_status, json.dumps(payload_dict)) return - error = value.get('error') - if not isinstance(error, str) or not error: + + if http_error_status is None or is_jsonwp_dict: + return + + flat_error = payload_dict.get('error') + if isinstance(flat_error, str) and flat_error: + self._delegate_w3c_error(flat_error, payload_dict) return - # Pass the W3C error string as Selenium's internal status, never a - # JSONWP numeric status. Selenium handles data.text and stacktrace. + raw_msg = value if isinstance(value, str) and value else json.dumps(payload_dict) + self._raise_http_error(http_error_status, raw_msg) + + def _delegate_w3c_error(self, error: str, value: dict[str, Any]) -> None: + normalized = {**value, 'data': {'text': value['data']}} if isinstance(value.get('data'), str) else value try: - super().check_response({'status': error, 'value': value}) + super().check_response({'status': error, 'value': normalized}) except sel_exceptions.WebDriverException as exc: if type(exc) is not sel_exceptions.WebDriverException: raise @@ -58,3 +79,21 @@ def check_response(self, response: dict[str, Any]) -> None: else: raise raise exception_class(msg=exc.msg, screen=exc.screen, stacktrace=exc.stacktrace) from exc + + def _raise_http_error(self, status: int, text: str) -> None: + msg = text or f'HTTP error status: {status}' + if status == HTTPStatus.METHOD_NOT_ALLOWED: + raise sel_exceptions.UnknownMethodException(msg=msg) + raise sel_exceptions.WebDriverException(msg=msg) + + +def _parse_payload_dict(payload: Any) -> dict[str, Any] | None: + if isinstance(payload, dict): + return payload + if isinstance(payload, str): + try: + loaded = json.loads(payload) + except (json.JSONDecodeError, TypeError): + return None + return loaded if isinstance(loaded, dict) else None + return None diff --git a/test/unit/webdriver/errorhandler_test.py b/test/unit/webdriver/errorhandler_test.py index 4ce841b4..db49d7fa 100644 --- a/test/unit/webdriver/errorhandler_test.py +++ b/test/unit/webdriver/errorhandler_test.py @@ -89,7 +89,94 @@ def test_driver_unexpected_alert_text(data): {'value': {'error': 'timeout', 'message': 'User script result'}}, {'status': 7, 'value': {'message': 'Legacy error'}}, {'status': 500, 'value': '{"status": 7, "value": {"message": "Legacy error"}}'}, + {'value': {'error': 'timeout', 'message': 'app payload'}}, ], ) def test_non_w3c_errors_are_not_interpreted(response): MobileErrorHandler().check_response(response) + + +@pytest.mark.parametrize( + ('response', 'expected_exc', 'expected_msg'), + [ + ({'status': 401, 'value': 'Authorization Required'}, exceptions.WebDriverException, 'Authorization Required'), + ( + {'status': 502, 'value': '502 Bad Gateway'}, + exceptions.WebDriverException, + '502 Bad Gateway', + ), + ({'status': 405, 'value': 'Method Not Allowed'}, exceptions.UnknownMethodException, 'Method Not Allowed'), + ({'status': 500, 'value': ''}, exceptions.WebDriverException, 'HTTP error status: 500'), + ({'status': 500, 'value': '["unexpected"]'}, exceptions.WebDriverException, '["unexpected"]'), + ( + {'status': 404, 'value': '{"error": "invalid session id", "message": "Session expired"}'}, + exceptions.InvalidSessionIdException, + 'Session expired', + ), + ( + {'status': 400, 'value': {'error': 'invalid argument', 'message': 'Invalid timeout value'}}, + exceptions.InvalidArgumentException, + 'Invalid timeout value', + ), + ( + {'status': 500, 'value': '{"value": "Plain error string"}'}, + exceptions.WebDriverException, + 'Plain error string', + ), + ({'status': 500, 'value': '{}'}, exceptions.WebDriverException, '{}'), + ], +) +def test_http_and_flat_error_responses_raise(response, expected_exc, expected_msg): + with pytest.raises(expected_exc) as caught: + MobileErrorHandler().check_response(response) + assert caught.value.msg is not None + assert caught.value.msg.startswith(expected_msg) + + +def test_unexpected_alert_extracts_string_data(): + response = { + 'status': 500, + 'value': '{"value": {"error": "unexpected alert open", "message": "Blocked", "data": "Legacy alert"}}', + } + with pytest.raises(exceptions.UnexpectedAlertPresentException) as caught: + MobileErrorHandler().check_response(response) + assert caught.value.alert_text == 'Legacy alert' + + +@httpretty.activate +def test_driver_raises_on_http_proxy_and_auth_errors(): + driver = android_w3c_driver() + + httpretty.register_uri( + httpretty.POST, + appium_command('/session/1234567890/element'), + status=401, + body='Unauthorized', + ) + with pytest.raises(exceptions.WebDriverException) as auth_exc: + driver.find_element(By.ID, 'btn') + assert auth_exc.value.msg == 'Authorization Required' + + httpretty.register_uri( + httpretty.GET, + appium_command('/session/1234567890/appium/settings'), + status=502, + body='502 Bad Gateway', + ) + with pytest.raises(exceptions.WebDriverException) as gateway_exc: + driver.get_settings() + assert gateway_exc.value.msg == '502 Bad Gateway' + + +@httpretty.activate +def test_driver_allows_http_200_user_dict_with_error_key(): + driver = android_w3c_driver() + httpretty.register_uri( + httpretty.POST, + appium_command('/session/1234567890/execute/sync'), + status=200, + content_type='application/json', + body='{"value": {"error": "timeout", "message": "app payload"}}', + ) + result = driver.execute_script('return arguments[0]', {'ok': True}) + assert result == {'error': 'timeout', 'message': 'app payload'} From 3027f56edaa64ed06fca007a62c33da477a1fd1a Mon Sep 17 00:00:00 2001 From: Nacy Dev Date: Mon, 16 Nov 2026 15:41:43 +0700 Subject: [PATCH 2/2] fix(webdriver): handle non-dict alert data before delegating to Selenium --- appium/webdriver/errorhandler.py | 8 +++++++- test/unit/webdriver/errorhandler_test.py | 11 +++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/appium/webdriver/errorhandler.py b/appium/webdriver/errorhandler.py index 1837c1d6..24abe0f2 100644 --- a/appium/webdriver/errorhandler.py +++ b/appium/webdriver/errorhandler.py @@ -63,7 +63,13 @@ def check_response(self, response: dict[str, Any]) -> None: self._raise_http_error(http_error_status, raw_msg) def _delegate_w3c_error(self, error: str, value: dict[str, Any]) -> None: - normalized = {**value, 'data': {'text': value['data']}} if isinstance(value.get('data'), str) else value + normalized = value + if 'data' in value and not isinstance(value['data'], dict): + data = value['data'] + if isinstance(data, str): + normalized = {**value, 'data': {'text': data}} + else: + normalized = {k: v for k, v in value.items() if k != 'data'} try: super().check_response({'status': error, 'value': normalized}) except sel_exceptions.WebDriverException as exc: diff --git a/test/unit/webdriver/errorhandler_test.py b/test/unit/webdriver/errorhandler_test.py index db49d7fa..48006310 100644 --- a/test/unit/webdriver/errorhandler_test.py +++ b/test/unit/webdriver/errorhandler_test.py @@ -143,6 +143,17 @@ def test_unexpected_alert_extracts_string_data(): assert caught.value.alert_text == 'Legacy alert' +@pytest.mark.parametrize('data', [None, ['item']]) +def test_unexpected_alert_ignores_non_dict_non_str_data(data): + response = { + 'status': 500, + 'value': json.dumps({'value': {'error': 'unexpected alert open', 'message': 'Blocked', 'data': data}}), + } + with pytest.raises(exceptions.UnexpectedAlertPresentException) as caught: + MobileErrorHandler().check_response(response) + assert caught.value.alert_text is None + + @httpretty.activate def test_driver_raises_on_http_proxy_and_auth_errors(): driver = android_w3c_driver()