def get_main(self, host, lujing=None, data=None, headers=None): try: if lujing != None: url = host + lujing else: url = host if headers != None: # print("ok") if type(headers) == dict: headers = headers else: headers = eval( headers) # 如果data 不是dict 类型 就必须先是str 然后转成dict res = requests.get(url=url, data=data, headers=headers, verify=False) # print(res) else: res = requests.get(url=url, data=data, verify=False) if res.status_code != 200: # 判断响应状态码是否不为200 print('响应状态码不等于200,实际为:{}'.format(res)) Log().info(res) except Exception as e: Log().info('post 请求错误 错误原因为%s' % e) else: # 响应状态码正确转为json response = res.json() # 将返回的数据转换为json格式的 字典 return response
def setUp(self): self.logger = Log() self.logger.log_info('「Login Test Start:') url = 'http://10.10.15.153' self.driver = webdriver.Chrome() self.driver.maximize_window() self.lp = LoginPage(self.driver, url) time.sleep(3)
def setUp(self): Current_class = os.path.basename(__file__) print(Current_class) self.log = Log(Current_class) #关联参数存储字典 self.OverallData = dict() #关联参数生成 self.LinkedValue = None self.interfacetest = InterfaceTest()
def post_main(self, host, lujing, data, headers=None): #host 为基础url ,lujing为路径 try: if lujing != None: url = host + lujing else: url = host # print(url) # print(type(data)) if type(data) == dict: #判断是否为dict 类型 data = data else: # print("nooo") data = eval(data) #如果data 不是dict 类型 就必须先是str 然后转成dict if headers != None: if type(headers) == dict: headers = headers else: headers = eval( headers) #如果data 不是dict 类型 就必须先是str 然后转成dict res = requests.post(url=url, json=data, headers=headers, verify=False) else: res = requests.post(url=url, json=data, verify=False) if res.status_code != 200: #判断响应状态码是否不为200 print('响应状态码不等于200,实际为:{}'.format(res)) Log().info(res) except Exception as e: Log().info('post 请求错误 错误原因为%s' % e) else: # 响应状态码正确转为json response = res.json() # 将返回的数据转换为json格式的 字典 return response
class TestCase(unittest.TestCase): def setUp(self): Current_class = os.path.basename(__file__) print(Current_class) self.log = Log(Current_class) #关联参数存储字典 self.OverallData = dict() #关联参数生成 self.LinkedValue = None self.interfacetest = InterfaceTest() def tearDown(self): pass @data(*datalist) def testJDproduct(self, Data): #测试用用例描述 Response, Result = None, None print("用例名称:{}".format(Data["CaseName"])) print("LinkedData" + Data["LinkedData"]) if (Data["LinkedData"] != ''): self.LinkedValue = str( Data["LinkedData"]) + "=" + self.OverallData[str( Data["LinkedData"])] self.log.info("Headers:%s" % (Data["Headers"])) if (self.LinkedValue != None): Result, Response = self.interfacetest.testrequest( Data["URL"], Data["URI"], Data["Param"] + self.LinkedValue, Data["RequestForm"], Data["File"], Data["CheckPoint"], Data["Headers"], Data["ID"], Data["CaseName"]) else: Result, Response = self.interfacetest.testrequest( Data["URL"], Data["URI"], Data["Param"], Data["RequestForm"], Data["File"], Data["CheckPoint"], Data["Headers"], Data["ID"], Data["CaseName"]) # print("Response:%s"%(Response)) if (re.findall(r"<td>(.*?)</td>", Response) != None): self.OverallData["id"] = re.findall(r"<td>(.*?)</td>", Response[0]) self.assertEqual("成功", Result)
def __init__(self, excelPath, sheet_id): if not os.path.exists(excelPath): Log().error('测试用例文件不存在!') sys.exit() self.excelPath = excelPath self.data = xlrd.open_workbook(excelPath) self.table = self.data.sheets()[sheet_id] # 获取第一行作为key值 self.keys = self.table.row_values(0) # 获取总行数 self.rowNum = self.table.nrows # 获取总列数 self.colNum = self.table.ncols
def send_email(file_path): # ----------1.跟发件相关的参数------ # smtpserver # 发件服务器 smtpserver = "smtp.qq.com" port = 465 # 端口 sender = "*****@*****.**" # 账号 shouquan = "rpybibdelqojbgfc" # 授权码 qq邮箱 receiver = ["*****@*****.**"] # 接收人 # ----------2.编辑邮件的内容------ subject = "主题:66ifuel接口测试报告" msg = MIMEMultipart('alternative') msg['from'] = sender msg['to'] = ";".join(receiver) # 发送多个接收人 msg['subject'] = subject with open(file_path, 'rb') as fb: mail_body = fb.read() # # 定义邮件正文为 html 格式 # body = MIMEText(mail_body, 'html', 'utf-8') # msg.attach(body) # # 定义邮件正文为 text 格式 msg.attach(MIMEText('请下载html附件进行查看', 'plain', 'utf-8')) # #附件 att = MIMEText(mail_body, 'base64', 'utf-8') att["Content-Type"] = "application/octet-stream" att["Content-Disposition"] = 'attachment; filename="test_report.html"' # 重命名的邮件 msg.attach(att) # # # # ----------3.发送邮件163------ # smtp = smtplib.SMTP() # smtp.connect(smtpserver) # 连服务器 try: # # ----------4.发送邮件QQ------ smtp = smtplib.SMTP_SSL(smtpserver, port) smtp.login(sender, shouquan) # 登录 smtp.sendmail(sender, receiver, msg.as_string()) # 发送 smtp.quit() # 关闭 except Exception as e: # print(e) Log().warning('邮件发送失败:%s' % e)
def mysql_execute(sql, number=None): '''执行 单表sql 语句''' # with db.cursor(cursor=pymysql.cursors.DictCursor) as cursor:#获取数据库连接的对象以字典形式 with db.cursor() as cursor: try: if number == 'one': cursor.execute(sql) print('执行成功') elif number == 'more': cursor.executemany(sql) else: pass except Exception as a: db.rollback() # sql 执行异常后回滚 Log().debug("执行 SQL 语句出现异常:%s" % a) # print("执行 SQL 语句出现异常:%s"%a) else: cursor.close() cursor.commit() # sql 无异常时提交 db.close()
def mysql_getrows(sql, number=None): ''' 返回查询结果''' with db.cursor() as cursor: try: if number == 'one': cursor.execute(sql) # print('执行成功') row = cursor.fetchone() return row elif number == 'more': cursor.executemany(sql) rows = cursor.fetchall() return rows else: pass except Exception as a: print("查询结果错误:%s" % a) Log().debug("查询结果错误:%s" % a) else: cursor.close() db.close()
def dict_data(self): """ 读取excel数据 :return: """ Log().info('开始读取excel数据') if self.rowNum <= 1: print("总行数小于1") else: r = [] j = 1 for i in list(range(self.rowNum - 1)): #循环行 s = {} # 从第二行取对应values值 s['rowNum'] = i + 2 values = self.table.row_values(j) # print(values) for x in list(range(self.colNum)): # 在行的循环下进行 循环列 s[self.keys[x]] = values[x] # # print(self.keys[x]) # print( values[x]) r.append(s) j += 1 return r
def get_xls(self): ''' 读取测试用例, xls_name为Excel表格名称 sheet_name为sheet的名称 ''' # config.ini文件存放路径 config_path = GetPath().get_conf_path() # 读取配置文件config.ini config = configparser.ConfigParser() config.read(config_path) # 获取[excel]中指定的file_name file_name = config.get('excel', 'file_name') # 获取[excel]中指定的sheet_name sheet_name = config.get('excel', 'sheet_name') # 测试用例文件路径:../TestCase case_path = os.path.join(GetPath().get_case_dir(), file_name) log = Log(__name__).getlog() # 判断用例文件是否存在 if not os.path.isfile(case_path): # 记录到日志并退出python程序 log.error("测试用例文件不存在!") os._exit(1) file = open_workbook(case_path) # 打开EXCEL sheets = sheet_name.split('|') cls = [] # 用于存储用例 for s in sheets: try: sheet = file.sheet_by_name(s) # 打开指定sheet except XLRDError as e: log.error("config.ini文件中sheet_name编辑错误") raise nrows = sheet.nrows # sheet的行数 for i in range(nrows): if sheet.row_values(i)[0] != 'Num': # 过滤顶栏目录 if sheet.row_values(i)[9] != 'no': # 过滤未激活的用例 cls.append(sheet.row_values(i)) return cls
# @Software :PyCharm from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import * from Common.log import Log from Common.dir_config import * import time import os import sys # 定义resultlog和processlog P_log = Log(processlog_dir) R_log = Log(resultlog_dir) class BasePage: def __init__(self, driver): self.driver = driver self.driver.maximize_window() # 等待元素可见 def wait_eleVisible(self, loctor, by=By.XPATH, wait_times=20): if by not in By.__dict__.values(): P_log.error("定位类型[ {0} ]不在支持的定位类型范围内".format(by)) raise InvalidSelectorException # 当前运行时间 t1 = time.time()
@file: sendMail.py @ide: PyCharm Community Edition @time: 2018-11-15 17:14 @blog: https://www.cnblogs.com/gotesting/ ''' import os import smtplib import time from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from Common.log import Log from Config.globalConfig import report_path logger = Log() # 配置收发件人 recv_address = ['*****@*****.**'] # 163的用户名和密码 send_addr_name = '*****@*****.**' send_addr_pswd = 'jiaxy19920319' class SendMail: def __init__(self, recver=None): """接收邮件的人:list or tuple""" if recver is None: self.sendTo = recv_address else: self.sendTo = recver
import unittest import HTMLTestRunner import time from Config.globalConfig import * from TestSuite import testSuite from Common.log import Log from Common.sendMail import SendMail def run_test(): runner = unittest.TextTestRunner() curTime = time.strftime('%Y-%m-%d_%H_%M_%S') report_name = report_path + '\\' + 'TestResult-' + curTime + '.html' with open(report_name,'wb') as f: runner = HTMLTestRunner.HTMLTestRunner( stream = f, title = '测试报告' ) runner.run(testSuite.suite) time.sleep(3) mail = SendMail() mail.send() if __name__ == '__main__': logger = Log() logger.log_info('*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Auto Test Comming -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*') run_test() logger.log_info('*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Auto Test Done -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*')
def testrequest(self, URL, URI, Param, RequestForm, File, CheckPoint, Headers, num, CaseName): Current_class = os.path.basename(__file__) print(Current_class) log = Log(Current_class) # 可选 ''' Headers = {'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'} Headers = {'Content-Type':'application/json;charset=utf-8'} ''' # 生成请求类的对象 req = Interface_Request() # req_get = req.req_get(url,params = params,Headers = Headers) # 请求前缀和接口地址的拼接 full_url = URL + URI # 判断请求类型 if (RequestForm == 'GET'): # 调用请求类的函数,得到返回结果 self.req_test = req.req_get(full_url, Param, Headers) # elif (RequestForm == 'POST' and DataForm == 'Form'): # self.req_test = req.post_kv(full_url, Param, Headers) # elif (RequestForm == 'POST' and DataForm == 'Json'): # Headers = {'Content-Type': 'application/json;charset=utf-8'} # self.req_test = req.post_json(full_url, Param, Headers) # elif (RequestForm == 'POST' and DataForm == 'File'): # Headers = {'Content-Type': 'multipart/form-data;boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA'} # self.req_test = req.post_json(full_url, Param, Headers) elif (RequestForm == 'POST' and re.search("application/x-www-form-urlencoded", Headers)): self.req_test = req.post_kv(full_url, Param, Headers) elif (RequestForm == 'POST' and re.search("application/json", Headers)): self.req_test = req.post_json(full_url, Param, Headers) elif (RequestForm == 'POST' and re.search("multipart/form-data", Headers)): Headers = {'Content-Type': 'multipart/form-data'} self.req_test = req.post_json(full_url, File, Headers) else: print("请求不通过,请检查case用例配置:{0}-{1}".format(num, CaseName)) log.error("请求不通过,请检查case用例配置:{0}-{1}".format(num, CaseName)) return "请求不通过,请检查case用例配置:{0}-{1}".format(num, CaseName), '' # 检查点与响应数据做对比 if (re.search(CheckPoint, str(self.req_test))): log.info("用例编号" + str(num) + " " + CaseName + "接口执行成功") return "成功", str(self.req_test) else: log.error("用例编号" + str(num) + " " + CaseName + "接口执行失败") return "失败", str(self.req_test) # #请求前缀 # url = "http://p.3.cn" # #接口地址 # uri = "/prices/mgets" # params = {"skuIds":"100004770249","type":"1"} # Headers = {} # #请求类型 # RequestForm = 'GET' # #数据类型 # dataform = 'json' # #检查点 # checkpoint = '"id":"J_100004770249"' # # it = InterfaceTest() # it.testrequest(url,uri,params,RequestForm,dataform,checkpoint,Headers)
class TestLogin(unittest.TestCase): def setUp(self): self.logger = Log() self.logger.log_info('「Login Test Start:') url = 'http://10.10.15.153' self.driver = webdriver.Chrome() self.driver.maximize_window() self.lp = LoginPage(self.driver, url) time.sleep(3) def tearDown(self): self.driver.quit() self.logger.log_info('_Login Test End」') # 登录成功 def test_1_login_success(self): self.lp.login('system', '123456') time.sleep(3) try: msg = self.driver.find_element_by_xpath( '//*[@class="gd-topbar-tool-text"]').text self.assertEquals('system', msg) self.logger.log_info('Test Case "test_1_login_success" Passed !') except Exception as e: self.logger.log_error( 'Test Case "test_4_login_fail" Failed ! \n{0}'.format(e)) raise e # 无用户名登录 def test_2_login_no_username(self): self.lp.login('', '123456') time.sleep(3) try: msg = self.driver.find_element_by_xpath( '//*[@class="gd-login-submit-text"]').text self.assertEquals('登 录', msg) self.logger.log_info( 'Test Case "test_2_login_no_username" Passed !') except Exception as e: self.logger.log_error( 'Test Case "test_4_login_fail" Failed ! \n{0}'.format(e)) raise e # 无密码登录 def test_3_login_no_passwd(self): self.lp.login('system', '') time.sleep(3) msg = self.driver.find_element_by_xpath( '//*[@class="gd-login-submit-text"]').text try: msg = self.driver.find_element_by_xpath( '//*[@class="gd-login-submit-text"]').text self.assertEquals('登 录', msg) self.logger.log_info('Test Case "test_3_login_no_passwd" Passed !') except Exception as e: self.logger.log_error( 'Test Case "test_4_login_fail" Failed ! \n{0}'.format(e)) raise e # 用户名/密码错误 def test_4_login_fail(self): self.lp.login('system', '1234567890') time.sleep(3) try: msg = self.driver.find_element_by_xpath( '//*[@class="gd-login-msg"]').text self.assertEquals('用户名或密码错误', msg) self.logger.log_info('Test Case "test_4_login_fail" Passed !') except Exception as e: self.logger.log_error( 'Test Case "test_4_login_fail" Failed ! \n{0}'.format(e)) raise e
#!/usr/bin/env python # -*- encoding: utf-8 -*- # @Author : Zhuzj # @file : test_login.py # @time : 2020/11/18 15:14 # @Software :PyCharm import pytest from PageObjects.login.login import login from PageObjects.index.firstpage import First_Page from Common.log import Log from Common import dir_config import TestDatas.公共数据.login_test_datas as LTD #定义resultlog和processlog P_log = Log(dir_config.processlog_dir) R_log = Log(dir_config.resultlog_dir) @pytest.mark.usefixtures("init_web") class Test_login: @pytest.mark.smoke def test_login_success(self, init_web): #动态添加description中的内容 self.test_login_success.__func__.__doc__ = LTD.success_data['dec'] P_log.info("*******开始执行{0}测试用例******".format(LTD.success_data['name'])) login(init_web).login_system(LTD.success_data['username'], LTD.success_data['pwd']) P_log.info("********{0}用例执行完成*******".format(LTD.success_data['name'])) #name=First_Page(init_web).get_login_name() #P_log.info("获取到的账户名为:{0}".format(name))
def send_requests(session,testdata): Log().info("开始发送请求") "封装requests请求" url = testdata["url"] method=testdata["method"] # 请求头部headers try: headers = eval(testdata["headers"]) except: headers = None # post请求body类型 body_type = testdata["type"] # 请求的datas参数 # 判断传data数据还是json datas=None #定义一个datas 作为返判断返回值 if body_type=='from': try: datas=eval(testdata["datas"]) #取出来的str 需转换为dict except: datas=None elif body_type=='json': try: datas =json.dumps(testdata["datas"]) #取出来的str 转变成json类型字典 except: datas=None #执行的id test_nub = testdata['id'] print("*******正在执行用例:----- %s ----**********" % test_nub) print("请求方式:%s, 请求url:%s" % (method, url)) # print(type(datas)) print("请求datas:%s" % datas) response = {} # 接受返回数据 后面写入数据 res=None #定义一个res 作为返回值 is_run= testdata['must'] # print(is_run) if is_run=='yes': #判断是否执行 try: if method=='get': res=session.get(url=url, headers=headers, params=datas, verify=False) response["Times"] =str(res.elapsed.total_seconds()) print("页面返回信息:%s" % res.content.decode("utf-8")) elif method=='post': res = session.post( url=url, headers=headers, data=datas, verify=False) response["Times"]=str(res.elapsed.total_seconds()) # print(response["Times"]) print("页面返回信息:%s" % res.content.decode("utf-8")) else: print('方法有误') return res # return是用来终止代码运行的 在返回结果后 response['rowNum'] = testdata['rowNum'] response["text"] = res.content.decode("utf-8") str_response=json.loads(res.text) # print(str_response["code"]) if str_response["code"]!=200: #如果状态码不为200时写入 Response response["Response"]=response["text"] else: response["Response"]="" #如果=200则写入空值 response["Msg"] = "" #提前定义Msg 默认为空 if testdata["CheckPoint"] in response["text"]: response["Result"]="pass" else: response["Result"] = "fail" print("用例测试结果: %s---->%s" % (test_nub, response["Result"])) return response except Exception as msg: response["Msg"] = str(msg) # print(response) return response else: response="" #如果不执行response 赋值为空 后面调用写入方法好判断 print("用例跳过") return response
#连接数据库 port必须为int %d类型 config = { "host": "123.157.219.74", "user": "******", "password": "******", "port": 33066, "database": "charging", "charset": "utf8" } try: db = pymysql.connect(**config) except Exception as a: print("数据库连接异常:%s" % a) Log().debug("数据库连接异常:%s" % a) def mysql_execute(sql, number=None): '''执行 单表sql 语句''' # with db.cursor(cursor=pymysql.cursors.DictCursor) as cursor:#获取数据库连接的对象以字典形式 with db.cursor() as cursor: try: if number == 'one': cursor.execute(sql) print('执行成功') elif number == 'more': cursor.executemany(sql) else: pass except Exception as a: