Esempio n. 1
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"))
Esempio n. 2
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
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) + " 秒!======")
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) +
                         " 秒!======")
Esempio n. 5
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))
Esempio n. 6
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
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