def gen_paradata(self, ruler_data): try: if ruler_data != None: gen_params = {} for k in ruler_data: if ruler_data[k]['type'].lower() == 'number': gen_params[k] = Ruler.RULER().paradata_int( ruler_data[k]) elif ruler_data[k]['type'].lower() == 'float': gen_params[k] = Ruler.RULER().paradata_float( ruler_data[k]) elif ruler_data[k]['type'].lower() == 'string': gen_params[k] = Ruler.RULER().paradata_context( ruler_data[k]) elif ruler_data[k]['type'].lower() == 'bool': gen_params[k] = Ruler.RULER().paradata_bool( ruler_data[k]) elif ruler_data[k]['type'].lower() == 'json': gen_params[k] = Ruler.RULER().paradata_bool( ruler_data[k]) elif ruler_data[k]['type'].lower() == 'list': gen_params[k] = Ruler.RULER().paradata_float( ruler_data[k]) elif ruler_data[k]['type'].lower() == 'obj': entity = ruler_data[k]['entity'] gen_params[k] = Ruler.RULER().paradata_jar(entity) else: HandleException.Exception().syntaxerror( 'The paratype of %s is invalid' % k) else: gen_params = None return gen_params except Exception, e: HandleException.Exception().exception( 'gen_paradata raise exception:\n' + e)
def run_onetime( self, interfacename, casename, config_data, expect_data, ): ''' path = os.path.dirname(os.getcwd()) parpath = os.path.dirname(path) yamlname = parpath + '/Config/interface/' + '%s/%s.yaml' % (interfacename, interfacename) config_data = Yaml.YAML().read_yaml(yamlname)''' try: start = time.clock() if config_data['protocol'].lower() == 'http': res = Http.http_runner(interfacename, casename) end = time.clock() Log.LOG(interfacename + '->' + casename).log_result( 'Http has get the response data using %s' % str(end - start)) logcache = '%s--->%s: Http has get the response data using %s\n' % ( interfacename, casename, str(end - start)) (judge, error_key, result) = self.r.assert_runner(res, expect_data) return judge, error_key, logcache, res, round((end - start), 2), result elif config_data['protocol'].lower() == 'https': res = Https.https_runner(interfacename, casename) end = time.clock() Log.LOG(interfacename + '->' + casename).log_result( 'Https has get the response data using %s' % str(end - start)) logcache = '%s--->%s: Http has get the response data using %s\n' % ( interfacename, casename, str(end - start)) (judge, error_key, result) = self.r.assert_runner(res, expect_data) return judge, error_key, logcache, res, round((end - start), 2), result elif config_data['protocol'].lower() == 'hessian': res = Hessian.hessian_runner(interfacename, casename) end = time.clock() Log.LOG(interfacename + '->' + casename).log_result( 'Hessian has get the response data using %s' % str(end - start)) logcache = '%s--->%s: Http has get the response data using %s\n' % ( interfacename, casename, str(end - start)) (judge, error_key, result) = self.r.assert_runnerhessian(res, expect_data) return judge, error_key, logcache, res, round((end - start), 2), result else: HandleException.Exception().syntaxerror( 'The interface type is not exist! ') except Exception, e: HandleException.Exception().exception(e)
def get_responsedata(self, res, tag): if tag == 1: res_data = handleresponse.HANDLERESPONSE().handle_httpres(res) return res_data else: HandleException.Exception().syntaxerror( 'The expect tag is invalid!')
def http_indata(self, http_data, interfacename, casename): try: path = os.path.dirname(os.getcwd()) parpath = os.path.dirname(path) host = http_data['host'] http_data['data'] = eval(http_data['data']) if http_data['data'] != None: data = json.dumps(http_data['data']['value'], ensure_ascii=False) else: data = None headers = http_data['headers'] params = http_data['params'] method = http_data['method'] cookie = http_data['cookie'] inputdata = {'host': host, 'data': data, 'headers': headers, 'params': params, 'method': method, 'cookie': cookie } self.print_inputdata(inputdata, http_data, interfacename, casename) return inputdata except Exception,e: HandleException.Exception().exception('http_indata raise exception:\n' + e)
def allpairs(self, paramslist): try: parameters_map = {} parameters = [] i = 0 for k in paramslist: parameters_map[str(i)] = k parameters.append(paramslist[k]) i += 1 pairwise = all_pairs(parameters) out = [] for i2, v in enumerate(pairwise): singleout = {} for i3 in range(len(v)): singleout[parameters_map[str(i3)]] = v[i3] out.append(singleout) for i4 in range(len(out)): single_para = out[i4] false = 0 for k2 in single_para: if single_para[k2]['except'] == False: single_para[k2] = single_para[k2]['value'] else: single_para[k2] = single_para[k2]['value'] false += 1 if false == 0: single_para['error'] = False else: single_para['error'] = True return out except Exception, e: HandleException.Exception().exception( 'allpairs raise exception:\n' + e)
def read_file(self, filename): try: with open(filename, 'r') as f: result = f.read() return result except: HandleException.Exception().systemerror('read %s is Error !' % filename)
def paradata_json(self, ruler_k): single_paradata = [] paraattr = {} if ruler_k['value'] != None: paraattr['value'] = ruler_k['value'] paraattr['except'] = False single_paradata.append(paraattr) return single_paradata else: HandleException.Exception().syntaxerror('The paraset is invalid!')
def get_configdata(self, interfacename): try: ''' path = os.path.dirname(os.getcwd()) parpath = os.path.dirname(path) yamlname = parpath + '/Config/interface/' + '%s/%s.yaml' % (interfacename, interfacename) config_data = Yaml.YAML().read_yaml(yamlname)''' config_data = HandleDB.HandleDB().db_readconfig(interfacename) return config_data except Exception, e: HandleException.Exception().exception('get_configdata raise exception:\n'+ e)
def https_runner(interfacename, casename): try: req = HTTPS_REQUEST(interfacename, casename) request = req.https_request() # 开始response处理 res = HTTPS_RESPONSE(request) result = res.https_response() res.print_responsedata() return result except Exception,e: HandleException.Exception().exception(e)
def paradata_list(self, ruler_k): single_paradata = [] if ruler_k['value'] != None: for i in range(len(ruler_k['value'])): paraattr = {} paraattr['value'] = ruler_k['value'][i] paraattr['except'] = False single_paradata.insert(i, paraattr) return single_paradata else: HandleException.Exception().syntaxerror('The paraset is invalid!')
def write_file(self, filename, write): try: if os.path.exists(filename): with open(filename, 'a+') as f: f.write(write) else: with open(filename, 'w') as f: f.write(write) except: HandleException.Exception().systemerror('write %s is Error !' % filename)
def ruler_data(self, interfacename): try: path = os.path.dirname(os.getcwd()) parpath = os.path.dirname(path) # 读取config yaml文件 '''yamlname = parpath + '/Config/interface/' + interfacename + '/' + interfacename + '_r.yaml' ruler_data = Yaml.YAML().read_yaml(yamlname)''' ruler_data = HandleDB.HandleDB().db_readruler(interfacename) return ruler_data except Exception, e: HandleException.Exception().exception( 'ruler_data raise exception:\n' + e)
def http_runner(interfacename, casename): try: req = HTTP_REQUEST(interfacename, casename) request = req.http_req() # 开始response处理 res = HTTP_RESPONSE(request) result = res.http_res() res.print_responsedata() return result except Exception,e: HandleException.Exception().exception('httprunner raise exception:\n'+ e)
def gen_htmlreport(self, interfacename, runsuite): try: path = os.path.dirname(os.getcwd()) parpath = os.path.dirname(path) filename = parpath + '/Report/Html/%s_report.html' % interfacename with open(filename, 'wb') as f: runner = HTMLTestRunner.HTMLTestRunner( stream=f, title='%s Test Report' % interfacename, description='This is %s Test Report' % interfacename) runner.run(runsuite) except Exception, e: HandleException.Exception().exception(e)
def paradata_float(self, ruler_k): single_paradata = [] if ruler_k['value'] != None: paraattr1 = {} paraattr1['value'] = ruler_k['value'] paraattr1['except'] = False single_paradata.append(paraattr1) return single_paradata elif ruler_k['max'] != None and ruler_k['min'] != None: # 产生边界值和一个随机等效 down = ruler_k['min'] up = ruler_k['max'] paraattr1 = {} paraattr1['value'] = down - 0.01 paraattr1['except'] = True single_paradata.append(paraattr1) paraattr2 = {} paraattr2['value'] = up + 0.01 paraattr2['except'] = True single_paradata.append(paraattr2) paraattr3 = {} paraattr3['value'] = BaseData.BASEDATA().gen_ranfloat(down, up) paraattr3['except'] = False single_paradata.append(paraattr3) return single_paradata elif ruler_k['max'] != None and ruler_k['min'] == None: up = ruler_k['max'] paraattr1 = {} paraattr1['value'] = up + 0.01 paraattr1['except'] = True single_paradata.append(paraattr1) paraattr2 = {} paraattr2['value'] = up paraattr2['except'] = False single_paradata.append(paraattr2) return single_paradata elif ruler_k['max'] == None and ruler_k['min'] != None: down = ruler_k['min'] paraattr1 = {} paraattr1['value'] = down - 0.01 paraattr1['except'] = True single_paradata.append(paraattr1) paraattr2 = {} paraattr2['value'] = down paraattr2['except'] = False single_paradata.append(paraattr2) return single_paradata else: HandleException.Exception().syntaxerror('The paraset is invalid!')
def paradata_context(self, ruler_k): single_paradata = [] paraattr = {} if ruler_k['value'] != None: paraattr['value'] = ruler_k['value'] paraattr['except'] = False single_paradata.append(paraattr) return single_paradata elif ruler_k['long'] != None: long = ruler_k['long'] paraattr['value'] = BaseData.BASEDATA().gen_rancontext(long) paraattr['except'] = False single_paradata.append(paraattr) return single_paradata else: HandleException.Exception().syntaxerror('The paraset is invalid!')
def all_case(self, interfacename): try: start = time.clock() '''path = os.path.dirname(os.getcwd()) parpath = os.path.dirname(path) dirname = parpath + '/TestCase/Function/' + interfacename''' casename = HandleDB.HandleDB().db_readcase(interfacename) end = time.clock() Log.LOG(interfacename).log_result( 'The case of %s has built using %s' % (interfacename, str(end - start))) Log.LOG(interfacename).log_result('The caselist is:\n %s' % str(casename)) return casename except Exception, e: HandleException.Exception().exception( 'all_case raise exception:\n' + e)
def lackpara(self, paramslist, ruler_data): try: paralist = {} # 先拼一种全值情况 for k in paramslist: paralist[k] = paramslist[k][0]['value'] for k in paralist: # 从ruler中判定必填项,删除遇到的第一个必填项 if ruler_data[k]['notnull'] == True: del paralist[k] break else: continue return paralist except Exception, e: HandleException.Exception().exception( 'lackpara raise exception:\n' + e)
def db_generaloperation(self, sql): try: conn = MySQLdb.connect(host=self.db_host, user=self.db_user, passwd=self.db_passwd, db=self.db_name, port=self.db_port, charset='utf8') cur = conn.cursor() cur.execute(sql) conn.commit() cur.close() conn.close() return 1 except Exception, e: HandleException.Exception().exception(e) return 0
def gen_lackcase(self, paradata, interfacename, expect_data, jarname, classname, funname): try: if funname != None: interfacename2 = interfacename + '_' + funname casename = interfacename2 + '_lack' else: casename = interfacename + '_lack' HandleDB.HandleDB().db_writecase(interfacename, casename, jarname, classname, funname) paradata = json.dumps(paradata, ensure_ascii=False) expect_data = json.dumps(expect_data, ensure_ascii=False) HandleDB.HandleDB().db_writecaseinfo(casename, paradata, expect_data, jarname, classname, funname) except Exception, e: HandleException.Exception().exception( 'gen_lackcase raise exception:\n' + e)
def read_inputdata(self, interfacename, casename): try: path = os.path.dirname(os.getcwd()) parpath = os.path.dirname(path) # 获取接口配置数据 config_data = self.get_configdata(interfacename) case_data = config_data # 从case中取参数 '''filename = parpath + '/TestCase/Function/' + '%s/%s.txt' % (interfacename, casename) with open(filename, 'r')as f: para_data = f.read() # 对case里取出的string流处理 para_data = TransCode.TransCode().transcode(para_data)''' para_data = HandleDB.HandleDB().db_readcaseinfo(casename) Log.LOG(interfacename + '--->' + casename).log_result('para_data: %s\n'%para_data) case_data['params'] = para_data return case_data except Exception,e: HandleException.Exception().exception('read_inputdata raise exception:\n'+ e)
def hessian_indata(self, interfacename, casename): try: config = HandleDB.HandleDB().db_readconfig(interfacename) jarname = config['jarname'] classname = config['classname'] funcname = config['funcname'] host = config['host'] # 'http://10.102.36.151:8080/hessian/orderService' # 'http://example.com/hession4.0server/remote/helloSpring' params = HandleDB.HandleDB().db_readcaseinfo(casename) inputdata = {'host': host, 'params': params, 'jarname': jarname, 'classname': classname, 'funcname': funcname } return inputdata except Exception,e: HandleException.Exception().exception('hessian_indata raise exception:\n' + e)
def db_readexpect(self, interfacename): try: conn = MySQLdb.connect(host=self.db_host, user=self.db_user, passwd=self.db_passwd, db=self.db_name, port=self.db_port, charset='utf8') cur = conn.cursor() sql = "select %s from `interface_config` where `interfacename`='%s'" % ( 'expect', interfacename) cur.execute(sql) row = cur.fetchone() cur.close() conn.close() return eval(row[0]) except Exception, e: HandleException.Exception().exception( 'db_readexpect raise exception:\n' + e)
error_key = json.dumps(error_key, ensure_ascii=False) # 设置一个存储日志内容的变量,将'替换成*号 logcache = str(logcache2).replace('\'', '*') content_type = str(res['req_headers']['Content-Type']) for k in res: if k == 'req_headers': res[k] = str(res[k]).replace("'", "\"") except Exception, e: res = { "req_status": 999, "req_headers": None, "req_content": None, "req_token": None, "req_cookie": None } HandleException.Exception().exception(casename + 'raise exception:\n' + e) judge = { "body": None, "headers": None, "schema": None, "content_type": None, "status_code": None } error_key = None runtimes = 0 logcache = None realvalue = None result = 'Not Run' content_type = None usetime = 'Unknown' iserror = case_error[casename]
def run_singleinterface(self, interfacename, taskid): # 建立case path = os.path.dirname(os.getcwd()) parpath = os.path.dirname(path) start = time.clock() # 取配置值 config_data = InputData.INPUTDATA().get_configdata(interfacename) jarname = config_data['jarname'] classname = config_data['classname'] funcname = config_data['funcname'] projectname = config_data['projectname'] ruler_data = Ruler.RULER().ruler_data(interfacename) Log.LOG(interfacename).log_result('The config data of %s:\n%s' % (interfacename, str(config_data))) # 取期望值 expect_data = HandleDB.HandleDB().db_readexpect(interfacename) case_error = self.build_case(interfacename, expect_data, ruler_data, jarname, classname, funcname) Log.LOG(interfacename).log_result('The case of %s build success...' % interfacename) casename = self.all_case(interfacename) print type(casename) report_case = {} # 如果不是无参接口 if ruler_data != None and isinstance(casename, list): for i in range(len(casename)): starttime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) try: (judge, error_key, runtimes, logcache2, res, usetime, result) = self.run_singlecase(interfacename, casename[i], config_data, expect_data, projectname) realvalue = str(res).replace("'", "\"") # realvalue = json.dumps(realvalue, ensure_ascii=False) # print realvalue, type(realvalue) error_key = json.dumps(error_key, ensure_ascii=False) logcache = str(logcache2).replace("'", "\"") # 处理res 写进response表 content_type = str(res['req_headers']['Content-Type']) for k in res: if k == 'req_headers': res[k] = str(res[k]).replace("'", "\"") except Exception, e: res = { "req_status": 999, "req_headers": None, "req_content": None, "req_token": None, "req_cookie": None } HandleException.Exception().exception( str(casename[i]) + 'raise exception:\n' + e) judge = { "body": None, "headers": None, "schema": None, "content_type": None, "status_code": None } error_key = None runtimes = 0 logcache = None realvalue = None result = 'Not Run' content_type = None usetime = 'Unknown' iserror = case_error[casename[i]] endtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) resultid = HandleDB.HandleDB().db_writeresult( taskid, interfacename, jarname, classname, funcname, casename[i], result, realvalue, error_key, str(runtimes - 1), iserror, judge, starttime, endtime, usetime) HandleDB.HandleDB().db_writecaselog(casename[i], logcache, interfacename, resultid) HandleDB.HandleDB().db_writeresponse(resultid, res, content_type) report_case[casename[i]] = { 'result': result, 'judge': judge, 'usetime': usetime }
def make_dir(self, dirname): if os.path.exists(dirname) == False: os.mkdir(dirname) else: HandleException.Exception().systemerror( '%s is exist! can not build %s' % dirname)
def run_singlecase(self, interfacename, casename, config_data, expect_data, projectname): try: # 测试前数据库操作 sql = config_data['sql_pre'] finish = self.sql_preoperation(sql) env = HandleDB.HandleDB().db_readenvirement(projectname) retry = env['isRetry'] wholetime = 0.00 if finish != 1: runtime = env['retrytimes'] judge = False error_key = 'Pre Sql Operation cannot pass !' res_data = '' logcache2 = '%s--->%s: %s' % (interfacename, casename, error_key) else: runtime = 0 logcache2 = '' while runtime < env['retrytimes'] and retry == True: (judge, error_key, logcache, res, usetime, result) = self.run_onetime(interfacename, casename, config_data, expect_data) wholetime += usetime if judge != True: Log.LOG(interfacename + '->' + casename).log_result( 'Run fail %d times,The error: \n %s' % (runtime + 1, str(error_key))) logcache = logcache + '%s-->%s: Run fail %d times,The error: \n %s' % ( interfacename, casename, runtime + 1, str(error_key)) + '\n' else: Log.LOG(interfacename + '->' + casename).log_result('Run success') Log.LOG(interfacename + '->' + casename).log_result( 'The check data: \n %s' % res_data) logcache = logcache + '%s-->%s: Run success\n The check data: \n %s' % ( interfacename, casename, res_data) + '\n' # 若通过不再重跑 runtime = env['retrytimes'] logcache2 += logcache runtime += 1 if retry != True: (judge, error_key, logcache, res, usetime, result) = self.run_onetime(interfacename, casename, config_data, expect_data) wholetime += usetime if judge != True: Log.LOG(interfacename + '->' + casename).log_result( 'Run fail %d times,The error: \n %s' % (runtime + 1, str(error_key))) logcache = logcache + '%s-->%s: Run fail %d times,The error: \n %s' % ( interfacename, casename, runtime + 1, str(error_key)) + '\n' else: Log.LOG(interfacename + '->' + casename).log_result('Run success') Log.LOG(interfacename + '->' + casename).log_result( 'The check data: \n %s' % res_data) logcache = logcache + '%s-->%s: Run success\n The check data: \n %s' % ( interfacename, casename, res_data) + '\n' logcache2 += logcache runtime += 1 return judge, error_key, runtime, logcache2, res, wholetime, result except Exception, e: HandleException.Exception().exception(e)