还是以我之前写过的一个脚本为例进行更改:
test_baidu.py
from selenium import webdriver import unittest import time class MyTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.maximize_window() self.driver.implicitly_wait(5) self.base_url = "http://www.baidu.com" def test_baidu(self): driver = self.driver driver.get(self.base_url + "/") driver.find_element_by_id("kw").clear() driver.find_element_by_id("kw").send_keys("unittest") driver.find_element_by_id("su").click() time.sleep(3) title = driver.title self.assertEqual(title, "unittest_百度搜索") def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main() |
from selenium import webdriver import unittest import time class MyTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.maximize_window() self.driver.implicitly_wait(10) self.base_url = "http://www.youdao.com" def test_youdao(self): driver = self.driver driver.get(self.base_url+"/") driver.find_element_by_id("translateContent").clear() driver.find_element_by_id("translateContent").send_keys("unittest") driver.find_element_by_xpath("/html/body/div[5]/div/form/button").click() time.sleep(3) title = driver.title self.assertEqual(title, "unittest - 有道搜索") def tearDown(self): # self.driver.close() pass if __name__ == '__main__': unittest.main() |
上面两个脚本,第一个可以通过,第二个则会失败。失败的原因很简单,就是断言出错。现在我们组织这两个用例,使得可以一次性执行。
假设上面两个脚本文件都在一个叫做 Webdriver 的文件夹里,那么我们在该文件夹内创建另一个文件 test.py。
test.py
import unittest test_dir = './' discover = unittest.defaultTestLoader.discover(test_dir,pattern='test*.py') if __name__ == '__main__': # 执行测试 runner = unittest.TextTestRunner() runner.run(discover) |
test.py执行结果如下:
/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/guxuecheng/Desktop/Webdriver/test.py .F ====================================================================== FAIL: test_youdao (test_youdao.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/guxuecheng/Desktop/Webdriver/test_youdao.py", line 22, in test_youdao self.assertEqual(title, "unittest - 有道搜索") AssertionError: '【unittest】什么意思_英语unittest的翻译_音标_读音_用法_例句_在线翻译_有道词典' != 'unittest - 有道搜索' - 【unittest】什么意思_英语unittest的翻译_音标_读音_用法_例句_在线翻译_有道词典 + unittest - 有道搜索 ---------------------------------------------------------------------- Ran 2 tests in 28.429s FAILED (failures=1) Process finished with exit code 0 |
从执行日志中我们可以看到,一共执行了2个用例(Ran 2 tests in 28.429s),其中有1个失败(FAILED (failures=1))。也可以看出是哪一个脚本失败以及失败原因。
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。