# 运行单个测试用例 # test = unittest.TestLoader().loadTestsFromName # (name='Test_function_demo.test_multi_list', module=test_function_demo) # 运行多个测试用例 # test = unittest.TestLoader().loadTestsFromNames(names=['Test_function_demo.test_multi_list', # 'Test_function_demo.test_div_exception'], # module=test_function_demo) # 将测试用例添加到测试用例集 suites.addTests(test) print(unittest.TestLoader().getTestCaseNames( testCaseClass=Test_function_demo)) # 生成本地文件测试报告 # with open('function_test.txt', 'a') as file: # # 创建一个运行器,运行测试用例集,并输出测试报告 # runner = unittest.TextTestRunner(stream=file, descriptions='测试报告', verbosity=2) # runner.run(suites) # 生成HTML测试报告 # with open("function_test.html", 'w', encoding='utf-8') as file: # runner = HTMLTestRunner.HTMLTestRunner(stream=file, title='测试报告', description='这是第一次执行用例的测试报告!', verbosity=2) # runner.run(suites) result = BeautifulReport(suites) result.report(filename="测试报告.excel", description="函数测试报告", report_dir='/', theme='theme_cyan')
def test_selfMap3(self): print("自己和自己比对哦~~~") operation = sample.SampleSolve3(order5, origin5, swap5, step5) if len(operation) > 0: raise SameMapError def test_findAnswerAfterSwapMap3(self): print("正在处理交换后得解的样例……") operation = sample.SampleSolve3(order6, origin6, swap6, step6) if len(operation) < step6: raise SwapError def test_answerOnlyBySwapMap3(self): print("正在处理只交换就出解的样例……") operation = sample.SampleSolve3(order7, origin7, swap7, step7) if operation[0] != ' ': raise MoveError if __name__ == '__main__': #unittest.main() tests = unittest.makeSuite(KlotskiTestCase) runner = BeautifulReport(tests) # => tests是通过discover查找并构建的测试套件 runner.report( description='华容道测试报告', # => 报告描述 filename='Klotski.html', # => 生成的报告文件名 log_path='.' # => 报告路径 )
def load_tests(loader, tests, pattern): suite = unittest.defaultTestLoader.discover(CASE_PATH,pattern='test_*.py') result = BeautifulReport(suite) tl = time.strftime('%Y%m%d%H%M', time.localtime()) result.report(filename='report{}.html'.format(tl), description='测试deafult报告', log_path=report_path)
# 正文模块 msg_raw = open(file_path, "r", encoding='utf-8').read() # 打开 msg = MIMEText(msg_raw, 'html') msg_total.attach(msg) # 附件模块 mfile = MIMEApplication(open(file_path, "rb").read()) # 读取测试报告内容 mfile.add_header('Content-Disposition', 'attachment', filename=name[-1]) # 添加附件的头信息 # 附件摸快添加到总的里面 msg_total.attach(mfile) smtp = smtplib.SMTP_SSL(s_server, 465) smtp.login(user, password) smtp.sendmail(user, to_email, msg_total.as_string()) smtp.quit() if __name__ == "__main__": test_suite = unittest.defaultTestLoader.discover('./case', pattern='t*.py') result = BeautifulReport(test_suite) result.report(filename=currentime + '测试报告', description='测试报告', log_path='./report') # report = repotr_path(file_path) # e = ['*****@*****.**'] # 多个收件人 # email(report, e)
# -*- coding: utf-8 -*- # @Time : 2019/7/24 13:43 # @Author: GaoJun import unittest from selenium import webdriver import time from BeautifulReport import BeautifulReport from .test_my_wifi import MyWifi from unittest import TestLoader def core(): s = [] class_tests = [MyWifi] for t in class_tests: suite = TestLoader().loadTestsFromTestCase(t) s.append(suite) t_s = unittest.TestSuite(s) return t_s if __name__ == '__main__': t_suites = core() result = BeautifulReport(t_suites) result.report(filename="WebUI-调试", description='Router-UiAuto测试报告', log_path='report/')
import os import sys import unittest import time from BeautifulReport import BeautifulReport from setting import CASE_PATH, REPORT_PATH from lib.send_mail import new_file, send_mail #查找用例 discover = unittest.defaultTestLoader.discover(CASE_PATH, "test_login.py") #执行并生成报告 title = "接口测试" time_now = time.strftime("%Y%m%d%H%M%S") report_name = "%s-接口测试报告" % (time_now) runner = BeautifulReport(discover) runner.report(description=title, filename=report_name, report_dir=REPORT_PATH) new_report_mail = new_file(REPORT_PATH) # log.info(new_report_mail) send_mail(new_report_mail) # fp.close() # pattern=
import unittest import os, sys, time from BeautifulReport import BeautifulReport from common.smtpOperation import Email case_path = sys.path[0]+"\\testcase" current_path = os.getcwd() report_path = os.path.join(current_path, "testreport") now = time.strftime("%Y-%m-%d_%H%M%S", time.localtime(time.time())) # 报告地址&名称 report_title = now +"_智能家居接口自动化测试报告.html" # 如果不能打开这个文件,可能是now的格式,不支持:和空格 # 报告描述 desc = '智能家居接口自动化测试' if __name__ == '__main__': suite = unittest.TestSuite() discover = unittest.defaultTestLoader.discover(case_path, pattern="test*.py") suite.addTest(discover) # suite.addTest(unittest.TestLoader().loadTestsFromTestCase(testCaseClass=test_GetRoomList.GetRoomListApi)) # suite.addTest(unittest.TestLoader().loadTestsFromTestCase(testCaseClass=test_CreateRoom.CreateRoomApi)) run = BeautifulReport(suite) run.report(description=desc, filename=report_title, log_path=report_path) em = Email() em.send(report_path+os.sep+report_title)
self.driver.implicitly_wait(10) self.driver.set_window_size(1366, 768) self.login_driver = LoginPage.login(self.driver, self.url, 'wjx', 'Admin123', 'ad') self.database = pymysql.connect(host='192.168.219.227', port=3306, user='******', password='******', db='csc') def test_switch_dc(self): '''切换数据中心''' homepage = HomePage(self.login_driver, self.url) # 选择某个数据中心的数据 homepage.dc_select('DC-PVC') print(homepage.dc_check()) print(homepage.db_check(self.database, 'DC-PVC')) def tearDown(self): self.driver.close() self.database.close() if __name__ == '__main__': TEST_SUITE = unittest.defaultTestLoader.discover(r'.\testcase', pattern='*_homepage.py') RESULT = BeautifulReport(TEST_SUITE) RESULT.report(filename='CSC7.0自动化测试报告_首页', description='首页模块测试报告', log_path='report')
import unittest from xml.etree import ElementTree as ET import HTMLTestReportCN from BeautifulReport import BeautifulReport if __name__ == '__main__': et = ET.parse('/Users/air/Documents/bill/config.xml') # print(len(et.findall('./cases/*'))) # 查询节点下测试用例的数量是否正确 li = et.findall('./cases/*') suite = unittest.TestSuite() for i in li: # print(i.tag) # 如何动态引入包,可以选择spit切割,如下: class_name = i.tag.split('-')[0] # print(class_name) #验证一下切割的对不对 method_name = i.tag.split('-')[1] exec('import %s' % class_name) # 导入包 exec("suite.addTest(%s.%s('%s'))" % (class_name, class_name, method_name)) # unittest.TextTestRunner().run(suite) result = BeautifulReport(suite) result.report(filename='测试报告', description='测试deafult报告', log_path='/Users/air/Documents/bill/测试报告') # HTMLTestReportCN.HTMLTestRunner(stream=open('./report.html', 'wb')).run(suite)
from .test_blacklist import Blacklist from .test_guestWifi import GuestWifi from .test_vpn import VPN from .test_devices import Devices def core(): s = [] class_tests = [ # 建议执行顺序(倒序排如下): # 管理路由器、管理密码、工作方式、限时(?如果被限制住未删掉情况怎么处理) # LimitTime, LimitRate,LimitWebsiteBlacklist GuestWifi, VPN, RouterManagement ] for t in class_tests: suite = TestLoader().loadTestsFromTestCase(t) s.append(suite) t_s = unittest.TestSuite(s) return t_s if __name__ == "__main__": t_suites = core() result = BeautifulReport(t_suites) log_path = 'report/rweb' if not os.path.exists(log_path): os.makedirs(log_path) result.report(filename="路由器Web自动化测试", description="路由器Web自动化测试报告", log_path=log_path)
#报告存放路径 #report_path = os.path.join('./test_report/') def all_case(): for case_path in case_paths: discover = unittest.defaultTestLoader.discover(case_path, pattern="test_demo.py", top_level_dir=None) return discover if __name__ == '__main__': result = BeautifulReport(all_case()) result.report(filename=u'demo自动化测试报告.html', description=u'接口调用自动化回归测试', report_dir='./test_report/') # import unittest # import HTMLTestRunnerNew # import sys # sys.path.append("..") # from test_case.test_demo import DeomTest # suite=unittest.TestSuite() # loader=unittest.TestLoader() # #加载 # suite.addTest(loader.loadTestsFromTestCase(DeomTest)) # #执行
# 添加1个用例 addTest(类名("用例名")) 添加一个测试用例 # s.addTest(TestLogin("test_login_ok")) # 添加多个用例 # s.addTests([TestLogin("test_login_ok"),TestLogin("test_login_wrong_user")]) # 从start_directory这个目录下开始,搜索所有的测试用例,并加载到测试套件当中。 # 1、指定搜索目录 # 2、文件过滤规则:以文件名匹配。test*.py # 3、在文件当中过滤用例:继承了unittest.TestCase类的测试类,类当中以test_开头的测试函数。 s = unittest.TestLoader().discover(r"D:\Pychram-Workspace\py30") print(type(s)) print(s) # 运行测试用例并生成结果 # runner = unittest.TextTestRunner() # runner.run(s) # 运行测试用例并生成html的结果 from HTMLTestRunnerNew import HTMLTestRunner # 创建一个html文件,以写的模式打开,支持中文 with open("report.html", "wb") as fs: # 运行测试用例,将结果写html当中 runner = HTMLTestRunner(fs, title="py30期单元测试报告", tester="小简") runner.run(s) from BeautifulReport import BeautifulReport br = BeautifulReport(s) br.report("py30期单元测试报告", "bp_report.html")
def run_test(path: str = 'testCase'): """ :param path: With default path testcase, the method will execute all testcases, otherwise it only execute the cases which in the specific path :return: test report """ host = g.host method = g.get_info('config_info', 'method') testsuits = TestSuite() report_name = "{}_{}".format(path, str(datetime.now().strftime("%Y%m%d%H%M%S"))) copyname = 'testReport/test_api_ressult.html' # 保证连接正常,testdata做了断网简单兼容,此处也做兼容 if host == "http://backend.pre.igengmei.com": host = "https://backend.igengmei.com" try: a = requests.get(f"http://{g.server_host}/testapi/checkedapi/", params={ 'env': host, "method": method }).json() with open(case_file, 'w', encoding='utf-8') as f: f.write(json.dumps(a)) except Exception: with open(case_file, 'r', encoding='utf-8') as f: _data = f.read() a = eval(_data) _a = copy.deepcopy(a) for case in a: _unit = unittest.defaultTestLoader.discover(path, pattern=case + '_test.py', top_level_dir='testCase') # print(_unit.__dict__) if case=='account_login_login_vfc' else None if _unit.__dict__.get('_tests'): testsuits.addTest(_unit) _a.remove(case) result = BeautifulReport(testsuits) result.report(filename=report_name, description="API接口", log_path='testReport') shutil.copy('testReport/%s.html' % report_name, copyname) result_list = [item for item in result.result_list if item[4] != '成功'] # 我们需要获取已经记录但是没有写脚本的接口和case,收录在_a中 from PIL import Image, ImageDraw, ImageFont length, weight_unit = 1000, 20 back_img = Image.new(mode='RGB', size=(length, weight_unit * ((len(result_list) or 1) + len(_a) + 2)), color=(255, 255, 255)) draw_img = ImageDraw.ImageDraw(back_img) font = ImageFont.truetype('arial.ttf', size=weight_unit, encoding='gbk') num = 0 if len(result_list) == 0: draw_img.text((0, weight_unit * num), 'ALL PASS!', font=font, fill='green') num += 1 for item in result_list: draw_img.text((0, weight_unit * num), item[0] + ':' + item[1], font=font, fill='red') num += 1 if _a: draw_img.text((0, weight_unit * num), 'The following interface scripts are missing!!', font=font, fill='red') num += 1 for item in _a: draw_img.text((0, weight_unit * num), item, font=font, fill='blue') num += 1 back_img.save('testReport/error.jpg') if len(result_list) > 0: #主动跑错 raise Exception('有接口没有执行通过!')
def run(test_suit): result = BeautifulReport(test_suit) result.report(filename='report.html', description='jxc_test', log_path='reports')
# -*- coding: utf-8 -*- # @Time : 2021/2/21 9:45 下午 # @Author : Lewin # @FileName: main.py # @Software: PyCharm import unittest from BeautifulReport import BeautifulReport ts = unittest.TestLoader().discover("/Users/lewin/pythonProject/柠檬班/day15") if __name__ == '__main__': br = BeautifulReport(ts) br.report('lewin的报告', "report.html")
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/8/12 15:32 # @Author : whj import unittest import os, sys import time from common.sendEmail import SendEmail from BeautifulReport import BeautifulReport from test_case.test11_01 import * path = os.path.abspath(os.path.join(os.getcwd(), "..")) sys.path.append(path) # 测试用例目录 test_dir = os.path.join(os.path.dirname(__file__), "test_case") # 测试报告目录 reportPath = os.path.join(os.path.dirname(__file__), "report") # print(test_dir) # print(reportPath) # 加载测试用例 discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py') pattern = 'test_*.py' now = time.strftime("%Y-%m-%d %H_%M_%S") reportName = now + '测试报告.html' description = 'H5自动化测试报告' if __name__ == '__main__': test_suite = unittest.defaultTestLoader.discover(test_dir, pattern=pattern) result = BeautifulReport(test_suite) result.report(filename=reportName, description=description, log_path=reportPath) # 发送邮件 # SendEmail.send_email()
#coding=utf-8 import unittest from airtest.core.api import * from BeautifulReport import BeautifulReport def case_all(): print('开始调用例进行测试') # testcase_dir=os.path.join(os.getcwd(),'../TestCase') testcase_dir = "../TestCases/" discovery = unittest.defaultTestLoader.discover(testcase_dir, pattern='*.py', top_level_dir=None) return discovery #HTMLTestRunner测试报告 # if __name__=="__main__": # report=open("../run_report/1.html",'wb') # runner=HTMLTestRunner.HTMLTestRunner(stream=report,title=u'2D游戏测试报告',description=u'2D测试用例结果情况',tester=u'2D测试组') # runner=unittest.TextTestRunner() # runner.run(case_all()) # result = BeautifulReport(case_all()) # result.report(filename='测试',description='测试deafult报告',log_path='') #BeautifulReport测试报告 if __name__ == '__main__': # test_suite = unittest.defaultTestLoader.discover('../othermobile', pattern='*.py') result = BeautifulReport(case_all()) result.report(filename='2D测试报告', description='2D测试报告', log_path='../run_report')
from BeautifulReport import BeautifulReport class GetUserTest(unittest.TestCase): def tearDown(self): print('tear down...') def setUp(self): print('tear...up') def test_get_user(self): self.assertEquals(10, 10) def test_get_user2(self): self.assertIn(10, [10, 9]) if __name__ == '__main__': my_test_suite = unittest.TestSuite() my_test_suite.addTest(GetUserTest('test_get_user')) my_test_suite.addTest(GetUserTest('test_get_user2')) # fp = open('my_report_01.html', 'wb') # runner = HTMLTestRunner.HTMLTestRunner( # stream=fp, # title='unite test', # description='This demonstrates the report output by HTMLTestRunner.' # ) # runner.run(my_test_suite) result = BeautifulReport(my_test_suite) result.report(filename='测试报告', description='测试deafult报告', report_dir='report', theme='theme_default')
def run_testcase(sample, start): """ :param sample: 实例化参数 :param start: 唯一标识 :return: 没有返回值 """ devices = sample.get_momentdevices() # 获取设备列表 devices_list = sample.get_deviceslist() # 获取测试类型 True=兼容,False=分布 testtype = sample.get_testtype() uwatepe = sample.get_uwatype() devices_name = os.popen( f"adb -s {devices} shell getprop ro.product.model").read().replace( ' ', '') nowtime = f'{time.strftime("%Y-%m-%d-%H-%M-%S", start)}' # 得到config中的所有待测用例 config_Test_List = sample.get_testcase() # 根据测试类型获取testcase下的所有用例 if uwatepe == '1': case_path = '/AirtestIDE/AutoTest_Project_DRInland/multi_processframe/TestCaseUWA' report_Name = devices_name.split()[0] + "-UWA_" + str(nowtime) else: case_path = '/AirtestIDE/AutoTest_Project_DRInland/multi_processframe/TestCase' report_Name = devices_name.split()[0] + "-BTV_" + str(nowtime) script_list = get_script_list(case_path) # 创建报告目录 report_path = (os.path.abspath( os.path.join(os.getcwd(), f"../platform/static/Report/{report_Name}"))) if not os.path.exists(report_path): os.makedirs(report_path + '/Screenshot') os.makedirs(report_path + '/data') os.makedirs(report_path + '/script') # 复制文件到报告 tempjs = (os.path.abspath( os.path.join(os.getcwd(), f"../platform/static/Report/script/highcharts.js"))) scriptjs = report_path + '/script' shutil.copy(tempjs, scriptjs) # 实例化测试套件 suite = unittest.TestSuite() cases = [] # 定义一个空的待测用例列表 for i in range(len(config_Test_List)): # 循环遍历 file_Name = "TC_" + config_Test_List[i] # 把配置列表中的用例加上tc标志 if file_Name in script_list: if testtype == "True": # 测试类型,如果是typeTest=1,就是兼容测试,否则就是单分测试 result = globals()[file_Name].Main(start, devices) suite.addTests(result) else: cases.append(file_Name) if i == len(config_Test_List) - 1: # 当TestCase全部用例循环加载之后 for b in range(devices_list.index(devices) + 1): # 根据设备的数量循环把用例分成若干等分 split_cases = cases[math.floor( b / len(devices_list) * len(cases)):math.floor( (b + 1) / len(devices_list) * len(cases))] # 到这里已经把当前用例给分片了 for c in range(len(split_cases)): result = globals()[split_cases[c]].Main(start, devices) suite.addTests(result) unittest_Report = BeautifulReport(suite) if uwatepe == '1': unittest_Report.report(filename=report_Name, description="龙之谷国内版本--UWA性能测试", report_dir=report_path) mailtype = 1 # UWA性能测试报告 else: unittest_Report.report(filename=report_Name, description="龙之谷国内版本--BTV功能测试", report_dir=report_path) mailtype = 0 # BTV功能测试报告 receivers = sample.get_email() if receivers != '': sendemail(report_Name, receivers, mailtype)
import unittest from BeautifulReport import BeautifulReport from common.handle_logging import log from common.handle_path import CASE_DIR, REPORT_DIR log.info( "---------------------------------------开始执行测试用例---------------------") # 创建测试套件 suite = unittest.TestSuite() # 加载用例套件 loader = unittest.TestLoader() suite.addTest(loader.discover(CASE_DIR)) bf = BeautifulReport(suite) bf.report("withdraw接口", filename="audit_report.html", report_dir=REPORT_DIR) log.info( "---------------------------------------测试用例执行完毕---------------------")
def create_beautiful(): result = BeautifulReport(discover) result.report(filename='接口测试报告', report_dir=report_path, description=now + '指标库接口数据验证')
# -*- coding:utf-8 -*- ''' @Author : xiaoyin_ing @Email : [email protected] @Software: PyCharm @File : main.py @Time : 2020/7/3 9:55 @Desc : 生成测试报告 ''' from unittest import TestLoader from BeautifulReport import BeautifulReport from Common.handle_path import cases_dir, reports_dir, local_time test_suit = TestLoader().discover(cases_dir) br = BeautifulReport(test_suit) report_module_name = local_time + "-keyou测试平台-v1.0-接口测试" report_name = local_time + "-keyou测试平台v1.0-接口—测试报告.html" br.report(report_module_name, report_name, reports_dir)
#!/usr/bin/env python # -*- coding: utf-8 -*- # encoding: utf-8 ''' # @Time : 2020/11/20 3:18 下午 # @Author : yantianpeng # @Site : # @File : main.py # @Software: PyCharm ''' import unittest from day_11.test_register import Test_Register from BeautifulReport import BeautifulReport if __name__ == '__main__': # suit = unittest.TestSuite(); # suit.addTest(Test_Register('test_register_ok')); # suit.addTest(Test_Register('test_register_agrsIsNull')); tld = unittest.TestLoader().discover('.') br = BeautifulReport(tld) br.report('闫天蓬', 'report_register.html')
def run(testmethod): if testmethod: result = BeautifulReport(testmethod) result.report(filename='report.html', description='test', log_path=reportpath)
import unittest2 as unittest from BeautifulReport import BeautifulReport if __name__ == '__main__': test_suite = unittest.defaultTestLoader.discover('./tests', pattern='test*.py') result = BeautifulReport(test_suite) result.report(filename='测试报告', description='测试deafult报告', log_path='.')
#!/usr/bin/env python # -*- coding: utf-8 -*- # encoding: utf-8 ''' # @Time : 2020/12/24 1:38 下午 # @Author : yantianpeng # @Site : # @File : main.py # @Software: PyCharm ''' import unittest from BeautifulReport import BeautifulReport if __name__ == '__main__': tld = unittest.TestLoader().discover(".") bf = BeautifulReport(tld) bf.report("闫天蓬", "report.html")
expected_conditions.presence_of_element_located((By.XPATH, "//*[@id='button1']"))) self.driver.find_element_by_xpath("xpath=//*[@id='button1']").click() time.sleep(3) self.driver.find_element_by_xpath("xpath=//*[@contentDescription='drawer opened']").click() self.driver.find_element_by_xpath("//*[@id='qbu_tv_account_subtitle']") flag = self.driver.find_element_by_xpath("//*[@id='qbu_tv_account_subtitle']").text assert flag == "CloudLink" """ def test_minus(self): print("5") #@classmethod def tearDown(self): print("close") self.driver.quit() if __name__ == '__main__': suite = unittest.TestSuite() #tests = ["test_minus1", "test_uu", "test_add", "test_mul", "test_minus"] for i in range(settings.loop_times): suite.addTests(unittest.makeSuite(Login)) # suite.addTests(unittest.TestLoader().loadTestsFromTestCase(yu)) #suite = unittest.TestSuite(map(yu, tests)) # suite.addTests(suite1) print(suite) result = BeautifulReport(suite) result.report(description=des, filename=report_title, log_path=report)
import unittest #引入自动化测试框架 import time #引入时间模块 from BeautifulReport import BeautifulReport #引入自动化测试报告模板 suite = unittest.defaultTestLoader.discover("../cases", "case*.py") # now = time.strftime("%Y%m%d%H%M%S") filename = "crm-report-{}.html".format(now) runner = BeautifulReport(suite) runner.report(description="登录用例", filename=filename, report_dir="../report")
import os from BeautifulReport import BeautifulReport """ 此类运行所有Case """ class RunCase(): def test_case01(self): #如果当前路径还有包的话则这样写case_path = os.path.join(os.getcwd(),'case_manage') #join连接当前路径 case_path = os.path.join(os.getcwd(), 'package_selenium\case') #引入Case文件,传参(路径,文件) suite = unittest.defaultTestLoader.discover(case_path, '*_case.py') unittest.TextTestRunner().run(suite) if __name__ == "__main__": #unittest.main() print("开始自动化测试") case_path = os.path.join(os.getcwd(), 'package_selenium\case') test_suite = unittest.defaultTestLoader.discover(case_path, '*_case.py') #test_suite = unittest.defaultTestLoader.discover("D:\AGZRuanJian\KuaiJie\公司\Git\csp-help-borrow-automation\src\seleniumMain_master\package_selenium\case",'*_case.py') result = BeautifulReport(test_suite) result.report(filename='测试报告3', description='测试deafult报告3', log_path=os.getcwd()) #result.report() print("输出报告了")
def run(): now_time = time.strftime('%Y_%m_%d %H_%M_%S', time.localtime(time.time())) result = BeautifulReport(all_case()) result.report(filename=now_time, description='pg3.0_TestReport', log_path=report_path())