def _get_attribute(self, name, *loc):
     try:
         attribute = self._find_element(*loc).get_attribute(name)
         log.info("获取到元素属性:%s" % name)
         return attribute
     except:
         log.error("Error:未获取元素到属性:%s" % name)
 def _get_property(self, name, *loc):
     try:
         property = self._find_element(*loc).get_property(name)
         log.info("获取到元素属性:%s" % name)
         return property
     except:
         log.error("Error:未获取元素到属性:%s" % name)
 def _get_text(self, *loc):
     try:
         text = self._find_element(*loc).text
         log.error("获取到文本:%s" % text)
         return text
     except:
         log.error("Error:未获取到文本内容")
Example #4
0
 def send_email(self):
     """
     发送邮件步骤:
     1.连接域名和端口号
     2.登录邮箱
     3.传入邮箱文本内容
     4.发送邮件
     5.关闭smtp连接
     :return:
     """
     self.email_header()
     self.email_content()
     self.check_file()
     self.email_attchment()
     try:
         self.smtp.connect(self.host, self.port)
     except:
         return ConnectionError
     try:
         # 注意username 应该一致,否则会报错
         self.smtp.login(self.username, self.password)
         self.smtp.sendmail(self.username, self.password,
                            self.msg.as_string())
     except TimeoutError:
         log.error("////// 发送邮件超时,请检查连接")
     except Exception as e:
         log.error("////// 发送邮件失败,错误:%e" % e)
     finally:
         self.smtp.close()
         self.smtp.quit()
Example #5
0
    def get_from_json(self, key):

        with open(self.JSON_PATH, "r+", encoding="utf-8") as f:
            data = json.load(f)
        if key in data.keys():
            return data.get(key)
        else:
            log.error("key值不存在,请检查key: %s" %key)
 def _find_element(self, *loc):
     try:
         # WebDriverWait(self._driver, 10).until(lambda x: x.find_element(*loc).is_displayed())
         # WebDriverWait(self._driver, 10).until(EC.visibility_of_element_located(*loc))
         WebDriverWait(self._driver, 10).until(self._is_located(*loc))
     except Exception as e:
         print("页面未能找到:(%s) 元素" % (loc))
         log.error("页面未能找到:(%s) 元素" % (loc))
     return self._driver.find_element(*loc)
 def _click(self, *loc):
     """
     重写元素点击方法
     :param loc:
     :return:
     """
     element = self._find_element(*loc)
     try:
         element.click()
     except Exception as e:
         log.error("Error:元素点击失败, 错误:%s" % e)
 def _excute_script(self, script):
     """
     执行 script 语句
     :param script:
     :return:
     """
     try:
         self._driver.execute_script(script)
         log.info("执行 script 语句: %s" % script)
     except Exception as e:
         print("Error:script语句执行失败, 错误:%s" % e)
         log.error("script语句执行失败, 错误:%s" % e)
 def _switch_to(self, *loc):
     """
     切入 frame
     :param loc:
     :return:
     """
     try:
         frame = self._find_element(*loc)
         self._driver.switch_to.frame(frame)
         log.info("切入 frame 成功")
     except:
         log.error("切入 frame 失败")
Example #10
0
    def execute_sql(self, sql, num=1):

        self.connect_db()
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchmany(num)
            self.db.commit()
            return result
        except Exception as e:
            self.db.rollback()
            log.error("ERROR: 执行SQL语句时发生错误, 信息: %s" % e, exc_info=True)
        finally:
            self.cursor.close()
Example #11
0
    def set_token_to_config(self):

        partner, leader = self.get_platform_token()
        student = self.get_students_token()
        cookie = self.get_jsessionid()
        try:
            rc.set_token('partner', str(partner))
            rc.set_token('leader', str(leader))
            rc.set_token('students', str(student))
            rc.set_token('cookie', str(cookie))
            log.info("凭证获取成功并写入 /common/config.txt 配置文件中")
        except Exception as e:
            log.error("凭证获取失败,请检查!错误: %s" %e)
