1. 测试代码如下 python3.5
import os import unittest,json,HTMLTestRunner from urllib import request, parse class Testbdapi(unittest.TestCase): def setUp(self): #如果不需要每个case都预置和清理环境,而是每个class用一次,只需要用setUpClass、tearDownClass代替即可,如果是整个文件只需要用一次,则用要用 setUpModule() 和 tearDownModule() 这两个函数了,注意是函数,与 TestCase 类同级 url = "http://fanyi.baidu.com/v2transapi" def testapi1(self): headers={ "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36" } params = { "from":"en", "to":"zh", "query": "hotel" #查询 } url = "http://fanyi.baidu.com/v2transapi" params=parse.urlencode(params).encode(‘utf-8‘) r = request.Request(url, headers=headers, data=params) page=request.urlopen(r).read() rs=json.loads(page.decode(‘utf8‘)) assert u‘酒店‘ in rs[‘trans_result‘][‘data‘][0][‘dst‘] def testapi2(self): headers={ "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36" } params = { "from":"en", "to":"zh", "query": "hot" # } url = "http://fanyi.baidu.com/v2transapi" params=parse.urlencode(params).encode(‘utf-8‘) r = request.Request(url, headers=headers, data=params) page=request.urlopen(r).read() #return page rs=json.loads(page.decode(‘utf8‘)) assert u‘酒店‘ in rs[‘trans_result‘][‘data‘][0][‘dst‘] def tearDown(self): pass if __name__==‘__main__‘: path= r‘test.html‘ open_sys= open(path,‘wb‘) #执行整个类的用例 suite=unittest.TestLoader().loadTestsFromTestCase(Testbdapi) #执行某一个用例 #定义一个测试容器 test = unittest.TestSuite() #将测试用例,加入到测试容器中 test.addTest(Testbdapi("testapi1")) test.addTest(Testbdapi("testapi2")) runner=HTMLTestRunner.HTMLTestRunner( stream=open_sys, #打开写入流 title=u‘百度翻译api接口测试报告‘, description=u‘接口测试详情‘ ) #runner.run(test) runner.run(suite) #写入用例执行结果 open_sys.close() #关闭写入流 os.system(‘start test.html‘) #打开html报告
html报告代码
2.将HTMLTestRunner.py 放到python安装目录的lib下
时间: 2024-10-04 08:38:32