对百度搜索的一次web自动化测试

代码:

import unittest
from time import sleep
from selenium import webdriver

class TestBaiDu(unittest.TestCase):
@classmethod
#用setUp,每执行一条测试用例就会启动和关闭一次浏览器,所以此处用setUpClass
def setUpClass(cls):
cls.driver = webdriver.Chrome()
cls.base_url = “https://www.baidu.com/”

# 模块化,将搜索封装成一个方法
def baidu_search(self,search_key):
self.driver.get(self.base_url)
self.driver.find_element_by_id(“kw”).send_keys(search_key)
self.driver.find_element_by_id(“su”).click()
sleep(2)

def test_search_key_selenium(self):
search_key = “selenium”
self.baidu_search(search_key)
self.assertEqual(self.driver.title,search_key+”_百度搜索”)

def test_search_key_unittest(self):
search_key = “unittest”
self.baidu_search(search_key)
self.assertEqual(self.driver.title,search_key+”_百度搜索”)

@classmethod
def tearDownClass(cls):
cls.driver.quit()

if __name__ == ‘__main__’:
unittest.main()
结果:

Ran 2 tests in 17.891s

OK