unittest框架结构
test_case:
测试套件,每一个.py文件代表一个测试用例,测试用例以test开头,否则框架读取不到测试用例
__init__.py是做什么的?
要弄明白这个问题,首先要知道,python 在执行 import 语句时,到底进行了什么操作,按照 python 的文档,它执行了如下操作:
第 1 步,创建一个新的,空的 module 对象(它可能包含多个 module);
第 2 步,把这个 module 对象插入 sys.module 中
第 3 步,装载 module 的代码(如果需要,首先必须编译)
第 4 步,执行新的 module 中对应的代码。
在执行第 3 步时,首先要找到 module 程序所在的位置,搜索的顺序是:
当前路径 (以及从当前目录指定的 sys.path),然后是 PYTHONPATH,然后是 python 的安装设置相关的默认路径。
正因为存在这样的顺序,如果当前路径或 PYTHONPATH 中存在与标准 module 同样的 module,则会覆盖标准 module。也就是说,如果当前目录下存在 xml.py,那么执行 import xml 时,导入的是当前目录下的 module,而不是系统标准的 xml。了解了这些,我们就可以先构建一个 package,以普通 module 的方式导入,就可以直接访问此 package中的各个 module 了。python 中的 package 必须包含一个__init__.py 的文件
public:存放测试用例所调用的公共模块
data:存放用于参数化的数据
report:存放测试报告
all_tests.py:执行test_case中的测试用例
qq邮箱登录测试用例:
1 #encoding:utf-8 2 from selenium import webdriver 3 import time 4 5 import unittest 6 from selenium.common.exceptions import NoSuchElementException 7 8 class Login(unittest.TestCase): 9 def setUp(self): 10 self.driver = webdriver.Chrome() 11 self.driver.get("https://mail.qq.com/") 12 self.driver.maximize_window() 13 def test_login(self): 14 #先跳转到frame框架 15 self.driver.switch_to.frame('login_frame') 16 time.sleep(3) 17 #self.driver.find_element_by_css_selector("#qqLoginCard").click() 18 self.driver.find_element_by_id('u').send_keys('[email protected]') 19 self.driver.find_element_by_id("p").send_keys('jing69602') 20 self.driver.find_element_by_id("login_button").click() 21 time.sleep(10) 22 23 #try: 24 # text = self.driver.find_element_by_id('useralias').text 25 # print(text) 26 # return True 27 #except: 28 # return False 29 30 def tearDown(self): 31 self.driver.quit() 32 33 34 if __name__ == '__main__': 35 unittest.main
all_test.py
1 #encoding:utf-8 2 import unittest 3 import HTMLTestRunner 4 import os,time 5 listaa = 'D:\\unittest\\test_case' #测试用例所在目录 6 def creatsuite1(): 7 testunit = unittest.TestSuite() 8 discover = unittest.defaultTestLoader.discover( #用discover读取测试用例 9 listaa, 10 pattern='*.py', 11 top_level_dir=None 12 ) 13 for test_suite in discover: 14 for test_case in test_suite: 15 testunit.addTests(test_case) 16 print(testunit) 17 return testunit 18 19 alltestnames = creatsuite1() 20 21 now = time.strftime('%Y-%m-%d-%H_%M_%S',time.localtime())#获取当前时间并设置时间格式 22 filename = "D:\\unittest\\test_case\\report"+now + "result.html" #将测试报告存到本地 23 24 fp = open(filename,'wb') 25 26 runner = HTMLTestRunner.HTMLTestRunner( #设置测试报告格式 27 stream=fp, 28 title= u'qq登录测试报告', 29 description=u'用例执行情况' 30 ) 31 32 runner.run(alltestnames)#运行测试用例并生成测试报告