Beispiel #1
0
class ReadExcel():
    def __init__(self):
        self.readConfig = ReadConfig()
        self.table = xlrd.open_workbook('./testfile/二维码支付.xlsx')
        self.sheet = self.table.sheet_by_index(0)

    def get_rows(self):
        return self.sheet.nrows

    def get_cell_value(self, row, session, option):
        col = int(self.readConfig.get(session, option))
        return self.sheet.cell_value(row, col)

    def getCol(self, session, option):
        return int(self.readConfig.get(session, option))

    def get_col_values(self, col_id=None):
        if col_id is None:
            return self.sheet.col_values(0)
        else:
            return self.sheet.col_values(col_id)

    def get_row_num(self, case_id):
        num = 0
        col_data = self.get_col_values()
        for data in col_data:
            if case_id == data:
                return num
            num = num + 1
Beispiel #2
0
 def __init__(self, logger_name='framework'):
     self.logger = logging.getLogger(logger_name)
     logging.root.setLevel(logging.NOTSET)
     c = ReadConfig()
     self.log_file_name = c.log_file_name if c and c.log_file_name else 'test.log'
     self.backup_count = c.log_limit if c and c.log_limit else 5
     self.console_output_level = c.log_console_level if c and c.log_console_level else 'DEBUG'
     self.file_output_level = c.log_file_output_level if c and c.log_file_output_level else 'DEBUG'
     pattern = c.log_pattern if c and c.log_pattern else '%(asctime)s - %(filename)s[line:%(lineno)d] - %(' \
                                                         'levelname)s: %(message)s'
     self.formatter = logging.Formatter(pattern)
     # 兼容mac os
     if sys.platform == 'darwin':
         self.log_path = os.path.join(
             os.path.split(os.path.dirname(__file__))[0], 'log')
     else:
         self.log_path = os.path.join(
             os.path.split(os.path.dirname(__file__))[0].replace("/", "\\"),
             'log')
Beispiel #3
0
# /user/bin/python3
# -*- coding : utf-8 -*-
# @Auther : Dong
# @Time : 2018/7/4 10:58
import pymysql
from common.ReadConfig import ReadConfig

rc = ReadConfig()
db = pymysql.connect(rc.get_db('ip'), rc.get_db('username'),
                     rc.get_db('password'), rc.get_db('db'))
cursor = db.cursor()
sqls = """
delete from tb_role  where role_name in ('apitest','apitest1');
delete from tb_sps where sp_code in ('Oauth','apitest01');
delete from ids_service_company_middle where companytype= 1 or name='';
DELETE FROM ids_org_relation;
delete from ids_service_company where name='apitestopSS1';
delete from sorg where sorg_name='testGG';
"""

for sql in sqls.strip().split(";"):
    if sql:
        cursor.execute(sql)
        db.commit()
db.close()
Beispiel #4
0
 def __init__(self):
     self.readConfig = ReadConfig()
     self.table = xlrd.open_workbook('./testfile/二维码支付.xlsx')
     self.sheet = self.table.sheet_by_index(0)
