Пример #1
0
class AppiumBaseApi(object):
    def __init__(self, driver, properties):
        self.android = AndroidDebugBridge()
        self.log4py = LoggingPorter()
        self.driver = driver
        self.actions = []
        self.taction = TouchAction(self.driver)
        self.xml_file_path = properties.dumpxmlPath
        self.capturePath = properties.capturePath
        self.pattern = re.compile(r"\d+")

    def end(self):
        """Stop the running application, specified in the desired capabilities, on
        the device.
        """
        self.driver.close_app()

    def is_displayed(self, by, value):
        is_displayed = False
        try:
            is_displayed = self.driver.find_element(by, value).is_displayed()
            self.log4py.debug("element [ " + str(value) + " ] displayed? " +
                              str(is_displayed))
        except Exception, e:
            self.log4py.error("element元素没有点位到" + str(e))
        return is_displayed
Пример #2
0
class SeleniumBaseApi(object):
    def __init__(self, driver, properties):
        self.capturePath = properties.capturePath
        self.pauseTime = properties.pauseTime
        self.implicitly_wait_time = properties.waitTimeout
        self.log4py = LoggingPorter()
        self.driver = driver
        self.Find = By

    def stop_web_driver(self):
        try:
            self.driver.quit()
            self.log4py.debug("stop Driver")
        except Exception, e:
            self.log4py.error("执行stopWebDriver()方法发生异常,异常信息:" + str(e))
Пример #3
0
class EmailController(object):
    def __init__(self):
        self.fc = FileInspector()
        bools = self.fc.is_has_file("owl-framework.ini")
        if bools:
            fp = self.fc.get_file_abspath()
            conf = ConfigReader(fp)
            self.smtp_host = conf.get_value("email", "smtp_host")
            self.pop3_host = conf.get_value("email", "pop3_host")
            self.receiver = conf.get_value("email", "receiver").split(",")
            self.receiver_pa = conf.get_value("email", "receiver_pa")
            self.sender = conf.get_value("email", "sender")
            self.sender_pa = conf.get_value("email", "sender_pa")
            self.report_path = os.path.join(
                self.fc.get_project_path(),
                conf.get_value("ResultPath", "htmlreportPath"))
        self.log4py = LoggingPorter()

    def send_email_is_html(self):
        latestfpath, fname, currentfolder = self.fc.get_latest_file(
            self.report_path)
        msgRoot = MIMEMultipart('related')
        ff = open(latestfpath, 'rb')
        message = MIMEText(ff.read(), 'html', 'utf-8')
        ff.close()
        message['From'] = self.sender
        #message['To'] = self.receiver
        subject = '实验室数字化平台-自动化测试报告'
        message['Subject'] = Header(subject, 'utf-8')
        msgRoot.attach(message)
        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(self.smtp_host)
            smtpObj.login(self.sender, self.sender_pa)
            smtpObj.sendmail(self.sender, self.receiver, msgRoot.as_string())
            self.log4py.debug("SendEmail_withFile邮件发送成功")
            smtpObj.close()
        except Exception, e:
            print e
            self.log4py.error("Error: 无法发送邮件::" + str(e))
Пример #4
0
class ExcelParser(object):
    def __init__(self, excelfilename):
        self.excelfilename = excelfilename
        fc = FileInspector()
        boolean = fc.is_has_file(excelfilename)
        if boolean:
            self.excel_path = fc.get_file_abspath()
        self.log4py = LoggingPorter()

    def read_excel(self, excel_sheet_name):
        """打开目标excel文件  r--读,w--写(覆盖),a--追加写"""
        xls_data = xlrd.open_workbook(self.excel_path, "rb")
        table = xls_data.sheet_by_name(excel_sheet_name)  # 打开sheet页
        self.log4py.debug("打开的%s文件中的sheet页" % self.excelfilename)
        return table  # 将指定的sheet页对象返回给调用者

    def writ_excel(self, row, column, value):
        x_data = xlrd.open_workbook(self.excel_path, "rb")  # 只能是xls文件
        copy_sheet = copy(x_data)  # copy,并对附件进行操作
        write_xls = copy_sheet.get_sheet(0)  # 得到附件中的sheet页
        write_xls.write(row, column, value)  # 将测试的结果追加到附件中sheet页中每一行的后面
        copy_sheet.save(self.excel_path)  # 覆盖保存(注意编码错误)
Пример #5
0
def html_reporter():
    logger = LoggingPorter()
    fc = FileInspector()
    pro_path = fc.get_project_path()
    boolean = fc.is_has_file("owl-framework.ini")
    if boolean:
        inipath = fc.get_file_abspath()
        cf = ConfigReader(inipath)
    htmlrp_path = cf.get_value("ResultPath", "htmlreportPath")
    htmreportl_abs_path = os.path.join(pro_path, htmlrp_path)
    timecurrent = formated_time("%Y-%m-%d-%H-%M-%S")
    logger.debug("=====创建了一个html文件报告,路径是::" + htmreportl_abs_path)
    file_path = str(
        htmreportl_abs_path) + timecurrent + "-LDP-TestingRreporter.html"
    try:
        if os.path.exists(file_path):
            html_obj = open(file_path, "a")  # 打开文件   追加
            return html_obj
        else:
            html_obj = file(file_path, "wb+")
            return html_obj
    except Exception, e:
        logger.error("创建html_reporter出现错误" + str(e))
Пример #6
0
class CreateConfigFile(object):
    def __init__(self):
        self.fkctl = FileInspector()

        if self.fkctl.is_has_file("owl-appium.ini"):
            fp = self.fkctl.get_file_abspath()
            self.cfg = ConfigReader(fp)
        self.log4py = LoggingPorter()
        self.log4py.info("-----配置文件操作开始-----")
        self.f_path = os.path.join(
            self.fkctl.get_project_path(),
            self.cfg.get_value("ResultPath", "appiumService"))

    def __del__(self):
        self.log4py.info("-----配置文件操作结束-----")

    def set_appium_uuids_ports(self, device_list, port_list):
        """
        遍历list,按照下表进行对应映射
        :param device_lsit: 手机uuid
        :param port_list: pc启动的appium服务端口
        """
        bol = self.create_config_file(self.f_path)
        if bol:
            self.log4py.info("创建appiumService.ini文件成功:{}".format(self.f_path))
            ap = ConfigReader(self.f_path)
            if len(device_list) > 0 and len(port_list) > 0:
                for i in range(len(device_list)):
                    filed = device_list[i]
                    key = filed
                    value = port_list[i]
                    # 因为是覆盖写入,没有section,需要先添加再设置, 初始化的服务都加一个run的标识
                    ap.add_section_key_value(filed, key, value)
                    ap.set_value(filed, "run", "0")
                ap.flush()
                self.log4py.debug(
                    "设备sno与appium服务端口映射已写入appiumService.ini配置文件:{}--{}".format(
                        key, value))

    def set_appium_uuid_port(self, device, port, bp):
        """
        如果这样一个一个的写入到配置文件中,是追加还是覆盖?如果是覆盖的,服务启动完成后就剩一个配置,所以不行
        如果是追加,需要判断配置文件中是否已经有了相同的section,有就更新,没有就添加
        :param device: 手机uuid
        :param port pc启动的appium服务端口
        """
        bol = self.create_config_file(self.f_path)
        if bol:
            if device is not None and port is not None:
                ap = ConfigReader(self.f_path)
                sec = device
                key = device
                value = port
                if ap.had_section(sec):
                    ap.set_value(sec, key, value)
                    ap.set_value(sec, "bp", bp)
                    ap.set_value(sec, "run", "0")
                else:
                    ap.add_section_key_value(sec, key, value)
                    ap.set_value(sec, "bp", bp)
                    ap.set_value(sec, "run", "0")
                ap.flush()
                self.log4py.debug(
                    "设备sno与appium服务端口映射已写入appiumService.ini配置文件:{}--{}".format(
                        key, value))

    def create_config_file(self, path):
        """
        如果path这个文件不存在,就创建这个文件;存在就清空文件
        :param path: 是一个文件的绝对路径
        :return: 
        """
        if os.path.exists(path) and os.path.isfile(path):
            return True
        dir_name = os.path.dirname(path)
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)
        f = open(path, "wb")
        f.close()
        if os.path.exists(path) and os.path.isfile(path):
            return True
        return False

    def get_all_appium_server_port(self):

        port_list = []
        if os.path.exists(self.f_path):
            ap = ConfigReader(self.f_path)
            section_list = ap.get_sections()
            for sl in section_list:
                port_list.append(ap.get_value(sl, sl))
                port_list.append(ap.get_value(sl, "bp"))
        return port_list

    def get_appium_logs_path(self):
        path = os.path.join(self.fkctl.get_project_path(),
                            self.cfg.get_value("ResultPath", "appiumlogPath"))
        if PATH(path):
            if not os.path.exists(path):
                os.makedirs(path)
            self.log4py.info("获取到appium服务的日志绝对路径 %s" % path)
            return path.replace("\\", "/")
        return None
Пример #7
0
class Requester(object):

    def __init__(self):
        self.log4py = LoggingPorter()
        self.timeout = 5
        self.s = Session()

    def init_config(self, url, headers, data):
        """
        主要这个处理header的构建和接口超时或重试设置
        :return:
        """
        flag = True
        if url is None or url == "":
            raise ValueError(" url cant be empty ! ")
        if headers is None or headers == "":
            self.log4py.debug("post 请求的header为空")
        if data is None or data == "":
            self.log4py.debug("post 请求的data为空")
        return flag

    def POST_FORM(self, url, headers, form_data):
        """
        url必须入参、headers可选入参、form_data可选入参
        这个方法处理的是将表单中的数据提交数据库,就是‘x-www-form-urlencoded’的内容
        """
        if self.init_config(url, headers, form_data):
            result = self.execute_request('POST', url, req_headers=headers, req_data=form_data)
            return result
        return None

    def POST_JSON(self, url, headers, json_data):
        """
        url必须入参、headers可选入参、json可选入参(data和json看后台接口需要识别什么形式的)
        接口如果使用json传输数据 ,那就使用这个也就是‘Content-Type: Application/json’
        """
        if self.init_config(url, headers, json_data):
            post_response = self.execute_request('POST', url, req_headers=headers, req_json=json_data)
            return post_response
        return None

    def POST(self, url, headers, form_data, json_data):
        """
        如果一个接口又是json又有form,就是用这个方法,但是我没有见过,姑且写上
        """
        if json_data is None or json_data == "":
            self.log4py.debug("post 请求的json data为空")
        if self.init_config(url, headers, form_data):
            result = self.execute_request('POST', url, req_headers=headers, req_data=form_data, req_json=json_data)
            return result
        return None

    def do_get(self, url, req_headers, req_params):
        """
        url必须入参、headers可选入参、params可选入参
        """
        if url is None or url == "":
            self.log4py.debug("get请求的url为空".decode("utf-8"))
            return None
        if req_headers is None or req_headers == "":
            self.log4py.debug("get请求的header为空".decode("utf-8"))
            req_headers = None
        if req_params is None or req_params == "":
            self.log4py.debug("get请求的parameter为空".decode("utf8"))
            req_params = None
        self.execute_request(method="get", url=url, req_headers=req_headers, req_params=req_params)

    def do_put(self, url, data, file_name):
        work_path = os.getcwd()
        f = open(os.path.join(work_path, file_name))
        json_data = json.dumps(f.read())
        f.close()
        s = Session()
        req = Request('PUT', url, json=json_data, headers=self.headers)
        prepped = req.prepare()
        resp = s.send(prepped, verify=True)
        s.close()
        if resp.ok:
            return True
        return False

    def execute_request(self, method, url, **key_value):
        """
         request(method, url, params=None, data=None, headers=None, cookies=None, timeout=None, verify=None, cert=None, json=None)
        :param method:
        :param url:
        :param key_value:
        :return:
        """
        req_params = None
        req_json = None
        req_headers = None
        req_data = None
        for key in key_value:
            if "req_params" == key:
                req_params = key_value[key]
            elif "req_json" == key:
                req_json = key_value[key]
            elif "req_headers" == key:
                req_headers = key_value[key]
            elif "req_data" == key:
                req_data = key_value[key]
        self.log4py.debug("{}接口{}请求的参数:header:{}; params: {}; data: {}; json: {}".format(url, method, req_headers, req_params, req_data, req_json))
        # s = Session()
        req = Request(method, url, params=req_params, data=req_data, headers=req_headers, json=req_json)
        # prepped = req.prepare()
        prepped = self.s.prepare_request(req)  # 建议使用这种方法
        resp = self.s.send(prepped, verify=True, timeout=self.timeout)

        # self.log4py.debug("返回结果:{} - {}".format(resp.status_code, resp.text.encode("utf-8")))
        try:
            res_json = resp.json()
            return res_json
        except ValueError as ve:
            self.log4py.debug("解析json返回结果出错:{}".format(ve))
        self.s.close()
        return resp
