Example #1
0
    def send_email(self, message_body):
        # 获取发送邮件的配置信息
        read_config = ReadConfig()
        sender = read_config.get_sender
        receviers = [read_config.get_receviers + "," + sender]
        password = read_config.get_email_password
        report_path = read_config.get_html_report_path

        # 组建邮件格式
        message = MIMEMultipart()
        message["From"] = formataddr(["测试组", sender])
        message["To"] = ','.join(receviers)
        message['Subject'] = Header("测试报告", 'utf-8')  # 邮件的主题
        message.attach(
            MIMEText(message_body, _subtype="html", _charset="utf-8"))
        # 构建邮件附件
        att1 = MIMEText(
            open(report_path, "r", encoding="utf-8").read(), "base64", 'utf-8')
        att1["Content-Type"] = 'application/octet-stream'
        att1["Content-Disposition"] = 'attachment; filename="TestReport.html"'
        message.attach(att1)

        # 发送邮件
        try:
            smtp = smtplib.SMTP("smtp.163.com", port=25)
            smtp.login(sender, password=password)
            smtp.sendmail(sender, message["To"].split(","),
                          message.as_string())
        except Exception as error:
            log("发送邮件发生错误%s" % error)
        else:
            log("发送邮件成功")
        finally:
            smtp.quit()
Example #2
0
 def get_value(self, sql, index):
     # 从数据库获取数据并返回
     self.userSqlsor.execute(sql)
     result = self.userSqlsor.fetchone()
     # 关闭光标对象
     self.userSqlsor.close()
     # 关闭数据库连接
     self.conn.close()
     log("查询数据库成功")
     return result[int(index)]
Example #3
0
 def __init__(self, set_name):
     # 读取请求数据
     file_path = ReadConfig().get_requests_data_path + set_name + ".json"
     self.reader = {}
     try:
         with open(file_path, "r", encoding="utf-8") as requests_data_file:
             self.reader = json.load(requests_data_file)
     except Exception as error:
         log("获取全部请求数据发生错误%s!", error)
     else:
         log("获取全部请求数据成功!")
Example #4
0
 def report(self):
     log("开始生成HTML报告")
     # 整理数据
     all_data = self.case_singleton.get_all_case_count()
     all_data["case"] = self.case_singleton.case_list
     all_data["start_time"] = self.start_time
     all_data["end_time"] = self.end_time
     # 生成测试报告
     html_report = HTMLTestRunner("接口自动化测试报告")
     html_report.generateReport(all_data)
     log("结束生成HTML报告")
     return html_report.SUBJECTHTML
Example #5
0
class CaseSingleton(object):
    def __init__(self):
        # 需要执行的案例
        self.case_list = []
        # 数据池
        self.relevance_data = {}

    def get_case_data(self):
        case_excel_operation = CaseExcelOperation()
        self.case_list = case_excel_operation.read_all_case_set()

    def get_all_case_count(self):
        '''获取通过的案例总数、失败的案例总数、未执行的总数'''
        all_count = 0
        pass_count = 0
        faile_count = 0
        no_run = 0
        for case_set in self.case_list:
            all_count += case_set.count
            pass_count += case_set.pass_count
            faile_count += case_set.faile_count
            no_run += case_set.no_run
        return {
            "count": all_count,
            "pass_count": pass_count,
            "faile_count": faile_count,
            "non-execution": no_run
        }

    def save_relevance_data(self, case, res):
        '''
        保存依赖数据
        '''
        if case.relevance_data != None:
            relevance_list = case.relevance_data.split(",")
            report = ""
            for relevance in relevance_list:
                if relevance != "" and relevance != None:
                    try:
                        self.relevance_data.update(eval(relevance))
                    except Exception as error:
                        report = "\n保存%s失败" % relevance
                        log("保存%s发生错误%s" % (relevance, error))
                        log(res)
                    else:
                        log("保存%s----%s成功" % (relevance, self.relevance_data))
            if report != "":
                # 设置案例执行状态为失败
                case.set_actual_result("False", report)
Example #6
0
 def run_main(self, url, method, data=None, headers=None):
     '''
     发送请求,根据method进行选择发送请求的方式
     :param method: 发送请求的方式(GET/POST)
     '''
     res = ""
     if method == 'GET':
         res = self.send_get(url, headers, data)
     elif method == 'POST':
         res = self.send_post(url, data, headers)
     try:
         return json.loads(res)
     except Exception as error:
         log("接受数据个数错误%s,数据为%s" % (error, res))
         return None
Example #7
0
    def read_case(self, case_set):
        '''读取交易集中的案例数据'''
        try:
            case_reader = self.excel_operation.get_datas(case_set.set_name)
            for k, v in case_reader.items():
                if k != "CaseNum" and k != None:
                    case_data = CaseModel(v)
                    case_set.run_case.append(case_data)
                    if case_data.is_run != "YES":
                        case_set.no_run += 1

        except Exception as error:
            log("读取案例数据发生错误%s", error)
        else:
            log("读取案例数据成功")
Example #8
0
 def send_get(self, url, headers=None, data=None):
     '''
     发送get请求
     :param url:请求的网址
     :param headers:headers默认为空
     :param data:请求的数据
     :return:请求响应体,如果请求失败则返回False
     '''
     try:
         res = requests.get(url=url, headers=headers, json=data)
     except Exception as error:
         log("GET:%s发送发成错误%s" % (url, error))
         return False
     else:
         log("GET:%s发送成功" % url)
         return res.text
Example #9
0
    def send_post(self, url, data, headers=None):
        '''
        发送POST请求
        :param url: 请求的网址
        :param data: 上传的数据
        :param headers: headers默认为空
        :return: 请求响应体,如果请求失败则返回False
        '''
        try:

            res = requests.post(url, headers=headers, data=json.dumps(data))
        except Exception as error:
            log("POST:%s发送发生错误%s" % (url, error))
            return False
        else:
            log("POST:%s发送成功" % url)
            return res.text
Example #10
0
 def run_case(self):
     # 执行案例
     read_requests_data = ReadRequestsData(self.case_set.set_name)
     requests = RunMain()
     host = "http://" + ReadRequest().get_url
     for case in self.case_set.run_case:
         if case.is_run == "YES":
             try:
                 log("开始执行案例%s" % case.caseNum)
                 # 执行sql
                 self.database_operation(case)
                 # 读取json
                 requests_data = read_requests_data.get_request_data(case, self.case_singleton.relevance_data)
                 # 发送请求
                 headers = None
                 token = None
                 if "YES" in case.is_headers:
                     # 整理数据
                     # 获取token
                     try:
                         token = self.case_singleton.relevance_data[case.is_headers.split(",")[-1]]
                     except Exception as error:
                         log("获取数据失败!")
                         continue
                     headers = read_requests_data.get_requests_header(case, token)
                     if headers == None or token == None:
                         log("执行案例%s发生错误" % case.caseNum)
                         continue
                 get_data = GetData(requests_data, token)
                 da1 = get_data.combination_data()
                 res = requests.run_main(host + case.url, case.requests_type, da1, headers)
                 if res != None:
                     self.save_assert(case, res)
                 else:
                     log("获取返回值为空")
                     case.set_actual_result("False", "获取返回值为空")
                 # 补充失败日志
                 if "False" in case.actual_result:
                     case.set_actual_result("False", "\n请求体:%s" % str(da1))
                     case.set_actual_result("False", "\n请求响应体:%s" % str(res))
                     log("案例%s执行失败" % case.caseNum)
                 else:
                     case.set_actual_result("Success", "\n请求响应体:%s" % str(res))
                     log("案例%s执行成功" % case.caseNum)
Example #11
0
 def create_report(self):
     '''生成EXCEL测试报告'''
     log("开始生成测试报告")
     from public.util.excel_operation import ExcelOperation
     from public.read_config.config import ReadConfig
     # 打开excel表读取数据
     config = ReadConfig()
     excel_operation = ExcelOperation(config.get_case_path)
     reader =  excel_operation.get_datas("case")
     # 填写结果
     for case in self.case_set.run_case:
         if case.is_run == "YES":
             try:
                 # 如果结果为空则写入执行失败
                 if case.actual_result == None:
                     case.set_actual_result("Flase", "执行失败,日志为空。")
                 color = config.get_success_color if "Success" in case.actual_result else config.get_failure_color
                 excel_operation.set_cell(reader[case.caseNum][14], color, case.actual_result)
             except Exception as error:
                 log("测试案例%s测试报告生成发生错误%s" % case.caseNum, error)
                 continue
Example #12
0
class ReadRequestsData(object):

    # 读取请求数据文件中的数据

    def __init__(self, set_name):
        # 读取请求数据
        file_path = ReadConfig().get_requests_data_path + set_name + ".json"
        self.reader = {}
        try:
            with open(file_path, "r", encoding="utf-8") as requests_data_file:
                self.reader = json.load(requests_data_file)
        except Exception as error:
            log("获取全部请求数据发生错误%s!", error)
        else:
            log("获取全部请求数据成功!")

    def get_request_data(self, case, data_pool):
        # 将有依赖的数据用数据池中对应的数据进行替换
        try:
            # 获取案例对应的请求数据的key值
            req_data = self.reader[case.requests_data][0]
            if case.relevance_field != None:
                # 获取需要替换的数据
                exchange_list = case.relevance_field.split(",")
                relenance_case = case.relevance_case.split(",")
                # 替换依赖数据
                for exchange_data, exchange_case in zip(
                        exchange_list, relenance_case):
                    if exchange_data != "":
                        try:
                            exec(exchange_data)
                        except Exception as error:
                            log("更换%s中保存的数据%s发生错误%s" %
                                (exchange_case, exchange_data, error))
                            case.set_actual_result(
                                "False", "\n更换数据失败%s" % exchange_data)
        except Exception as error:
            log("获取%s的请求数据发生错误%s" % case.caseNum, error)
            return False
        else:
            log("获取%s的请求数据成功" % case.caseNum)
            return req_data
