You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

BSTestRunner.py 31 KiB

2 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. """
  2. A TestRunner for use with the Python unit testing framework. It generates a HTML report to show the result at a glance.
  3. The simplest way to use this is to invoke its main method. E.g.
  4. import unittest
  5. import BSTestRunner
  6. ... define your tests ...
  7. if __name__ == '__main__':
  8. BSTestRunner.main()
  9. For more customization options, instantiates a BSTestRunner object.
  10. BSTestRunner is a counterpart to unittest's TextTestRunner. E.g.
  11. # output to a file
  12. fp = file('my_report.html', 'wb')
  13. runner = BSTestRunner.BSTestRunner(
  14. stream=fp,
  15. title='My unit test',
  16. description='This demonstrates the report output by BSTestRunner.'
  17. )
  18. # Use an external stylesheet.
  19. # See the Template_mixin class for more customizable options
  20. runner.STYLESHEET_TMPL = '<link rel="stylesheet" href="my_stylesheet.css" type="text/css">'
  21. # run the test
  22. runner.run(my_test_suite)
  23. ------------------------------------------------------------------------
  24. Copyright (c) 2004-2007, Wai Yip Tung
  25. Copyright (c) 2016, Eason Han
  26. All rights reserved.
  27. Redistribution and use in source and binary forms, with or without
  28. modification, are permitted provided that the following conditions are
  29. met:
  30. * Redistributions of source code must retain the above copyright notice,
  31. this list of conditions and the following disclaimer.
  32. * Redistributions in binary form must reproduce the above copyright
  33. notice, this list of conditions and the following disclaimer in the
  34. documentation and/or other materials provided with the distribution.
  35. * Neither the name Wai Yip Tung nor the names of its contributors may be
  36. used to endorse or promote products derived from this software without
  37. specific prior written permission.
  38. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  39. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  40. TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  41. PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
  42. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  43. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  44. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  45. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  46. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  47. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  48. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  49. """
  50. __author__ = "Wai Yip Tung && Eason Han"
  51. __version__ = "0.8.4"
  52. """
  53. Change History
  54. Version 0.8.3
  55. * Modify html style using bootstrap3.
  56. Version 0.8.3
  57. * Prevent crash on class or module-level exceptions (Darren Wurf).
  58. Version 0.8.2
  59. * Show output inline instead of popup window (Viorel Lupu).
  60. Version in 0.8.1
  61. * Validated XHTML (Wolfgang Borgert).
  62. * Added description of test classes and test cases.
  63. Version in 0.8.0
  64. * Define Template_mixin class for customization.
  65. * Workaround a IE 6 bug that it does not treat <script> block as CDATA.
  66. Version in 0.7.1
  67. * Back port to Python 2.3 (Frank Horowitz).
  68. * Fix missing scroll bars in detail log (Podi).
  69. """
  70. # TODO: color stderr
  71. # TODO: simplify javascript using ,ore than 1 class in the class attribute?
  72. import datetime
  73. import unittest
  74. from xml.sax import saxutils
  75. import os
  76. import sys, copy
  77. from io import StringIO as StringIO
  78. # ------------------------------------------------------------------------
  79. # The redirectors below are used to capture output during testing. Output
  80. # sent to sys.stdout and sys.stderr are automatically captured. However
  81. # in some cases sys.stdout is already cached before BSTestRunner is
  82. # invoked (e.g. calling logging.basicConfig). In order to capture those
  83. # output, use the redirectors for the cached stream.
  84. #
  85. # e.g.
  86. # >>> logging.basicConfig(stream=BSTestRunner.stdout_redirector)
  87. # >>>
  88. def to_unicode(s):
  89. return s
  90. # try:
  91. # return unicode(s)
  92. # except UnicodeDecodeError:
  93. # # s is non ascii byte string
  94. # return s.decode('unicode_escape')
  95. class OutputRedirector(object):
  96. """ Wrapper to redirect stdout or stderr """
  97. def __init__(self, fp):
  98. self.fp = fp
  99. def write(self, s):
  100. self.fp.write(s)
  101. def writelines(self, lines):
  102. lines = map(to_unicode, lines)
  103. self.fp.writelines(lines)
  104. def flush(self):
  105. self.fp.flush()
  106. stdout_redirector = OutputRedirector(sys.stdout)
  107. stderr_redirector = OutputRedirector(sys.stderr)
  108. # ----------------------------------------------------------------------
  109. # Template
  110. class Template_mixin(object):
  111. """
  112. Define a HTML template for report customerization and generation.
  113. Overall structure of an HTML report
  114. HTML
  115. +------------------------+
  116. |<html> |
  117. | <head> |
  118. | |
  119. | STYLESHEET |
  120. | +----------------+ |
  121. | | | |
  122. | +----------------+ |
  123. | |
  124. | </head> |
  125. | |
  126. | <body> |
  127. | |
  128. | HEADING |
  129. | +----------------+ |
  130. | | | |
  131. | +----------------+ |
  132. | |
  133. | REPORT |
  134. | +----------------+ |
  135. | | | |
  136. | +----------------+ |
  137. | |
  138. | ENDING |
  139. | +----------------+ |
  140. | | | |
  141. | +----------------+ |
  142. | |
  143. | </body> |
  144. |</html> |
  145. +------------------------+
  146. """
  147. STATUS = {
  148. 0: '通过',
  149. 1: '失败',
  150. 2: '错误',
  151. }
  152. DEFAULT_TITLE = '测试报告'
  153. DEFAULT_DESCRIPTION = ''
  154. # ------------------------------------------------------------------------
  155. # HTML Template
  156. HTML_TMPL = r"""<!DOCTYPE html>
  157. <html lang="zh-cn">
  158. <head>
  159. <meta charset="utf-8">
  160. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  161. <meta name="viewport" content="width=device-width, initial-scale=1">
  162. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  163. <title>%(title)s</title>
  164. <meta name="generator" content="%(generator)s"/>
  165. <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" ">
  166. <script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
  167. %(stylesheet)s
  168. <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
  169. <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  170. <!--[if lt IE 9]>
  171. <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  172. <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
  173. <![endif]-->
  174. </head>
  175. <body>
  176. <div class="container">
  177. %(heading)s
  178. %(report)s
  179. %(ending)s
  180. </div>
  181. %(scripts)s
  182. """
  183. # variables: (title, generator, stylesheet, heading, report, ending)
  184. # ------------------------------------------------------------------------
  185. # Stylesheet
  186. #
  187. # alternatively use a <link> for external style sheet, e.g.
  188. # <link rel="stylesheet" href="$url" type="text/css">
  189. STYLESHEET_TMPL = """
  190. <style type="text/css" media="screen">
  191. /* -- css div popup ------------------------------------------------------------------------ */
  192. .popup_window {
  193. display: none;
  194. position: relative;
  195. left: 0px;
  196. top: 0px;
  197. /*border: solid #627173 1px; */
  198. padding: 10px;
  199. background-color: #99CCFF;
  200. font-family: "Lucida Console", "Courier New", Courier, monospace;
  201. text-align: left;
  202. font-size: 10pt;
  203. width: 1200px;
  204. }
  205. /* -- report ------------------------------------------------------------------------ */
  206. #show_detail_line .label {
  207. font-size: 85%;
  208. cursor: pointer;
  209. }
  210. #show_detail_line {
  211. margin: 2em auto 1em auto;
  212. }
  213. #total_row { font-weight: bold; }
  214. .hiddenRow { display: none; }
  215. .testcase { margin-left: 2em; }
  216. </style>
  217. """
  218. # ------------------------------------------------------------------------
  219. # Heading
  220. #
  221. HEADING_TMPL = """<div class='heading'>
  222. <div >
  223. <h1>%(title)s</h1>
  224. %(parameters)s
  225. <p class='description'>%(description)s</p>
  226. </div> </div >
  227. """
  228. HEADING_TMPL_New = """
  229. <div class='heading'>
  230. <div style='width: 50%%;float:left;margin-top:inherit'>
  231. <h1>%(title)s</h1>
  232. %(parameters)s
  233. <p class='description'>%(description)s</p>
  234. </div>
  235. <div id='container2' style='width:50%%;float:left;margin-top:20px;height:200px;'>
  236. </div>
  237. </div >
  238. <div id='containerchart' style='height: 300px;margin-top: 20%%;'></div>
  239. """
  240. HEADING_OLD = """<div class='heading'>
  241. <h1>%(title)s</h1>
  242. %(parameters)s
  243. <p class='description'>%(description)s</p>
  244. </div>
  245. """
  246. HEADING_ATTRIBUTE_TMPL = """<p><strong>%(name)s:</strong> %(value)s</p>
  247. """ # variables: (name, value)
  248. # ------------------------------------------------------------------------
  249. # Report
  250. #
  251. REPORT_TMPL = """
  252. <p id='show_detail_line'>
  253. <span class="label label-primary" onclick="showCase(0)">公用</span>
  254. <span class="label label-danger" onclick="showCase(1)">失败</span>
  255. <span class="label label-default" onclick="showCase(2)">所有</span>
  256. </p>
  257. <table id='result_table' class="table">
  258. <thead>
  259. <tr id='header_row'>
  260. <th>测试组/测试用例</td>
  261. <th>数量</td>
  262. <th>通过</td>
  263. <th>失败</td>
  264. <th>错误</td>
  265. <th>查看</td>
  266. </tr>
  267. </thead>
  268. <tbody>
  269. %(test_list)s
  270. </tbody>
  271. <tfoot>
  272. <tr id='total_row'>
  273. <td>总计</td>
  274. <td>%(count)s</td>
  275. <td class="text text-success">%(Pass)s</td>
  276. <td class="text text-danger">%(fail)s</td>
  277. <td class="text text-warning">%(error)s</td>
  278. <td>&nbsp;</td>
  279. </tr>
  280. </tfoot>
  281. </table>
  282. """ # variables: (test_list, count, Pass, fail, error)
  283. REPORT_CLASS_TMPL = r"""
  284. <tr class='%(style)s'>
  285. <td>%(desc)s</td>
  286. <td>%(count)s</td>
  287. <td>%(Pass)s</td>
  288. <td>%(fail)s</td>
  289. <td>%(error)s</td>
  290. <td><a class="btn btn-xs btn-primary"href="javascript:showClassDetail('%(cid)s',%(count)s)">详情</a></td>
  291. </tr>
  292. """ # variables: (style, desc, count, Pass, fail, error, cid)
  293. REPORT_TEST_WITH_OUTPUT_TMPL = r"""
  294. <tr id='%(tid)s' class='%(Class)s'>
  295. <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
  296. <td colspan='5' align='center'>
  297. <!--css div popup start-->
  298. <a class="popup_link btn btn-xs btn-default" onfocus='this.blur();' href="javascript:showTestDetail('div_%(tid)s')" >
  299. %(status)s</a>
  300. <div id='div_%(tid)s' class="popup_window">
  301. <div style='text-align: right;cursor:pointer'>
  302. <a onfocus='this.blur();' onclick="document.getElementById('div_%(tid)s').style.display = 'none' " >
  303. [x]</a>
  304. </div>
  305. <pre>
  306. %(script)s
  307. </pre>
  308. </div>
  309. <!--css div popup end-->
  310. </td>
  311. </tr>
  312. """ # variables: (tid, Class, style, desc, status)
  313. REPORT_TEST_NO_OUTPUT_TMPL = r"""
  314. <tr id='%(tid)s' class='%(Class)s'>
  315. <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
  316. <td colspan='5' align='center'>%(status)s</td>
  317. </tr>
  318. """ # variables: (tid, Class, style, desc, status)
  319. REPORT_TEST_OUTPUT_TMPL = r"""
  320. %(id)s: %(output)s
  321. """ # variables: (id, output)
  322. # ------------------------------------------------------------------------
  323. # ENDING
  324. #
  325. ENDING_TMPL = """<div id='ending'>&nbsp;</div>"""
  326. SCRPICTold = """
  327. <script language='javascript' type='text/javascript'>
  328. output_list = Array();
  329. /* level - 0:Summary; 1:Failed; 2:All */
  330. function showCase(level) {
  331. trs = document.getElementsByTagName('tr');
  332. for (var i = 0; i < trs.length; i++) {
  333. tr = trs[i];
  334. id = tr.id;
  335. if (id.substr(0,2) == 'ft') {
  336. if (level < 1) {
  337. tr.className = 'hiddenRow';
  338. }
  339. else {
  340. tr.className = '';
  341. }
  342. }
  343. if (id.substr(0,2) == 'pt') {
  344. if (level > 1) {
  345. tr.className = '';
  346. }
  347. else {
  348. tr.className = 'hiddenRow';
  349. }
  350. }
  351. }
  352. }
  353. function showClassDetail(cid, count) {
  354. var id_list = Array(count);
  355. var toHide = 1;
  356. for (var i = 0; i < count; i++) {
  357. tid0 = 't' + cid.substr(1) + '.' + (i+1);
  358. tid = 'f' + tid0;
  359. tr = document.getElementById(tid);
  360. if (!tr) {
  361. tid = 'p' + tid0;
  362. tr = document.getElementById(tid);
  363. }
  364. id_list[i] = tid;
  365. if (tr.className) {
  366. toHide = 0;
  367. }
  368. }
  369. for (var i = 0; i < count; i++) {
  370. tid = id_list[i];
  371. if (toHide) {
  372. document.getElementById('div_'+tid).style.display = 'none'
  373. document.getElementById(tid).className = 'hiddenRow';
  374. }
  375. else {
  376. document.getElementById(tid).className = '';
  377. }
  378. }
  379. }
  380. function showTestDetail(div_id){
  381. var details_div = document.getElementById(div_id)
  382. var displayState = details_div.style.display
  383. if (displayState != 'block' ) {
  384. displayState = 'block'
  385. details_div.style.display = 'block'
  386. }
  387. else {
  388. details_div.style.display = 'none'
  389. }
  390. }
  391. function html_escape(s) {
  392. s = s.replace(/&/g,'&amp;');
  393. s = s.replace(/</g,'&lt;');
  394. s = s.replace(/>/g,'&gt;');
  395. return s;
  396. }
  397. </script>
  398. </body>
  399. </html>
  400. """
  401. SCRPICTDATA = r"""
  402. <script language='javascript' type='text/javascript'>
  403. var dom = document.getElementById('containerchart');
  404. var myChart = echarts.init(dom);
  405. var domone = document.getElementById('container2');
  406. var myChartone = echarts.init(domone);
  407. var optionsone;
  408. optionsone = {
  409. title: {
  410. text: '历史记录'
  411. },
  412. tooltip: {
  413. trigger: 'axis'
  414. },
  415. legend: {
  416. data: ['成功', '失败','错误']
  417. },
  418. grid: {
  419. left: '3%%',
  420. right: '4%%',
  421. bottom: '3%%',
  422. containLabel: true
  423. },
  424. toolbox: {
  425. feature: {
  426. saveAsImage: {}
  427. }
  428. },
  429. xAxis: {
  430. type: 'category',
  431. boundaryGap: false,
  432. data: %(reslutname)s
  433. },
  434. yAxis: {
  435. type: 'value'
  436. },
  437. series: [
  438. {
  439. name: '成功',
  440. type: 'line',
  441. stack: '总量',
  442. data: %(success)s
  443. },
  444. {
  445. name: '失败',
  446. type: 'line',
  447. stack: '总量',
  448. data: %(fail)s
  449. },
  450. {
  451. name: '错误',
  452. type: 'line',
  453. stack: '总量',
  454. data: %(error)s
  455. }
  456. ]
  457. };
  458. if (optionsone && typeof optionsone === 'object') {
  459. myChartone.setOption(optionsone);
  460. }
  461. output_list = Array();
  462. /* level - 0:Summary; 1:Failed; 2:All */
  463. function showCase(level) {
  464. trs = document.getElementsByTagName('tr');
  465. for (var i = 0; i < trs.length; i++) {
  466. tr = trs[i];
  467. id = tr.id;
  468. if (id.substr(0,2) == 'ft') {
  469. if (level < 1) {
  470. tr.className = 'hiddenRow';
  471. }
  472. else {
  473. tr.className = '';
  474. }
  475. }
  476. if (id.substr(0,2) == 'pt') {
  477. if (level > 1) {
  478. tr.className = '';
  479. }
  480. else {
  481. tr.className = 'hiddenRow';
  482. }
  483. }
  484. }
  485. }
  486. function showClassDetail(cid, count) {
  487. var id_list = Array(count);
  488. var toHide = 1;
  489. for (var i = 0; i < count; i++) {
  490. tid0 = 't' + cid.substr(1) + '.' + (i+1);
  491. tid = 'f' + tid0;
  492. tr = document.getElementById(tid);
  493. if (!tr) {
  494. tid = 'p' + tid0;
  495. tr = document.getElementById(tid);
  496. }
  497. id_list[i] = tid;
  498. if (tr.className) {
  499. toHide = 0;
  500. }
  501. }
  502. for (var i = 0; i < count; i++) {
  503. tid = id_list[i];
  504. if (toHide) {
  505. document.getElementById('div_'+tid).style.display = 'none'
  506. document.getElementById(tid).className = 'hiddenRow';
  507. }
  508. else {
  509. document.getElementById(tid).className = '';
  510. }
  511. }
  512. }
  513. function showTestDetail(div_id){
  514. var details_div = document.getElementById(div_id)
  515. var displayState = details_div.style.display
  516. if (displayState != 'block' ) {
  517. displayState = 'block'
  518. details_div.style.display = 'block'
  519. }
  520. else {
  521. details_div.style.display = 'none'
  522. }
  523. }
  524. function html_escape(s) {
  525. s = s.replace(/&/g,'&amp;');
  526. s = s.replace(/</g,'&lt;');
  527. s = s.replace(/>/g,'&gt;');
  528. return s;
  529. }
  530. </script>
  531. </body>
  532. </html>
  533. """
  534. # -------------------- The end of the Template class -------------------
  535. TestResult = unittest.TestResult
  536. class MyResult(TestResult):
  537. def __init__(self, verbosity=1, trynum=1):
  538. # 默认次数是0
  539. TestResult.__init__(self)
  540. self.outputBuffer = StringIO()
  541. self.stdout0 = None
  542. self.stderr0 = None
  543. self.success_count = 0
  544. self.failure_count = 0
  545. self.error_count = 0
  546. self.verbosity = verbosity
  547. self.trynnum = trynum
  548. self.result = []
  549. self.trys = 0 #
  550. self.istry = False
  551. def startTest(self, test):
  552. TestResult.startTest(self, test)
  553. self.stdout0 = sys.stdout
  554. self.stderr0 = sys.stderr
  555. def complete_output(self):
  556. if self.stdout0:
  557. sys.stdout = self.stdout0
  558. sys.stderr = self.stderr0
  559. self.stdout0 = None
  560. self.stderr0 = None
  561. return self.outputBuffer.getvalue()
  562. def stopTest(self, test):
  563. # 判断是否要重试
  564. if self.istry is True:
  565. # 如果执行的次数小于重试的次数 就重试
  566. if self.trys < self.trynnum:
  567. # 删除最后一个结果
  568. reslut = self.result.pop(-1)
  569. # 判断结果,如果是错误就把错误的个数减掉
  570. # 如果是失败,就把失败的次数减掉
  571. if reslut[0] == 1:
  572. self.failure_count -= 1
  573. else:
  574. self.error_count -= 1
  575. sys.stderr.write('{}:用例正在重试中。。。'.format(test.id()) + '\n')
  576. # 深copy用例
  577. test = copy.copy(test)
  578. # 重试次数增加+1
  579. self.trys += 1
  580. # 测试
  581. test(self)
  582. else:
  583. self.istry = False
  584. self.trys = 0
  585. self.complete_output()
  586. def addSuccess(self, test):
  587. # 成功就不要重试
  588. self.istry = False
  589. self.success_count += 1
  590. TestResult.addSuccess(self, test)
  591. output = self.complete_output()
  592. self.result.append((0, test, output, ''))
  593. if self.verbosity > 1:
  594. sys.stderr.write('ok ')
  595. sys.stderr.write(str(test))
  596. sys.stderr.write('\n')
  597. else:
  598. sys.stderr.write('.')
  599. def addError(self, test, err):
  600. # 重试+1,错误次数+1
  601. self.istry = True
  602. self.error_count += 1
  603. TestResult.addError(self, test, err)
  604. _, _exc_str = self.errors[-1]
  605. output = self.complete_output()
  606. self.result.append((2, test, output, _exc_str))
  607. if self.verbosity > 1:
  608. sys.stderr.write('E ')
  609. sys.stderr.write(str(test))
  610. sys.stderr.write('\n')
  611. else:
  612. sys.stderr.write('E')
  613. def addFailure(self, test, err):
  614. self.istry = True
  615. TestResult.startTestRun(self)
  616. self.failure_count += 1
  617. TestResult.addFailure(self, test, err)
  618. _, _exc_str = self.failures[-1]
  619. output = self.complete_output()
  620. self.result.append((1, test, output, _exc_str))
  621. if self.verbosity > 1:
  622. sys.stderr.write('F ')
  623. sys.stderr.write(str(test))
  624. sys.stderr.write('\n')
  625. else:
  626. sys.stderr.write('F')
  627. def stop(self) -> None:
  628. pass
  629. class _TestResult(MyResult):
  630. # note: _TestResult is a pure representation of results.
  631. # It lacks the output and reporting ability compares to unittest._TextTestResult.
  632. def __init__(self, verbosity=1, trynum=1):
  633. TestResult.__init__(self)
  634. super().__init__(verbosity, trynum)
  635. class BSTestRunner(Template_mixin):
  636. """
  637. """
  638. def __init__(self, stream=sys.stdout,
  639. verbosity=1,
  640. title=None,
  641. description=None,
  642. trynum=1,
  643. is_show=False,
  644. filepath=""):
  645. self.stream = stream
  646. self.verbosity = verbosity
  647. self.trynum = trynum
  648. self.is_show = is_show
  649. self.filepath = filepath
  650. if title is None:
  651. self.title = self.DEFAULT_TITLE
  652. else:
  653. self.title = title
  654. if description is None:
  655. self.description = self.DEFAULT_DESCRIPTION
  656. else:
  657. self.description = description
  658. self.startTime = datetime.datetime.now()
  659. def run(self, test):
  660. "Run the given test case or test suite."
  661. result = _TestResult(self.verbosity, trynum=self.trynum)
  662. try:
  663. test(result)
  664. except TypeError:
  665. pass
  666. self.stopTime = datetime.datetime.now()
  667. if self.is_show:
  668. name = os.path.join(self.filepath, self.stopTime.strftime('%Y_%m_%d_%H_%M_%S') + '.txt')
  669. with open(name, 'w+') as f:
  670. f.write(
  671. result.success_count.__str__() + "_" + result.error_count.__str__() + "_" + result.failure_count.__str__())
  672. f.close()
  673. self.generateReport(test, result)
  674. print('\n测试耗时: %s' % (self.stopTime - self.startTime))
  675. return result
  676. def sortResult(self, result_list):
  677. # unittest does not seems to run in any particular order.
  678. # Here at least we want to group them together by class.
  679. rmap = {}
  680. classes = []
  681. for n, t, o, e in result_list:
  682. cls = t.__class__
  683. if not cls in rmap:
  684. rmap[cls] = []
  685. classes.append(cls)
  686. rmap[cls].append((n, t, o, e))
  687. r = [(cls, rmap[cls]) for cls in classes]
  688. return r
  689. def getReportAttributes(self, result):
  690. """
  691. Return report attributes as a list of (name, value).
  692. Override this to add custom attributes.
  693. """
  694. startTime = str(self.startTime)[:19]
  695. duration = str(self.stopTime - self.startTime)
  696. status = []
  697. if result.success_count: status.append(
  698. '<span class="text text-success">通过 <strong>%s</strong></span>' % result.success_count)
  699. if result.failure_count: status.append(
  700. '<span class="text text-danger">失败 <strong>%s</strong></span>' % result.failure_count)
  701. if result.error_count: status.append(
  702. '<span class="text text-warning">错误 <strong>%s</strong></span>' % result.error_count)
  703. if status:
  704. status = ' '.join(status)
  705. else:
  706. status = 'none'
  707. return [
  708. ('开始时间', startTime),
  709. ('持续时间', duration),
  710. ('状态', status),
  711. ]
  712. def generateReport(self, test, result):
  713. report_attrs = self.getReportAttributes(result)
  714. generator = 'BSTestRunner %s' % __version__
  715. stylesheet = self._generate_stylesheet()
  716. heading = self._generate_heading(report_attrs)
  717. report = self._generate_report(result)
  718. ending = self._generate_ending()
  719. if self.is_show:
  720. scrpit = self.___generate_scrpitone()
  721. else:
  722. scrpit = self._generate_scrpit()
  723. output = self.HTML_TMPL % dict(
  724. title=saxutils.escape(self.title),
  725. generator=generator,
  726. stylesheet=stylesheet,
  727. scripts=scrpit,
  728. heading=heading,
  729. report=report,
  730. ending=ending
  731. )
  732. self.stream.write(output.encode("utf-8"))
  733. def _generate_stylesheet(self):
  734. return self.STYLESHEET_TMPL
  735. def _generate_heading(self, report_attrs):
  736. ISSHOWPERDATA = True
  737. if ISSHOWPERDATA:
  738. a_lines = []
  739. for name, value in report_attrs:
  740. line = self.HEADING_ATTRIBUTE_TMPL % dict(
  741. name=saxutils.escape(name), ####更改
  742. # value = saxutils.escape(value),
  743. value=value,
  744. )
  745. a_lines.append(line)
  746. if self.is_show:
  747. heading = self.HEADING_TMPL_New % dict(
  748. title=saxutils.escape(self.title), parameters=''.join(a_lines),
  749. description=saxutils.escape(self.description), )
  750. else:
  751. heading = self.HEADING_TMPL % dict(
  752. title=saxutils.escape(self.title),
  753. parameters=''.join(a_lines),
  754. description=saxutils.escape(self.description),
  755. )
  756. return heading
  757. else:
  758. a_lines = []
  759. for name, value in report_attrs:
  760. line = self.HEADING_ATTRIBUTE_TMPL % dict(
  761. name=saxutils.escape(name), ####更改
  762. # value = saxutils.escape(value),
  763. value=value,
  764. )
  765. a_lines.append(line)
  766. heading = self.HEADING_OLD % dict(
  767. title=saxutils.escape(self.title),
  768. parameters=''.join(a_lines),
  769. description=saxutils.escape(self.description),
  770. )
  771. return heading
  772. def _generate_report(self, result):
  773. rows = []
  774. sortedResult = self.sortResult(result.result)
  775. for cid, (cls, cls_results) in enumerate(sortedResult):
  776. # subtotal for a class
  777. np = nf = ne = 0
  778. for n, t, o, e in cls_results:
  779. if n == 0:
  780. np += 1
  781. elif n == 1:
  782. nf += 1
  783. else:
  784. ne += 1
  785. # format class description
  786. if cls.__module__ == "__main__":
  787. name = cls.__name__
  788. else:
  789. name = "%s.%s" % (cls.__module__, cls.__name__)
  790. doc = cls.__doc__ and cls.__doc__.split("\n")[0] or ""
  791. desc = doc and '%s: %s' % (name, doc) or name
  792. row = self.REPORT_CLASS_TMPL % dict(
  793. style=ne > 0 and 'text text-warning' or nf > 0 and 'text text-danger' or 'text text-success',
  794. desc=desc,
  795. count=np + nf + ne,
  796. Pass=np,
  797. fail=nf,
  798. error=ne,
  799. cid='c%s' % (cid + 1),
  800. )
  801. rows.append(row)
  802. for tid, (n, t, o, e) in enumerate(cls_results):
  803. self._generate_report_test(rows, cid, tid, n, t, o, e)
  804. report = self.REPORT_TMPL % dict(
  805. test_list=''.join(rows),
  806. count=str(result.success_count + result.failure_count + result.error_count),
  807. Pass=str(result.success_count),
  808. fail=str(result.failure_count),
  809. error=str(result.error_count),
  810. )
  811. return report
  812. def _generate_report_test(self, rows, cid, tid, n, t, o, e):
  813. # e.g. 'pt1.1', 'ft1.1', etc
  814. has_output = bool(o or e)
  815. tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid + 1, tid + 1)
  816. name = t.id().split('.')[-1]
  817. doc = t.shortDescription() or ""
  818. desc = doc and ('%s: %s' % (name, doc)) or name
  819. tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL
  820. # o and e should be byte string because they are collected from stdout and stderr?
  821. if isinstance(o, str):
  822. # TODO: some problem with 'string_escape': it escape \n and mess up formating
  823. # uo = unicode(o.encode('string_escape'))
  824. uo = o
  825. else:
  826. uo = o
  827. if isinstance(e, str):
  828. # TODO: some problem with 'string_escape': it escape \n and mess up formating
  829. # ue = unicode(e.encode('string_escape'))
  830. ue = e
  831. else:
  832. ue = e
  833. script = self.REPORT_TEST_OUTPUT_TMPL % dict(
  834. id=tid,
  835. output=saxutils.escape(uo + ue),
  836. )
  837. row = tmpl % dict(
  838. tid=tid,
  839. Class=(n == 0 and 'hiddenRow' or 'none'),
  840. # Class = (n == 0 and 'hiddenRow' or 'text text-success'),
  841. # style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none'),
  842. style=n == 2 and 'text text-warning' or (n == 1 and 'text text-danger' or 'text text-success'),
  843. desc=desc,
  844. script=script,
  845. status=self.STATUS[n],
  846. )
  847. rows.append(row)
  848. if not has_output:
  849. return
  850. def _generate_ending(self):
  851. return self.ENDING_TMPL
  852. def ___generate_scrpitone(self):
  853. namerun, faillist, success, error = self._readresult()
  854. return self.SCRPICTDATA % dict(reslutname=namerun,
  855. success=success,
  856. fail=faillist,
  857. error=error)
  858. def _readresult(self):
  859. namerun = []
  860. faillist = []
  861. success = []
  862. error = []
  863. for root, dirs, files in os.walk(self.filepath):
  864. for file in files:
  865. if file.endswith(".txt"):
  866. namerun.append(file.split(".")[0].split("/")[-1])
  867. with open(os.path.join(root, file), 'r') as f:
  868. reslut = f.readline().split('\n')[0].split("_")
  869. success.append(reslut[0])
  870. error.append(reslut[1])
  871. faillist.append(reslut[2])
  872. return namerun, faillist, success, error
  873. def _generate_scrpit(self):
  874. return self.SCRPICTold
  875. ##############################################################################
  876. # Facilities for running tests from the command line
  877. ##############################################################################
  878. # Note: Reuse unittest.TestProgram to launch test. In the future we may
  879. # build our own launcher to support more specific command line
  880. # parameters like test title, CSS, etc.
  881. class TestProgram(unittest.TestProgram):
  882. """
  883. A variation of the unittest.TestProgram. Please refer to the base
  884. class for command line parameters.
  885. """
  886. def runTests(self):
  887. # Pick BSTestRunner as the default test runner.
  888. # base class's testRunner parameter is not useful because it means
  889. # we have to instantiate BSTestRunner before we know self.verbosity.
  890. if self.testRunner is None:
  891. self.testRunner = BSTestRunner(verbosity=self.verbosity)
  892. unittest.TestProgram.runTests(self)
  893. main = TestProgram
  894. ##############################################################################
  895. # Executing this module from the command line
  896. ##############################################################################

Introduction

生成接口测试报告

No topics