上一节是接口测试单条测试get/post,加上封装。
通过学习到unittest,使用其中的unittest.TestCase和Testsuit
#!/usr/bin/env python3 # -*-coding:utf-8-*- # __author__: hunter import unittest from conn.run_demo import RunMain # 上一节写的类,进行调用 import HTMLTestRunner import json class TestMethod(unittest.TestCase): # 定义一个类,集成自unittest.TestCase def setUp(self): self.run = RunMain() # 在初始化方法实例化一个对象,这样就不需要在每个测试用例中在进行实例化 def test01(self): ‘‘‘此用例正常‘‘‘ # 描述用例 url = ‘http://192.168.0.157:18005/oauth/token‘ data = { ‘clientId‘: ‘xxxxxxxxxxxx‘, ‘password‘: ‘123456‘, ‘userName‘: ‘admin‘, ‘VerificationCode‘: ‘‘, ‘VerificationCodeKey‘: "xxxxxxxxxxxx" } r = self.run.run_main(url, ‘POST‘, data) re = json.loads(r) self.assertEqual(re[‘msg‘], ‘OK‘, ‘pass‘) # 断言出参的内容,进行判断,就跟测试用例里面的实际结果预期结果一样 def test02(self): ‘‘‘此用例正常‘‘‘ # 描述用例 url = ‘http://192.168.0.157:18005/oauth/token‘ data = { ‘clientId‘: ‘xxxxxxxxxxx‘, ‘password‘: ‘123456‘, ‘userName‘: ‘admin‘, ‘VerificationCode‘: ‘‘, ‘VerificationCodeKey‘: "xxxxxxxxxxx" } r = self.run.run_main(url, ‘POST‘, data) re = json.loads(r) self.assertEqual(re[‘msg‘], ‘OK‘, ‘Pass‘) ‘‘‘ 断言前,用json库的json.loads()进行解码,因为之前传参的时候用json.dumps()对json格式的编码, 虽然python字典格式与json格式都是一样的,但他们是不一样的;所以要进行编码解码操作 ‘‘‘ def test03(self): ‘‘‘错误的客户端‘‘‘ url = ‘http://192.168.0.157:18005/oauth/token‘ data = { ‘clientId‘: ‘xxxxxxxxx‘, ‘password‘: ‘123456‘, ‘userName‘: ‘admin‘, ‘VerificationCode‘: ‘‘, ‘VerificationCodeKey‘: "xxxxxxxx" } r = self.run.run_main(url, ‘POST‘, data) re = json.loads(r) self.assertEqual(re[‘msg‘], ‘OK‘, ‘Pass‘) #@unittest.skip(‘test04‘) skip()可以进行跳过这条测试用例操作 def test04(self): ‘‘‘密码错误‘‘‘ url = ‘http://192.168.0.157:18005/oauth/token‘ data = { ‘clientId‘: ‘xxxxxxxxxxxxxxxxxx‘, ‘password‘: ‘1123456‘, ‘userName‘: ‘admin‘, ‘VerificationCode‘: ‘‘, ‘VerificationCodeKey‘: "xxxxxxxxxxxxxxxxxx" } r = self.run.run_main(url, ‘POST‘, data) re = json.loads(r) self.assertEqual(re[‘msg‘], ‘OK‘, ‘Pass‘) if __name__ == ‘__main__‘: suite = unittest.TestSuite() # 调用unittest的TestSuite(),理解为管理case的一个容器(测试套件) suite.addTest(TestMethod(‘test001‘)) # 向测试套件中添加用例,"TestMethod"是上面定义的类名,"test01"是用例名 suite.addTest(TestMethod(‘test002‘)) suite.addTest(TestMethod(‘test003‘)) runner = unittest.TextTestRunner() runner.run(suite)
得到结果
原文地址:https://www.cnblogs.com/hemingwei/p/11562187.html
时间: 2024-11-13 10:35:30