def run_suite(suites, suitename): testsuite = unittest.TestSuite() for suite in suites: casedict = suite['case'] apidic = suite['api'] testsuite.addTest( SimpleTest(methodName=casedict['examineType'], casedict=casedict, apidic=apidic)) report_path = os.path.join(urls.get_media_root(), 'report') # report_path = os.path.join(BASE_DIR, 'report') now = datetime.datetime.now().strftime('%Y%m%d%H%M%S') try: run = bf(testsuite) run.title = suitename + now filename = suitename + now + '.html' run.report(description='', filename=filename, report_dir=report_path) except Exception as e: print(e) return run # if __name__ == '__main__': # newdata = [{'case': {'id': 1, 'casename': '测试用例', 'relateapi': '测试接口1', 'examineType': 'only_check_status', # 'expecthttpCode': '200', 'expectdata': 'get_succees', 'createtime': '2020-04-05', 'creater': 'admin'}, # 'api': {'id': 1, 'name': '测试接口1', 'requestType': 'GET', 'apiAddress': 'http://127.0.0.1:8000/testapi/', # 'head': "{\r\n'xxx':'xxx'\r\n}", 'data': '', 'description': '', 'createtime': '2020-04-05 08:19:12', # 'creater': 'admin'}}, { # 'case': {'id': 3, 'casename': '测试用例2', 'relateapi': '测试接口2', 'examineType': 'only_check_status', # 'expecthttpCode': '200', 'expectdata': 'value is right', 'createtime': '2020-04-06', # 'creater': 'admin'}, # 'api': {'id': 2, 'name': '测试接口2', 'requestType': 'POST', 'apiAddress': 'http://127.0.0.1:8000/testapi/', # 'head': '', 'data': "{'value':'i',}", 'description': '', 'createtime': '2020-04-09 08:38:42', # 'creater': 'admin'}}] # run_suite(newdata,'testsuite')
def test_case(param): suite = unittest.TestSuite() suite.addTest( ParametrizedTestCase.parametrize(TestMathFunc, param=param)) unittest.TextTestRunner(verbosity=2) run = bf(suite) run.report(filename='test', description='芝麻快译测试环境单用户功能测试')
def run_case(all_case, reportpath=report_path): '''执行所有的用例, 并把结果写入测试报告''' reportName = "接口测试报告.html" runner = bf(all_case) runner.report(description="接口测试", filename=reportName, log_path=report_path)
def run_all_case(): suite = unittest.TestSuite() all_py = unittest.defaultTestLoader.discover(CASE_PATH, '*.py') #寻找Py文件 [suite.addTests(py) for py in all_py] #将测试用例(class)添加到测试集 run = bf(suite) today = datetime.datetime.today().strftime('%Y%m%d%H%M%S') title = '%s_接口测试报告.html' % today report_abs_path = os.path.join(REPORT_PATH, title) # report_abs_path = os.path.join('.',title) run.report(title, filename=title, log_path=REPORT_PATH) return run.success_count, run.failure_count, report_abs_path
def RunnerBeautifulReport(self): suite = unittest.TestLoader().loadTestsFromTestCase(RunnerTestCase) runner = bf(suite) report_path = REPORT_PATH# 报告存放位置 timestr = time.strftime('%Y%m%d%H%M', time.localtime(time.time())) filename = report_path+'\\'+timestr+'.html' runner.report(filename = '\\'+'测试报告'+timestr+'.html', description=u"测试报告",report_dir=report_path,theme="theme_cyan") # if __name__ == '__main__': # RunnerTestCase().RunnerBeautifulReport()
def run_all_case(): # 获取测试套件 suite = unittest.TestSuite() # 加载指定路径下所有以py为后缀的测试文件 all_py = unittest.defaultTestLoader.discover(setting.CASE_PATH,'*.py') # 列表生成式,遍历这些文件添加到测试组件中 [ suite.addTests(py) for py in all_py] # 实例化一个BeautifulReport,基于这个测试套件 run=bf(suite) today = datetime.datetime.today().strftime('%Y%m%d%H%M%S') title = '%s_接口测报告.html'%today # 拼接存储测试报告的路径 report_abs_path = os.path.join(setting.REPORT_PATH,title) # 运行测试套件中的所以测试,并生成测试报告 run.report(title,filename=title,log_path=setting.REPORT_PATH) # 返回执行测试成功和失败的数量一级测试报告的绝对路径 return run.success_count,run.failure_count,report_abs_path
""" @project:code @author:lenovo @file:run_test.py @ide:PyCharm @time:2020/8/26 14:19 @month:八月 """ """ 运行所有测试案例 """ from BeautifulReport import BeautifulReport as bf import unittest import os local_dir = os.path.dirname(os.path.dirname( os.path.abspath(__file__))) + "\\test" report_dir = os.path.dirname(os.path.dirname( os.path.abspath(__file__))) + "\\reports" print(local_dir) if __name__ == "__main__": testsuite = unittest.defaultTestLoader.discover(local_dir, pattern='test*.py') result = bf(testsuite) report = result.report(description="测试报告", filename="自动化报告", log_path=report_dir)
import unittest from BeautifulReport import BeautifulReport as bf from xmdCW.testcase.test_login import TestLogin from xmdCW.testcase.test_gongzuotai import TestGongDan from xmdCW.testcase.test_daihezhun import TestDaiHeZhun from xmdCW.testcase.test_zhunru import TestZhunRu from xmdCW.testcase.test_wentiFK import TestFanKui from xmdCW.testcase.test_xianxiaqianyue import TestXianXiaQianYue if __name__ == "__main__": # 定义一个测试集合 suite = unittest.TestSuite() # 把需要执行的用例循环加进来 for i in (TestGongDan, TestLogin, TestDaiHeZhun, TestZhunRu, TestFanKui, TestXianXiaQianYue): suite.addTest(unittest.makeSuite(i)) # 执行单条用例 # suite.addTest(unittest.makeSuite(TestLogin)) run = bf(suite) # 实例化BeautifulReport模块 run.report(filename='test', description='车务测试结果')
import unittest # from HtmlTestRunner import HTMLTestRunner import os import time from BeautifulReport import BeautifulReport as bf # addTest加载每个test开头的函数 # suite = unittest.TestSuite() # suite.addTest(BaiduSearch('test_baidu_search')) # suite.addTest(BaiduSearch('test_baidu_search2')) # suite.addTest(SportNewsClick('test_sportnews_click')) path = os.path.dirname(os.path.abspath('.')) + '/test_report/' now = time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime(time.time())) report_path = path + now suite = unittest.TestLoader().discover("testsuites") if __name__ == '__main__': run = bf(suite) run.report(filename="wb01", description='盒子管理后台', report_dir=report_path) # with open(report_path, 'wb') as f: # runner = HTMLTestRunner(f, report_title=u"WB01测试报告", descriptions=u"测试结果", verbosity=2) # runner.run(suite)
import BeautifulReport from BeautifulReport import BeautifulReport as bf import unittest import os import time current_path = os.getcwd() # 当前文件路径 print(current_path) case_path = os.path.join(current_path, "case") # 用例路径 print(case_path) # 存放报告路径 report_path = os.path.join(current_path, "report") print(report_path) # discover找出以case开头的用例 def all_case(): discover = unittest.defaultTestLoader.discover(case_path, pattern="case*.py") print(discover) return discover if __name__ == "__main__": runner = bf(all_case()).report(filename='report\\BeautyTest.html', description="登录接口自动化测试")
def run(casename="多线程APP1"): # 运行的相对路径 path = '.' # 用例路径 casepath = '' resultpath = '' logger.info("开始用例") try: casepath = sys.argv[1] except: casepath = '' casefile = casename # 为空,则使用默认的 if casepath == '': casepath = path + '/data/cases/' + casefile + '.xls' resultpath = path + '/outputs/resultcases/chint结果-' + casefile + '.xls' else: # 如果是绝对路径,就使用绝对路径 if casepath.find(':') >= 0: # 获取用例文件名 resultpath = path + '/outputs/resultcases/chint结果-' + casepath[ casepath.rfind('\\') + 1:] else: logger.error('非法用例路径') config.get_config(path + '/conf/conf.properties') # logger.info(config.config) # mysql = Mysql() # mysql.init_mysql(path + '/lib/userinfo.sql') logger.info("传递的参数是:%s,%s" % (casepath, resultpath)) datadriven.getparams(casepath, resultpath) # print(datadriven.alllist) ### 下面三行代码为BeautifulReport 报告 # suite = unittest.defaultTestLoader.discover("./utest/", pattern="WebTest.py", top_level_dir=None) # # 生成执行用例的对象 # runner = bf(suite) # runner.report(filename='./report/test'+ casefile + '.html', description=datadriven.title) ### 下面几行代码为HTMLTestRunner 报告 suite = unittest.defaultTestLoader.discover("./utest/", pattern="WebTest.py", top_level_dir=None) # 生成执行用例的对象 runner = bf(suite) runner.report(filename='./outputs/report/test' + casefile + '.html', description=datadriven.title) # 记录结束时间,写入结果文件 endtime = str( datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) # 用例结束时间 datadriven.writer.set_sheet((datadriven.writer.get_sheets())[0]) datadriven.writer.write(1, 4, endtime) # 对结果文件第二行第四列写入开始时间 # 保存结果文件 datadriven.writer.save_close() # # 得到报告数据 res = Res() r = res.get_res(resultpath) # 读取配置文件 config.get_config('./conf/conf.properties') # logger.info(config.config) # logger.info(config.config['mail']) # 修改邮件数据 html = config.config['mailtxt'] # 读取报告模板 html = html.replace('title', r['title']) # 替换模板中的数据 html = html.replace('runtype', r['runtype']) html = html.replace('passrate', r['passrate']) html = html.replace('status', r['status']) html = html.replace('casecount', r['casecount']) html = html.replace('starttime', r['starttime']) html = html.replace('endtime', r['endtime']) if r['status'] == 'Fail': html = html.replace('#00d800', 'red') # 根据结果决定是否发送邮件 if r['status'] == 'Fail': logger.info("开始发送邮件") mail = Mail() # mail.send(html) logger.info("结束用例")
res = requests.post(url, data=data).text self.assertEqual() self.assertIn(c, res, msg='预计结果不符,预期结果【%s】,实际结果【%s】' % (c, res)) except Exception as e: print('') res = e for c in check: self.assertIn( c, res, msg='预计结果不符,预期结果【%s】,实际结果【%s】' % (c, res) ) #查看是否包含 断言查看一次错误就停止,后面加如错误提示 但check在yml中得是list方便查看是否包含。 sutie = unittest.TestSuite() sutie.addTest(unittest.makeSuite(Login)) # 添加用例 #bf 报告生成 run = bf(sutie) # 实例化 它是一个类 必须实列化使用 run.report('login_test', 'token检测') print(run.success_count) # 通过的次数 print(run.failure_count) # 失败的次数
#from ..testcases import function_test import unittest import os import sys from BeautifulReport import BeautifulReport as bf import time from test_framework.testcases.logoTemplateTest import * top_path = os.path.abspath("..") sys.path.append(top_path) caces_path = os.path.join(top_path, "testcases") log_path = os.path.join(top_path, "report") filename = "report-" + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time())) print(filename) discover = unittest.defaultTestLoader.discover(caces_path, pattern="logoTemplateTest.py", top_level_dir=None) sys.stdout.flush() # runner = unittest.TextTestRunner() # runner.run(discover) run = bf(discover) run.report(filename=filename, description="报告描述参数", report_dir=log_path)
#在所有用例都执行完之后运行的 print('teardownclass') def test_lu(self): #用例执行顺序是按照首字母的顺序(在报告中可看出) #通过‘’‘来加入用例描述 报告中就会加入用例描述 print('aina') self.assertEqual(1,1) #该子类没有 继承父类比较两个值 后面也可以再加参数作为提示信息。 def test_zch(self): #以test开头就可以运行用例 否则不会自动运行 print('赵传慧') self.assertEqual(1,1,msg="没有问题") #if __name__ == '__main__': # unittest.main() #会运行当前python文件里面的所有测试用例 **运行时注意run 产生报告时不用该模式 ## 1、先把所有的测试用例都放到用例集。用例集也做测试套件是用来存放测试用例的 ##2、运行这些测试用例 ##3、产生报告 suite = unittest.TestSuite() #测试集合 存放用例 其实是一个list suite.addTest( unittest.makeSuite(TestCalc) ) #把刚才写的用例加进来 **写入类名 #bf报告生成 run = bf(suite) #实例化一下,他是一个类必须实例化使用 run.report(description='描述必须写',filename='test') #还可指定log位置等 #HtmlTESTRunner如何产生报告 # f = open('test.html','wb') #以2进制模式 不考虑编码集的问题 # runner = HTMLTestRunner.HTMLTestRunner(f,title='双鱼座用例标题',description='这是用例描述') #后面两个参数是非必须的 # runner.run(suite) #运行用例
if method == 'get': res = requests.get(url, params=data, cookies=cookie, headers=header).text # 因为接口有异常的情况下, 可能返回的不是json串,会报错 else: res = requests.post(url, data=data, cookies=cookie, headers=header).text except Exception as e: print('接口请求出错') res = e for c in check: self.assertIn(c, res, msg='预计结果不符,预期结果包含[%s],实际结果[%s]' % (c, res)) # 查看是否包含 断言查看一次错误就停止,后面加如错误提示 但check在yml中得是list方便查看是否包含。 sutie = unittest.TestSuite() sutie.addTest(unittest.makeSuite(Login)) # 添加用例 run = bf(sutie) # 实例化 run.report('api_test', '冒烟测试用例') print(run.success_count) # 通过的次数 print(run.failure_count) # 失败的次数
# data = f.read() # exp_file_md5 = hashlib.md5(data).hexdigest() # self.assertEqual(exp_file_md5, file_md5) def test02(self): config = self.load_config(self._p('conf/2_test.yml')) try: run(config) except SystemExit as e: pass diff_res = sh.diff(self._p("test_output/I88_stop_profit_loss.csv"), self._p("expect_output/2_I88_stop_profit_loss.csv")) self.assertEqual(diff_res, "") # with open(self._p("test_output/I88_stop_profit_loss.csv"), "rb") as f: # data = f.read() # file_md5 = hashlib.md5(data).hexdigest() # with open(self._p("expect_output/2_I88_stop_profit_loss.csv"), "rb") as f: # data = f.read() # exp_file_md5 = hashlib.md5(data).hexdigest() # self.assertEqual(exp_file_md5, file_md5) if __name__ == '__main__': suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestModStopProfitLoss)) bf_run = bf(suite) bf_run.report(filename='report', report_dir='/tmp/unittest_report', description='rqalpha rqalpha_unittest report')
casepath = '' # 为空,则使用默认的 if casepath == '': casepath = path + '/lib/cases/HTTP接口用例.xls' resultpath = path + '/lib/results/result-HTTP接口用例.xls' else: # 如果是绝对路径,就使用绝对路径 if casepath.find(':') >= 0: # 获取用例文件名 resultpath = path + '/lib/results/result-' + casepath[ casepath.rfind('\\') + 1:] else: logger.error('非法用例路径') config.get_config(path + '/lib/conf/conf.txt') # logger.info(config.config) # mysql = Mysql() # mysql.init_mysql(path + '/lib/conf/userinfo.sql') datadriven.getparams(casepath, resultpath) # unittest.main() # suite = unittest.TestSuite() # suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(baidu)) suite = unittest.defaultTestLoader.discover("./myunittest/", pattern="WebTest.py", top_level_dir=None) # 生成执行用例的对象 runner = bf(suite) runner.report(filename='./test.html', description='这个描述参数是必填的')
def report_bf(reppath, fname): '使用BeautifulReport库生成格式更美观的html报告' run = bf(all_case()) #实例化BeautifulReport模块 run.report(filename=fname, report_dir=reppath, description=email_conf.subject)