def testRun(self, id, urlstr, name, method, param, expect, real, status): header = {'User-Agent': 'Mozilla/6.0'} print("url:", urlstr) print('param:', param) print('expect:', expect) #调用run方法,进行接口请求 cf = ConfigHttp() status_code, real = cf.run(urlstr, method, param) print('id:', id, "real:", real, "expect:", expect) #断言每个接口的返回结果 try: if status_code == 200: status = self.assertEqual(real, eval(expect)) print("status:=================", status, type(status_code)) except BaseException as m: print(urlstr) print(param) # print('id:', id, "real:",real,"expect:", expect) # print(re.text) status = 'Error' finally: pass if status == None: wr.writeData(int(id), int(real), 'sucess') else: wr.writeData(int(id), int(real), 'fail')
def __init__(self, case_name): self.config = ReadConfig() self.case_excle = ReadCase('mltest4.xlsx', '工作表1') # 写死,就用这个excle作为接口测试的用例 self.case_name = case_name self.serivce_url = self.case_excle.get_interface_url(self.case_name) self.service_header = self.case_excle.get_intetface_headers(self.case_name) self.service_data = self.case_excle.get_interface_data(self.case_name) self.service_method = self.case_excle.get_method(self.case_name) self.config_http = ConfigHttp(self.serivce_url, self.service_header, self.service_data, self.service_method)
def testrun(self, id, interfaceUrl, name, Method, value, expect, real, status): print('----', id, interfaceUrl, name, Method, value, expect, real, status) ch = ConfigHttp(interfaceUrl, value, Method, expect) realError = ch.run() status = 'Fail' self.assertEqual(str(expect), str(realError)) status = 'Success'
def login_cookie_service(self, case_name, result_type_is_str=False): service_header = self.add_cookie_header() service_data = str(self.case_excle.get_interface_data(case_name))+self.user_check()+self.userid()+self.username() service_url = self.case_excle.get_interface_url(case_name) service_method = self.case_excle.get_method(case_name) config_http = ConfigHttp(service_url, service_header, service_data, service_method) # print("这次的headers: " + str(service_header)) # print("这次的url:" + str(service_url)) # print("这次的data: " + str(service_data)) # print("这次的method:" + str(service_method)) result = config_http.request_result(result_type_is_str) return result
def test_sendH5(self): path = "/wkStRoute/api/sms/sendH5" post_parm = {"phoneNo": "18610660297", "validate": "001897f346018a61da3a46034203f6e9"} response = ConfigHttp() response.set_url(self.url+path) response.set_headers(self.header) response.set_data(post_parm) print(self.url+path) results = ConfigHttp.post_origi(response)
def __init__(self, case_name): self.config = ReadConfig() self.case_excel = ReadCase('mltest8.xlsx', '工作表1') #写死,作为这个excel接口测试的用例 self.case_name = case_name # 这里可能需要改一下 self.service_url = self.case_excel.get_interface_url( self.case_name, True, True) self.service_header = self.case_excel.get_interface_headers( self.case_name) self.service_data = self.case_excel.get_interface_data(self.case_name) self.service_method = self.case_excel.get_method(self.case_name) self.config_http = ConfigHttp(self.service_url, self.service_header, self.service_data, self.service_method)
class BaseService: def __init__(self, case_name): self.config = ReadConfig() self.case_excle = ReadCase('mltest.xlsx', '工作表1') # 写死,就用这个excle作为接口测试的用例 self.case_name = case_name self.serivce_url = self.case_excle.get_interface_url(self.case_name) self.service_header = self.case_excle.get_intetface_headers( self.case_name) self.service_data = self.case_excle.get_interface_data(self.case_name) self.service_method = self.case_excle.get_method(self.case_name) self.config_http = ConfigHttp(self.serivce_url, self.service_header, self.service_data, self.service_method) # 默认返回dict类型的result, 如果需要str类型的,设置str_format=True def set_case_name(self, case_name): self.case_name = case_name def get_case_name(self): return self.case_name # 传入result_type_is_str字段,传入False返回dict类型,传入True返回Str类型 def request_service(self, result_type_is_str): return self.config_http.request_result(result_type_is_str) # 获得返回状态码 def status_code(self): return self.config_http.status_code # 获得返回的text文本 def text(self): return self.config_http.text # 获得返回的content def content(self): return self.config_http.content # 返回一个cookiejar def cookies(self): return self.config_http.cookies def cookie(self): return self.config_http.get_cookie() def add_cookie(self, cookie): self.service_header.update(cookie) return self.service_header
def test_login_null(self): result = ConfigHttp().run_main('get', self.login_url_null, self.login_headers_null, self.login_data_null, True) # result为str类型的返回结果 s = json.loads(result) # s为dict类型的返回结果 print(result) ("断言一:结果是否包含200字段:" + str(self.assertIn(str(10001), result))) ("断言二:结果msg信息是否是登录成功" + str(self.assertEqual(s['message'], '参数不能为空!'))) (self.assertEqual(s['code'], 10001))
class TestCase(): def __init__(self): self.c = ConfigHttp() def res1(self): if self.c.method.lower() == 'post': r = requests.post(url=self.c.urlstr, data=self.c.payload) real = r.json()['errorCode'] print(real) #断言 self.c.run(real) def res2(self): if self.c.method.lower() == 'get': r = requests.get(url=self.c.urlstr, params=self.c.payload) real = r.json()['errorCode'] print(real) #断言 self.c.run(real)
def test_run(self,id,interfaceUrl,name,Method,value,expect,real,status): method = Method url = interfaceUrl value = value expect = expect id = id ch = ConfigHttp(url, value, method) status_code,real_errorcode =ch.run() try: self.assertEqual(str(status_code),'200') self.assertEqual(str(real_errorcode),str(expect)) # 5.1-相同即通过,succes status = 'succes' # 5.2-不同即失败,fail except AssertionError as msg : print('系统提示:',msg) status = 'fail' raise # 6-将接口断言得到的结果写入excel finally: we = WriteExcel() we.writedata(id,6,real_errorcode,status)
def checkResult(self): new_url = url + self.path # 系统地址后追加接口路径,如 http://123.56.183.13:8086 + /v1/mds-pc/sys-user/vpn-token data = json.loads(self.query) # 请求参数由字符串类型转换成json类型 info = ConfigHttp().run_main(self.method, new_url, data) s = json.loads(info) # 将响应转换为字典格式 if self.case_name == "登录成功": self.assertEqual(s['code'], self.code) if self.case_name == "账户错误": self.assertEqual(s['code'], self.code) if self.case_name == "密码错误": self.assertEqual(s['code'], self.code) if self.case_name == "账号密码为空": self.assertEqual(s['code'], self.code)
def test_matchStation_error(self): request = ConfigHttp() data = self.data_list[1] if data[1].lower() == 'post': request.set_url(data[2]) request.set_headers({ "content-type": "application/x-www-form-urlencoded;charset=utf-8" }) request.set_data({"lng": data[3], "lat": data[4]}) response = request.post() response_json = response.json() code = response_json.get('code') message = response_json.get('message') print(code, message) self.assertEqual(code, int(data[5])) self.assertEqual(message, data[6])
class BaseService: def __init__(self, case_name): self.config = ReadConfig() self.case_excel = ReadCase('mltest8.xlsx', '工作表1') #写死,作为这个excel接口测试的用例 self.case_name = case_name # 这里可能需要改一下 self.service_url = self.case_excel.get_interface_url( self.case_name, True, True) self.service_header = self.case_excel.get_interface_headers( self.case_name) self.service_data = self.case_excel.get_interface_data(self.case_name) self.service_method = self.case_excel.get_method(self.case_name) self.config_http = ConfigHttp(self.service_url, self.service_header, self.service_data, self.service_method) # 默认返回dict类型的result,如果需要,str类型的,设置str_format = True def set_case_name(self, case_name): self.case_name = case_name def get_case_name(self): return self.case_name # 传入result_typr_is_str字段,传入False返回dict类型,传入True返回Str类型 def request_service(self, result_type_is_str): return self.config_http.request_result(result_type_is_str) # 获取返回状态码 def status_code(self): return self.config_http.status_code # 获取返回的text文本 def text(self): return self.config_http.text # 获取返回的content def content(self): return self.config_http.content # 返回一个cookiejar def cookies(self): return self.config_http.cookies
def test_hardware_version_03(self): test_case = test_cases[2] logger.info(test_case[0]) ch = ConfigHttp() url = test_case[2] params = {"ip": test_case[4], "password": test_case[5]} ch.set_url(url) ch.set_params(params) result = ch.get().json() try: self.assertEqual(result['status'], int(test_case[7]), test_case[0] + ":测试失败,status错误") self.assertEqual(result['data'], ast.literal_eval(test_case[8]), test_case[0] + ":测试失败,data错误") self.assertEqual(result['operation'], test_case[9], test_case[0] + ":测试失败,operation错误") self.assertEqual(result['msg'], test_case[10], test_case[0] + ":测试失败,msg错误") except Exception as ex: logger.error(str(ex) + "\n实际返回内容:" + str(result))
import json import readConfig as readConfig from common import common_utils from common.LogUtil import LogUtil from common.configHttp import ConfigHttp localReadConfig = readConfig.ReadConfig() localConfigHttp = ConfigHttp() localLogin_xls = common_utils.get_xls("userCase.xlsx", "login") # login def loginBiz(): """ login :return: token """ # set url url = common_utils.get_url_from_xml('login') localConfigHttp.set_url(url) config = readConfig.ReadConfig() config.set_headers("token", '') config.set_headers("secret", '') # set params account = localLogin_xls[4][3] password = localLogin_xls[4][4] data = {"account": account, "password": password, "source": "app"} localConfigHttp.set_data(data) LogUtil.info("step2:设置参数==>" + json.dumps(data, ensure_ascii=False))
# --*-- coding:utf-8 --*-- import HTMLTestRunner import unittest from common.configHttp import ConfigHttp from common.Log import Logger # import json localhttp = ConfigHttp() log = Logger() logger = log.get_logger() class MyTest(unittest.TestCase): #继承unittest.TestCase @classmethod def setUpClass(cls): print("开始执行test_main---->") @classmethod def tearDownClass(cls): print("end----->") def tearDown(self): #每个测试用例执行之后做操作 print('---') def setUp(self): #每个测试用例执行之前做操作 print('---') def test_run(self): self.assertEqual(1, 1)
6)test_service_ports:测试获取所有服务端口详情,无ip键值 7)test_service_ports:测试获取所有服务端口详情,无password键值 ''' # 配置测试接口名称 case_name = "test_service_ports" # 配置excel表格名称 xls_name = "testFile.xlsx" # 配置sheet名称 sheet_name = "test_censign_key_normal" # 开启日志 logging.config.dictConfig(common.log.LOGGING_DIC) logger = logging.getLogger(__name__) # 获取所有该接口测试用例 test_cases = cm.get_xls_cases(xls_name, sheet_name, case_name) # 实例化ConfigHttp()类 ch = ConfigHttp() class Test_service_ports(unittest.TestCase): def setUp(self): urllib3.disable_warnings() def tearDown(self): pass def test_service_ports_01(self): test_case = test_cases[0] logger.info(test_case[0]) # 设置访问url、传递参数 url = test_case[2] params = {"ip": test_case[4], "password": test_case[5]}
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Author: ZhaoFeng Email: date: 2019/10/15 16:36 """ from common.configHttp import ConfigHttp # from common.setCookie import SetCookie import json cfh = ConfigHttp() headers = { 'Content-Type': 'application/json', # 'Content-Type':'application/x-www-form-urlencoded', } # 10.11.3.105 加入集群 # curl -s http://10.11.3.104:7601/join?NodeAddr=10.11.3.105:7501&NodeID=105 # 获得10.11.3.104 节点的信息 # curl -w '\n' http://10.11.3.104:7601/nodestatus # # 获得当前集群的全体成员 # curl -w '\n' http://10.11.3.105:7601/clusters?NodeID=All # # 返回集群的领导者 # curl -w '\n' http://10.11.3.105:7601/leader # cfh.url = "http://10.11.3.105:7601/leader"
from common.Log import Logger from common.configHttp import ConfigHttp from common.commons import Readkey import readConfig red = readConfig.ReadConfig() http = ConfigHttp() log = Logger() logger = log.get_logger() keys = Readkey() try: value = keys.get_xls('login.xlsx', 'user') user_phone = int(value[0][0]) user_password = int(value[0][1]) http.set_data( data={ 'lang': 'zh-CN', 'userId': '', 'token': '', 'companyId': '', 'country': '', 'phone': user_phone, 'password': user_password }) http.set_url('/sysUser/login') ts = http.post().json() for key, vl in ts['datas'].items(): # 写入到配置文件 red.set_user(str(key), str(vl)) except Exception as e:
once = "once=" + MD5Util.md5s(config.get_headers("client_key")) + timestamp + ";" developkey = "developkey=" + config.get_headers("develop_key") return timestampstr + oauth2Str + signatureStr + secret + once + developkey @staticmethod def create_signature(confighttp, timestamp, request_method): content = HeadConfig.get_requestParams(confighttp, request_method) # type:ConfigHttp request_url = "request_url=" + confighttp.path + "&" contentstr = "content=" + content + "&" request_method = "request_method=" + request_method + "&" timestampstr = "timestamp=" + timestamp + "&" config = ReadConfig() secret = config.get_headers("secret") if secret == '': secret = "secret=" + MD5Util.md5s(timestamp) else: secret = "secret=" + secret timestampstr_secret = request_url + contentstr + request_method + timestampstr + secret return MD5Util.md5s(timestampstr_secret) if __name__ == '__main__': configHttp = ConfigHttp() configHttp.set_url("biz/users/login") configHttp.set_data({"account": "*****@*****.**", "password": "******", "source": "app"}) timestamp = "1553137347" authorization = HeadConfig.get_authorization(configHttp, "post", timestamp) print(authorization)
from common.configHttp import ConfigHttp from common.readExcel import getExcelData from common.writeExcel import writerExcel import unittest, json from ddt import ddt, data, unpack import HTMLTestRunner import time, os wr = writerExcel() re = ConfigHttp() excelData = getExcelData() test_data = excelData.assembleDta() @ddt class MytestCase(unittest.TestCase): @ddt @data(*test_data) @unpack def test_request(self, id, url, name, method, param, expect): print(id, url, name, method, param, expect) param = param[0] expect = expect[0] real = re.getRequest(method, url, param) print("kankanleixing ", type(real)) try: status = self.assertEqual(real, int(expect)) print(status) except AssertionError as msg: status = "Error" finally:
def test_baidu(self): longin = get_xls('xls_name.xlsx', 'Sheet1') list_num = len(longin) for i in range(list_num): url = longin[i][2] methon = longin[i][1] username = longin[i][3] passwd = longin[i][4] header = {'content-type': 'application/json'} long_params = ConfigHttp() long_params.set_url(url) long_params.set_headers(header) parms = {'user_id': username, 'email': username} data = {'email': username, 'password': passwd} long_params.set_params(parms) long_params.set_data(data) print(url, methon, username, passwd) if methon == 'post': long_params.post() print(long_params.post().status_code) elif methon == 'get': long_params.get() print(long_params.get().status_code) else: print("end")
import HTMLTestRunner import unittest from common.Log import Logger from common.configHttp import ConfigHttp from common.commons import Readkey import readConfig red = readConfig.ReadConfig() http = ConfigHttp() log = Logger() logger = log.get_logger() xls = Readkey() class MyTest(unittest.TestCase): #继承unittest.TestCase @classmethod def setUpClass(self): print("----->>>>test_companys") #读取数据 self.id_ = red.get_user('id') self.token = red.get_user('token') self.lang = red.get_http('lang') @classmethod def tearDownClass(cls): print("--->>>end")
def __init__(self): self.c = ConfigHttp()
#! /usr/bin/env python # -*- coding:utf-8 -*- import requests import json from common.configHttp import ConfigHttp cfh = ConfigHttp() params = {} ''' from 查询起始时间戳 秒 to 查询结束时间戳 秒 topoIds(可选) <=10个 该数组为空或不填时默认所有业务系统进行查询 streamIds(可选) 流ID数组 多个以','隔开 <=10个 该数组为空或不填时默认对所有流进行查询 monitorLevels(可选) 告警级别数组 支持查询EMERGENCY(严重)、HIGH(高)、MEDIUM(中) 、LOW(低) 选填,该数组为空或不填时默认不对告警级别条件加限制 monitorTypes(可选) 告警类型数组 暂时只支持FIXED_THRESHOLD(静态阈值)、COMBINE(复合关联)两个条件(支持条件内多个).选填, 该数组为空或不填时为默认不对告警类型条件加以限制 targetMetrics(可选) 暂时只支持_count(交易量)、_response_rate(响应率)、_no_response_count(交易未响应数)、 _success_rate(交易成功率)、_fail_count(交易失败数)、_latency_msec(交易响应时间)、customized(其他) 7个条件进行(支持条件内多个),选填,该数组为空或不填时为默认不对告警指标条件加以限制 ''' # from=1526956200&to=1526958000& # streamIds[]=5afc0e19e4b054b2b5d14499& # groupByField=_trans_ref.TermNum& # targetMetrics[]=_success_rate,_response_rate&sortMetric=_success_rate params['from'] = "1528974940" params['to'] = "1528975260" params['streamIds[]'] = "5afe3bf3e4b054b2b5d5581c," params['topoIds[]'] = "" params['monitorLevels[]'] = "" params['monitorTypes'] = "FIXED_THRESHOLD"
import os from xlrd import open_workbook from common.configHttp import ConfigHttp from readConfig import proDir import logging.config import common.log loacalConfigHttp = ConfigHttp() logging.config.dictConfig(common.log.LOGGING_DIC) logger = logging.getLogger(__name__) # 从 excel文件中读取测试用例,获取所有用例 def get_xls(xls_name, sheet_name): cls = [] # get xls file's path xlsPath = os.path.join(proDir, "testFile", xls_name) # open xls file file = open_workbook(xlsPath) # get sheet by name sheet = file.sheet_by_name(sheet_name) # get one sheet's rows nrows = sheet.nrows for i in range(nrows): if sheet.row_values(i)[0] != u'case_name': cls.append(sheet.row_values(i)) return cls # 根据指定用例名称,从 excel文件中读取测试用例 def get_xls_cases(xls_name, sheet_name, case_name):
# @File : test_case.py # @Software: PyCharm import unittest import json from ddt import ddt, data, unpack import requests from common.readExcel import readExcel from common.writeExcel import writeExcel from common.configHttp import ConfigHttp d = readExcel() testda = d.assembleData() print(testda) w = writeExcel() r = ConfigHttp() @ddt class MyTestCase1(unittest.TestCase): @data(*testda) @unpack def test1(self, id, url, method, param, expect): #print(id,url,method,param,expect) # param = json.loads(param) result = r.getRequest(url, param, method) # print(result) # if method == 'post': # response = requests.post(url=url,data=param) # #print(response.status_code) # else: