user3174886
user3174886

Reputation: 301

How to test Alert/Popup in Selenium using Python

I'm stuck with my automation where when I enter wrong username and password it will pop up saying "Unable to login. Try different username"

def test_logonWrongUserName(self):
    self.setUpClass() # Initialize the driver 
    self.sh.navigateToUrl("http://test.com")
    self.sh.member_Login("Foo", "asd") 

Now need to test the Alert or popup (Not sure it is an alert or popup window) which has the text "Unable to login. Try different username". If it's find the text then the test pass. If not then the test has to fail.

Note:Just want to add, We can't access the html dom until we close the alert/popup window

Upvotes: 3

Views: 7659

Answers (1)

alecxe
alecxe

Reputation: 473873

You need to wait for the alert to be present, assert you have the expected text inside and then close/accept the alert:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present())

alert = driver.switch_to.alert
assert "Unable to login. Try different username" in alert.text
alert.accept()

Upvotes: 8

Related Questions