Example #13
0
    def run(self):
        self.case_singleton.get_case_data()

        self.start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        for case_set in self.case_singleton.case_list:
            try:
                log("开始执行用例集%s" % case_set.set_name)
                runCase = RunCase(case_set, self.case_singleton)
                runCase.run_case()
                runCase.get_cases()
            except Exception as error:
                log("发生错误%s,用例集执行%s失败" % (error, case_set.set_name))
                continue
            else:
                log("用例集%s执行完成" % case_set.set_name)
        self.end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
Example #14
0
        config = ReadConfig()
        excel_operation = ExcelOperation(config.get_case_path)
        reader =  excel_operation.get_datas("case")
        # 填写结果
        for case in self.case_set.run_case:
            if case.is_run == "YES":
                try:
                    # 如果结果为空则写入执行失败
                    if case.actual_result == None:
                        case.set_actual_result("Flase", "执行失败,日志为空。")
                    color = config.get_success_color if "Success" in case.actual_result else config.get_failure_color
                    excel_operation.set_cell(reader[case.caseNum][14], color, case.actual_result)
                except Exception as error:
                    log("测试案例%s测试报告生成发生错误%s" % case.caseNum, error)
                    continue
        log("测试报告生成完成")

    def get_start_time(self):
        # 返回开始时间
        return time.strftime("%Y-%m-%d %H:%M", time.gmtime(self.__start_time))

    def get_elapsed_time(self):
        # 返回执行总时间
        return int(self.__end_time - self.__start_time)

    def get_cases(self):
        # 计算成功、失败的案例个数
        for case in self.case_set.run_case:
            if "YES" in case.is_run:
                if "Success" in case.actual_result:
                    self.case_set.pass_count += 1
Example #15
0
 def send_report(self, message_body):
     log("开始发送邮件")
     send = SendEmail()
     send.send_email(message_body)
     log("结束发送邮件")
Example #16
0
class MysqlOperation(object):
    def __init__(self):
        self.conn = None
        self.userSqlsor = None

    def connent_database(self, host):
        read_config = ReadConfig()
        self.conn = pymysql.connect(
            host=host,
            user=read_config.get_database_user,
            password=read_config.get_database_password,
        )
        self.userSqlsor = self.conn.cursor()

    def update_database(self, sql):
        self.userSqlsor.execute(sql)
        self.conn.commit()

    def get_value(self, sql, index):
        # 从数据库获取数据并返回
        self.userSqlsor.execute(sql)
        result = self.userSqlsor.fetchone()
        # 关闭光标对象
        self.userSqlsor.close()
        # 关闭数据库连接
        self.conn.close()
        log("查询数据库成功")
        return result[int(index)]

    def database_operation(self, case, data_pool):
        read_requests = ReadRequest()
        host = ""
        database = case.database.split(",")
        if "url" in database[0]:
            host = read_requests.get_url
        else:
            host = database[0]
        for index, sq in enumerate(database):
            if index >= 1 and sq != "":
                self.connent_database(host)
                if "==" not in sq:
                    # 修改数据库
                    try:
                        self.update_database(eval(sq))
                        log("修改数据库成功")
                    except Exception as error:
                        log("%s在修改数据库%s发生错误%s" % (case.caseNum, sq, error))
                    finally:
                        # 关闭光标对象
                        self.userSqlsor.close()
                        # 关闭数据库连接
                        self.conn.close()
                else:
                    # 从数据库获取信息
                    data = sq.split("==")
                    try:
                        result = self.get_value(eval(data[2]), data[1])
                        data_pool.update(
                            {case.caseNum + "_" + data[0]: result})
                    except Exception as error:
                        log("%s在获取数据库%s发生错误%s" %
                            (case.caseNum, data[1], error))
Example #17
0
                            exec(exchange_data)
                        except Exception as error:
                            log("更换%s中保存的数据%s发生错误%s" %
                                (exchange_case, exchange_data, error))
                            case.set_actual_result(
                                "False", "\n更换数据失败%s" % exchange_data)
        except Exception as error:
            log("获取%s的请求数据发生错误%s" % case.caseNum, error)
            return False
        else:
            log("获取%s的请求数据成功" % case.caseNum)
            return req_data

    def get_requests_header(self, case, token):
        # 将对应的token替换进headers并返回headers
        try:
            headers = self.reader[case.requests_data][1]
            headers["token"] = token
        except Exception as error:
            log("发生错误%s,请检查json文件中是否写入headers部分" % error)
            return None
        else:
            log("获取%s的heasers数据成功" % case.caseNum)
            return headers


if __name__ == "__main__":
    with open(r"D:\测试\自动化\TEST-case\data\order.json", "r",
              encoding="utf-8") as requestsDataFile:
        data = requestsDataFile.read()
        print(type(data))