Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 61 additions & 16 deletions appium/webdriver/errorhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -23,28 +24,54 @@

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

# Pass the W3C error string as Selenium's internal status, never a
# JSONWP numeric status. Selenium handles data.text and stacktrace.
flat_error = payload_dict.get('error')
if isinstance(flat_error, str) and flat_error:
self._delegate_w3c_error(flat_error, payload_dict)
return

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
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': value})
super().check_response({'status': error, 'value': normalized})
except sel_exceptions.WebDriverException as exc:
if type(exc) is not sel_exceptions.WebDriverException:
raise
Expand All @@ -58,3 +85,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
98 changes: 98 additions & 0 deletions test/unit/webdriver/errorhandler_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,105 @@ 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': '<html>502 Bad Gateway</html>'},
exceptions.WebDriverException,
'<html>502 Bad Gateway</html>',
),
({'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'


@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()

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='<html>502 Bad Gateway</html>',
)
with pytest.raises(exceptions.WebDriverException) as gateway_exc:
driver.get_settings()
assert gateway_exc.value.msg == '<html>502 Bad Gateway</html>'


@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'}
Loading