Пример #8
0
class InitWebDriver(object):
    """
        这边是通过驱动实例化selenium webdriver,的服务启动者, 并返回webdriver
    """
    def __init__(self, properties):
        self.log4py = LoggingPorter()
        self.driver = None
        self.properties = properties
        self.waitTimeout = properties.waitTimeout
        self.scriptTimeout = properties.scriptTimeout
        self.pageLoadTimeout = properties.pageLoadTimeout

    def run_browser(self):
        """
        根据实例对象的参数,来具体启动浏览器,不管启动是否成功或启动异常,都会返回driver
        :return:
        """
        browsername = self.properties.browser
        if "chrome" == browsername:
            self.driver = self.start_chrome_driver()
        elif "ie" == browsername:
            self.driver = self.start_ie_driver()
        elif "firefox" == browsername:
            self.driver = self.start_firefox_driver()
        else:
            self.driver = self.start_firefox_driver()
        return self.driver

    def start_firefox_driver(self):
        driver = None
        try:
            # 设置浏览器的配置参数
            # fp = webdriver.FirefoxProfile()
            # fp.set_preference("browser.download.folderList", 2)
            # fp.set_preference("browser.download.manager.showWhenStarting", False)
            # fp.set_preference("browser.download.dir", os.getcwd())
            # fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream")
            # fp.add_extension("path: url, path to .xpi, or directory of addons")
            # browser = webdriver.Firefox(firefox_profile=fp)

            if self.properties.type == '0':
                # 实例化remote driver
                pass
            elif self.properties.type == '1':
                os.environ[
                    "webdriver.firefox.driver"] = self.properties.browserdriver
                log_path = os.path.join(self.properties.logsPath,
                                        "geckodriver.log")
                driver = webdriver.Firefox(
                    executable_path=self.properties.browserdriver,
                    log_path=log_path)
            driver.set_page_load_timeout(self.pageLoadTimeout)
            self.log4py.debug("set pageLoadTimeout : " + self.pageLoadTimeout)
            driver.implicitly_wait(self.waitTimeout)
            self.log4py.debug("set waitTimeout : " + self.waitTimeout)
            driver.set_script_timeout(self.scriptTimeout)
            self.log4py.error("set scriptTimeout : " + self.scriptTimeout)
            self.log4py.debug("初始化火狐浏览器成功")
            driver.maximize_window()
            self.get(driver, self.properties.baseURL, 3)
        except Exception, e:
            self.log4py.error("getFirefoxDriver()方法发生异常,异常信息:" + str(e))
            driver.quit()
            return None
        return driver