Ejemplo n.º 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
Ejemplo n.º 2
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
Ejemplo n.º 3
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"))
Ejemplo n.º 4
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 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) +
                         " 秒!======")
Ejemplo n.º 6
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))
Ejemplo n.º 7
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) + " 秒!======")
Ejemplo n.º 8
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
Ejemplo n.º 9
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))
Ejemplo n.º 10
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))
Ejemplo n.º 11
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))
Ejemplo n.º 12
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
Ejemplo n.º 13
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
Ejemplo n.º 14
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