Reputation: 530
I have a pytest script that has multiple classes which each have a set of test. Currently, each test within each class has the same TimeoutException defined. For example,
class Test1:
def test_1:
try:
"do something"
except TimeoutException:
"handle exception"
def test_2:
try:
"do something"
except TimeoutException:
"handle exception"
class Test2:
def test_3:
try:
"do something"
except TimeoutException:
"handle exception"
The "handle exception" part is where I have the same code for each module. I was wondering if there was a more pythonic way to do this. It seems sloppy to have the same lines pasted within each module for my TimeoutException handler.
Any help is appreciated and if more information is desired please let me know.
Thanks in advance!
Upvotes: 0
Views: 238
Reputation: 63
Maybe try to add some explicit waits for functions you want to handle. Explicit waits are dedicated especially for test cases, when you have individual logic for every test. I suppose your issue concerns selenium, as I see you tagged your question. You can define it in every test, for every element you want to wait for.
To implement such explicit wait, you can use the most popular tool designed for WebDrivers: WebdriverWait. You can set the Timeout duration and the conditions defined when the TimeoutException needs to be raised.
Here is and example from official Selenium site:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
finally:
driver.quit()
I modified this case a little bit according to your code and here is an example of customizing TimeoutException (in the simplest way ignoring Page Object Model):
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
class Test1:
def test_1:
try:
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "myDynamicElement")))
except TimeoutException:
"handle exception"
Another wait that is really awesome is the implicit wait, that sets overall timeout for all actions done by Selenium like this:
driver.implicitly_wait(10)
That means, the webdriver will wait ten seconds for an Webelement, and after that TimeoutException will be raised. However, this kind of wait should be treated as a global, case-independent wait.
I hope this answer helps.
Here you have a documentation how to do this: https://selenium-python.readthedocs.io/waits.html
Upvotes: 1