1. 下载HTMLTestRunner,放到Python安装目录的Lib下
导入验证一下,没有报错,说明是成功的
二、代码实现部分
1. RunMain模块:
#coding=utf-8 import requests import json class RunMain: """无构造器""" def send_get(self, url, data): res = requests.get(url=url, params=data).json() return res def send_post(self, url, data): res = requests.post(url=url, data=data).json() return res def run_main(self, url, method, data=None): res = None if method == 'GET': res = self.send_get(url, data) else: res = self.send_post(url, data) return res
2. 主代码:
1 #coding:utf-8 2 3 import unittest 4 from TestDemo_No_init import RunMain # 导入之前写好的模块 5 import json 6 import HTMLTestRunner # 导入刚才下载的HTMLTestRunner 7 8 9 class TestMethod(unittest.TestCase): 10 11 def setUp(self): 12 self.run = RunMain() 13 14 15 def test01(self): 16 """这是一个POST的接口自动化测试""" # 添加用例描述,增加HTML测试报告生成后的可读性 17 url = 'http://127.0.0.1:8000/login/' 18 data = { 19 'username': 'Jessie', 20 'password': '123456' 21 } 22 r = self.run.run_main(url, 'POST', data) 23 print(r) 24 re = json.dumps(r, indent=2, sort_keys=False, ensure_ascii=False) 25 re_new = json.loads(re) 26 self.assertEqual(re_new['user'], 'Jessie', '测试失败') 27 28 29 def test02(self): 30 """查询翻译词的接口""" 31 url = 'http://fanyi.youdao.com/translate' 32 data = { 33 'doctype': 'json', 34 'type': 'AUTO', 35 'i': 'weather' 36 } 37 r = self.run.run_main(url, 'GET', data) 38 print(r) 39 re = json.dumps(r, indent=2, sort_keys=False, ensure_ascii=False) 40 re_new = json.loads(re) 41 self.assertEqual(re_new['errorCode'], 0, '测试失败') 42 43 44 @unittest.skip('test03') # 跳过test03测试用例 45 def test03(self): 46 url = 'http://fanyi.youdao.com/translate' 47 data = { 48 'doctype': 'json', 49 'type': 'AUTO', 50 'i': '天气' 51 } 52 r = self.run.run_main(url, 'GET', data) 53 print(r) 54 re = json.dumps(r, indent=2, sort_keys=False, ensure_ascii=False) 55 re_new = json.loads(re) 56 self.assertEqual(re_new['errorCode'], 0, '测试失败') 57 58 59 60 if __name__ == '__main__': 61 # unittest.main() 62 63 filepath = 'G:/ImoocInterface/report/test_report.html' # 测试报告生成的地址 64 fp = open(filepath, 'wb') # 文件流 65 66 suite = unittest.TestSuite() 67 suite.addTest(TestMethod('test01')) 68 suite.addTest(TestMethod('test02')) 69 # suite.addTest(TestMethod('test03')) 70 71 # runner = unittest.TextTestRunner() 72 # runner.run(suite) 73 # unittest.TextTestRunner().run(suite) 74 75 # stream:文件流 title:报告的标题 description:报告的描述信息 76 runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='测试报告', description='测试结果') 77 78 runner.run(suite) #HTML报告和Unittest结合 79 fp.close()
3. 运行
注意:一定是运行这个py文件
三、查看测试报告
1. 找到设置存放报告的目录G:\ImoocInterface\report,果然有一份测试报告
2. 打开报告查看详情