"InvalidSessionIdException" while calling driver.quit()

496 views
Skip to first unread message

Chandra Sekhar

unread,
Sep 23, 2023, 5:19:53 AM9/23/23
to Selenium Users

Hi Community, 


I used https://github.com/SeleniumHQ/docker-selenium helm charts to create the selenium grid in my GKE cluster but when I run the automation on that cluster, I could see “InvalidSessionIdException” very frequently while running.


I am using Python with pytest-selenium plugin for running the test cases.


The Majority of times I could see the issue when the test case failed and the pytest-selenium called driver.quit(). 


Does anyone has any idea?


request = <SubRequest 'driver' for <Function test_grid_find_REMOTE>>

driver_class = <class 'selenium.webdriver.remote.webdriver.WebDriver'>

driver_kwargs = {'command_executor': 'http://<IPAddress>/wd/hub', 'desired_capabilities': {'browserName': 'chrome', '...args': ['headless', '--window-size=1366,768', '--ignore-gpu-blocklist', '--disable-dev-shm-usage'], 'extensions': []}}}


@pytest.fixture

def driver(request, driver_class, driver_kwargs):

"""Returns a WebDriver instance based on options and capabilities"""


retries = int(request.config.getini("max_driver_init_attempts"))

for retry in Retrying(

stop=stop_after_attempt(retries), wait=wait_exponential(), reraise=True

):

with retry:

LOGGER.info(

f"Driver init, attempt {retry.retry_state.attempt_number}/{retries}"

)

driver = driver_class(**driver_kwargs)


event_listener = request.config.getoption("event_listener")

if event_listener is not None:

# Import the specified event listener and wrap the driver instance

mod_name, class_name = event_listener.rsplit(".", 1)

mod = __import__(mod_name, fromlist=[class_name])

event_listener = getattr(mod, class_name)

if not isinstance(driver, EventFiringWebDriver):

driver = EventFiringWebDriver(driver, event_listener())


request.node._driver = driver

yield driver

> driver.quit()


../../../venv/selenium-tests/lib/python3.9/site-packages/pytest_selenium/pytest_selenium.py:221:

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

../../../venv/selenium-tests/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py:562: in quit

self.execute(Command.QUIT)

../../../venv/selenium-tests/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py:440: in execute

self.error_handler.check_response(response)

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _


self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x102fcfa30>

response = {'status': 404, 'value': '{\n "value": "\\u002fsession\\u002f18a500b1aab424d9ca05340995d7dd3d",\n "message": "Unable...\'5.15.109+\', java.version: \'11.0.18\'\\nDriver info: driver.version: unknown",\n "error": "invalid session id"\n}'}


def check_response(self, response: Dict[str, Any]) -> None:

"""Checks that a JSON response from the WebDriver does not have an

error.


:Args:

- response - The JSON response from the WebDriver server as a dictionary

object.


:Raises: If the response contains an error message.

"""

status = response.get("status", None)

if not status or status == ErrorCode.SUCCESS:

return

value = None

message = response.get("message", "")

screen: str = response.get("screen", "")

stacktrace = None

if isinstance(status, int):

value_json = response.get("value", None)

if value_json and isinstance(value_json, str):

import json


try:

value = json.loads(value_json)

if len(value) == 1:

value = value["value"]

status = value.get("error", None)

if not status:

status = value.get("status", ErrorCode.UNKNOWN_ERROR)

message = value.get("value") or value.get("message")

if not isinstance(message, str):

value = message

message = message.get("message")

else:

message = value.get("message", None)

except ValueError:

pass


exception_class: Type[WebDriverException]

if status in ErrorCode.NO_SUCH_ELEMENT:

exception_class = NoSuchElementException

elif status in ErrorCode.NO_SUCH_FRAME:

exception_class = NoSuchFrameException

elif status in ErrorCode.NO_SUCH_SHADOW_ROOT:

exception_class = NoSuchShadowRootException

elif status in ErrorCode.NO_SUCH_WINDOW:

exception_class = NoSuchWindowException

elif status in ErrorCode.STALE_ELEMENT_REFERENCE:

exception_class = StaleElementReferenceException

elif status in ErrorCode.ELEMENT_NOT_VISIBLE:

exception_class = ElementNotVisibleException

elif status in ErrorCode.INVALID_ELEMENT_STATE:

exception_class = InvalidElementStateException

elif (

status in ErrorCode.INVALID_SELECTOR

or status in ErrorCode.INVALID_XPATH_SELECTOR

or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER

):

exception_class = InvalidSelectorException

elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE:

exception_class = ElementNotSelectableException

elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE:

exception_class = ElementNotInteractableException

elif status in ErrorCode.INVALID_COOKIE_DOMAIN:

exception_class = InvalidCookieDomainException

elif status in ErrorCode.UNABLE_TO_SET_COOKIE:

exception_class = UnableToSetCookieException

elif status in ErrorCode.TIMEOUT:

exception_class = TimeoutException

elif status in ErrorCode.SCRIPT_TIMEOUT:

exception_class = TimeoutException

elif status in ErrorCode.UNKNOWN_ERROR:

exception_class = WebDriverException

elif status in ErrorCode.UNEXPECTED_ALERT_OPEN:

exception_class = UnexpectedAlertPresentException

elif status in ErrorCode.NO_ALERT_OPEN:

exception_class = NoAlertPresentException

elif status in ErrorCode.IME_NOT_AVAILABLE:

exception_class = ImeNotAvailableException

elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED:

exception_class = ImeActivationFailedException

elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS:

exception_class = MoveTargetOutOfBoundsException

elif status in ErrorCode.JAVASCRIPT_ERROR:

exception_class = JavascriptException

elif status in ErrorCode.SESSION_NOT_CREATED:

exception_class = SessionNotCreatedException

elif status in ErrorCode.INVALID_ARGUMENT:

exception_class = InvalidArgumentException

elif status in ErrorCode.NO_SUCH_COOKIE:

exception_class = NoSuchCookieException

elif status in ErrorCode.UNABLE_TO_CAPTURE_SCREEN:

exception_class = ScreenshotException

elif status in ErrorCode.ELEMENT_CLICK_INTERCEPTED:

exception_class = ElementClickInterceptedException

elif status in ErrorCode.INSECURE_CERTIFICATE:

exception_class = InsecureCertificateException

elif status in ErrorCode.INVALID_COORDINATES:

exception_class = InvalidCoordinatesException

elif status in ErrorCode.INVALID_SESSION_ID:

exception_class = InvalidSessionIdException

elif status in ErrorCode.UNKNOWN_METHOD:

exception_class = UnknownMethodException

else:

exception_class = WebDriverException

if not value:

value = response["value"]

if isinstance(value, str):

raise exception_class(value)

if message == "" and "message" in value:

message = value["message"]


screen = None # type: ignore[assignment]

if "screen" in value:

screen = value["screen"]


stacktrace = None

st_value = value.get("stackTrace") or value.get("stacktrace")

if st_value:

if isinstance(st_value, str):

stacktrace = st_value.split("\n")

else:

stacktrace = []

try:

for frame in st_value:

line = frame.get("lineNumber", "")

file = frame.get("fileName", "<anonymous>")

if line:

file = f"{file}:{line}"

meth = frame.get("methodName", "<anonymous>")

if "className" in frame:

meth = f"{frame['className']}.{meth}"

msg = " at %s (%s)"

msg = msg % (meth, file)

stacktrace.append(msg)

except TypeError:

pass

if exception_class == UnexpectedAlertPresentException:

alert_text = None

if "data" in value:

alert_text = value["data"].get("text")

elif "alert" in value:

alert_text = value["alert"].get("text")

raise exception_class(message, screen, stacktrace, alert_text) # type: ignore[call-arg] # mypy is not smart enough here

> raise exception_class(message, screen, stacktrace)

E selenium.common.exceptions.InvalidSessionIdException: Message: Unable to execute request for an existing session: Unable to find session with ID: 18a500b1aab424d9ca05340995d7dd3d

E Build info: version: '4.8.3', revision: 'b19b418e60'

E System info: os.name: 'Linux', os.arch: 'amd64', os.version: '5.15.109+', java.version: '11.0.18'

E Driver info: driver.version: unknown


../../../venv/selenium-tests/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py:245: InvalidSessionIdException


santhosh soma

unread,
Sep 23, 2023, 10:35:45 PM9/23/23
to seleniu...@googlegroups.com, chandra.s...@gmail.com
@chandra.s...@gmail.com  Following reasons that I can think of to get this exception.  Share the Test client code to get better understanding.

  1. Session Already Closed: If you have already closed the WebDriver session using driver.quit() earlier in your script, calling it again on the same driver instance will result in an InvalidSessionIdException. Ensure that you are not attempting to quit the session multiple times.
  2. Driver Instance Not Initialized: If you are trying to quit a driver instance that was not properly initialized or created, you may encounter this exception. Ensure that you have created and initialized the driver before calling driver.quit().
  3. Concurrent Sessions: If you are working with multiple WebDriver instances or managing WebDriver sessions concurrently, make sure you are calling driver.quit() on the correct driver instance. It's easy to mistakenly quit the wrong session if you have multiple drivers.
  4. Network Issues: In rare cases, network issues or communication problems between the script and the WebDriver server can lead to the session being invalidated. Ensure that your WebDriver server is running and accessible.  Look out for the Grid Setting to keep the session time validity here.
Regards
Santhosh.


--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to selenium-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/selenium-users/5ea04818-e6a3-4f00-80d2-405e85cf398an%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages