Exemplo n.º 1
0
 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
Exemplo n.º 2
0
 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
Exemplo n.º 3
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
Exemplo n.º 4
0
 def __init__(self, file_path):
     self.log4py = LoggingPorter()
     if not os.path.exists(file_path):
         assert IOError
     self.ini_reader = ConfigParser.ConfigParser()
     self.ini_reader.read(file_path)
     self.file_path = file_path
Exemplo n.º 5
0
class ConfigReader(object):
    def __init__(self, file_path):
        self.log4py = LoggingPorter()
        if not os.path.exists(file_path):
            assert IOError
        self.ini_reader = ConfigParser.ConfigParser()
        self.ini_reader.read(file_path)
        self.file_path = file_path

    def flush(self):
        self.ini_reader.write(open(self.file_path, 'wb'))
        self.log4py.info("已将内容写入了{}配置文件中".format(
            str(os.path.basename(self.file_path))))

    def had_section(self, section):
        return self.ini_reader.has_section(section)

    def had_option(self, section, option):
        return self.ini_reader.has_option(section, option)

    def get_sections(self):
        try:
            return self.ini_reader.sections()
        except Exception, e:
            self.log4py.error("获取ini文件的所有section时,发生错误:{}".format(
                str(e)).decode("utf-8"))
Exemplo n.º 6
0
 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()
Exemplo n.º 7
0
class InitAppiumDriver(object):
    def __init__(self, properties):
        self.log4py = LoggingPorter()
        self.run_cfg = properties
        self.android = AndroidDebugBridge()
        self.run_data = None

    def __get_desired_capabilities(self, sno):
        device_info = {"udid": sno}
        try:
            result = subprocess.Popen(
                "adb -s %s shell getprop" % sno,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE).stdout.readlines()
            for res in result:
                if re.search(r"ro\.build\.version\.release", res):
                    device_info["platformVersion"] = (
                        res.split(': ')[-1].strip())[1:-1]
                elif re.search(r"ro\.product\.model", res):
                    device_info["deviceName"] = (
                        res.split(': ')[-1].strip())[1:-1]
                if "platformVersion" in device_info.keys(
                ) and "deviceName" in device_info.keys():
                    break
        except Exception, e:
            self.log4py.error("获取手机信息时出错 :" + str(e))
            return None
        desired_caps_conf = self.run_cfg.get_desired_caps_conf()
        desired_caps = device_info.copy()
        desired_caps.update(desired_caps_conf)
        return desired_caps
Exemplo n.º 8
0
    def __init__(self):
        self.log4py = LoggingPorter()
        self.cfg = CreateConfigFile()
        self.appium_log_path = self.cfg.get_appium_logs_path()
        self.appium_port_list = []
        self.bootstrap_port_list = []
        self.device_list = []

        self.tmp = {}
 def __init__(self):
     self.driver = None
     self.className = None
     self.mcg = MobileConfigGetter()
     self.log4py = LoggingPorter()
     self.__beforeSuiteStarts = 0
     self.__beforeClassStarts = 0
     self.__beforeTestStarts = 0
     self.init = None
Exemplo n.º 10
0
 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+")
Exemplo n.º 11
0
 def __init__(self):
     self.__fileabspath = None
     self.__projectpath = None
     self.log4py = LoggingPorter()
     fc = FileInspector()
     boolean = fc.is_has_file("owl-selenium.ini")
     if boolean:
         self.__fileabspath = fc.get_file_abspath()
         self.__projectpath = fc.get_project_path()
     self.conf = ConfigReader(self.__fileabspath)
Exemplo n.º 12
0
    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"))
Exemplo n.º 13
0
 def __init__(self, clzss):
     """
     :param clzss: 获取脚本的文件名和class名
     """
     self.driver = None
     self.className = clzss.__class__.__module__ + "." + clzss.__class__.__name__
     self.seProperties = WebConfingGetter().properties
     self.log4py = LoggingPorter()
     self.__beforeSuiteStarts = 0
     self.__beforeClassStarts = 0
     self.__beforeTestStarts = 0
     self.init = None
Exemplo n.º 14
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))
Exemplo n.º 15
0
 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()
Exemplo n.º 16
0
class MobileConfigGetter(object):
    def __init__(self):
        self.__fileabspath = None
        self.__projectpath = None
        self.log4py = LoggingPorter()
        fc = FileInspector()
        boolean = fc.is_has_file("owl-appium.ini")
        if boolean: 
            self.__fileabspath = fc.get_file_abspath()
            self.__projectpath = fc.get_project_path()
        self.cf = ConfigReader(self.__fileabspath)

    @property
    def properties(self):
        """
        获取配置文件中的内容并返回对应的对象
        :return:
        """
        ap = AppiumIniDomain()
        try:
            ap.pageLoadTimeout = self.cf.get_value("TimeSet", "pageLoadTimeout")
            ap.waitTimeout = self.cf.get_value("TimeSet", "waitTimeout")
            ap.scriptTimeout = self.cf.get_value("TimeSet", "scriptTimeout")
            ap.pauseTime = self.cf.get_value("TimeSet", "pauseTime")

            ap.capturePath = os.path.join(self.__projectpath, self.cf.get_value("ResultPath", "capturePath"))
            if not os.path.exists(ap.capturePath):
                os.makedirs(ap.capturePath)
            ap.htmlreportPath = os.path.join(self.__projectpath, self.cf.get_value("ResultPath", "htmlreportPath"))
            if not os.path.exists(ap.htmlreportPath):
                os.makedirs(ap.htmlreportPath)
            ap.dumpxmlPath = os.path.join(self.__projectpath, self.cf.get_value("ResultPath", "dumpxmlPath"))
            if not os.path.exists(ap.dumpxmlPath):
                os.makedirs(ap.dumpxmlPath)
            ap.appiumlogPath = os.path.join(self.__projectpath, self.cf.get_value("ResultPath", "appiumlogPath"))
            if not os.path.exists(ap.appiumlogPath):
                os.makedirs(ap.appiumlogPath)
            ap.permissionPath = os.path.join(self.__projectpath, self.cf.get_value("ResultPath", "permissionPath"))
            if not os.path.exists(ap.permissionPath):
                os.makedirs(ap.permissionPath)
            ap.appiumService = os.path.join(self.__projectpath, self.cf.get_value("ResultPath", "appiumService"))

        except Exception, e:
            self.log4py.error("实例化appium配置文件对象时,出现异常 :" + str(e))
        return ap
Exemplo n.º 17
0
class WindowCmder(object):
    def __init__(self):
        self.log4py = LoggingPorter()

    def is_port_used(self, port_num):
        """
        检查端口是否被占用
        netstat -aon | findstr port 能够获得到内容证明端口被占用
        :param port_num: 
        :return: 
        """
        flog = True
        try:
            port_res = subprocess.Popen(
                'netstat -ano | findstr %s' % port_num,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE).stdout.readlines()
            if len(port_res) <= 0:
                self.log4py.info(str(port_num) + " port unoccupied.")
                flog = False
            else:
                self.log4py.error(str(port_num) + " port has been occupied.")
        except Exception, e:
            self.log4py.error(
                str(port_num) + " port get occupied status failure: " + str(e))
        return flog
Exemplo n.º 18
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))
Exemplo n.º 19
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)  # 覆盖保存(注意编码错误)
Exemplo n.º 20
0
class FileInspector(object):

    def __init__(self):
        self.__fileabspath = None    # 不可访问的
        self.log4py = LoggingPorter()

    def is_has_file(self, filename):
        """
        是否存在指定的文件,路径默认为当前项目的目录
        :param filename:  文件名
        :return:  True or False
        """
        propath = self.get_project_path()
        boolean = self.is_path_has_file(propath, filename)
        return boolean

    def is_path_has_file(self, path, filename):
        """指定目录下是否存在指定的文件"""
        boolean = self.check_has_file(path, filename)
        return boolean

    def check_has_file(self, path, filename):
        """   扫描指定目录下的所有文件,找到所要找的文件,return True or False"""
        # 20180626 过滤一些不必要的目录
        try:
            for filep, dirs, filelist in os.walk(path):
                if os.path.basename(filep) in set([".idea", ".git"]):
                    # self.log4py.debug("跳过这个目录的检索工作:[{}]".format(str(filep)))
                    continue
                for fl in filelist:
                    fl = fl.decode("GBK").encode("UTF-8")
                    # @TUDO 这个字符串的比较存在风险,python3不支持,待修改
                    if cmp(fl, filename) == 0:
                        self.__fileabspath = os.path.join(filep, fl)
                        self.log4py.info("当前项目下查找的[%s]配置文件存在." %filename)
                        return True
            return False
        except Exception, e:
            self.log4py.error("check_has_file()方法出现异常"+ str(e))
