Python之Unittest和Requests库详解
1.按类来执行
import unittestclass f1(unittest.TestCase): def setUp(self):
pass
def tearDown(self):
pass
def test_001(self):
pass
def test_002(self):
pass
'''按类来执行'''if __name__ == '__main__':
suite = unittest.TestSuite(unittest.makeSuite(f1))
unittest.TextTestRunner(verbosity=2).run(suite)
2.加载测试模块来执行
import unittestfrom selenium import webdriverclass BaiduLink(unittest.TestCase): def setUp(self):
self.driver
=webdriver.Chrome() self.driver.maximize_window()
self.driver.implicitly_wait(
30) self.driver.
get(url="htttp://www.baidu.com") def tearDown(self):
self.driver.quit()
def test_001(self):
self.driver.find_element_by_link_text(
"新闻").click() def test_002(self):
self.driver.find_element_by_link_text(
"地图").click()'''加载测试模块来执行(TestLoader)'''if __name__ == '__main__':
suite=unittest.TestLoader().loadTestsFromModule(BaiduLink)
# suite=unittest.TestLoader().loadTestsFromModule("f2.py")
unittest.TextTestRunner(verbosity=2).run(suite)
3.优化测试套件
import unittestfrom selenium import webdriverclass BaiduLink(unittest.TestCase): def setUp(self):
self.driver
=webdriver.Chrome() self.driver.maximize_window()
self.driver.implicitly_wait(
30) self.driver.
get(url="htttp://www.baidu.com") def tearDown(self):
self.driver.quit()
def test_001(self):
self.driver.find_element_by_link_text(
"新闻").click() def test_002(self):
self.driver.find_element_by_link_text(
"地图").click() def suite(self):
suite
= unittest.TestLoader().loadTestsFromModule(BaiduLink)return suite'''加载测试模块来执行(TestLoader)'''if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(BaiduLink.suite())
4.skip的应用
5.批量执行测试用例discover
6.分离测试固件
7.生成测试报告
import unittestimport os
from testCase1 import HTMLTestRunner_cnimport time
'''批量执行所有的测试用例'''def allTests():
suite
= unittest.TestLoader().discover( start_dir
=os.path.dirname(__file__), pattern
="test_*.py", top_level_dir
=None )
return suitedef getNowTime():
return time.strftime("%Y-%m-%d %H_%M_%S",time.localtime(time.time()))def run():
# unittest.TextTestRunner(verbosity
=2).run(allTests()) fp
= os.path.join(os.path.dirname(__file__),"report",getNowTime() + "testReport.html") HTMLTestRunner_cn.HTMLTestRunner(
stream
=open(fp,"wb"), title
="自动化测试报告", description
="自动化测试报告详细信息" ).run(allTests())
if __name__ == '__main__': run()
8.
9.
10.关闭证书
11.cookie关联
12.对用户名密码的认证方式
13.session
14.上传文件
15.数据驱动操作elcel文件的操作方法
import xlrdimport os
from xlutils.copy import copydef base_dir(filename):
return os.path.join(os.path.dirname(__file__),filename)#
'''elcel文件的操作'''# work
= xlrd.open_workbook(base_dir("data.xls"))# sheet
= work.sheet_by_index(0)# #查看文件有多少行
# print(sheet.nrows)
# #获取单元格的内容
# print(sheet.cell_value(
2,2))'''excel文件内容的修改'''work
= xlrd.open_workbook(base_dir("data.xls"))old_content
=copy(work)ws
= old_content.get_sheet(0)ws.write(
4,2,"321")old_content.save(base_dir(
"data1.xls"))
以上是 Python之Unittest和Requests库详解 的全部内容, 来源链接: utcz.com/z/510254.html