© Sujay Raghavendra 2021
S. RaghavendraPython Testing with Seleniumhttps://doi.org/10.1007/978-1-4842-6249-8_9

9. Exceptions

Sujay Raghavendra1 
(1)
Dharwad, Karnataka, India
 

The last chapter discussed assertions, which evaluate a specified condition in a test case. This chapter focuses on exceptions that occur in Python with Selenium. First, you need to know what Selenium exceptions are and their various types. Several aspects raise exceptions in a Selenium test case. Each exception is caused by a specific reason, which is explained in this chapter. Selenium provides many built-in exceptions that later lead to the termination of a test case. To avoid these unusual terminations, an exception should be handled so that the test case follows the normal (default) execution flow. In this chapter, we study different types of exceptions, the causes that raise these exceptions, and how to handle exceptions in a Selenium test case. Let’s start by defining exceptions and the need to have exceptions in a test case.

What Is an Exception?

An exception occurs when the execution of a program is interrupted by an unusual event. A test case stops its normal flow and is terminated when an exception is raised or occurs.

Why Use Exceptions?

The following are some of the reasons to use exceptions in Selenium.
  • It separates the default test case code with error-handling code.

  • There is no need to check errors at each point of the test case.

  • An exception allows you to complete the default execution of a test case by any handling errors.

  • It makes error reporting easier in a test case.

  • Errors are easily classified when exceptions are used.

Exceptions in Selenium

Now that you have considered the reasons to have exceptions in a test case, let’s look at all the exceptions that can occur in Selenium when you execute a test case. Each exception is defined with the event that triggers the exception.

ConnectionClosedException

When a web driver is disconnected, Selenium raises this exception.

ElementClickInterceptedException

This exception occurs when a command to click an element is not executed correctly because the requested element that needs to be clicked is concealed or hidden.

ElementNotInteractableException

In this exception type, a defined web element cannot be interacted with or directs to another element, even if it is present in the Document Object Model (DOM).

ElementNotSelectableException

A web element cannot be selected, even when it is present in the DOM. This raises an exception. This action belongs to select in Selenium. The exception is more likely to occur in buttons to be slected like radio button, checkbox, etc.

ElementNotVisibleException

This exception is raised when an element is present on a web page, but it is not visible for actions to be performed on it. The invisibility of elements is due to a hidden type in an HTML tag, or some actions need to be performed first. This exception is solved by using a wait, which waits for an element to become visible.

ErrorInResponseException

This exception happens when there is an error on the server side. It is commonly seen when communicating with a remote server or a Firefox extension. The following lists some of these errors.
  • 400 – BadRequest

  • 401 – Unauthorized

  • 403 – Forbidden

  • 405 – MethodNotAllowed

  • 409 – Conflict

  • 500 – InternalServerError

ErrorHandler.UnknownServerException

When a server gives an error without a stack-trace, this exception is used as a placeholder.

ImeActivationFailedException

This exception is raised when the IME engine fails to activate. IME is the acronym for input method engine. It is generally used with Chinese, Japanese, or multibyte characters that are taken as input by Selenium. IBus is an example of an input framework that supports a Japanese engine like anthy.

ImeNotAvailableException

This exception occurs when IME support is not available on the device.

InsecureCertificateException

The TLS (Transport Layer Security) certificate, if expired or invalid, raises this exception at the user end.

InvalidArgumentException

When invalid or distorted arguments are passed, Selenium raises this exception.

InvalidCookieDomainException

Selenium invokes this exception when there is an effort to add a cookie for other domains or URLs rather than the present or current URL.

InvalidCoordinateException

This exception is activated when the defined coordinates are incorrect or invalid when the user needs to perform actions or operations on a corresponding web element. When mouse actions that move web elements or click buttons with provided coordinates fail, this exception is evoked.

InvalidElementStateException

When a web element is disabled or not in a state to perform the action specified to it, Selenium raises this exception. For example, the Submit button works when all the respective fields are filled, and if you try to click Submit beforehand, this exception is raised.

InvalidSelectorException

When users do not return specified web elements from the web page, InvalidSelectorException is raised. It is more likely to be raised by XPath because a path is invalid or changed, which means locating the web element fails.

InvalidSessionIdException

If a session ID in a test case is inactive, has expired, or does not exists, then Selenium raises this exception.

InvalidSwitchToTargetException

This exception occurs when a frame or window element is not available on a web page that needs to be placed or switched to a targeted location.

JavascriptException

If there is an issue regarding the execution of a JavaScript file or snippet, then this exception is invoked.

JsonException

This exception occurs when session capabilities are obtained when the session is not created.

MoveTargetOutOfBoundsException

When a target web element or mouse movement cannot be directed to the defined boundaries (i.e., beyond the boundary of the web page, or it is invalid), this exception is retained by ActionChains( ).

NoAlertPresentException

This exception happens when an alert popup (e.g., an alert box, prompt box, confirmation box, etc.) is not currently available. JavaScript guides the alert popup. Other reasons to raise this exception include an alert box requires more time to load or is unavailable at the current stage, JavaScript is blocked at the browser end, or the popup is already closed.

NoSuchAttributeException

If a web element is unable to return its attribute, then this exception is raised. It is one of the rarest Selenium exceptions that can occur in a test case. You can avoid this exception by knowing whether or not a web element has an attribute associated with it.

The exception can also be handled by updating the attribute value from the DOM that may have changed.

NoSuchCookieException

This exception is raised when there is no match for the cookie defined within the cookies present in the active document of the browser’s current context.

NoSuchElementException

This is the most commonly occurring exception in Selenium WebDriver test cases. This exception is revoked when a web locator is unable to trace or locate the defined web element from a web page. The web element is not located because the DOM does not contain it, or it is invalid.

When the defined web element is not available on a web page, Selenium throws NoSuchElementFoundException. This exception may occurring do to any of the following reasons.
  • The web element locator value is incorrect or does not match.

  • The page takes a long time to load, so the web element is not located.

  • The web element is unavailable or unseen on the web page at the time of test execution.

NoSuchElementException is handled by choosing a specific web locator from eight available locators (see Chapter 4 for more information). It also specifies wait to ensure that the web element has completely loaded.

NoSuchFrameException

This exception occurs when you want to switch to a frame that is currently unavailable. This happens when the specific details to switch the frame changes while refreshing the page, or the information does not match any of the frames available, or the web element is not a frame, or loading time is insufficient.

NoSuchWindowException

When certain actions should be performed in a browser window (like switch to a defined window or move the window’s position), this exception is raised if the window is not currently present. It also occurs when the window has not yet loaded and actions are attempted on it.

NoSuchContextException

In mobile testing, ContextAware evokes this exception.

ScreenshotException

This exception happens when Selenium fails to take a screenshot of the web page. The exception, when raised, turns the screenshot into a black image.

StaleElementReferenceException

This exception occurs when a web element is no longer present in the DOM because it was deleted or in a stable state. It is common because most web elements are now dynamic. A simple example is that a refreshing page may result in the unavailability of the defined web element.

This exception can be handled by XPath, which handles dynamic web elements on a web page.

TimeoutException

When the execution is not completed within the defined time frame, Selenium returns a timeout exception. The exception is handled using waits that enable you to provide more time for execution. The time value should be standard so that there is no delay in the further execution of the test case.

UnableToSetCookieException

This exception is raised when Selenium WebDriver is not able to set a cookie.

UnexpectedAlertPresentException

Selenium raises this alert when an unexpected alert appears on a web page, which is due to stalling Python commands from alerts (i.e., popups) .

UnexpectedTagNameException

This exception happens when the expected web element is unable to be located or found by the support class. It more commonly occurs in drop-down elements.

UnknownMethodException

This exception is raised when the requested Selenium commands match the known URL but fail to match the methods specified for the URL. To avoid this exception, you need to check the method before stating it in a test case.

WebDriverException

This is a base class Selenium WebDriver exception that is invoked when there is an incompatibility between WebDriver and the target web browser. All other exceptions come under this base class.

Exception Handling

Now that you know all the exceptions that occur in a Selenium test case, let’s examine the proper ways to handle them. The process to continue the execution of a test case after an exception is raised is known as exception handling or handling exceptions . Exceptions are handled to execute and avoid the unnecessary termination of a test case.

Exceptions hamper the next valid statements that need to be executed, and hence, Selenium provides a solution to handle exceptions. An exception can be handled by skipping or ignoring the raised exception, and thus, the test case continues to execute in its normal flow.

Note

Handling exceptions reduces debugging time.

An exception is handled using the try-except method in Python. By defining an exception, you can ignore or skip it when it appears during test case execution. Exception handling helps to reduce false failures in a test case and leads to finding actual bugs, if any. Some common examples of exception handling in test cases are discussed next.

Timeout Exception

The web element locator waits for a specified time so that there is a provision to load the complete page.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
driver=webdriver.Firefox(executable_path=r'C:foldergeckodriver.exe)
driver.get("https://apress.com")
try:
        # Web driver waits for 5 seconds to locate web element
        WebDriverWait(driver,5).until(EC.presence_of_element_located((By.ID, "query")))
except TimeoutException:
        # When loading page takes more time
        print("Taking more time to load.")

Element Not Found

This is one of the most common exceptions that occurs in Python with Selenium.
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
driver=webdriver.Firefox()
driver.get("https://apress.com")
try:
            web1 =driver.find_element_by_id("privacy")
        web1.click()
except NoSuchElementException as exception:
        print ("Web Element is not Available in the given Web Page.")

Stale Element

A stale element occurs when the web element is no longer present in the DOM. This exception is raised in the following program by submitting the web element after a while of its first submission. The handled exception is ignored or skipped that tries to terminate a test case. Similarly any exception can be handled. The same method can also be used for multiple exceptions that may occur in a test case.
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
import time
driver= webdriver.Firefox(')
driver.get('http://apress.com')
driver.find_element_by_name('query').send_keys('python selenium')
while True:
        try:
                      s=driver.find_element_by_class_name('search__submit')
                s.submit()
                time.sleep(2)
                s.submit()
        except StaleElementReferenceException:
                print('Stale Exception is Skipped.')
        break
driver.quit()
Note

Each exception in Selenium is handled in the same way that it is handled in Python (i.e., using the try-except method).

The exception handles the ignores or skips that terminate a test case. Any exception can be handled. The same method can also be used for multiple exceptions that may occur in a test case.

Summary

This chapter introduced and defined Selenium exceptions. You learned about the reasons to have Selenium exceptions in a test case.

Nearly all the exceptions that can occur in a Selenium test case were defined, and the reasons for their occurrence during test execution were explained. In the last section, you studied handling the most common exceptions in an example test case.

The next chapter discusses waits, in which a test case is delayed for a specified amount of time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.181.81