unnitest是Python语言下的单元测试框架,可能大家会有疑问,这与自动化测试工具selenium有什么关系,在selenium IDE中我们录制的脚本可以通过Export Test Case As导出Python 2/unittest/WebDriver形式,如下图所示,所以学习unittest可以更好的修改和完善selenium IDE录制的脚本。
之前有同事分享过unittest单元框架的介绍,请结合其他人写的介绍,查看下面的实例,例子是演示DLMMCP系统登录的unittest单元测试,其中具体的细节也在注释中表明了,请查看。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | #!/usr/bin/python # -*- coding: utf-8 -*- ############################################################# #操作:通过unittest单元测试框架测试DLMMCP系统登录 #version:V1.0 #author:ZLL ############################################################## 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 from selenium.common.exceptions import NoAlertPresentException import unittest, time, re class UnittestLogin(unittest.TestCase): ''' 初始化。 ''' def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.base_url = "http://192.168.39.141:8080/" self.verificationErrors = [] #脚本运行时的错误信息将被记录到这个数组中 self.accept_next_alert = True #是否继续接受下一个警告,初始状态为True ''' 登录脚本。 ''' def test_unittest_login(self): driver = self.driver driver.get(self.base_url + "dlmmcp/index.action") driver.find_element_by_id("username").clear() driver.find_element_by_id("username").send_keys("yjs") driver.find_element_by_id("password").clear() driver.find_element_by_id("password").send_keys("yjs12345678") driver.find_element_by_id("enter").click() time.sleep(3) ''' 用于查找页面元素是否存在,通过find_element()来接收元素的定位方法和定位值, 如果定位到元素,则返回为True,否则抛出异常并返回false。 ''' def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException as e: return False return True ''' 用于判断当前页面是否存在警告框,利用WebDriver提供的switch_to_alert()方法来 捕捉页面上的警告框。如果捕捉到警告框则返回True,否则抛出异常并返回false。 ''' def is_alert_present(self): try: self.driver.switch_to_alert() except NoAlertPresentException as e: return False return True ''' 关闭警告并获得警告信息。通过switch_to_alert()获得警告,通过text获得警告框信息。 通过if语句判断accept_next_alert的状态,在setUP()中已经初始化状态为True,如果 为True,如果为True,则通过accept()接受,否则dismiss()忽略此警告。 ''' 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() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() |