Beispiel #1
0
def driver_setup():
    udid = "F2425EF2-D6B9-4636-9997-4D3CA592B0BD"
    log = Logger(udid + "_" + now).getlog()
    desired_caps = {
        "bundleId": "com.jindidata.SkyEyes",
        "platformName": "iOS",
        "platformVersion": "13.2",
        "deviceName": "iPhone XR",
        "automationName": "XCUITest",
        # # 会话结束时删除所有生成的文件
        "clearSystemFiles": True,
        "udid": udid,
        "app": "{}/app/NewSkyEyes.zip".format(BASE_DIR),
        "xcodeOrgId": "7Y32L5GA75",
        "xcodeSigningId": "J26G4D2GCV",
        # 执行完全重置
        "fullReset": False,
        # 获取权限
        "autoAcceptAlerts": True,
        # 设置键盘
        "unicodeKeyboard": True,
        "resetKeyboard": True,
        "wdaLocalPort": 8010,
        # 不与系统同步粘贴板,提高启动模拟器的性能
        "simulatorPasteboardAutomaticSync": "off",
        # 从WDA获取JSON源,并在Appium服务器上解析为XML,加快速度
        "useJSONSource": True,
    }
    warnings.simplefilter('ignore', ResourceWarning)
    driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
    log.info("设备:{},启动成功,用例集开始执行".format(udid))
    return driver, udid, log
Beispiel #2
0
 def __init__(self, driver, log=None):
     if log is None:
         self.log = Logger("预处理步骤").getlog()
     else:
         self.log = log
     self.driver = driver
     self.excel = ReadExcel().read_excel("common")
     self.operation = Operation(driver, self.log)
     self.by = MobileBy()
Beispiel #3
0
 def __init__(self, log=None):
     db_config = {
         "host": "10.2.22.232",
         # "host": "localhost",
         "port": 3306,
         "database": "android_appium",
         "user": "******",
         "password": "******",
         # "password": "******",
         "charset": "utf8",
     }
     self.db = pymysql.connect(**db_config)
     if log is None:
         self.log = Logger("账号管理处").getlog()
     else:
         self.log = log
import re
from appium.webdriver import webdriver
from appium.webdriver.common.mobileby import MobileBy
from providers.common.base_client import BaseClick
from providers.common.base_operation import Operation
from providers.common.read_data import ReadExcel
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
import warnings
import unittest
from providers.common.logger import Logger, error_format
import time

log = Logger("查公司01").getlog()


class TestSearchCompany1(BaseClick):

    a = ReadExcel()
    ELEMENT = a.read_excel("Search_company")

    def searh_keyword(self, keyword):
        '''首页进入搜索中间页搜索关键词'''
        self.operation.new_element(MobileBy.IOS_CLASS_CHAIN,
                                   self.ELEMENT['company_search_box']).click()
        self.operation.new_element(
            MobileBy.IOS_PREDICATE,
            self.ELEMENT['middle_search_box']).send_keys(keyword)

    def go_back(self):
        """返回上一页"""
Beispiel #5
0
 def __init__(self, driver, log=None):
     self.driver = driver
     if log is None:
         self.log = Logger("基础操作").getlog()
     else:
         self.log = log
Beispiel #6
0
class Operation():
    def __init__(self, driver, log=None):
        self.driver = driver
        if log is None:
            self.log = Logger("基础操作").getlog()
        else:
            self.log = log

    def _re_count(self, count_text):
        """
        正则匹配文本中的数字
        @param count_text:
        @return:
        """
        try:
            match = re.search(r"([0-9]\d*)", count_text).group()
            return int(match)
        except AttributeError as ae:
            self.log.info("没有匹配到数字")
            raise ae
        except Exception as e:
            self.log.error(error_format(e))
            raise e

    def mobile_swipe(self, direction):
        """
        在指定的屏幕上的控件或App的控件上执行“滑动”操作,一般是针对整个屏幕。这个方法不支持通过坐标来操作,
        并且仅仅是简单的模拟单个手指滑动。这个方法对于诸如相册分页、切换视图等情况可能会发挥比较大的作用
        @param direction: left, right, up, down
        @return:
        """
        self.driver.execute_script('mobile: swipe', {'direction': direction})

    def mobile_scroll(self, direction):
        """
        滑动整屏
        @param direction: ‘up’, ‘down’, ‘left’ or ‘right’. 该参数与swipe中的比,差别在于scroll会尝试将当前界面完全移动到下一页
        @return:
        mobile:scroll;该方法在实际使用调用时,会滚动2次。执行时间很长
        """
        self.driver.execute_script('mobile:scroll', {"direction": direction})

    def mobile_pinch(self, element, scale, velocity=1.1):
        """
        在给定的控件或应用程序控件上执行捏合手势
        @param element: 需要捏合的控件ID。如果没有提供该参数的话,则会使用App的控件作为替代
        @param scale: 浮动型夹点尺度。使用0和1之间的比例来“捏紧”或缩小,大于1的比例“撑开”或放大
        @param velocity: 每秒缩放速度(浮点值)
        @return:
        """
        self.driver.execute_script('mobile:pinch', {
            'element': element,
            'scale': scale,
            'velocity': velocity
        })

    def mobile_tap(self, element=None, x=0, y=0):
        """
        在指定控件或屏幕上的坐标执行点击手势
        @param element:  如果设置了element参数,则x、y代表的是以当前element为边界的xy轴。若未设置,则x,y代表的是以手机屏幕为边界
        @param x:
        @param y:
        @return:
        """
        time.sleep(1)
        if element is None:
            self.driver.execute_script('mobile:tap', {"x": x, "y": y})
        else:
            self.driver.execute_script('mobile:tap', {
                "element": element,
                "x": x,
                "y": y
            })

    def mobile_double_tap(self, element=None, x=0, y=0):
        """
        在指定控件上或屏幕上执行双击手势
        @param element:  需要双击的控件ID
        @param x: 屏幕x轴坐标点,浮点型. 仅当element未设置时才是强制参数
        @param y: 屏幕y轴坐标点,浮点型. 仅当element未设置时才是强制参数
        @return:
        """
        if element is None:
            self.driver.execute_script("mobile:doubleTap", {"x": x, "y": y})
        else:
            self.driver.execute_script("mobile:doubleTap", {
                "element": element,
                "x": x,
                "y": y
            })

    def mobile_touch_hole(self, element=None, duration=2.0, x=0, y=0):
        """
        在指定控件上或屏幕上长按的手势操作
        @param element: 需要长按的控件ID
        @param duration: 长按的持续时间(秒),浮点型
        @param x: 屏幕x轴坐标点,浮点型. 仅当element未设置时才是强制参数
        @param y: 屏幕y轴坐标点,浮点型. 仅当element未设置时才是强制参数
        @return:
        """
        if element is None:
            self.driver.execute_script("mobile:touchAndHole", {
                "x": x,
                "y": y,
                "duration": duration
            })
        else:
            self.driver.execute_script("mobile:touchAndHole", {
                "element": element,
                "duration": duration
            })

    def mobile_two_finger_tap(self, element):
        """
        在给定元素或应用程序元素上执行两个手指点击手势
        @param element:
        @return:
        """
        self.driver.execute_script("mobile:twoFingerTap", {"element": element})

    def mobile_drag_to_duration(
        self,
        fromX,
        fromY,
        toX,
        toY,
        duration=0.5,
        element=None,
    ):
        """
        通过坐标点执行拖放手势。可以在控件上执行,也可以在屏幕上执行
        @param duration: 开始拖动点之前的点击手势需要多长时间才能开始拖动
        @param element: 控件ID,可以指定为None,为None时以整个手机屏幕为边界, 如果滑动中起点坐标在控件上,会触发点击操作
        @param fromX: 起点X坐标
        @param fromY: 起点Y坐标
        @param toX: 终点X坐标
        @param toY: 终点Y坐标
        @return:
        """
        width, height = self.get_size()
        self.log.info("起点X、Y坐标:({},{})、终点X、Y坐标:({},{})".format(
            width * fromX, height * fromY, height * toX, width * toY))
        self.driver.execute_script(
            "mobile:dragFromToForDuration", {
                "duration": duration,
                "element": element,
                "fromX": width * fromX,
                "fromY": height * fromY,
                "toX": width * toX,
                "toY": height * toY
            })

    def mobile_alert(self, action, button_label):
        """
        对弹窗执行操作
        @param action: accept, dismiss, getButtons
        @param button_label:
        @return:
        """
        self.driver.execute_script("mobile:alert", {
            "action": action,
            "buttonLabel": button_label
        })

    def is_element(self, find_type, find_element, outtime=5):
        """
        判断元素是否存在
        @param loc:
        @param outtime:
        @return:
        """
        element = self.new_element(find_type, find_element, outtime=outtime)
        if element:
            return True
        else:
            return False

    def new_element(self, find_type, find_element, outtime=10):
        """
        查找元素
        @param loc:
        @param outtime:
        @return:
        """
        try:
            element = WebDriverWait(
                self.driver, outtime,
                0.01).until(lambda driver: driver.find_element(
                    by=find_type, value=find_element))
            return element
        except Exception as e:
            self.log.error("页面中找不到元素:({}:{})".format(find_type, find_element))
            return None

    def new_elements(self, find_type, find_element, outtime=10):
        """
        查找一组元素
        @param loc:
        @param outtime:
        @return:
        """
        try:
            elements = WebDriverWait(
                self.driver, outtime,
                0.01).until(lambda driver: driver.find_elements(
                    by=find_type, value=find_element))
            return elements
        except Exception as e:
            self.log.error("页面中找不到元素:({}:{})".format(find_type, find_element))
            return None

    def repeatedly_element(self,
                           find_type,
                           find_element,
                           re_element,
                           outtime=10):
        """
        当有A/B时,class_chain链式查找方法
        @param find_type:
        @param find_element:
        @param re_element:
        @param outtime:
        @return:
        """
        ele = self.new_element(find_type, find_element, outtime)
        if ele:
            return ele
        self.log.info("使用第二元素查找")
        re_ele = self.new_element(find_type, re_element, outtime)
        if re_ele:
            return re_ele
        return None

    def repeatedly_elements(self,
                            find_type,
                            find_element,
                            re_element,
                            outtime=10):
        """
        当有A/B时,class_chain链式查找方法
        @param find_type:
        @param find_element:
        @param re_element:
        @param outtime:
        @return:
        """
        ele = self.new_elements(find_type, find_element, outtime)
        if ele:
            return ele
        self.log.info("使用第二元素查找")
        re_ele = self.new_elements(find_type, re_element, outtime)
        if re_ele:
            return re_ele
        return None

    def get_size(self):
        """
        获取屏幕尺寸
        @return:
        """
        size = self.driver.get_window_size()
        width = size['width']
        height = size['height']
        return width, height

    def get_count(self, **kwargs):
        """
        正则匹配文本中的数字,适用于 查找count数
        @param kwargs:
                elements:一个element对象集合,用于批量匹配
                单个匹配必传参数 find_type、find_element
        @return:
        """
        try:
            if kwargs.get('elements'):
                result = list()
                for element in kwargs['elements']:
                    count_num = self._re_count(element)
                    result.append(count_num)
                return result
            else:
                if kwargs.get('find_type') and kwargs.get('find_element'):
                    count_text = self.new_element(kwargs['find_type'],
                                                  kwargs['find_element']).text
                    return self._re_count(count_text)
        except Exception as e:
            self.log.error(error_format(e))
            raise e

    def send(self, find_type, find_element, content):
        """
        输入内容并搜索
        @param find_type:   查找方式
        @param find_element:    查找元素
        @param content: 输入内容
        @return:
        """
        self.new_element(find_type=find_type,
                         find_element=find_element).send_keys(content + "\n")
Beispiel #7
0
class Account:
    def __init__(self, log=None):
        db_config = {
            "host": "10.2.22.232",
            # "host": "localhost",
            "port": 3306,
            "database": "android_appium",
            "user": "******",
            "password": "******",
            # "password": "******",
            "charset": "utf8",
        }
        self.db = pymysql.connect(**db_config)
        if log is None:
            self.log = Logger("账号管理处").getlog()
        else:
            self.log = log

    # 判断表是否存在
    def _table_exists(self, table):
        sql = "show tables"
        with self.db.cursor() as cursor:
            cursor.execute(sql)
        tables = cursor.fetchall()
        tables_list = re.findall("('.*?')", str(tables))
        tables_list = [re.sub("'", "", each) for each in tables_list]
        if table in tables_list:
            self.log.info("table exists")
            return True
        else:
            try:
                sql = "CREATE TABLE IF NOT EXISTS {} (id BIGINT(10) NOT NULL AUTO_INCREMENT, phone VARCHAR(11) NOT NULL COMMENT '手机号', status VARCHAR(1) NOT NULL COMMENT '使用状态', vip VARCHAR(1) COMMENT '是否vip', special VARCHAR(1) COMMENT '是否特殊账号', create_time DATETIME COMMENT '创建时间', update_time DATETIME COMMENT '更新时间', user VARCHAR(120) COMMENT '使用人', PRIMARY KEY(id))".format(
                    table
                )
                with self.db.cursor() as cursor:
                    cursor.execute(sql)
                self.db.commit()
                self.log.info("Successfully added table")
                return False
            except Exception as e:
                self.db.rollback()
                self.log.error(error_format(e))

    def _make_account(self):
        """
        制造account
        @return:
        """
        try:
            # self._table_exists("account")
            base = 11099995001
            vip_base = 11099990101
            with self.db.cursor() as cursor:
                for i in range(0, 100):
                    dt = datetime.datetime.now()
                    dt_now = dt.strftime("%Y-%m-%d %H:%M:%S")
                    # 是否是特殊账号
                    if str(base + i) in exclude_account:
                        account_sql = "insert into account (phone, status, create_time, vip, special) values ('{}','{}','{}', '{}', '{}')".format(
                            str(base + i), "0", dt_now, "0", "1"
                        )
                    else:
                        account_sql = "insert into account (phone, status, create_time, vip, special) values ('{}','{}','{}', '{}', '{}')".format(
                            str(base + i), "0", dt_now, "0", "0"
                        )
                    # VIP 是否是特殊账号
                    if str(vip_base + i) in exclude_account:
                        account_sql_vip = "insert into account (phone, status, create_time, vip, special) values ('{}','{}','{}', '{}', '{}')".format(
                            str(vip_base + i), "0", dt_now, "1", "1"
                        )
                    else:
                        account_sql_vip = "insert into account (phone, status, create_time, vip, special) values ('{}','{}','{}', '{}', '{}')".format(
                            str(vip_base + i), "0", dt_now, "1", "0"
                        )
                    cursor.execute(account_sql)
                    cursor.execute(account_sql_vip)
            self.db.commit()
            self.log.info("账号批量生成成功")
        except Exception as e:
            self.log.error(error_format(e))
            self.db.rollback()

    def init_account(self):
        """
        初始化账号
        @return:
        """
        try:
            # 判断表是否存在
            if self._table_exists("account"):
                # 存在则将账号状态重置
                with self.db.cursor() as cursor:
                    dt = datetime.datetime.now()
                    dt_now = dt.strftime("%Y-%m-%d %H:%M:%S")
                    update_sql = "UPDATE account SET status = '0', update_time = '{}'".format(
                        dt_now
                    )
                    cursor.execute(update_sql)
                self.db.commit()
                self.log.info("账号状态批量重置")
            else:
                # 不存在 则新建表,并添加账号
                self._make_account()
        except Exception as e:
            self.log.error(error_format(e))
            self.db.rollback()

    def _operation_account(self, vip_type, account_special):
        """
        处理具体获取账号流程
        @param vip_type: 0:非VIP、1:VIP
        @return:
        """
        account_sql = "SELECT * FROM account WHERE status='0' and vip='{}' and special='{}'".format(
            vip_type, account_special
        )
        with self.db.cursor() as cursor:
            cursor.execute(account_sql)
        fetchall = cursor.fetchall()
        fetchall_count = len(fetchall)
        if fetchall_count == 0:
            self.log.info("没有可用的账号")
            return None
        random_num = random.randint(0, fetchall_count - 1)
        account = fetchall[random_num][1]
        self._update_account_status(account, "1", vip_type, account_special)
        if vip_type == "0":
            self.log.info("获取普通账号:{},并更新使用状态".format(account))
        elif vip_type == "1":
            self.log.info("获取VIP账号:{},并更新使用状态".format(account))
        return account

    def _update_account_status(self, account, status, vip_type, account_special):
        """
        更新account状态
        @param account: 账号
        @param status: 使用状态
        @param vip_type: 账号类型
        @return:
        """
        try:
            user = getpass.getuser()
            with self.db.cursor() as cursor:
                dt = datetime.datetime.now()
                dt_now = dt.strftime("%Y-%m-%d %H:%M:%S")
                update_sql = "UPDATE account SET status = '{}', update_time = '{}', user = '******' WHERE phone='{}' and vip='{}' and special='{}'".format(
                    status, dt_now, user_dict.setdefault(user.lower(), user), account, vip_type, account_special
                )
                cursor.execute(update_sql)
            self.db.commit()
        except Exception as e:
            self.log.error(error_format(e))
            self.db.rollback()

    def get_account(self, account_type="account", account_special="0"):
        """
        根据类型获取账号,默认为非VIP账户
        @param account_type: 账号类型
        @param account_special: 是否特殊账号 0:不是、1:是
        @return:
        """
        global account_dict, account_vip_dict
        with lock:
            if account_type.lower() == "account":
                vip_type = "0"
            elif account_type.lower() == "vip":
                vip_type = "1"
            else:
                self.log.error("无效的账户类型")
            account = self._operation_account(vip_type, account_special)
            return account

    def release_account(self, account, account_type="account", account_special="0"):
        """
        归还使用的账号
        @param account: 账号
        @param account_type: 账号类型
        @param account_special: 是否特殊账号 0:不是、1:是
        @return:
        """
        global account_dict, account_vip_dict
        with lock:
            if account_type == "account":
                vip_type = "0"
            elif account_type.lower() == "vip":
                vip_type = "1"
            else:
                self.log.error("无效的账户类型")
            self._update_account_status(account, "0", vip_type, account_special)
        self.log.info("账号:{} 已归还".format(account))

    def get_pwd(self):
        """
        默认密码
        @return:
        """
        return "ef08beca"
Beispiel #8
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/2/7
# @Author  : Soner
# @version : 1.0.0

import os
from random import randint
from providers.common.logger import Logger

log = Logger("case_files").getlog()


class CaseFilses:
    def __init__(self, file_name="test_", ex_name=".py"):
        """
        模糊查找文件
        :param now_dir:
        :param test_dir:
        :param file_name: 文件名匹配搜索的关键字
        :param ex_name: 文件的扩展名
        :return:
        """
        self.jenkins_param = os.environ["run_cases"]
        self.now_dir = os.path.dirname(
            os.path.dirname(os.path.abspath(__file__)))
        test_dir = self.now_dir + "/testcase/"

        log.info("case文件路径:{}".format(test_dir))

        # 获取指定路径下的所有文件
# -*- coding: utf-8 -*-
# @Time    : 2020-05-26 15:37
# @Author  : XU
# @File    : test_relation_sift_01.py
# @Software: PyCharm
import time
import unittest
from appium.webdriver.common.mobileby import MobileBy
from providers.common.logger import Logger, error_format
from providers.common.base_client import BaseClick
from providers.sift.operation import SiftOperation
from providers.sift.process import SiftProcess

log = Logger("查关系-筛选01").getlog()


class TestRelationSift01(BaseClick):

    vip_num = None

    def setUp(self):
        self.sift_operate = SiftOperation(self.driver)
        self.elements = self.sift_operate.get_element()
        self.sift_process = SiftProcess(self.driver)

    def test_relation_sift_001(self):
        """查关系:更多筛选,搜索范围"""
        log.info(self.test_relation_sift_001.__doc__)
        try:
            self.vip_num = self.account.get_account(account_type='vip')
            vip_passwd = self.account.get_pwd()
import re
from appium.webdriver import webdriver
from appium.webdriver.common.mobileby import MobileBy
from providers.common.base_client import BaseClick
from providers.common.base_operation import Operation, getimage
from providers.common.read_data import ReadExcel
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
import warnings
import unittest
from providers.common.logger import Logger, error_format
import time

log = Logger("查公司02").getlog()


class TestSearchCompany1(BaseClick):

    a = ReadExcel()
    ELEMENT = a.read_excel("Search_company")

    def searh_keyword(self, keyword):
        '''搜索中间页搜索关键词'''
        self.operation.new_element(
            MobileBy.IOS_PREDICATE,
            self.ELEMENT['middle_search_box']).send_keys(keyword)

    def send_keyword(self, keyword):
        '''搜索中间页搜索关键词(有搜索记录)'''
        self.operation.send(MobileBy.IOS_PREDICATE,
                            self.ELEMENT['middle_search_box'], keyword)
Beispiel #11
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/2/18
# @Author  : Soner
# @version : 1.0.0

import os
import json
import random
from providers.device.phone_info import PhoneInfo
from providers.common.logger import Logger

log = Logger("device_info").getlog()

driver_dict = {}


class MachinePool():
    #  获取项目根目录
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    file = BASE_DIR + '/config/driver_list.json'
    config_file = BASE_DIR + '/config/'
    phone = PhoneInfo()

    def init(self):
        global driver_dict

        data = {}
        # self.driver_dict = {}
        # 判断文件是否存在
        if not os.path.isfile(self.file):
