class TestLogin(unittest.TestCase): logger.info('开始执行TestLogin测试类') testdata = DoExcel(contants.case_file, 'login').read_data() @classmethod def setUpClass(cls): cls.session = HttpRequest2() @data(*testdata) def testLogin(self, case): case.data = Context().replace(case.data) res = self.session.request(method=case.method, url=case.url, data=case.data) logger.info('执行用例是:{},请求url是:{}'.format(case.title, case.url)) logger.info('请求数据是:{}'.format(case.data)) try: self.assertEqual(case.expected, res.text) except AssertionError as e: DoExcel(contants.case_file, 'login').write_data(case.case_id + 1, res.text, 'failed') logger.error('断言出错,错误信息是:{}'.format(e)) else: DoExcel(contants.case_file, 'login').write_data(case.case_id + 1, res.text, 'pass') logger.info('用例执行成功')
class TestAdd(unittest.TestCase): logger.info('开始执行TestAdd测试类') testdata = DoExcel(case_file, 'add').read_data() @classmethod def setUpClass(cls): cls.session = HttpRequest2() cls.mysql = DoMysql() @data(*testdata) def testInvest(self, case): case.data = Context().replace( case.data) #使用正则表达式,将Excel中参数化的值替换为配置文件中读取出来的值 res = self.session.request(method=case.method, url=case.url, data=case.data) logger.info('执行用例是:{},请求url是:{}'.format(case.title, case.url)) logger.info('请求数据是:{}'.format(case.data)) try: self.assertEqual(case.expected, int(res.json()["code"])) except AssertionError as e: DoExcel(case_file, 'add').write_data(case.case_id + 1, res.text, 'failed') logger.error("断言失败,错误信息是:{}".format(e)) else: DoExcel(case_file, 'add').write_data(case.case_id + 1, res.text, 'pass') logger.info('用例执行成功') if res.json()['msg'] == '加标成功': case.sql = Context().replace(case.sql) loadId = self.mysql.fetch_one(case.sql)['id'] setattr(Context, 'loanId', str(loadId))
def __init__(self, excel_name, sheet_name): ''' 初始化DoExcel和ConfigHttp ''' self.excel = DoExcel(excel_name, sheet_name) self.row_num = self.excel.get_row_num(0, "bd-001") self.excel.write_excel(0, self.row_num, 10, None) self.new_request = ConfigHttp("HTTP", "host", "port", "timeout") self.url = self.excel.read_cell(self.row_num, 2)
class GetToken: def __init__(self): self.test_data_excel = DoExcel("case.xls", "weixin") self.row_num = self.test_data_excel.get_row_num(0, "weixin-001") self.new_request = ConfigHttp("HTTP2", "host", "port", "timeout") def get_token(self): self.new_request.set_url(url) self.new_request.set_params(params) res = self.new_request.get() self.test_data_excel.write_excel(0, self.row_num, 6, res.text) return res
class AuditTest(unittest.TestCase): doexcel = DoExcel(contants.cases_dir) cases = doexcel.read("audit") request = HttpRequest() def setUp(self): pass @data(*cases) def test_audit(self, case): logger.info("执行第{}条用例,用例标题是:{}".format(case["case_id"], case["title"])) res = self.request.request(case["method"], case["url"], case["data"]) print("响应的结果:{}".format(res.json())) try: self.assertEqual(case["expectedresult"], res.text, "audit error") self.doexcel.write_back("audit", case["case_id"] + 1, res.text, "Pass") logger.error("第{}条用例执行的结果是:PASS".format(case["case_id"])) except AssertionError as e: self.doexcel.write_back("audit", case["case_id"] + 1, res.text, "Fail") logger.error("第{}条用例执行的结果是:FAIL".format(case["case_id"])) raise e def tearDown(self): pass
class TestRegister(unittest.TestCase): logger.info('开始执行TestRegister测试类') testdata = DoExcel(contants.case_file, 'register').read_data() @classmethod def setUpClass(cls): cls.session = HttpRequest2() cls.mysql = DoMysql() @data(*testdata) def testRegister(self, case): #将注册手机号在Excel中参数化,方式一:使用字符串替换 # if case.data.find('register_phone') > -1: # #如果在case.data中找到register_phone,就去数据库找到最大的手机号并+1。 # max_phone = self.mysql.fetch_one('select max(mobilephone) from member')[0]#如果返回数据是元组,用索引取值 # max_phone = int(max_phone)+1 # #把case.data字符串中的register_phone替换为重新赋值的最大手机号, # #replace方法是替换之后返回一个新的字符串,所有要重新定义变量去接收 # case.data = case.data.replace('register_phone',str(max_phone)) #方式二:使用字典的方式,给字典的key重新赋值 case.data = eval(case.data) if case.data.__contains__('mobilephone') and case.data[ 'mobilephone'] == 'register_phone': max_phone = self.mysql.fetch_one( 'select max(mobilephone) from future.member')[ 'max(mobilephone)'] #返回数据是字典,用key取值 max_phone = int(max_phone) + 1 case.data['mobilephone'] = max_phone
class AddTest(unittest.TestCase): request = HttpRequest() doexcel = DoExcel(cases_dir) cases = doexcel.read("add") #获取测试数据 def setUp(self): #用例运行它就运行 pass @data(*cases) def test_add(self, case): logger.info("开始执行{}条用例了,用例标题是:{}".format(case["case_id"], case["title"])) res = self.request.request(case["method"], case["url"], case["data"]) print("响应的结果:{}".format(res.json())) try: #self.assertEqual(case["expectedresult"],res.text,"add error!!") #self.doexcel.write_back("add",case["case_id"]+1,res.text,"PASS") logger.error("第{}条用例执行的结果是:PASS".format(case["case_id"])) except AssertionError as e: #try监控断言,出错了继续执行下面的代码(假如不加断言,用例失败了,代码就停了) self.doexcel.write_back("add", case["case_id"] + 1, res.text, "FAIL") logger.error("第{}条用例执行的结果是:FAIL".format(case["case_id"])) raise e def tearDown(self): #用例运行它就运行 pass
class RechargeTest(unittest.TestCase): doexcel=DoExcel(cases_dir) cases=doexcel.read("recharge") request=HttpRequest()#实例化一个对象request,再用request调用里面的函数 def setUp(self): pass @data(*cases) def test_recharge(self,case): logger.info("正在执行{}条用例,用例标题是:{}".format(case["case_id"],case["title"])) res=self.request.request(case["method"],case["url"],case["data"]) print('响应结果:',res.text) try: self.assertEqual(str(case["expectedresult"]),res.json()["code"],"recharge error!!!") self.doexcel.write_back("recharge",case["case_id"]+1,res.text,"PASS") logger.error("第{}条用例执行的结果是:PASS".format(case["case_id"])) except AssertionError as e: self.doexcel.write_back("recharge", case["case_id"] + 1, res.text, "FAIL") logger.error("第{}条用例执行的结果是:FAIL".format(case["case_id"])) raise e def tearDown(self): pass
class TestSendMCode(unittest.TestCase): testdata = DoExcel(case_file,'sendMCode').read_data() @classmethod def setUpClass(cls): cls.excel = DoExcel(case_file,'sendMCode') cls.mysql = DoMysql() @data(*testdata) def testSendMCode(self,case): logger.info('执行用例是:{},请求url是:{},请求数据是:{}'.format(case.title, case.url, case.data)) try: case.data = Context().replace(case.data) res = Request('sendMCode').request(case.url,eval(case.data)) try: self.assertEqual(res['retCode'],eval(case.expected)['retCode']) self.excel.write_data(case.case_id+1, str(res), 'pass') if res['retCode'] == '0' and res['retInfo'] == 'ok': case.sql = Context().replace(case.sql) mcode = self.mysql.fetch_one(case.sql)['Fverify_code'] if mcode: logger.info('成功获取验证码:{}'.format(mcode)) else: logger.info('获取验证码失败') except AssertionError as e: self.excel.write_data(case.case_id + 1, str(res), 'filed') logger.error('断言失败,错误是:{}'.format(e)) except suds.WebFault as e: try: self.assertEqual(e.fault['faultstring'],case.expected) self.excel.write_data(case.case_id + 1, str(e.fault), 'pass') except AssertionError as e: self.excel.write_data(case.case_id + 1, str(e.fault), 'failed') logger.error('断言失败,错误是:{}'.format(e))
class LoginTest(unittest.TestCase): request = HttpRequest() doexcel = DoExcel(cases_dir) cases = doexcel.read("login") # 获取登录的测试用例 def setUp(self): pass @data(*cases) def test_login(self, case): logger.info("正在执行{}条用例,用例标题:{}".format(case["case_id"], case["title"])) res = self.request.request(case["method"], case["url"], case["data"]) print("请求的url:", res.url) print("响应的结果:", res.json()) try: # 用期望结果和实际结果做断言 self.assertEqual(case["expectedresult"], res.text, "login error") #如果期望结果和实际结果相等,就写回 self.doexcel.write_back("login", case["case_id"] + 1, res.text, "PASS") logger.error("第{}条用例执行结果:PASS".format(case["case_id"])) except AssertionError as e: self.doexcel.write_back("login", case["case_id"] + 1, res.text, "Fail") logger.error("第{}条用例执行结果:FAIL".format(case["case_id"])) raise e def tearDown(self): pass
class WeiXinTest(unittest.TestCase): '''微信公众号测试''' def setUp(self): self.excel = DoExcel("case.xls", "weixin") self.weixin = WeiXin(self.excel) self.logger = Logger("FOX", cmd_log_level=logging.INFO, file_log_level=logging.INFO) def test_get_token(self): access_token = self.weixin.get_token().json()["access_token"] print(access_token) row_num = self.excel.get_row_num(0, "weixin-001") self.excel.write_excel(0, row_num, 6, access_token) def test_post_message(self): self.weixin.send_message() row_num = self.excel.get_row_num(0, "weixin-002") result = self.excel.read_cell(row_num, 10) self.assertEqual(result, "pass") def tearDown(self): pass
class RegisterTest(unittest.TestCase): request = HttpRequest() doexcel = DoExcel(cases_dir) cases = doexcel.read("register") #获取注册的测试用例 # print(type(max_mobilephone))#数据库取出来的vachar类型,也就是str类型 def setUp(self): #每个用例执行开始前,都要运行,获取数据库里面最大的手机号 self.mysql = MysqlUtil() # 创建数据库连接,打开查询页面 sql = "select MAX(MobilePhone)from future.member" # 查询数据库里面最大的手机号 self.max_mobilephone = self.mysql.fetch_one(sql)[ 0] # 从数据库里面查询出来的数据类型是:元组,要用下标取值;数据库里面最大的手机号是:max_mobilephone @data(*cases) def test_register(self, case): logger.info("正在执行{}条用例,用例标题是:{}".format(case["case_id"], case["title"])) import json data_dict = json.loads( case["data"]) #excel表中的data数据是str类型,需要转成json字典格式的字符串 if data_dict[ "mobilephone"] == "$register_mobilephone": #转成json格式,可以根据key取值,判断value是否等于excel表中做的标记$register_mobilephone data_dict["mobilephone"] = int( self.max_mobilephone ) + 1 #如果value等于excel表中做的标记$register_mobilephone,那查出来的最大手机号再加上1,再去请求 # 调用请求接口,接口请求后,会有返回结果,也就是实际结果 res = self.request.request(case["method"], case["url"], data_dict) #把case[data]换成最新的data_dict字典去做请求 #预期结果和实际结果的断言 try: self.assertEqual(case["expectedresult"], res.text, "register error!!!") #断言成功,测试结果就写PASS self.doexcel.write_back("register", case["case_id"] + 1, res.text, "PASS") logger.error("第{}条用例执行的结果是:PASS".format(case["case_id"])) except AssertionError as e: # 断言失败,测试结果就写Fail self.doexcel.write_back("register", case["case_id"] + 1, res.text, "FAIL") logger.error("第{}条用例执行的结果是:FAIL".format(case["case_id"])) raise e def tearDown(self): self.mysql.close()
class TestInvest(unittest.TestCase): logger.info('开始执行TestInvest测试类') testdata = DoExcel(case_file, 'invest').read_data() @classmethod def setUpClass(cls): cls.session = HttpRequest2() cls.mysql = DoMysql() @data(*testdata) def testInvest(self, case): case.data = Context().replace( case.data) #使用正则表达式,将Excel中参数化的值替换为配置文件中读取出来的值 if case.sql is not None: case.sql = Context().replace(case.sql)
class TestRecharge(unittest.TestCase): logger.info('开始执行TestRecharge测试类') testdata = DoExcel(contants.case_file,'recharge').read_data() @classmethod def setUpClass(cls): cls.session = HttpRequest2() cls.mysql = DoMysql() @data(*testdata) def testRecharge(self,case): case.data = Context().replace(case.data) if case.title == '充值成功': case.sql = Context().replace(case.sql) before_leaveamount = self.mysql.fetch_one(case.sql)['leaveamount'] logger.info('用例开始执行前,账户余额是:{}'.format(before_leaveamount))
class TestUserAuth(unittest.TestCase): testdata = DoExcel(case_file,'verifiedUserAuth').read_data() @classmethod def setUpClass(cls): cls.excel = DoExcel(case_file, 'verifiedUserAuth') cls.mysql = DoMysql() @data(*testdata) def testUserAuth(self,case): case.data = eval(case.data) if case.data.__contains__("mobile") and case.data["mobile"] == "register_phone": max_phone = self.mysql.fetch_one('select max(Fmobile_no) from sms_db_25.t_mvcode_info_5;')['max(Fmobile_no)'] max_phone = int(max_phone) + 1000 case.data["mobile"] = max_phone setattr(Context,'register_phone', str(max_phone))
class Baidu: def __init__(self, excel_name, sheet_name): ''' 初始化DoExcel和ConfigHttp ''' self.excel = DoExcel(excel_name, sheet_name) self.row_num = self.excel.get_row_num(0, "bd-001") self.excel.write_excel(0, self.row_num, 10, None) self.new_request = ConfigHttp("HTTP", "host", "port", "timeout") self.url = self.excel.read_cell(self.row_num, 2) def baidu_get(self): self.new_request.set_url(url=self.url) self.new_request.set_headers(headers) self.new_request.set_params(params=params) r = self.new_request.get() print(r.status_code) self.excel.write_excel(0, self.row_num, 10, r.status_code) return r.status_code
class WeiXinSendMessage: def __init__(self, excel_name, sheet_name): self.excel = DoExcel(excel_name, sheet_name) self.row_num = self.excel.get_row_num(0, "weixin-002") self.url = self.excel.read_cell(self.row_num, 2) self.new_request = ConfigHttp("HTTP2", "host", "port", "timeout") def send_message(self): row_num = self.excel.get_row_num(0, "weixin-001") access_token = self.excel.read_cell(row_num, 6) params = {"access_token": access_token} if access_token: self.new_request.set_url(self.url) self.new_request.set_data(data=data) self.new_request.set_params(params) r = self.new_request.post() errmsg = r.json()["errmsg"] if errmsg == "send job submission success" or errmsg == "clientmsgid exist": self.excel.write_excel(0, self.row_num, 10, errmsg) else: print("send job submission fail") else: print("access_token is null")
case.data) #使用正则表达式,将Excel中参数化的值替换为配置文件中读取出来的值 if case.sql is not None: case.sql = Context().replace(case.sql) if case.title == '成功竞标': before_leaveamount = self.mysql.fetch_one(case.sql)['leaveamount'] logger.info('成功竞标前,用户余额是:{}'.format(before_leaveamount)) res = self.session.request(method=case.method, url=case.url, data=case.data) logger.info('执行用例是:{},请求url是:{}'.format(case.title, case.url)) logger.info('请求数据是:{}'.format(case.data)) try: self.assertEqual(case.expected, int(res.json()["code"])) except AssertionError as e: DoExcel(case_file, 'invest').write_data(case.case_id + 1, res.text, 'failed') logger.error("断言失败,错误信息是:{}".format(e)) else: DoExcel(case_file, 'invest').write_data(case.case_id + 1, res.text, 'pass') logger.info('用例执行成功') if res.json()['msg'] == '加标成功': loadId = self.mysql.fetch_one(case.sql)['id'] setattr(Context, 'loanId', str(loadId)) logger.info('成功加标的ID是:{}'.format(getattr(Context, 'loanId'))) if res.json()['msg'] == '竞标成功': loan_amount = int(eval(case.data)['amount']) after_leaveamount = self.mysql.fetch_one( case.sql)['leaveamount'] logger.info('成功竞标的ID是:{},竞标金额是:{},竞标成功后账户余额是{}'.format(
def setUp(self): self.excel = DoExcel("case.xls", "weixin") self.weixin = WeiXin(self.excel) self.logger = Logger("FOX", cmd_log_level=logging.INFO, file_log_level=logging.INFO)
def __init__(self, excel_name, sheet_name): self.excel = DoExcel(excel_name, sheet_name) self.row_num = self.excel.get_row_num(0, "weixin-002") self.url = self.excel.read_cell(self.row_num, 2) self.new_request = ConfigHttp("HTTP2", "host", "port", "timeout")
return res def send_message(self): access_token = self.get_token() if access_token: row_num = self.test_data_excel.get_row_num(0, "weixin-002") url = self.test_data_excel.read_cell(row_num, 2) self.new_request.set_url(url) self.new_request.set_data(data=send_message_data) params = { "access_token": access_token } self.new_request.set_params(params) r = self.new_request.post() errmsg = r.json()["errmsg"] if errmsg == "send job submission success" or errmsg == "clientmsgid exist": self.test_data_excel.write_excel(0, row_num, 10, errmsg) else: print("send job submission fail") else: print("access_token is null") # ====================== # 测试代码 # ====================== excel = DoExcel("case.xls", "weixin") wei_xin = WeiXin(excel) wei_xin.get_token()
from suds.client import Client from common.read_config import config class Request: def __init__(self, api): self.api = api def request(self, url, data): url = config.get_str('api', 'pre_url') + url client = Client(url) if self.api == 'sendMCode': result = client.service.sendMCode(data) elif self.api == 'userRegister': result = client.service.userRegister(data) elif self.api == 'verifiedUserAuth': result = client.service.verifyUserAuth(data) elif self.api == 'bindBankCard': result = client.service.bindBankCard(data) return result if __name__ == '__main__': from common.doexcel import DoExcel from common.contants import case_file url = DoExcel(case_file, 'sendMCode').read_data()[0].url data = eval(DoExcel(case_file, 'sendMCode').read_data()[0].data) a = Request('sendMCode').request(url, data)
def setUpClass(cls): cls.excel = DoExcel(case_file,'sendMCode') cls.mysql = DoMysql()
import configparser import re from common.read_config import config class Context: def replace(self, data): p = '#(.*?)#' while re.search(p, data): m = re.search(p, data) g = m.group(1) try: v = config.get_str('testdata', g) except configparser.NoOptionError as e: if hasattr(Context, g): v = getattr(Context, g) else: print('找不到值') raise e data = re.sub(p, v, data, count=1) return data if __name__ == '__main__': from common.doexcel import DoExcel from common.contants import case_file data = DoExcel(case_file, 'sendMCode').read_data() new = Context().replace(data[0].data) print(new)
'mobilephone'] == 'register_phone': max_phone = self.mysql.fetch_one( 'select max(mobilephone) from future.member')[ 'max(mobilephone)'] #返回数据是字典,用key取值 max_phone = int(max_phone) + 1 case.data['mobilephone'] = max_phone res = self.session.request(method=case.method, url=case.url, data=case.data) logger.info('执行用例是:{},请求url是:{}'.format(case.title, case.url)) logger.info('请求数据是:{}'.format(case.data)) try: self.assertEqual(case.expected, res.text) except AssertionError as e: DoExcel(contants.case_file, 'register').write_data(case.case_id + 1, res.text, 'filed') logger.error("断言失败,错误是:{}".format(e)) else: DoExcel(contants.case_file, 'register').write_data(case.case_id + 1, res.text, 'pass') logger.info('用例执行成功') if res.json()['msg'] == '注册成功': new_mobile = self.mysql.fetch_one( 'select mobilephone from future.member where mobilephone = ' + str(case.data['mobilephone'])) try: self.assertEqual(str(case.data['mobilephone']), str(new_mobile['mobilephone'])) logger.info('注册成功,注册使用手机号是:{},注册成功的手机号是:{}'.format( case.data['mobilephone'], new_mobile['mobilephone'])) except AssertionError as e:
def __init__(self): self.test_data_excel = DoExcel("case.xls", "weixin") self.row_num = self.test_data_excel.get_row_num(0, "weixin-001") self.new_request = ConfigHttp("HTTP2", "host", "port", "timeout")
def setUpClass(cls): cls.excel = DoExcel(case_file, 'verifiedUserAuth') cls.mysql = DoMysql()
cls.mysql = DoMysql() @data(*testdata) def testRecharge(self,case): case.data = Context().replace(case.data) if case.title == '充值成功': case.sql = Context().replace(case.sql) before_leaveamount = self.mysql.fetch_one(case.sql)['leaveamount'] logger.info('用例开始执行前,账户余额是:{}'.format(before_leaveamount)) res = self.session.request(method=case.method,url=case.url,data=case.data) logger.info('执行用例是:{},请求url是:{}'.format(case.title,case.url)) logger.info('请求数据是:{}'.format(case.data)) try: self.assertEqual(case.expected,res.json()['msg']) except AssertionError as e: DoExcel(contants.case_file,'recharge').write_data(case.case_id+1,res.text,'failed') logger.error('断言失败,报错信息{}'.format(e)) else: DoExcel(contants.case_file, 'recharge').write_data(case.case_id + 1, res.text, 'pass') logger.info('用例执行成功') if res.json()['msg'] == '充值成功': after_leaveamount = self.mysql.fetch_one(case.sql)['leaveamount'] logger.info('充值成功后,账户余额是:{}'.format(after_leaveamount)) recharge_amount = eval(case.data)['amount'] try: self.assertEqual(before_leaveamount+recharge_amount,after_leaveamount) logger.info('充值成功后,账户余额正确') except AssertionError as e: logger.info('充值成功后,账户余额错误。错误是{}'.format(e)) @classmethod
def setUpClass(cls): cls.excel = DoExcel(case_file, 'bindBankCard') cls.mysql = DoMysql()
def setUpClass(cls): cls.excel = DoExcel(case_file, 'userRegister') cls.mysql = DoMysql()