Exemplo n.º 21
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))
Exemplo n.º 22
0
class ServicePort(object):
    def __init__(self):
        self.log4py = LoggingPorter()
        self.cfg = CreateConfigFile()
        self.appium_log_path = self.cfg.get_appium_logs_path()
        self.appium_port_list = []
        self.bootstrap_port_list = []
        self.device_list = []

        self.tmp = {}

    def is_port_used(self, port_num):
        """
        检查端口是否被占用
        netstat -aon | findstr port 能够获得到内容证明端口被占用
        """
        flag = False
        try:
            port_res = subprocess.Popen(
                'netstat -ano | findstr %s | findstr LISTENING' % port_num,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE).stdout.readlines()
            reg = re.compile(str(port_num))
            for i in range(len(port_res)):
                ip_port = port_res[i].strip().split("   ")
                if re.search(reg, ip_port[1]):
                    flag = True
                    self.log4py.info(
                        str(port_num) + " 端口已经在使用,对应的进程是:" + str(ip_port[-1]))
                    self.tmp[port_num] = ip_port[-1]
            if not flag:
                self.log4py.info(str(port_num) + " 端口没有对应监听的服务.")
        except Exception, e:
            self.log4py.error(
                str(port_num) + " port get occupied status failure: " + str(e))
        return flag
Exemplo n.º 23
0
 def __init__(self):
     self.log4py = LoggingPorter()
     self.timeout = 5
     self.s = Session()
Exemplo n.º 24
0
class WebConfingGetter(object):
    def __init__(self):
        self.__fileabspath = None
        self.__projectpath = None
        self.log4py = LoggingPorter()
        fc = FileInspector()
        boolean = fc.is_has_file("owl-selenium.ini")
        if boolean:
            self.__fileabspath = fc.get_file_abspath()
            self.__projectpath = fc.get_project_path()
        self.conf = ConfigReader(self.__fileabspath)

    @property
    def properties(self):
        """
        获取配置文件中的内容并返回对应的对象
        :return:
        """
        wp = SeIniDomain()
        try:
            wp.pageLoadTimeout = self.conf.get_value("TimeSet",
                                                     "pageLoadTimeout")
            wp.waitTimeout = self.conf.get_value("TimeSet", "waitTimeout")
            wp.scriptTimeout = self.conf.get_value("TimeSet", "scriptTimeout")
            wp.pauseTime = self.conf.get_value("TimeSet", "pauseTime")

            wp.capturePath = os.path.join(
                self.__projectpath,
                self.conf.get_value("ResultPath", "capturePath"))
            if not os.path.exists(wp.capturePath):
                os.makedirs(wp.capturePath)
            wp.htmlreportPath = os.path.join(
                self.__projectpath,
                self.conf.get_value("ResultPath", "htmlreportPath"))
            if not os.path.exists(wp.htmlreportPath):
                os.makedirs(wp.htmlreportPath)
            wp.logsPath = os.path.join(
                self.__projectpath,
                self.conf.get_value("ResultPath", "logsPath"))
            if not os.path.exists(wp.logsPath):
                os.makedirs(wp.logsPath)
            wp.baseURL = self.conf.get_value("baseURL", "baseURL")
            wp.browser = self.conf.get_value("run", "browser")
            wp.type = self.conf.get_value("run", "type")
            wp.browserdriver = os.path.join(
                self.__projectpath, self.conf.get_value("driver", wp.browser))

            if wp.type == "0":
                d = {}
                d['url'] = self.conf.get_value('remoteProfile', 'url')
                d['browserName'] = self.conf.get_value('remoteProfile',
                                                       'browserName')
                d['version'] = self.conf.get_value('remoteProfile', 'version')
                d['maxinstance'] = self.conf.get_value('remoteProfile',
                                                       'maxinstance')
                d['platform'] = self.conf.get_value('remoteProfile',
                                                    'platform')
                wp.remoteProfile = d
        except Exception, e:
            self.log4py.error("实例化selenium配置文件对象时,出现异常 :" + str(e))
        return wp
Exemplo n.º 25
0
 def __init__(self, properties):
     self.log4py = LoggingPorter()
     self.run_cfg = properties
     self.android = AndroidDebugBridge()
     self.run_data = None
Exemplo n.º 26
0
class MobileDriverBeforeTest(object):
    def __init__(self):
        self.driver = None
        self.className = None
        self.mcg = MobileConfigGetter()
        self.log4py = LoggingPorter()
        self.__beforeSuiteStarts = 0
        self.__beforeClassStarts = 0
        self.__beforeTestStarts = 0
        self.init = None

    def get_api_driver(self, sno):
        """
        通过sno获取对应的手机的驱动及其实例化的api对象
        :param sno:
        :return:
        """
        self.init = InitAppiumDriver(self.mcg)
        self.driver = self.init.get_android_driver(sno)
        if self.driver is None:
            self.log4py.error("appium实例化driver失败,请重新检查驱动及启动参数")
            return None
        return AppiumBaseApi(self.driver, self.mcg.properties)

    def before_suite(self):
        begins = formated_time("%Y-%m-%d %H:%M:%S:%f")
        self.__beforeSuiteStarts = time.time()
        self.log4py.info("======" + begins + ":测试集开始======")

    def after_suite(self):
        ends = formated_time("%Y-%m-%d %H:%M:%S:%f")
        self.__afterSuiteStops = time.time()
        self.log4py.info("======" + ends + ":测试集结束======")
        self.log4py.info("======本次测试集运行消耗时间 " + str(self.__afterSuiteStops -
                                                    self.__beforeSuiteStarts) +
                         " 秒!======")

    def before_class(self):
        begins = formated_time("%Y-%m-%d %H:%M:%S:%f")
        self.__beforeClassStarts = time.time()
        self.log4py.info("======" + str(begins) + ":测试【" +
                         str(self.className) + "】开始======")

    def after_class(self):
        # 如果执行了case,必然已经启动了webdriver,在这里做一次关闭操作
        try:
            self.driver.quit()
        except Exception, e:
            self.log4py.error(
                "after class with stoping web driver happend error")
        ends = formated_time("%Y-%m-%d %H:%M:%S:%f")
        self.__afterClassStops = time.time()
        self.log4py.info("======" + str(ends) + ":测试【" + str(self.className) +
                         "】结束======")
        self.log4py.info("======本次测试运行消耗时间 " + str(self.__afterClassStops -
                                                   self.__beforeClassStarts) +
                         " 秒!======")
Exemplo n.º 27
0
class WebDriverDoBeforeTest(object):

    def __init__(self, clzss):
        """
        :param clzss: 获取脚本的文件名和class名
        """
        self.driver = None
        self.className = clzss.__class__.__module__ + "." + clzss.__class__.__name__
        self.seProperties = WebConfingGetter().properties
        self.log4py = LoggingPorter()
        self.__beforeSuiteStarts = 0
        self.__beforeClassStarts = 0
        self.__beforeTestStarts = 0
        self.init = None

    def get_api_driver(self):
        self.init = InitWebDriver(self.seProperties)
        try:
            resp = requests.get(self.seProperties.baseURL)

            if resp.status_code != 200:
                self.log4py.error("浏览器实例化driver失败,请检查你的被测试服务是否启动或baseURL是否设置正确: {}".format(self.seProperties.baseURL))
                return None
        except exceptions.ConnectionError as e:
            self.log4py.error("浏览器实例化driver失败,请检查你的被测试服务是否启动或baseURL是否设置正确: {}".format(self.seProperties.baseURL))
            return None
        self.driver = self.init.run_browser()
        if self.driver is None:
            self.log4py.error("浏览器实例化driver失败,请重新检查驱动及启动参数")
            return None
        return SeleniumBaseApi(self.driver, self.seProperties)
    
    def before_suite(self):
        begins = formated_time("%Y-%m-%d %H:%M:%S:%f")
        self.__beforeSuiteStarts = time.time()
        self.log4py.info("======" + begins + ":测试集开始======")

    def after_suite(self):
        ends = formated_time("%Y-%m-%d %H:%M:%S:%f")
        self.__afterSuiteStops = time.time()
        self.log4py.info("======" + ends + ":测试集结束======")
        self.log4py.info("======本次测试集运行消耗时间 " + str(self.__afterSuiteStops - self.__beforeSuiteStarts) + " 秒!======")

    def before_class(self):
        begins = formated_time("%Y-%m-%d %H:%M:%S:%f")
        self.__beforeClassStarts = time.time()
        self.log4py.info("======" + str(begins) + ":测试【" + str(self.className) + "】开始======")

    def after_class(self):
        # 如果执行了case,必然已经启动了webdriver,在这里做一次关闭操作
        try:
            self.init.stop_web_driver()
        except Exception, e:
            self.log4py.error("after class with stoping web driver happend error")
        ends = formated_time("%Y-%m-%d %H:%M:%S:%f")
        self.__afterClassStops = time.time()
        self.log4py.info("======" + str(ends) + ":测试【" + str(self.className) + "】结束======")
        self.log4py.info("======本次测试运行消耗时间 " + str(self.__afterClassStops - self.__beforeClassStarts) + " 秒!======")
Exemplo n.º 28
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
Exemplo n.º 29
0
 def __init__(self):
     self.__fileabspath = None    # 不可访问的
     self.log4py = LoggingPorter()
Exemplo n.º 30
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