def send_request(self):
        """ 发请求 """
        try:
            response = requests.request(method=self.case['case_method'],
                                        url=self.case['case_url'],
                                        params=self._check_params())
            content_type = response.headers['Content-Type']
            content_type = content_type.split(";")[0].split(
                '/')[-1] if ';' in content_type else content_type.split(
                    "/")[-1]
            if hasattr(self, '_check_{}_response'.format(content_type)):
                response = getattr(
                    self, '_check_{}_response'.format(content_type))(response)
            else:
                raise '返回类型为: {}, 无法解析'.format(content_type)
        except:
            logger().error({
                'response':
                "请求发送失败,详细信息: url={}".format(self.case['case_url'])
            })
            return {
                'response': "请求发送失败,详细信息: url={}".format(self.case['case_url'])
            }, self.case['case_expect']

        return response
Exemple #2
0
 def send_depend_request(self, url, method, type, data=None):
     """ 发请求 """
     method = method.upper()
     type = type.upper()
     try:
         if data != '':
             if isinstance(data, str):
                 data = json.loads(data)
         if method == 'GET':
             if data != None:
                 response = requests.request(method=method,
                                             url=url,
                                             params=data)
             else:
                 response = requests.request(method=method, url=url)
             response_data = response.json()
             return response_data
         elif method == 'POST':
             if type == 'FORM':  # 发送表单数据,使用data参数传递
                 response = requests.request(method=method,
                                             url=url,
                                             data=data)
             elif type == 'JSON':  # 如果接口支持application/json类型,则使用json参数传递
                 response = requests.request(method=method,
                                             url=url,
                                             json=data)
             else:  # 如果接口需要传递其他类型的数据比如 上传文件,调用下面的请求方法
                 response = requests.request(method=method, url=url)
                 # 如果请求方式非 get 和post 会报错,当然你也可以继续添加其他的请求方法
             response_data = response.json()
             return response_data
     except:
         logger().error({'依赖接口执行失败': " url={}".format(url)})
 def send_request(self):
     """ 发请求 """
     try:
         response = requests.request(
             method=self.case['case_method'],
             url=self.case['case_url'],
             params=self._check_params()  # 调用私有方法,外部类不要去访问它
         )
         # ## 这里通过response返回的Content-Type,进行内容格式判断
         # content_type = response.headers['Content-Type']
         # content_type = content_type.split(";")[0].split('/')[-1] if ';' in content_type else \
         # content_type.split("/")[-1]
         # ## 判定格式后,对返回内容进行取值
         # if hasattr(self, '_check_{}_response'.format(content_type)):                # hasattr() 函数用于判断对象是否包含对应的属性
         #     response = getattr(self, '_check_{}_response'.format(content_type))(response)           # getattr() 函数用于返回一个对象属性值,,这里会跳转到_check_html_response
         # else:
         #     raise '返回类型为: {}, 无法解析'.format(content_type)
     except:
         ## 如果格式判断和取值异常,就返回固定内容,这里并不适合我们接口约定,从内容判断和取值都得修改
         logger().error({
             'response':
             "请求发送失败,详细信息: url={}".format(self.case['case_url'])
         })
         return {
             'response': "请求发送失败,详细信息: url={}".format(self.case['case_url'])
         }, self.case['case_expect']
     return response.text, self.case['case_expect']
 def _check_json_response(self, response):
     """  处理json类型的返回值 """
     response = response.json()  # {'success': True}
     for key in self.case_expect:
         if self.case_expect[key] != response[key]:  # 用例执行失败的
             return {key: self.case_expect[key]}, {key: response[key]}
     else:  # 执行成功
         logger("发送请求").info('{} 执行成功'.format(self.case['case_url']))
         return {key: self.case_expect[key]}, {key: response[key]}
 def get_all_excel_data(self):
     '''获取所有excel数据'''
     allexceldata = []
     # 遍历所有输入文件名
     for file_name in self.file_name_list:
         file = file_name + '.xlsx'
         if file in self.case_path:
             file_path = os.path.join(self.dir, file)
             exceldata = self.get_excel_data(file_path)
             # print(exceldata)
             allexceldata.extend(exceldata)
         else:
             logger().error('没有找到{},请检查case文件夹及输入文件名,'.format(file))
     return allexceldata
    def send_email(self):
        """ 发送邮件 """

        # 第三方 SMTP 服务
        mail_host = "smtp.qq.com"  # 设置服务器
        mail_user = "******"  # 用户名
        # mail_pass = "******"  # 口令

        # 设置收件人和发件人
        sender = '*****@*****.**'
        receivers = [
            '*****@*****.**', '*****@*****.**', '*****@*****.**'
        ]  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

        # 创建一个带附件的实例对象
        message = MIMEMultipart()

        # 邮件主题、收件人、发件人
        subject = '请查阅--测试报告'  # 邮件主题
        message['Subject'] = Header(subject, 'utf-8')
        message['From'] = Header("{}".format(sender), 'utf-8')  # 发件人
        message['To'] = Header("{}".format(';'.join(receivers)),
                               'utf-8')  # 收件人

        # 邮件正文内容 html 形式邮件
        send_content = self.read_report()  # 获取测试报告
        html = MIMEText(_text=send_content, _subtype='html',
                        _charset='utf-8')  # 第一个参数为邮件内容

        # 构造附件
        att = MIMEText(_text=send_content, _subtype='base64', _charset='utf-8')
        att["Content-Type"] = 'application/octet-stream'
        file_name = 'report.html'
        att["Content-Disposition"] = 'attachment; filename="{}"'.format(
            file_name)  # # filename 为邮件附件中显示什么名字
        message.attach(html)
        message.attach(att)

        try:
            smtp_obj = smtplib.SMTP()
            smtp_obj.connect(mail_host, 25)  # 25 为 SMTP 端口号
            smtp_obj.login(mail_user, mail_pass)
            smtp_obj.sendmail(sender, receivers, message.as_string())
            smtp_obj.quit()
            logger().info("邮件发送成功")

        except smtplib.SMTPException:
            logger().error("Error: 无法发送邮件")
 def send_request(self):
     """ 发请求 """
     method = self.case['case_method'].upper()
     data = self._check_params()
     # print(data)
     url = self.case['case_url']
     type = self.case['params_type'].upper()
     try:
         if method == 'GET':
             if data != '':
                 response = requests.request(method=method, url=url, params=data)
             else:
                 response = requests.request(method=method, url=url)
         elif method == 'POST':
             if type == 'FORM':  # 发送表单数据,使用data参数传递
                     response = requests.request(method=method, url=url, data=data)
             elif type == 'JSON':  # 如果接口支持application/json类型,则使用json参数传递
                     response = requests.request(method=method, url=url, json=data)
             else:  # 如果接口需要传递其他类型的数据比如 上传文件,调用下面的请求方法
                 response = requests.request(method=method, url=url)
                 # 如果请求方式非 get 和post 会报错,当然你也可以继续添加其他的请求方法
             # response_text = response.text
         else:
             raise ValueError('request method "{}" error ! please check'.format(method))
         content_type = response.headers['Content-Type']
         content_type = content_type.split(";")[0].split('/')[-1] if ';' in content_type else \
         content_type.split("/")[-1]
         if hasattr(self, '_check_{}_response'.format(content_type)):
             assert_data = getattr(self, '_check_{}_response'.format(content_type))(response)
         else:
             raise '返回类型为: {}, 无法解析'.format(content_type)
     except:
         logger().error({'response': "请求发送失败,详细信息: url={}".format(self.case['case_url'])})
         return {'response': "请求发送失败,详细信息: url={}".format(self.case['case_url'])}, self.case['case_expect']
     response = response.json()
     return response,assert_data