Python+requests+exce接口自动化测试框架

一、接口自动化测试框架

二、工程目录

三、Excel测试用例设计

四、基础数据base

封装post/get:runmethod.py

 
  1. #!/usr/bin/env python3

  2. # -*-coding:utf-8-*-

  3. # __author__: hunter

  4. import requests

  5. import json

  6. class RunMain:

  7. def send_get(self, url, data):

  8. res = requests.get(url=url, params=data).json()

  9. # return res

  10. return json.dumps(res, indent=2, sort_keys=False, ensure_ascii=False)

  11. def send_post(self, url, data):

  12. res = requests.post(url=url, data=json.dumps(data)).json()

  13. # return res

  14. return json.dumps(res, indent=2, sort_keys=False, ensure_ascii=False)

  15. def run_main(self, url, method, data=None):

  16. if method == 'POST':

  17. res = self.send_post(url, data)

  18. else:

  19. res = self.send_get(url, data)

  20. return res

HTMLTestrunner:测试报告

 
  1. """

  2. A TestRunner for use with the Python unit testing framework. It

  3. generates a HTML report to show the result at a glance.

  4. The simplest way to use this is to invoke its main method. E.g.

  5. import unittest

  6. import HTMLTestRunner

  7. ... define your tests ...

  8. if __name__ == '__main__':

  9. HTMLTestRunner.main()

  10. For more customization options, instantiates a HTMLTestRunner object.

  11. HTMLTestRunner is a counterpart to unittest's TextTestRunner. E.g.

  12. # output to a file

  13. fp = file('my_report.html', 'wb')

  14. runner = HTMLTestRunner.HTMLTestRunner(

  15. stream=fp,

  16. title='My unit test',

  17. description='This demonstrates the report output by HTMLTestRunner.'

  18. )

  19. # Use an external stylesheet.

  20. # See the Template_mixin class for more customizable options

  21. runner.STYLESHEET_TMPL = '<link rel="stylesheet" href="my_stylesheet.css" type="text/css">'

  22. # run the test

  23. runner.run(my_test_suite)

  24. ------------------------------------------------------------------------

  25. Copyright (c) 2004-2007, Wai Yip Tung

  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. # URL: http://tungwaiyip.info/software/HTMLTestRunner.html

  51. __author__ = "Wai Yip Tung"

  52. __version__ = "0.8.2"

  53. """

  54. Change History

  55. Version 0.8.2

  56. * Show output inline instead of popup window (Viorel Lupu).

  57. Version in 0.8.1

  58. * Validated XHTML (Wolfgang Borgert).

  59. * Added description of test classes and test cases.

  60. Version in 0.8.0

  61. * Define Template_mixin class for customization.

  62. * Workaround a IE 6 bug that it does not treat <script> block as CDATA.

  63. Version in 0.7.1

  64. * Back port to Python 2.3 (Frank Horowitz).

  65. * Fix missing scroll bars in detail log (Podi).

  66. """

  67. # TODO: color stderr

  68. # TODO: simplify javascript using ,ore than 1 class in the class attribute?

  69. import datetime

  70. import io

  71. import sys

  72. import time

  73. import unittest

  74. from xml.sax import saxutils

  75. # ------------------------------------------------------------------------

  76. # The redirectors below are used to capture output during testing. Output

  77. # sent to sys.stdout and sys.stderr are automatically captured. However

  78. # in some cases sys.stdout is already cached before HTMLTestRunner is

  79. # invoked (e.g. calling logging.basicConfig). In order to capture those

  80. # output, use the redirectors for the cached stream.

  81. #

  82. # e.g.

  83. # >>> logging.basicConfig(stream=HTMLTestRunner.stdout_redirector)

  84. # >>>

  85. class OutputRedirector(object):

  86. """ Wrapper to redirect stdout or stderr """

  87. def __init__(self, fp):

  88. self.fp = fp

  89. def write(self, s):

  90. self.fp.write(s)

  91. def writelines(self, lines):

  92. self.fp.writelines(lines)

  93. def flush(self):

  94. self.fp.flush()

  95. stdout_redirector = OutputRedirector(sys.stdout)

  96. stderr_redirector = OutputRedirector(sys.stderr)

  97. # ----------------------------------------------------------------------

  98. # Template

  99. class Template_mixin(object):

  100. """

  101. Define a HTML template for report customerization and generation.

  102. Overall structure of an HTML report

  103. HTML

  104. +------------------------+

  105. |<html> |

  106. | <head> |

  107. | |

  108. | STYLESHEET |

  109. | +----------------+ |

  110. | | | |

  111. | +----------------+ |

  112. | |

  113. | </head> |

  114. | |

  115. | <body> |

  116. | |

  117. | HEADING |

  118. | +----------------+ |

  119. | | | |

  120. | +----------------+ |

  121. | |

  122. | REPORT |

  123. | +----------------+ |

  124. | | | |

  125. | +----------------+ |

  126. | |

  127. | ENDING |

  128. | +----------------+ |

  129. | | | |

  130. | +----------------+ |

  131. | |

  132. | </body> |

  133. |</html> |

  134. +------------------------+

  135. """

  136. STATUS = {

  137. 0: 'pass',

  138. 1: 'fail',

  139. 2: 'error',

  140. }

  141. DEFAULT_TITLE = 'Unit Test Report'

  142. DEFAULT_DESCRIPTION = ''

  143. # ------------------------------------------------------------------------

  144. # HTML Template

  145. HTML_TMPL = r"""<?xml version="1.0" encoding="UTF-8"?>

  146. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  147. <html xmlns="http://www.w3.org/1999/xhtml">

  148. <head>

  149. <title>%(title)s</title>

  150. <meta name="generator" content="%(generator)s"/>

  151. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

  152. %(stylesheet)s

  153. </head>

  154. <body>

  155. <script language="javascript" type="text/javascript"><!--

  156. output_list = Array();

  157. /* level - 0:Summary; 1:Failed; 2:All */

  158. function showCase(level) {

  159. trs = document.getElementsByTagName("tr");

  160. for (var i = 0; i < trs.length; i++) {

  161. tr = trs[i];

  162. id = tr.id;

  163. if (id.substr(0,2) == 'ft') {

  164. if (level < 1) {

  165. tr.className = 'hiddenRow';

  166. }

  167. else {

  168. tr.className = '';

  169. }

  170. }

  171. if (id.substr(0,2) == 'pt') {

  172. if (level > 1) {

  173. tr.className = '';

  174. }

  175. else {

  176. tr.className = 'hiddenRow';

  177. }

  178. }

  179. }

  180. }

  181. function showClassDetail(cid, count) {

  182. var id_list = Array(count);

  183. var toHide = 1;

  184. for (var i = 0; i < count; i++) {

  185. tid0 = 't' + cid.substr(1) + '.' + (i+1);

  186. tid = 'f' + tid0;

  187. tr = document.getElementById(tid);

  188. if (!tr) {

  189. tid = 'p' + tid0;

  190. tr = document.getElementById(tid);

  191. }

  192. id_list[i] = tid;

  193. if (tr.className) {

  194. toHide = 0;

  195. }

  196. }

  197. for (var i = 0; i < count; i++) {

  198. tid = id_list[i];

  199. if (toHide) {

  200. document.getElementById('div_'+tid).style.display = 'none'

  201. document.getElementById(tid).className = 'hiddenRow';

  202. }

  203. else {

  204. document.getElementById(tid).className = '';

  205. }

  206. }

  207. }

  208. function showTestDetail(div_id){

  209. var details_div = document.getElementById(div_id)

  210. var displayState = details_div.style.display

  211. // alert(displayState)

  212. if (displayState != 'block' ) {

  213. displayState = 'block'

  214. details_div.style.display = 'block'

  215. }

  216. else {

  217. details_div.style.display = 'none'

  218. }

  219. }

  220. function html_escape(s) {

  221. s = s.replace(/&/g,'&amp;');

  222. s = s.replace(/</g,'&lt;');

  223. s = s.replace(/>/g,'&gt;');

  224. return s;

  225. }

  226. /* obsoleted by detail in <div>

  227. function showOutput(id, name) {

  228. var w = window.open("", //url

  229. name,

  230. "resizable,scrollbars,status,width=800,height=450");

  231. d = w.document;

  232. d.write("<pre>");

  233. d.write(html_escape(output_list[id]));

  234. d.write("\n");

  235. d.write("<a href='javascript:window.close()'>close</a>\n");

  236. d.write("</pre>\n");

  237. d.close();

  238. }

  239. */

  240. --></script>

  241. %(heading)s

  242. %(report)s

  243. %(ending)s

  244. </body>

  245. </html>

  246. """

  247. # variables: (title, generator, stylesheet, heading, report, ending)

  248. # ------------------------------------------------------------------------

  249. # Stylesheet

  250. #

  251. # alternatively use a <link> for external style sheet, e.g.

  252. # <link rel="stylesheet" href="$url" type="text/css">

  253. STYLESHEET_TMPL = """

  254. <style type="text/css" media="screen">

  255. body { font-family: verdana, arial, helvetica, sans-serif; font-size: 80%; }

  256. table { font-size: 100%; }

  257. pre { }

  258. /* -- heading ---------------------------------------------------------------------- */

  259. h1 {

  260. font-size: 16pt;

  261. color: gray;

  262. }

  263. .heading {

  264. margin-top: 0ex;

  265. margin-bottom: 1ex;

  266. }

  267. .heading .attribute {

  268. margin-top: 1ex;

  269. margin-bottom: 0;

  270. }

  271. .heading .description {

  272. margin-top: 4ex;

  273. margin-bottom: 6ex;

  274. }

  275. /* -- css div popup ------------------------------------------------------------------------ */

  276. a.popup_link {

  277. }

  278. a.popup_link:hover {

  279. color: red;

  280. }

  281. .popup_window {

  282. display: none;

  283. position: relative;

  284. left: 0px;

  285. top: 0px;

  286. /*border: solid #627173 1px; */

  287. padding: 10px;

  288. background-color: #E6E6D6;

  289. font-family: "Lucida Console", "Courier New", Courier, monospace;

  290. text-align: left;

  291. font-size: 8pt;

  292. width: 500px;

  293. }

  294. }

  295. /* -- report ------------------------------------------------------------------------ */

  296. #show_detail_line {

  297. margin-top: 3ex;

  298. margin-bottom: 1ex;

  299. }

  300. #result_table {

  301. width: 80%;

  302. border-collapse: collapse;

  303. border: 1px solid #777;

  304. }

  305. #header_row {

  306. font-weight: bold;

  307. color: white;

  308. background-color: #777;

  309. }

  310. #result_table td {

  311. border: 1px solid #777;

  312. padding: 2px;

  313. }

  314. #total_row { font-weight: bold; }

  315. .passClass { background-color: #6c6; }

  316. .failClass { background-color: #c60; }

  317. .errorClass { background-color: #c00; }

  318. .passCase { color: #6c6; }

  319. .failCase { color: #c60; font-weight: bold; }

  320. .errorCase { color: #c00; font-weight: bold; }

  321. .hiddenRow { display: none; }

  322. .testcase { margin-left: 2em; }

  323. /* -- ending ---------------------------------------------------------------------- */

  324. #ending {

  325. }

  326. </style>

  327. """

  328. # ------------------------------------------------------------------------

  329. # Heading

  330. #

  331. HEADING_TMPL = """<div class='heading'>

  332. <h1>%(title)s</h1>

  333. %(parameters)s

  334. <p class='description'>%(description)s</p>

  335. </div>

  336. """ # variables: (title, parameters, description)

  337. HEADING_ATTRIBUTE_TMPL = """<p class='attribute'><strong>%(name)s:</strong> %(value)s</p>

  338. """ # variables: (name, value)

  339. # ------------------------------------------------------------------------

  340. # Report

  341. #

  342. REPORT_TMPL = """

  343. <p id='show_detail_line'>Show

  344. <a href='javascript:showCase(0)'>Summary</a>

  345. <a href='javascript:showCase(1)'>Failed</a>

  346. <a href='javascript:showCase(2)'>All</a>

  347. </p>

  348. <table id='result_table'>

  349. <colgroup>

  350. <col align='left' />

  351. <col align='right' />

  352. <col align='right' />

  353. <col align='right' />

  354. <col align='right' />

  355. <col align='right' />

  356. </colgroup>

  357. <tr id='header_row'>

  358. <td>Test Group/Test case</td>

  359. <td>Count</td>

  360. <td>Pass</td>

  361. <td>Fail</td>

  362. <td>Error</td>

  363. <td>View</td>

  364. </tr>

  365. %(test_list)s

  366. <tr id='total_row'>

  367. <td>Total</td>

  368. <td>%(count)s</td>

  369. <td>%(Pass)s</td>

  370. <td>%(fail)s</td>

  371. <td>%(error)s</td>

  372. <td>&nbsp;</td>

  373. </tr>

  374. </table>

  375. """ # variables: (test_list, count, Pass, fail, error)

  376. REPORT_CLASS_TMPL = r"""

  377. <tr class='%(style)s'>

  378. <td>%(desc)s</td>

  379. <td>%(count)s</td>

  380. <td>%(Pass)s</td>

  381. <td>%(fail)s</td>

  382. <td>%(error)s</td>

  383. <td><a href="javascript:showClassDetail('%(cid)s',%(count)s)">Detail</a></td>

  384. </tr>

  385. """ # variables: (style, desc, count, Pass, fail, error, cid)

  386. REPORT_TEST_WITH_OUTPUT_TMPL = r"""

  387. <tr id='%(tid)s' class='%(Class)s'>

  388. <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>

  389. <td colspan='5' align='center'>

  390. <!--css div popup start-->

  391. <a class="popup_link" onfocus='this.blur();' href="javascript:showTestDetail('div_%(tid)s')" >

  392. %(status)s</a>

  393. <div id='div_%(tid)s' class="popup_window">

  394. <div style='text-align: right; color:red;cursor:pointer'>

  395. <a onfocus='this.blur();' onclick="document.getElementById('div_%(tid)s').style.display = 'none' " >

  396. [x]</a>

  397. </div>

  398. <pre>

  399. %(script)s

  400. </pre>

  401. </div>

  402. <!--css div popup end-->

  403. </td>

  404. </tr>

  405. """ # variables: (tid, Class, style, desc, status)

  406. REPORT_TEST_NO_OUTPUT_TMPL = r"""

  407. <tr id='%(tid)s' class='%(Class)s'>

  408. <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>

  409. <td colspan='5' align='center'>%(status)s</td>

  410. </tr>

  411. """ # variables: (tid, Class, style, desc, status)

  412. REPORT_TEST_OUTPUT_TMPL = r"""

  413. %(id)s: %(output)s

  414. """ # variables: (id, output)

  415. # ------------------------------------------------------------------------

  416. # ENDING

  417. #

  418. ENDING_TMPL = """<div id='ending'>&nbsp;</div>"""

  419. # -------------------- The end of the Template class -------------------

  420. TestResult = unittest.TestResult

  421. class _TestResult(TestResult):

  422. # note: _TestResult is a pure representation of results.

  423. # It lacks the output and reporting ability compares to unittest._TextTestResult.

  424. def __init__(self, verbosity=1):

  425. TestResult.__init__(self)

  426. self.stdout0 = None

  427. self.stderr0 = None

  428. self.success_count = 0

  429. self.failure_count = 0

  430. self.error_count = 0

  431. self.verbosity = verbosity

  432. # result is a list of result in 4 tuple

  433. # (

  434. # result code (0: success; 1: fail; 2: error),

  435. # TestCase object,

  436. # Test output (byte string),

  437. # stack trace,

  438. # )

  439. self.result = []

  440. def startTest(self, test):

  441. TestResult.startTest(self, test)

  442. # just one buffer for both stdout and stderr

  443. self.outputBuffer = io.BytesIO()

  444. stdout_redirector.fp = self.outputBuffer

  445. stderr_redirector.fp = self.outputBuffer

  446. self.stdout0 = sys.stdout

  447. self.stderr0 = sys.stderr

  448. sys.stdout = stdout_redirector

  449. sys.stderr = stderr_redirector

  450. def complete_output(self):

  451. """

  452. Disconnect output redirection and return buffer.

  453. Safe to call multiple times.

  454. """

  455. if self.stdout0:

  456. sys.stdout = self.stdout0

  457. sys.stderr = self.stderr0

  458. self.stdout0 = None

  459. self.stderr0 = None

  460. return self.outputBuffer.getvalue()

  461. def stopTest(self, test):

  462. # Usually one of addSuccess, addError or addFailure would have been called.

  463. # But there are some path in unittest that would bypass this.

  464. # We must disconnect stdout in stopTest(), which is guaranteed to be called.

  465. self.complete_output()

  466. def addSuccess(self, test):

  467. self.success_count += 1

  468. TestResult.addSuccess(self, test)

  469. output = self.complete_output()

  470. self.result.append((0, test, output, ''))

  471. if self.verbosity > 1:

  472. sys.stderr.write('ok ')

  473. sys.stderr.write(str(test))

  474. sys.stderr.write('\n')

  475. else:

  476. sys.stderr.write('.')

  477. def addError(self, test, err):

  478. self.error_count += 1

  479. TestResult.addError(self, test, err)

  480. _, _exc_str = self.errors[-1]

  481. output = self.complete_output()

  482. self.result.append((2, test, output, _exc_str))

  483. if self.verbosity > 1:

  484. sys.stderr.write('E ')

  485. sys.stderr.write(str(test))

  486. sys.stderr.write('\n')

  487. else:

  488. sys.stderr.write('E')

  489. def addFailure(self, test, err):

  490. self.failure_count += 1

  491. TestResult.addFailure(self, test, err)

  492. _, _exc_str = self.failures[-1]

  493. output = self.complete_output()

  494. self.result.append((1, test, output, _exc_str))

  495. if self.verbosity > 1:

  496. sys.stderr.write('F ')

  497. sys.stderr.write(str(test))

  498. sys.stderr.write('\n')

  499. else:

  500. sys.stderr.write('F')

  501. class HTMLTestRunner(Template_mixin):

  502. """

  503. """

  504. def __init__(self, stream=sys.stdout, verbosity=1, title=None, description=None):

  505. self.stream = stream

  506. self.verbosity = verbosity

  507. if title is None:

  508. self.title = self.DEFAULT_TITLE

  509. else:

  510. self.title = title

  511. if description is None:

  512. self.description = self.DEFAULT_DESCRIPTION

  513. else:

  514. self.description = description

  515. self.startTime = datetime.datetime.now()

  516. def run(self, test):

  517. "Run the given test case or test suite."

  518. result = _TestResult(self.verbosity)

  519. test(result)

  520. self.stopTime = datetime.datetime.now()

  521. self.generateReport(test, result)

  522. print(sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime))

  523. return result

  524. def sortResult(self, result_list):

  525. # unittest does not seems to run in any particular order.

  526. # Here at least we want to group them together by class.

  527. rmap = {}

  528. classes = []

  529. for n,t,o,e in result_list:

  530. cls = t.__class__

  531. if not cls in rmap:

  532. rmap[cls] = []

  533. classes.append(cls)

  534. rmap[cls].append((n,t,o,e))

  535. r = [(cls, rmap[cls]) for cls in classes]

  536. return r

  537. def getReportAttributes(self, result):

  538. """

  539. Return report attributes as a list of (name, value).

  540. Override this to add custom attributes.

  541. """

  542. startTime = str(self.startTime)[:19]

  543. duration = str(self.stopTime - self.startTime)

  544. status = []

  545. if result.success_count: status.append('Pass %s' % result.success_count)

  546. if result.failure_count: status.append('Failure %s' % result.failure_count)

  547. if result.error_count: status.append('Error %s' % result.error_count )

  548. if status:

  549. status = ' '.join(status)

  550. else:

  551. status = 'none'

  552. return [

  553. ('Start Time', startTime),

  554. ('Duration', duration),

  555. ('Status', status),

  556. ]

  557. def generateReport(self, test, result):

  558. report_attrs = self.getReportAttributes(result)

  559. generator = 'HTMLTestRunner %s' % __version__

  560. stylesheet = self._generate_stylesheet()

  561. heading = self._generate_heading(report_attrs)

  562. report = self._generate_report(result)

  563. ending = self._generate_ending()

  564. output = self.HTML_TMPL % dict(

  565. title = saxutils.escape(self.title),

  566. generator = generator,

  567. stylesheet = stylesheet,

  568. heading = heading,

  569. report = report,

  570. ending = ending,

  571. )

  572. self.stream.write(output.encode('utf8'))

  573. def _generate_stylesheet(self):

  574. return self.STYLESHEET_TMPL

  575. def _generate_heading(self, report_attrs):

  576. a_lines = []

  577. for name, value in report_attrs:

  578. line = self.HEADING_ATTRIBUTE_TMPL % dict(

  579. name = saxutils.escape(name),

  580. value = saxutils.escape(value),

  581. )

  582. a_lines.append(line)

  583. heading = self.HEADING_TMPL % dict(

  584. title = saxutils.escape(self.title),

  585. parameters = ''.join(a_lines),

  586. description = saxutils.escape(self.description),

  587. )

  588. return heading

  589. def _generate_report(self, result):

  590. rows = []

  591. sortedResult = self.sortResult(result.result)

  592. for cid, (cls, cls_results) in enumerate(sortedResult):

  593. # subtotal for a class

  594. np = nf = ne = 0

  595. for n,t,o,e in cls_results:

  596. if n == 0: np += 1

  597. elif n == 1: nf += 1

  598. else: ne += 1

  599. # format class description

  600. if cls.__module__ == "__main__":

  601. name = cls.__name__

  602. else:

  603. name = "%s.%s" % (cls.__module__, cls.__name__)

  604. doc = cls.__doc__ and cls.__doc__.split("\n")[0] or ""

  605. desc = doc and '%s: %s' % (name, doc) or name

  606. row = self.REPORT_CLASS_TMPL % dict(

  607. style = ne > 0 and 'errorClass' or nf > 0 and 'failClass' or 'passClass',

  608. desc = desc,

  609. count = np+nf+ne,

  610. Pass = np,

  611. fail = nf,

  612. error = ne,

  613. cid = 'c%s' % (cid+1),

  614. )

  615. rows.append(row)

  616. for tid, (n,t,o,e) in enumerate(cls_results):

  617. self._generate_report_test(rows, cid, tid, n, t, o, e)

  618. report = self.REPORT_TMPL % dict(

  619. test_list = ''.join(rows),

  620. count = str(result.success_count+result.failure_count+result.error_count),

  621. Pass = str(result.success_count),

  622. fail = str(result.failure_count),

  623. error = str(result.error_count),

  624. )

  625. return report

  626. def _generate_report_test(self, rows, cid, tid, n, t, o, e):

  627. # e.g. 'pt1.1', 'ft1.1', etc

  628. has_output = bool(o or e)

  629. tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid+1,tid+1)

  630. name = t.id().split('.')[-1]

  631. doc = t.shortDescription() or ""

  632. desc = doc and ('%s: %s' % (name, doc)) or name

  633. tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL

  634. # o and e should be byte string because they are collected from stdout and stderr?

  635. if isinstance(o,str):

  636. # TODO: some problem with 'string_escape': it escape \n and mess up formating

  637. # uo = unicode(o.encode('string_escape'))

  638. uo = o.decode('latin-1')

  639. else:

  640. uo = o

  641. if isinstance(e,str):

  642. # TODO: some problem with 'string_escape': it escape \n and mess up formating

  643. # ue = unicode(e.encode('string_escape'))

  644. ue = e

  645. else:

  646. ue = e

  647. script = self.REPORT_TEST_OUTPUT_TMPL % dict(

  648. id = tid,

  649. output = saxutils.escape(str(uo)+ue),

  650. )

  651. row = tmpl % dict(

  652. tid = tid,

  653. Class = (n == 0 and 'hiddenRow' or 'none'),

  654. style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none'),

  655. desc = desc,

  656. script = script,

  657. status = self.STATUS[n],

  658. )

  659. rows.append(row)

  660. if not has_output:

  661. return

  662. def _generate_ending(self):

  663. return self.ENDING_TMPL

  664. ##############################################################################

  665. # Facilities for running tests from the command line

  666. ##############################################################################

  667. # Note: Reuse unittest.TestProgram to launch test. In the future we may

  668. # build our own launcher to support more specific command line

  669. # parameters like test title, CSS, etc.

  670. class TestProgram(unittest.TestProgram):

  671. """

  672. A variation of the unittest.TestProgram. Please refer to the base

  673. class for command line parameters.

  674. """

  675. def runTests(self):

  676. # Pick HTMLTestRunner as the default test runner.

  677. # base class's testRunner parameter is not useful because it means

  678. # we have to instantiate HTMLTestRunner before we know self.verbosity.

  679. if self.testRunner is None:

  680. self.testRunner = HTMLTestRunner(verbosity=self.verbosity)

  681. unittest.TestProgram.runTests(self)

  682. main = TestProgram

  683. ##############################################################################

  684. # Executing this module from the command line

  685. ##############################################################################

  686. if __name__ == "__main__":

  687. main(module=None)

五、data操作Excel的读写、日志

handle_excel.py:封装Excel的读写

 
  1. #!/usr/bin/env python3

  2. # -*-coding:utf-8-*-

  3. # __author__: hunter

  4. import xlrd

  5. from xlutils.copy import copy

  6. class HandleExcel:

  7. """封装操作Excel的方法"""

  8. def __init__(self, file='D:/hunter_/interfaceTest/hunter_interface/case/demo2.xlsx', sheet_id=0):

  9. self.file = file

  10. self.sheet_id = sheet_id

  11. self.data = self.get_data()

  12. # 为了创建一个实例时就获得Excel的sheet对象,可以在构造器中调用get_data()

  13. # 因为类在实例化时就会自动调用构造器,这样创建一个实例时就会自动获得sheet对象了

  14. # 获取某一页sheet对象

  15. def get_data(self):

  16. data = xlrd.open_workbook(self.file)

  17. sheet = data.sheet_by_index(self.sheet_id)

  18. return sheet

  19. # 获取Excel数据行数

  20. def get_rows(self):

  21. rows = self.data.nrows

  22. return rows

  23. # 获取某个单元格写入数据

  24. def get_value(self, row, col):

  25. value = self.data.cell_value(row, col)

  26. return value

  27. # 向某个单元格写入数据

  28. def write_value(self, row, col, value):

  29. data = xlrd.open_workbook(self.file) # 打开文件

  30. data_copy = copy(data) # 复制源文件

  31. sheet = data_copy.get_sheet(0) # 取得复制文件的sheet对象

  32. sheet.write(row, col, value) # 在某一单元格写入value

  33. data_copy.save(self.file) # 保存文件

  34. def get_caseNmber():

  35. caseNmber = 0

  36. return caseNmber

  37. def get_caseType():

  38. caseType = 1

  39. return caseType

  40. def get_caseName():

  41. caseName = 2

  42. return caseName

  43. def get_priority():

  44. priority = 3

  45. return priority

  46. def get_url():

  47. url = 4

  48. return url

  49. def get_mothod():

  50. mothod = 5

  51. return mothod

  52. def get_header():

  53. header = 6

  54. return header

  55. def get_purpose():

  56. purpose = 7

  57. return purpose

  58. def get_params():

  59. params = 8

  60. return params

  61. def get_expectvalue():

  62. expectvalue = 9

  63. return expectvalue

  64. def get_actualvalue():

  65. actualvalue = 10

  66. return actualvalue

  67. def get_resultvalue():

  68. resultvalue = 11

  69. return resultvalue

logger:封装日志

 
  1. #!/usr/bin/env python3

  2. # -*-coding:utf-8-*-

  3. # __author__: hunter

  4. import logging

  5. import os

  6. import time

  7. class Logger:

  8. def __init__(self, loggername):

  9. # 创建一个logger

  10. self.logger = logging.getLogger(loggername)

  11. print(self.logger)

  12. self.logger.setLevel(logging.DEBUG)

  13. # 创建一个handler,用于写入文件

  14. rq = time.strftime('%Y%m%d', time.localtime(time.time()))

  15. log_path = os.path.dirname(os.path.abspath('.')) + '/logs/' # 指定文件输出路径,注意logs是一个文件夹,

  16. logname = log_path + rq + 'test.log' # 指定输出的日志文件名

  17. fh = logging.FileHandler(logname, encoding='utf-8') # 指定utf-8格式编码,避免输出的日志文本乱码

  18. print(fh)

  19. fh.setLevel(logging.DEBUG)

  20. # 创建一个handler,用于将日志输出到控制台

  21. ch = logging.StreamHandler()

  22. ch.setLevel(logging.DEBUG)

  23. # 定义handler的输出格式

  24. formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')

  25. fh.setFormatter(formatter)

  26. ch.setFormatter(formatter)

  27. # 给logger添加handler

  28. self.logger.addHandler(fh)

  29. self.logger.addHandler(ch)

  30. def get_log(self):

  31. """定义一个函数,回调logger实例"""

  32. return self.logger

六、日志

20190928test.log

七、main主函数

  run_test.py

 
  1. #!/usr/bin/env python3

  2. # -*-coding:utf-8-*-

  3. # __author__: hunter

  4. from conn.run_demo import RunMain

  5. from hunter_interface.data.handle_excel import *

  6. from hunter_interface.data.logger import Logger

  7. import json

  8. from hunter_interface.base.runmethod import RunMain

  9. class RunTestCase:

  10. def __init__(self):

  11. self.Runmain = RunMain()

  12. self.data = HandleExcel()

  13. self.logger = Logger(__name__)

  14. def go_run(self):

  15. rows_count = self.data.get_rows() # 获取Excel行数

  16. for i in range(1, rows_count):

  17. url = self.data.get_value(i, get_url()) # 循环获取URL的值

  18. method = self.data.get_value(i, get_mothod()) # 循环获取method的值

  19. print(self.data.get_value(i, get_params()))

  20. data = json.loads(self.data.get_value(i, get_params()))

  21. expect = self.data.get_value(i, get_expectvalue())

  22. is_run = self.data.get_value(i, get_priority())

  23. if is_run == 'high':

  24. res = self.Runmain.run_main(url, method, data)

  25. self.logger.get_log().debug('第' + str(i) + '个接口的返回结果为:%s', res) # 日志:输出接口响应内容

  26. self.data.write_value(i, get_actualvalue(), res) # 将实际结果写入Excel中

  27. if expect in res: # res返回的内容是否包含expect,是否与期望一致

  28. print((expect))

  29. print(type(expect))

  30. print((res))

  31. print(type(res))

  32. print('测试通过')

  33. self.logger.get_log().error('第' + str(i) + '接口测试通过')

  34. self.data.write_value(i, get_resultvalue(), 'pass') # 调用写入数据方法,将结果写进Excel

  35. else:

  36. # print("测试失败")

  37. self.logger.get_log().info('第' + str(i) + '接口测试失败')

  38. self.data.write_value(i, get_resultvalue(), 'fail')

  39. if __name__ == '__main__':

  40. run = RunTestCase()

  41. run.go_run()

八、测试报告report

 最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值