Example #12
0
 def get_value_by_js(self, *loc):
     """
     通过js获取元素指定的值
     :param loc:
     :return:
     """
     try:
         element = self.driver.find_element(*loc)
         value = self.driver.execute_script("return arguments[0].value", element)
         log.info("通过js获取元素的值:%s" %value)
         return str(value)
     except:
         log.error("Error:通过js未获取的元素的值")
Example #13
0
    def send_email(self):
        self.email_content()

        try:
            self.smtp.connect(self.email_host)
            self.smtp = SMTP_SSL(self.email_host, timeout=5)
            # self.smtp.ehlo_or_helo_if_needed()
            self.smtp.login(self.username, self.password)
            self.smtp.sendmail(self.username, self.recievers,
                               self.msg.as_string().encode())
            log.info("##### 邮件发送成功 !!!!!")
        except SMTPException as e:
            log.error("////// 发送邮件失败,错误:%s" % e)
        finally:
            self.smtp.close()
            self.smtp.quit()
Example #14
0
    def connect_db(self):

        try:
            self.db = pymysql.connect(host=self.host,
                                      port=int(self.port),
                                      user=self.user,
                                      password=self.password)
            self.cursor = self.db.cursor()
            print('###### DB connected success')
        except ConnectionError as e:
            print('Error: DB Connected Error !!')
            log.error('Error: DB Connected Error !!', exc_info=True)
            raise e
        except Exception as e:
            log.error("Error: 数据库连接时发生错误, 信息: %s" % e, exc_info=True)
            raise e
 def _send_value(self, value, clear=True, *loc):
     """
     重写 send_keys 方法
     :param loc:
     :param value:
     :param clear:
     :return:
     """
     element = self._find_element(*loc)
     if clear:
         element.clear()
     try:
         element.send_keys(value)
     except Exception as e:
         print("值:%s 输入失败, 错误:%s" % (value, e))
         log.error("值:%s 输入失败" % value)
Example #16
0
 def set_token_to_config(self):
     '''
     将凭证数据写入配置文件
     :return: None
     '''
     leader = self.get_platform_token()
     # students = self.get_students_token()
     cookie = self.get_jsessionid()
     try:
         # rc.set_token('partner', str(partner))
         rc.set_token('leader', str(leader))
         # rc.set_token('students', str(students))
         rc.set_token('cookie', str(cookie))
         log.info("凭证获取成功并写入 /common/config.txt 配置文件中")
     except Exception as e:
         log.error("凭证获取失败,请检查!错误: %s" % e)
Example #17
0
 def find_element(self, *loc):
     """
     定位元素方法
     :param loc:定位因子
     :return:
     """
     try:
         # 因为传入*loc的是元组所以需要加*号
         # WebDriverWait(self.driver, 30).until(lambda x: x.find_element(*loc).is_displayed())
         # 注意:以下入参本身是元组,不需要加*
         WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(loc))
     except Exception:
         print("%s 页面中未能找到 %s 元素" % (self, loc))
         log.error("%s 页面中未能找到 %s 元素" % (self, loc))
         raise
     return self.driver.find_element(*loc)
 def _get_screen_short(self):
     """
     1.在error_img文件夹下创建一个以当前日期的文件夹
     2.再在当前日期的文件夹中创建一个以时分秒命名的文件夹
     3.将文件存入文件夹中
     """
     current_date = time.strftime("%Y-%m-%s", time.localtime(time.time()))
     currrent_time = time.strftime("%H-%M-%S", time.localtime(time.time()))
     error_img_path = os.path.join(rc.PROJECT_PATH, "error_img")
     # listdir = os.listdir(error_img_path)
     img_path = os.path.join(error_img_path, current_date)
     if not os.path.exists(img_path):
         os.mkdir(img_path)
         self._driver.get_screenshot_as_png()
         self._driver.save_screenshot(img_path)
     else:
         print("当前路径已存在:%s" % img_path)
         log.error("当前路径已存在:%s" % img_path)