Beispiel #5
0
def do_request(file_name: str) -> Any:
    """
    读取yml文件发送http请求
    :param file_name: yml文件名称,完整的文件名称
    """
    file = os.path.join(ReadConfig().testDataDir, file_name)
    yml = YamlRead(file).yml
    # cases类型 list(dict1,dict2)
    cases = yml['testcase']
    for case in cases:
        case_name = case["name"]
        logger.debug(f"开始处理名称为:{case_name}的接口")
        requests_data = None
        url = None
        method = None
        headers = None
        data = None
        extract = None
        validate = None
        response = None
        try:
            requests_data = jsonpath(case, "$..requests")[0]
            logger.info(f"获取requests_data成功:{requests_data}")
        except Exception as e:
            logger.error(f"获取request_data失败,失败原因为:{e}")
        try:
            url = requests_data["url"]
            logger.info(f"获取url成功:{url}")
        except Exception as e:
            logger.error(f"获取url失败,失败原因为:{e}")
        try:
            method: str = requests_data["method"]
            logger.info(f"获取method成功:{method}")
            if method.upper() not in RequestMethodEnum.get_value():
                logger.warn(f"请求方式不合法:{method}")
        except Exception as e:
            logger.error(f"获取method失败,失败原因为:{e}")
        try:
            headers = requests_data["headers"]
            logger.info(f"获取headers成功:{headers}")
            if not headers:
                logger.warn("====请求头为空,即将采用默认请求头替换===")
        except Exception as e:
            logger.error(f"获取headers失败,失败原因为:{e}")
        try:
            data = requests_data["data"]
            logger.info(f"获取data成功:{data}")
        except Exception as e:
            logger.error(f"获取请求参数data失败,失败原因为:{e}")
        try:
            extract = requests_data['extract']
            logger.info(f"获取extract成功:{extract}")
        except Exception as e:
            logger.error(f"获取extract失败,失败原因为:{e}")
        try:
            validate = requests_data['validate']
            logger.info(f"获取validate成功:{validate}")
        except Exception as e:
            logger.error(f"获取validate失败,失败原因为:{e}")
        if not headers:
            headers = RequestHeaderEnum.NORMALHEADERS.value
            logger.warn(f"===采用默认请求头{headers}===")
        if is_params_need_handle(data):
            logger.info(f"接口请求体有需要处理的参数{data}")
            try:
                data = replace_params(data, global_vars)
                logger.info(f"处理请求参数成功,替换结束之后的参数为:{data}")
            except Exception as e:
                logger.error(f"参数处理失败,失败原因:{e}")
        try:
            response = requests.request(method=method,
                                        url=url,
                                        data=data,
                                        headers=headers,
                                        verify=False)
            logger.info(f"接口{case_name}请求成功,响应为:{response.text}")
        except Exception as e:
            logger.error(
                f"接口请求失败,接口请求url:{url}\n接口请求参数:{data}\n接口请求头:{headers}\n接口响应状态码:"
                f"{response.status_code}\n错误信息:{e}")
        if extract:
            logger.info(f"需要从响应体中提取参数:{extract}")
            try:
                eval_jsonpath_str(json.loads(response.text), extract)
                logger.info(f"参数提取成功,全局变量字典更新为:{global_vars}")
            except Exception as e:
                logger.error(f"参数提取失败,失败原因为:{e}")
        # todo
        if validate:
            pass
Beispiel #6
0
from selenium.webdriver.common.keys import Keys
import paramiko
from common.ReadConfig import ReadConfig
from common.get_csv import *
from common.myHttp import post
from selenium import webdriver
rc = ReadConfig()
path = Propath()


def get_optoken():
    url = get_url(path + '\\testFile\\om\\om.csv', 'login')
    data = {'uname': 'admin', 'upass': '******'}
    re = post(url, data)
    token = re.json()['date']['token']
    return token


def get_markettoken():
    driver = webdriver.Chrome()
    driver.get('https://bccastle.com/eps/')
    driver.maximize_window()
    driver.find_element_by_id("j_username").clear()
    driver.find_element_by_id("j_username").send_keys('yulin')
    driver.find_element_by_id("j_password").clear()
    driver.find_element_by_id("j_password").send_keys('a123456')
    driver.find_element_by_id("loginBtn").send_keys(Keys.ENTER)
    trans = paramiko.Transport(('192.168.146.27', 22))
    trans.connect(username='******', password='******')
    res = paramiko.SSHClient()
    res._transport = trans
Beispiel #7
0
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
from common.ReadConfig import ReadConfig
from common.Log import Log

log = Log()
rc = ReadConfig()


def send_mail(report_file):
    sender = rc.get_email('sender')
    psw = rc.get_email('psw')
    receiver = rc.get_email('receiver')
    smtpserver = rc.get_email('smtp_server')
    port = rc.get_email('port')
    with open(report_file, 'rb') as f:
        mailbody = f.read()
    # 定义邮件内容
    msg = MIMEMultipart()
    body = MIMEText(mailbody, _subtype='html', _charset='utf-8')
    msg['Subject'] = u'自动化测试报告'
    msg['from'] = sender
    msg['To'] = ', '.join(eval(receiver))
    msg.attach(body)
    # 添加附件
    att = MIMEText(open(report_file, 'rb').read(), 'base64', 'utf-8')
    att['Content-Type'] = 'application/octet-stream'
    att['Content-Disposition'] = 'attachment; filename = "TestReport.html"'
    msg.attach(att)