一、下面是it.py 脚本,把浏览器前置和后置条件分离了
"""套件公用测试类可进行分离"""
import unittest
from selenium import webdriver
class Init(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(30)
self.driver.get("Http://www.baidu.com")
def tearDown(self):
self.driver.quit()
二、BaiduLink 继承 Init的类
"""套件分离测试"""
import unittest
from unittest_1.it import Init
class BaiduLink(Init):
def test_baidu_news(self):
self.driver.find_element_by_link_text('新闻').click()
def test_002(self):
self.driver.find_element_by_link_text('地图').click()
# 静态方法,直接调用suite方法
@staticmethod
def suite():
suite = unittest.TestSuite(unittest.makeSuite(BaiduLink))
return suite
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(BaiduLink.suite())
三、小牛试刀,结合浏览器对百度业务进行单元测试
from unittest_1.it import *
import unittest
class BaiduLink(Init):
def test_baidu_shouye(self):
"""百度业务,测试百度的title是否正确"""
self.assertEqual(self.driver.title,"百度一下,你就知道")
# self.assertEqual(self.driver.title,"百度一下,你就知道".encode("gdk"))
def test_baidu_title(self):
if self.driver.title == "百度一下,你就知道":
print("pass")
else:
print("Fail")
def test_baidu_title(self):
try:
self.assertEqual(self.driver.title,"百度一下,你就知道")
except Exception as e:
print("Fail info:{0}".format(e.args))
def test_baidu_login(self):
"""断言so 是否为真,返回的为 bool 型"""
so= self.driver.find_element_by_id("kw")
self.assertTrue(so.is_enabled())
def test_baidu_title(self):
"""断言百度是否再title里面"""
self.assertIn("百度",self.driver.title)
if __name__ == '__main__':
#把BaiduLink模块类加载到测试套件中,然后执行测试用例操作
suite = unittest.TestLoader().loadTestsFromModule(BaiduLink)
unittest.TextTestRunner(verbosity=2).run(suite)
四、测试执行
import unittest
from selenium import webdriver
class BaiduLink(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(30)
self.driver.get("Http://www.baidu.com")
def tearDown(self):
self.driver.quit()
def test_baidu_news(self):
self.driver.find_element_by_link_text("新闻").click()
def test_baidu_map(self):
self.driver.find_element_by_link_text("地图").click()
class BaiduSo(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(30)
self.driver.get("Http://www.baidu.com")
def tearDown(self):
self.driver.quit()
def test_baidu_so(self):
self.driver.find_element_by_id("kw").send_keys("webdriver")
self.driver.find_element_by_id("su").click()
if __name__ == '__main__':
"""执行F7中所有的用例,TestLoader加载测试类"""
suite = unittest.TestLoader().loadTestsFromModule("test_runnrt.py")
unittest.TextTestRunner(verbosity=2).run(suite)