Example #19
0
 def main(self):
     suit = self.set_suit()
     REPORT_DIR = os.path.join(rc.PROJECT_PATH, "report")
     date = time.strftime("%Y-%m-%d %H:%M")
     reportname = REPORT_DIR + date + ".html"
     try:
         if suit is not None:
             log.info("********************   TEST START  ********************")
             with open(reportname, "w+", encoding="utf-8") as file:
                 bstrunner = BSTestRunner(stream=file, title=self.title, description=self.description)
                 bstrunner.run(suit)
     except Exception as e:
         log.error("run test 失败,错误:%s" %e)
     finally:
         log.info("********************   TEST END   ********************")
         if self.on_off == "on":
             ce.send_email()
         elif self.on_off == "off":
             log.info("邮件控制器选择:不发送邮件")
Example #20
0
    def send_email(self):

        self.email_header()
        self.email_content()
        self.email_attachment()

        try:
            # self.smtp.connect(self.email_host)
            self.smtp = SMTP_SSL(self.email_host)
            self.smtp.ehlo_or_helo_if_needed()
            self.smtp.login(self.username, self.password)
            # login的user参数与sendmail的from_addr参数需一致,否则报错501:mail from address must be same as authorization user
            self.smtp.sendmail(self.username, self.msg["To"].split(";"),
                               self.msg.as_string())
            log.info("##### 邮件发送成功 !!!!!")
        except TimeoutError:
            log.error("////// 发送邮件超时,请检查网络连接")
        except Exception as e:
            log.error("////// 发送邮件失败,错误:%s" % e)
        finally:
            # self.smtp.close()
            self.smtp.quit()
Example #21
0
    def send_request(self,
                     url,
                     method,
                     headers=None,
                     data=None,
                     cookies=None,
                     **kwargs):
        """
        发起 http 请求:
        首先判断 method 请求方法,如果是 post 方法, 依据头部中的 content-type 字段判断传参方式

        eg: request = HttpRequests()
            response = request(method, url, data)
            or
            response = request.send_request(method, url, data)
            print(response.text)

        :param url: 完整请求地址
        :param method: 请求方法,默认post请求
        :param headers: 请求头部信息
        :param data: 请求正文
        :param cookies: cookies信息,非必传
        :return:
        """

        method = method.upper()
        log.info("请求地址: %s" % url)
        log.info("请求方法: [- %s -]" % method)
        log.info("请求头部: %s" % headers)
        if cookies:
            log.info("Set Cookies: %s" % cookies)
        if isinstance(data, str):
            try:
                data = json.loads(data)
            except Exception:
                data = eval(data)
        log.info("请求正文: %s" % data)
        if method == "POST":
            # 依据头部被信息中的 content-type 判断传参方式
            if headers["content-type"] == "application/x-www-form-urlencoded":
                response = requests.post(url=url,
                                         data=data,
                                         headers=headers,
                                         cookies=cookies,
                                         timeout=30,
                                         **kwargs)
            elif headers["content-type"] == "application/json":
                response = requests.post(url=url,
                                         json=data,
                                         headers=headers,
                                         cookies=cookies,
                                         timeout=30,
                                         **kwargs)
            else:
                response = requests.post(url=url,
                                         data=data,
                                         headers=headers,
                                         cookies=cookies,
                                         timeout=30,
                                         **kwargs)
        elif method == "GET":
            response = requests.get(url=url,
                                    params=data,
                                    headers=headers,
                                    cookies=cookies,
                                    timeout=30,
                                    **kwargs)
        else:
            print("Method 值错误,请检查!!!")
        try:
            if response.status_code == 200:
                log.info("响应消息: %s" % response.json())
                return response.json()
        except json.decoder.JSONDecodeError:
            return response
        except Exception as e:
            log.error("Error: %s" % e)
        return response