Python Selenium webdriver:不检测Alert生成也不提供Error

时间:2013-12-12 18:08:25

标签: python testing automation selenium-webdriver alert

*我正在使用Python中的Selenium Webdriver进行WebPage的测试用例自动化 *我需要验证网页上生成的警报消息 *使用Webdriver当我尝试处理警报时,它表示没有发现警报。即使我没有处理警报,它也不会给出任何错误消息(如生成的Unexcepted Alert)。 *请建议,为什么Webdriver没有检测到警报。

Code:

from selenium import webdriver  
from selenium.webdriver.common.by import By  
from selenium.webdriver.common.keys import Keys  
from selenium.webdriver.support.ui import Select  
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re

class Tcgr1(unittest.TestCase):  
    def setUp(self):  
        self.driver = webdriver.Firefox()                             
        self.driver.implicitly_wait(30)   
        self.base_url = "https://colama5863.co5863domain.net/infracc/app/Workspace#VMs"
        self.accept_next_alert = True

    def test_tcgr1(self):
        driver = self.driver
        driver.find_element_by_link_text("Settings").click()
        driver.find_element_by_link_text("Group Mgmt").click()
        driver.find_element_by_xpath("//button[contains(text(), \"Create\")]").click()
        driver.find_element_by_name("groupname").clear()
        driver.find_element_by_name("groupname").send_keys("tcgr1_group")
        driver.find_element_by_xpath("//span[2]/span/button[contains(text(), \"Create\")]").click()
        for i in range(60):
            try:
                if self.is_alert_present(): break
            except: pass
            time.sleep(1)
        else: self.fail("time out")
        self.assertEqual("Group created successfully", self.close_alert_and_get_its_text())

    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True

    def is_alert_present(self):
        try: self.driver.switch_to_alert()
        except NoAlertPresentException, e: return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally: self.accept_next_alert = True

    def tearDown(self):
        self.driver.quit()


if __name__ == "__main__":     
   unittest.main()

1 个答案:

答案 0 :(得分:0)

Webdriver按预期工作。在未执行的警报窗口上执行操作时, NoAlertPresentException会引发。切换到未显示的警报窗口时,它不会引发。

因此,您的功能代码需要对所谓的警报执行操作:

def is_alert_present(self):
    try: 
        alert = self.driver.switch_to_alert()  # this doesn't raise Exception
        alert.text  # this DOES RISE Exception if there isn't an alert
        return True

    except NoAlertPresentException:
        return False