Beispiel #12
0
class Preprocessing():
    def __init__(self, driver, log=None):
        if log is None:
            self.log = Logger("预处理步骤").getlog()
        else:
            self.log = log
        self.driver = driver
        self.excel = ReadExcel().read_excel("common")
        self.operation = Operation(driver, self.log)
        self.by = MobileBy()

    def skip_guide(self, number=4):
        """
        跳过引导页
        @param number:
        @return:
        """
        try:
            for i in range(number):
                self.operation.mobile_swipe('left')
            self.log.info("跳过首页引导")
        except Exception as e:
            self.log.error(error_format(e))
            raise e

    def agree_license(self):
        """
        点击用户协议
        @return:
        """
        try:
            element = self.operation.is_element(self.by.IOS_PREDICATE,
                                                self.excel['agree_license'])
            if element:
                self.operation.new_element(
                    self.by.IOS_PREDICATE,
                    self.excel['agree_license']).click()
                self.log.info("点击同意用户协议")
        except Exception as e:
            self.log.error('点击同意用户协议失败!!!')
            self.log.error(error_format(e))
            raise e

    def cancel_update(self):
        """
        跳过 升级弹窗
        @return:
        """
        try:
            element = self.operation.is_element(self.by.IOS_PREDICATE,
                                                self.excel['update_title'],
                                                outtime=10)
            if element:
                self.operation.new_element(self.by.IOS_PREDICATE,
                                           self.excel['close_update']).click()
                self.log.info("跳过升级弹窗")
        except Exception as e:
            self.log.error(error_format(e))
            raise e

    def skip_monitor(self):
        """
        跳过监控日报
        @return:
        """
        try:
            element = self.operation.is_element(self.by.IOS_PREDICATE,
                                                self.excel['monitor_title'])
            if element:
                self.operation.new_element(
                    self.by.IOS_PREDICATE,
                    self.excel['close_monitor']).click()
                self.log.info("跳过监控日报")
        except Exception as e:
            self.log.error(error_format(e))
            raise e

    def skip_monitor_daily_email(self, select=False, email=None):
        """
        监控日报相关操作
        @param select:
        @param email:
        @return:
        """
        if self.operation.new_element(
                MobileBy.IOS_CLASS_CHAIN,
                "XCUIElementTypeWindow[1]/XCUIElementTypeOther[2]/XCUIElementTypeOther[1]/XCUIElementTypeStaticText[1]"
        ):
            if select:
                if email:
                    self.operation.new_element(
                        MobileBy.IOS_CLASS_CHAIN,
                        "XCUIElementTypeWindow[1]/XCUIElementTypeOther[2]/XCUIElementTypeOther[1]/XCUIElementTypeOther[1]/XCUIElementTypeTextField[1]"
                    ).click()
                    self.operation.new_element(
                        MobileBy.IOS_CLASS_CHAIN,
                        "XCUIElementTypeWindow[1]/XCUIElementTypeOther[2]/XCUIElementTypeOther[1]/XCUIElementTypeOther[1]/XCUIElementTypeTextField[1]"
                    ).send_keys(email)
                self.operation.new_element(MobileBy.ACCESSIBILITY_ID,
                                           "保存").click()
            else:
                self.operation.new_element(MobileBy.ACCESSIBILITY_ID,
                                           "跳过").click()

    def back_index(self):
        """
        回到首页
        @return:
        """
        back_count = 0
        while back_count < 10:
            back_count += 1
            flag = self.operation.is_element(MobileBy.IOS_CLASS_CHAIN,
                                             self.excel['index'].format(1),
                                             outtime=1)
            if flag:
                self.log.info("已返回到首页")
                break
            else:
                self.log.info("未返回到首页,点击「返回」按钮")
                self.backtrack()

    def backtrack(self):
        """
        返回
        @return:
        """
        elements = self.operation.new_elements(MobileBy.IOS_CLASS_CHAIN,
                                               self.excel['button'])
        for element in elements:
            if element.get_attribute(
                    "visible") == "true" and element.get_attribute('name') in [
                        'nav back new', 'App Back'
                    ]:
                element.click()
                break

    def hide_keyboard(self):
        """
        隐藏键盘 + 搜索 按钮功能
        @return:
        """
        self.operation.new_element(MobileBy.IOS_CLASS_CHAIN,
                                   self.excel['search_bar']).send_keys("\n")

    def clear_text(self):
        """
        一键清除 按钮
        @return:
        """
        self.operation.new_element(MobileBy.ACCESSIBILITY_ID, "清除文本").click()

    def clear_history(self, select=True):
        """
        历史 「清空」按钮
        @return:
        """
        self.operation.new_element(MobileBy.ACCESSIBILITY_ID, "清空").click()
        if select:
            self.operation.new_element(MobileBy.ACCESSIBILITY_ID, "确定").click()
        else:
            self.operation.new_element(MobileBy.ACCESSIBILITY_ID, "取消").click()

    def get_permission(self):
        """
        获取 所有权限
        @return:
        """
        permission = self.operation.new_element(MobileBy.IOS_PREDICATE,
                                                self.excel['permission'],
                                                outtime=2)
        if permission is not None:
            permission.click()
            self.log.info("获取权限")

    def is_login(self):
        """
        判断 登陆状态
        @return:
        """
        # 回到首页
        self.back_index()
        # 进入 我的
        self.operation.new_element(MobileBy.IOS_CLASS_CHAIN,
                                   self.excel['index'].format(5)).click()
        # 是否有 登陆 按钮
        login_status = self.operation.is_element(MobileBy.ACCESSIBILITY_ID,
                                                 "立即登录",
                                                 outtime=3)
        if login_status:
            self.log.info("未登录账号")
            result = not login_status
        else:
            self.log.info("已登录账号")
            result = not login_status
        return result

    def login(self, phone_num, password):
        """"
        登录公用方法
         @return:
        """
        try:
            flag = self.operation.is_element(MobileBy.IOS_PREDICATE,
                                             "name == '密码登录'")
            if flag:
                self.operation.new_element(MobileBy.IOS_PREDICATE,
                                           "name == '密码登录'").click()
                phone = self.operation.is_element(MobileBy.IOS_PREDICATE,
                                                  "value == '输入手机号'")
                if phone:
                    self.operation.new_element(MobileBy.IOS_PREDICATE,
                                               "value == '输入手机号'").click()
                else:
                    self.operation.new_element(
                        MobileBy.IOS_CLASS_CHAIN,
                        self.excel['login_phone']).click()
                    self.operation.new_element(MobileBy.IOS_PREDICATE,
                                               "name == '清除文本'").click()
                self.operation.new_element(
                    MobileBy.IOS_PREDICATE,
                    "value == '输入手机号'").send_keys(phone_num)
                self.operation.new_element(MobileBy.IOS_PREDICATE,
                                           "value == '输入密码'").click()
                self.operation.new_element(
                    MobileBy.IOS_PREDICATE,
                    "value == '输入密码'").send_keys(password)
                self.hide_keyboard()
                self.operation.new_element(
                    MobileBy.IOS_CLASS_CHAIN,
                    self.excel['agreement_button']).click()
                self.operation.new_element(MobileBy.IOS_PREDICATE,
                                           "name == '登录'").click()
                element = self.operation.is_element(
                    self.by.IOS_PREDICATE, self.excel['monitor_title'])
                if element:
                    self.operation.new_element(
                        self.by.IOS_PREDICATE,
                        self.excel['close_monitor']).click()
                    self.log.info("跳过监控日报")
            else:
                self.back_index()
                self.operation.new_element(MobileBy.IOS_CLASS_CHAIN,
                                           self.excel['mytab_button']).click()
                self.operation.mobile_swipe('down')
                self.operation.new_element(MobileBy.IOS_PREDICATE,
                                           "name == '立即登录'").click()
                self.operation.new_element(MobileBy.IOS_PREDICATE,
                                           "name == '密码登录'").click()
                phone = self.operation.is_element(MobileBy.IOS_PREDICATE,
                                                  "value == '输入手机号'")
                if phone:
                    self.operation.new_element(MobileBy.IOS_PREDICATE,
                                               "value == '输入手机号'").click()
                else:
                    self.operation.new_element(
                        MobileBy.IOS_CLASS_CHAIN,
                        self.excel['login_phone']).click()
                    self.operation.new_element(MobileBy.IOS_PREDICATE,
                                               "name == '清除文本'").click()
                self.operation.new_element(
                    MobileBy.IOS_PREDICATE,
                    "value == '输入手机号'").send_keys(phone_num)
                self.operation.new_element(MobileBy.IOS_PREDICATE,
                                           "value == '输入密码'").click()
                self.operation.new_element(
                    MobileBy.IOS_PREDICATE,
                    "value == '输入密码'").send_keys(password)
                self.hide_keyboard()
                self.operation.new_element(
                    MobileBy.IOS_CLASS_CHAIN,
                    self.excel['agreement_button']).click()
                self.operation.new_element(MobileBy.IOS_PREDICATE,
                                           "name == '登录'").click()

                element = self.operation.is_element(
                    self.by.IOS_PREDICATE, self.excel['monitor_title'])
                if element:
                    self.operation.new_element(
                        self.by.IOS_PREDICATE,
                        self.excel['close_monitor']).click()
                    self.log.info("跳过监控日报")
                login_status = self.operation.is_element(
                    MobileBy.IOS_PREDICATE, "name == '立即登录'")
                if login_status is not True:
                    self.operation.new_element(
                        MobileBy.IOS_CLASS_CHAIN,
                        self.excel['index'].format(1)).click()
                    self.log.info("登录成功,并回到首页")
        except Exception as e:
            self.log.error(error_format(e))
            raise e

    def logout(self):
        """
        退出登录
        @return:
        """
        flag = self.operation.is_element(MobileBy.IOS_CLASS_CHAIN,
                                         self.excel['index'].format(1))
        if flag is not True:
            self.back_index()
        self.operation.new_element(MobileBy.IOS_CLASS_CHAIN,
                                   self.excel['index'].format(5)).click()
        login_status = self.operation.is_element(MobileBy.IOS_PREDICATE,
                                                 "name == '立即登录'")
        if login_status:
            self.log.info("已经是未登录状态")
        else:
            swip_up_count = 0
            while swip_up_count < 4:
                swip_up_count += 1
                elment = self.operation.is_element(MobileBy.IOS_PREDICATE,
                                                   "name == '设置'")
                if elment:
                    self.log.info("找到设置按钮")
                    self.operation.new_element(MobileBy.IOS_CLASS_CHAIN,
                                               self.excel['set_icon']).click()
                    break
                else:
                    self.log.info("未找到设置按钮,继续向上滑")
                    self.operation.mobile_swipe('up')
            self.operation.new_element(MobileBy.IOS_PREDICATE,
                                       "name == '退出'").click()
            self.operation.new_element(MobileBy.IOS_PREDICATE,
                                       "name == '确定'").click()
            swip_down_count = 0
            while swip_down_count < 4:
                swip_down_count += 1
                log_stu = self.operation.is_element(MobileBy.IOS_PREDICATE,
                                                    "name == '立即登录'")
                if log_stu:
                    self.operation.new_element(
                        MobileBy.IOS_CLASS_CHAIN,
                        self.excel['index'].format(1)).click()
                    self.log.info("已退出登录并回到首页")
                    break
                else:
                    self.log.info("未找到立即登录按钮,继续向上滑")
                    self.operation.mobile_swipe('down')

    def enter_monitor_list(self):
        """
        进入到 我的->监控列表
        @return:
        """
        # 返回到「首页」
        try:
            self.back_index()
            # 点击「我的」
            self.operation.new_element(MobileBy.IOS_CLASS_CHAIN,
                                       self.excel['index'].format(5)).click()
            # 点击「我的监控」
            self.operation.new_element(MobileBy.ACCESSIBILITY_ID,
                                       '我的监控').click()
            # 点击「监控列表」
            self.operation.new_element(MobileBy.ACCESSIBILITY_ID,
                                       '监控列表').click()
        except Exception as e:
            self.log.error(error_format(e))

    def random_options(self,
                       find_type,
                       find_element,
                       num=None,
                       x=0.03,
                       fromy=0.6,
                       toy=0.5):
        """
        随机查找一个选项
        @param find_type:  查找方法
        @param find_element:  查找元素
        @param num: 指定第几个筛选项,默认为None,随机选择
        @param x: 滑动 x 起始/结束坐标
        @param fromy: 滑动 y 起始坐标
        @param toy:  滑动 y 结束坐标
        @return: 会返回选择项的文本名字
        """
        groups = self.operation.new_elements(find_type=find_type,
                                             find_element=find_element)
        groups_len = len(groups)
        if not num is None:
            random_num = num - 1
        else:
            random_num = random.randint(0, groups_len - 1)
        self.log.info("随机项下标:{}".format(random_num))
        random_name = groups[random_num].text
        self.log.info("共有 {} 选项,选择第 {} 个:{}".format(groups_len, random_num + 1,
                                                    random_name))
        loop_num = 5
        while loop_num > 0:
            if loop_num == 5:
                find_groups = groups
            else:
                find_groups = self.operation.new_elements(
                    find_type=find_type, find_element=find_element)
            self.log.info("选项是否可见:{}".format(
                find_groups[random_num].get_attribute("visible")))

            if find_groups[random_num].get_attribute("visible") == "true":
                if find_groups[random_num].text == random_name:
                    find_groups[random_num].click()
                    return random_name
                else:
                    raise NoSuchElementException("随机的选项:{},实际要点击的选项:{}".format(
                        random_name, find_groups[random_num].text))
            self.operation.mobile_drag_to_duration(fromX=x,
                                                   fromY=fromy,
                                                   toX=x,
                                                   toY=toy)
            loop_num -= 1
        else:
            raise NoSuchElementException("随机项:{} 未找到".format(random_name))
# -*- coding: utf-8 -*-
# @Time    : 2020-04-21 14:02
# @Author  : XU
# @File    : test_search_relation_01.py
# @Software: PyCharm
import time
import unittest
from appium.webdriver.common.mobileby import MobileBy
from providers.common.logger import Logger, error_format
from providers.common.base_client import BaseClick
from providers.relation.operating import RelationOperate
from providers.relation.process import RelationProcess

log = Logger("查关系01").getlog()


class TestSearchRelation01(BaseClick):

    def setUp(self):
        self.relation_operate = RelationOperate(self.driver)
        self.elements = self.relation_operate.get_element()
        self.relation_process = RelationProcess(self.driver)

    def test_001_cgx_ss_p0(self):
        """点击热搜关系"""
        log.info(self.test_001_cgx_ss_p0.__doc__)
        try:
            relation_point_tag = self.relation_operate.hot_relation()
            home_page_tag = self.relation_process.relation_demo()
            self.assertTrue(relation_point_tag, "查关系:样例关系节点,展示失败")
            self.assertTrue(home_page_tag, "查关系:点击右上角天眼查logo,返回首页失败")
Beispiel #14
0
from threading import Thread, Lock
from random import randint
import unittest
import HTMLTestRunner_PY3
import time
import datetime
import os
from providers.file.get_files import CaseFilses
from providers.device.device_info import MachinePool
from providers.create_sum import create_summary
from providers.common.logger import Logger
from providers.account.account import Account
from providers.send.send_email import sendmail
from providers.send.send_ding_message import send_message

log = Logger("main_program").getlog()
# 获取当前路径
now_dir = os.path.dirname(os.path.abspath(__file__))
# case路径
test_dir = now_dir + "/testcase"
# 报告路径
test_report = now_dir + "/report/HTML"
now = time.strftime("%Y-%m-%d-%H%M%S")
jenkins_path = "/opt/tomcat8/webapps/log/app_auto_result"


def kill_adb():
    os.popen("killall adb")
    os.popen("killall node")
    os.system("adb start-server")