Exemplo n.º 1
0
class mongoTool:
    log = Logging.Logs()
    # gm = GlobalMap()
    log = Logs()

    def __init__(self, host):
        self.log.debug("开始连接数据库: {}".format(host, ))
        self.client = pymongo.MongoClient(host)  #连接数据库
        # self.client = pymongo.MongoClient(self.gm.get_value("mongohost"))		#连接数据库
        self.log.debug("数据库连接成功")

    #
    # def __del__(self):
    # 	self.log.debug("close Client")
    # 	self.client.close()		#关闭数据库

    # 迭代判断是否最后一个值
    def lookahead(iterable):
        """Pass through all values from the given iterable, augmented by the
        information if there are more values to come after the current one
        (True), or if it is the last value (False).
        """
        # Get an iterator and pull the first value.
        it = iter(iterable)
        last = next(it)
        # Run the iterator to exhaustion (starting from the second value).
        for val in it:
            # Report the *previous* value (more to come).
            yield last, True
            last = val
        # Report the last value.
        yield last, False

    def findData(self, database, collection, query):

        db = self.client[database]
        for result in db[collection].find(query):
            self.log.debug("查询的数据为", result)
            return result

    def aggregate(self, database, collection, query):

        db = self.client[database]
        for result in db[collection].aggregate(query):
            self.log.debug("查询的数据为", result)
            return result

    def UpdataData(self,
                   database=None,
                   collection=None,
                   query=None,
                   setdata=None):
        db = self.client[database]
        # db["accounts"].update({"phone":"15089514626",  "forLogin":True} , { "$set" : { "currentRoute" : "/account"} })
        db[collection].update_one(query, setdata)
Exemplo n.º 2
0
class Test_faceid():

    # mongo = mongoTool('mongodb+srv://eddiddevadmin:[email protected]')
    gm = GlobalMap()
    log = Logs()
    fix_routetitle = ['人脸识别']

    @allure.story("人脸识别")
    @pytest.mark.usefixtures('reloadRoute')
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_bankCard(self, poco):
        mongo = mongoTool(self.gm.get_value("mongohost"))
        pubTool = publicTool(poco)
        pubTool.get_appcationNumber()
        with allure.step("修改数据库currentRoute"):
            # 判断申请编号, 判断是APP还是H5数据还是老版APP数据

            if self.gm.get_value("environment").find("aos") != -1:
                collection = "accounts"
                query = {"applyCode":self.gm.get_value("appcationNumber"),  "forLogin":True}
                setdata = {"$set": {"currentRoute": "/account"}}
            elif self.gm.get_value("environment") == "uat" != -1 or self.gm.get_value("environment") == "test" != -1:
                collection = "apply"
                query = {"applySeqId":self.gm.get_value("appcationNumber")}
                setdata = { "$set" : { "step" : "AccountInformation"} }
            else:
                self.log.debug("数据可能有问题哦!!!")


            mongo.UpdataData(database=self.gm.get_value("environment"), collection=collection , query=query, setdata = setdata)

        with allure.step("退出开户表单"):
            pubTool.closeform()

        with allure.step("重新进入表单"):
            pass
Exemplo n.º 3
0
class Bank_Report(BasePage):
    log = Logs()

    def same_listofdict(self, pagelist, apilist):
        for i in range(len(pagelist)):
            self.log.debug("i == {}".format(i))
            self.log.debug("pagelist[i] == {}".format(pagelist[i]))
            self.log.debug("apilist[i] == {}".format(apilist[i]))

            allure.attach('页面的数据 : {} \n\n 接口返回的数据 : {}'.format(pagelist[i], apilist[i]), '对比第 {} 条数据'.format(i),allure.attachment_type.TEXT)

            assert pagelist[i]['pub_time'] == datetime.datetime.strptime(apilist[i]['pub_time'],
                                                                         "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
            assert pagelist[i]['name'][0] in apilist[i]['name']
            assert pagelist[i]['name'][1] in apilist[i]['name']
            assert pagelist[i]['previous_rating'] == (apilist[i]['previous_rating'] or '')
            assert pagelist[i]['latest_rating'] == (apilist[i]['latest_rating'] or '')
            assert pagelist[i]['previous_target_price'] == (apilist[i]['previous_target_price'] or '')
            assert pagelist[i]['latest_target_price'] == (apilist[i]['latest_target_price'] or '')
            assert pagelist[i]['institution'] == (apilist[i]['institution'] or '')

    def bankReport_lxml_parse(self):
        # 解析网页
        soup = BeautifulSoup(self.driver.page_source,'lxml')
        tablelist = soup.select("div.list.container  tbody > tr")

        lxmlList = []
        for tr in tablelist:
            trDict = {}
            trDict['pub_time'] = tr.select("td")[0].get_text()
            trDict['name'] = tr.select("td")[1].get_text().split(" ")
            trDict['previous_rating'] = tr.select("td")[2].get_text().replace("  ", "").split("\n\n")[0].replace("\n", "")
            trDict['latest_rating'] = tr.select("td")[2].get_text().replace("  ", "").split("\n\n")[1].replace("\n", "")
            trDict['previous_target_price'] = tr.select("td")[3].get_text().replace("  ", "").split("\n\n")[0].replace("\n", "")
            trDict['latest_target_price'] = tr.select("td")[3].get_text().replace("  ", "").split("\n\n")[1].replace("\n", "")
            trDict['institution'] = tr.select("td")[4].get_text()

            lxmlList.append(trDict)

        return lxmlList

    def get_bank_report_hk(self):
        # 打开浏览器
        self.open()
        wait_loading(self.driver)
        # 点击投行报告
        bankreport_loc = (By.XPATH, '//a[contains(text(), "投行报告")]')
        self.find_element(*bankreport_loc).click()
        wait_loading(self.driver)

        bankReportList = self.bankReport_lxml_parse()
        print("投行报告初始长度为: {}".format(len(bankReportList)))

        # 点击加载更多按钮
        add_btn = self.driver.find_element_by_xpath('//button//div[@class="md-button-content"]')
        # self.scrollinto(add_btn)
        self.script("arguments[0].scrollIntoView();", add_btn)
        ActionChains(self.driver).move_to_element(add_btn).click().perform()
        wait_loading(self.driver)
        add_bankReportList = self.bankReport_lxml_parse()
        print("加载更多后投行报告初始长度为: {}".format(len(add_bankReportList)))

        self.driver.quit()

        self.log.info("页面初始数据flashList为 : {}".format(bankReportList, ))
        self.log.info("页面点击加载更多后的数据addflashList为 : {}".format(add_bankReportList, ))
        return bankReportList, add_bankReportList

    def get_bank_report_us(self):
        # 打开浏览器
        self.open()
        wait_loading(self.driver)
        # 点击投行报告
        bankreport_loc = (By.XPATH, '//a[contains(text(), "投行报告")]')
        self.find_element(*bankreport_loc).click()
        wait_loading(self.driver)

        us_loc = (By.XPATH, '//a[contains(text(), "美股目标价")]')
        self.find_element(*us_loc).click()
        wait_loading(self.driver)

        bankReportList = self.bankReport_lxml_parse()
        print("美股-投行报告初始长度为: {}".format(len(bankReportList)))

        # 点击加载更多按钮
        add_btn = self.driver.find_element_by_xpath('//button//div[@class="md-button-content"]')
        # self.scrollinto(add_btn)
        self.script("arguments[0].scrollIntoView();", add_btn)
        ActionChains(self.driver).move_to_element(add_btn).click().perform()

        wait_loading(self.driver)
        add_bankReportList = self.bankReport_lxml_parse()
        print("加载更多后美股-投行报告初始长度为: {}".format(len(add_bankReportList)))

        self.driver.quit()

        self.log.info("页面初始数据flashList为 : {}".format(bankReportList, ))
        self.log.info("页面点击加载更多后的数据addflashList为 : {}".format(add_bankReportList, ))
        return bankReportList, add_bankReportList
class Test_employmentInfomation():

    gm = GlobalMap()
    log = Logs()

    fix_routetitle = ["就业及财务状况"]  #当fixture的参数

    # 无业--全年总收入
    Unemployed_totalAnnual = [
        ("小于20万", []),
        ("20-50万", ['退休金', '投资回报', '租金', '其他']),
        ("50-100万", ['退休金', '投资回报', '租金', '其他']),
        ("大于100万", ['退休金', '投资回报', '租金', '其他']),
    ]

    # 无业--资产净值
    Unemployed_assetslist = [
        ("小于100万", []),
        ("100-300万", ["退休金", "物业投资", "车辆投资", "储蓄", "股票/债券投资", "遗产", "其他"]),
        ("300-800万", ["退休金", "物业投资", "车辆投资", "储蓄", "股票/债券投资", "遗产", "其他"]),
        ("大于800万", ["退休金", "物业投资", "车辆投资", "储蓄", "股票/债券投资", "遗产", "其他"]),
    ]

    # 就业--全年总收入
    Employed_totalAnnual = [
        ("小于20万", []),
        ("20-50万", []),
        ("50-100万", []),
        ("大于100万", ['薪金', '投资回报', '租金', '佣金', '其他']),
    ]

    # 就业--资产净值
    Employed_assetslist = [
        ("小于100万", []),
        ("100-300万", []),
        ("300-800万", ["薪金", "物业投资", "车辆投资", "储蓄", "股票/债券投资", "遗产", "其他"]),
        ("大于800万", ["薪金", "物业投资", "车辆投资", "储蓄", "股票/债券投资", "遗产", "其他"]),
    ]

    # 自雇--全年总收入
    selfEmployed_totalAnnual = [
        ("小于20万", []),
        ("20-50万", ["自营业务收益", "投资回报", "租金", "其他"]),
        ("50-100万", ["自营业务收益", "投资回报", "租金", "其他"]),
        ("大于100万", ["自营业务收益", "投资回报", "租金", "其他"]),
    ]

    # 自雇--资产净值
    selfEmployed_assetslist = [
        ("小于100万", []),
        ("100-300万",
         ["薪金", "自营业务收益", "物业投资", "储蓄", "股票/债券投资", "车辆投资", "遗产", "其他"]),
        ("300-800万",
         ["薪金", "自营业务收益", "物业投资", "储蓄", "股票/债券投资", "车辆投资", "遗产", "其他"]),
        ("大于800万",
         ["薪金", "自营业务收益", "物业投资", "储蓄", "股票/债券投资", "车辆投资", "遗产", "其他"]),
    ]

    # @CommonsTool.retry()
    @allure.step("用例标题: 不选择就业情况, 直接选择全年总收入和资产净值")
    @allure.title("全年总收入选择: {totalAnnual}, 资产净值全栈: {customer}")
    @pytest.mark.parametrize('totalAnnual',
                             ['小于20万', '20-50万', '50-100万', '大于100万'])
    @pytest.mark.parametrize('customer',
                             ['小于100万', '100-300万', '300-800万', '大于800万'])
    @pytest.mark.skipif(gm.get_value("Routetitle") == "选择交易信息",
                        reason="就业情况已有值, 跳过该用例")
    @pytest.mark.usefixtures('reloadRoute')
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_nullemploy(self, poco, totalAnnual, customer):
        self.log.debug("正在执行用例 {} ".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        employment = employmentInfomationPage(poco)
        with allure.step("选择全年总收入选择 {}".format(totalAnnual)):
            employment.click_totalAnnualCustomerRevenueHK(totalAnnual)

        with allure.step("资产净值选择 {}".format(customer)):
            employment.click_customerNetAssetValueHK(customer)

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()
            assert_equal(pubTool.get_Routetitle(),
                         "就业及财务状况",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.step(
        "用例标题: 就业情况选择: {employed}, 全年总收入选择: {totalAnnual}, 资金来源选择: {fundlist}, 资产净值选择: {customer}, 资产净值来源选择: {assetslist}"
    )
    @pytest.mark.parametrize("employed", ["无业"])
    @pytest.mark.parametrize("totalAnnual, fundlist", Unemployed_totalAnnual)
    @pytest.mark.parametrize("customer, assetslist", Unemployed_assetslist)
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_unemployedandnot(self, poco, reloadRoute, employed, totalAnnual,
                              fundlist, customer, assetslist):
        self.log.debug("正在执行用例 {} ".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        employment = employmentInfomationPage(poco)
        with allure.step("就业情况选择无业"):
            employ = employment.click_employment(employed)

        with allure.step("全年总收入选择{}".format(totalAnnual)):
            totalAnnual = employment.click_totalAnnualCustomerRevenueHK(
                totalAnnual, fundlist=fundlist)

        with allure.step("资产净值选择{}".format(customer)):
            customer = employment.click_customerNetAssetValueHK(
                customer, assetslist=assetslist)

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()

        with allure.step("点击下一步成功, 跳转到'选择交易界面'"):
            self.log.debug("{}".format(self.gm.get_value("istotalAnnual"), ))
            assert_equal(pubTool.get_Routetitle(),
                         "选择交易信息",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

        with allure.step("点击返回按钮返回账户信息界面"):
            pubTool.backform()
            assert_equal(pubTool.get_Routetitle(),
                         "就业及财务状况",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.step(
        "用例标题: 就业情况选择: {employed}, 全年总收入选择: {totalAnnual}, 资金来源选择: {fundlist}, 资产净值选择: {customer}, 资产净值来源选择: {assetslist}"
    )
    @pytest.mark.parametrize("employed", ["就业"])
    @pytest.mark.parametrize("totalAnnual, fundlist", Employed_totalAnnual)
    @pytest.mark.parametrize("customer, assetslist", Employed_assetslist)
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_Employed(self, poco, reloadRoute, employed, totalAnnual, fundlist,
                      customer, assetslist):
        self.log.debug("正在执行用例 {} ".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        employment = employmentInfomationPage(poco)
        with allure.step("就业情况选择就业"):
            employ = employment.click_employment(employed)

        with allure.step("输入办公室地址"):
            employaddr = employment.send_officeAddr()

        with allure.step("全年总收入选择{}".format(totalAnnual)):
            totalAnnual = employment.click_totalAnnualCustomerRevenueHK(
                totalAnnual, fundlist=fundlist)

        with allure.step("资产净值选择{}".format(customer)):
            customer = employment.click_customerNetAssetValueHK(
                customer, assetslist=assetslist)

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()

        with allure.step("校验就业地址弹框标题和内容"):
            boxtitle, boxcontent = pubTool.get_boxtitle()
            assert_equal(boxtitle, "请确认您的办公室地址", "办公室地址弹框标题有误")
            assert_equal(boxcontent, employaddr, "办公室地址弹框内容与填写的地址不一致")

        with allure.step("确认地址弹框--点击确定"):
            pubTool.click_boxconfirm()

        with allure.step("点击下一步成功, 跳转到'选择交易界面'"):
            self.log.debug("{}".format(self.gm.get_value("istotalAnnual"), ))
            assert_equal(pubTool.get_Routetitle(),
                         "选择交易信息",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

        with allure.step("点击返回按钮返回账户信息界面"):
            pubTool.backform()
            assert_equal(pubTool.get_Routetitle(),
                         "就业及财务状况",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.step(
        "用例标题: 就业情况选择: {employed}, 全年总收入选择: {totalAnnual}, 资金来源选择: {fundlist}, 资产净值选择: {customer}, 资产净值来源选择: {assetslist}"
    )
    @pytest.mark.parametrize("employed", ["自雇"])
    @pytest.mark.parametrize("totalAnnual, fundlist", selfEmployed_totalAnnual)
    @pytest.mark.parametrize("customer, assetslist", selfEmployed_assetslist)
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_selfEmployed(self, poco, reloadRoute, employed, totalAnnual,
                          fundlist, customer, assetslist):
        self.log.debug("正在执行用例 {} ".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        employment = employmentInfomationPage(poco)
        with allure.step("就业情况选择自雇"):
            employ = employment.click_employment(employed)

        with allure.step("输入办公室地址"):
            employaddr = employment.send_officeAddr()

        with allure.step("全年总收入选择{}".format(totalAnnual)):
            totalAnnual = employment.click_totalAnnualCustomerRevenueHK(
                totalAnnual, fundlist=fundlist)

        with allure.step("资产净值选择{}".format(customer)):
            customer = employment.click_customerNetAssetValueHK(
                customer, assetslist=assetslist)

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()

        with allure.step("校验就业地址弹框标题和内容"):
            boxtitle, boxcontent = pubTool.get_boxtitle()
            assert_equal(boxtitle, "请确认您的办公室地址", "办公室地址弹框标题有误")
            assert_equal(boxcontent, employaddr, "办公室地址弹框内容与填写的地址不一致")

        with allure.step("确认地址弹框--点击确定"):
            pubTool.click_boxconfirm()

        with allure.step("点击下一步成功, 跳转到'选择交易界面'"):
            self.log.debug("{}".format(self.gm.get_value("istotalAnnual"), ))
            assert_equal(pubTool.get_Routetitle(),
                         "选择交易信息",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

        with allure.step("点击返回按钮返回账户信息界面"):
            pubTool.backform()
            assert_equal(pubTool.get_Routetitle(),
                         "就业及财务状况",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))
Exemplo n.º 5
0
import traceback

import allure
import pytest
from airtest.cli.parser import cli_setup
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from pymongo.errors import ServerSelectionTimeoutError

from Commons.GlobalMap import GlobalMap
from Commons.Logging import Logs
from Commons.mongoTool import mongoTool
from ElementPage.publicTool import publicTool

gm = GlobalMap()
log = Logs()
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = curPath[:curPath.find("airtest-APP\\") + len("airtest-APP\\")]


@pytest.fixture(scope="class")
def query_initialData(poco):
    """
    # 查询数据库获取初始值

    textMatches: 模糊匹配
    """
    # gm = GlobalMap()
    # log = Logs()
    log.debug("正在执行{} 方法".format(sys._getframe().f_code.co_name))
    mongo = mongoTool(gm.get_value("mongohost"))
Exemplo n.º 6
0
from apscheduler.schedulers.blocking import BlockingScheduler

from Commons import CommonsTool
from Commons.GlobalMap import GlobalMap
from Commons.Logging import Logs
from News_API import get_flashAPI, bank_report_API, calendar_data_API, calendar_event_API, calendar_holiday_API
from pages.GET_New_flash import News_Flash
from pages.GET_News_bankReport import Bank_Report
from pages.GET_News_calendar import News_calendar

# 生产环境
url = 'https://download.eddidapp.com/page/eddid-news/index.html'
# uat环境
# url = 'https://download.eddidapp.com/page/eddid-news-dev/index.html'

log = Logs()
log.debug("开始执行程序 {}".format(
    datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))


@allure.feature("校验快讯-期货的数据")
@allure.description(
    "affect有值时 : pagelist['content'] == apilist['data']['country'] + apilist['data']['time_period'] + apilist['data']['name']\n\n"
    "affect == 0 时, actual > (预测值 or 前值) 为 利多, 反则为利空\n\n"
    "affect == 1 时, actual < (预测值 or 前值) 为 利多, 反则为利空")
def test_flash_futures(driver):
    # 快讯-期货
    n = News_Flash(driver, url)
    with allure.step("爬取快讯-期货页面数据"):
        flashList, addflashList, opentime = n.get_flash_futures()
Exemplo n.º 7
0
class BaseView():

    gm = GlobalMap()
    log = Logs()

    def __init__(self, poco):
        self.poco = poco
        # 当前目录
        curPath = os.path.abspath(os.path.dirname(__file__))
        # 项目根目录
        rootPath = curPath[:curPath.find("airtest-APP\\") +
                           len("airtest-APP\\")]

        # 公用
        self.nextStepbtn = self.poco(text="下一步").parent()
        self.boxCancel = self.poco(text="取消")
        self.boxconfirm = self.poco(text="确定")
        self.gallery = self.poco(text="相册选取")
        self.loading = self.poco("android.widget.ProgressBar")
        self.Routetitle = self.poco("android.widget.FrameLayout").offspring(
            "android.widget.TextView")  # 页面标题
        self.permission_allow_button = self.poco(
            "com.android.packageinstaller:id/permission_allow_button",
            text="始终允许")  # 权限弹框: 允许
        self.permission_title = self.poco(
            "com.android.packageinstaller:id/permission_title")  # 权限弹框标题

        self.loginbtn = self.poco("button_login")
        self.passwordedit = self.poco("password_input")
        self.tel_edit = self.poco("tel_input")

        try:
            # APP弹框
            # self.box_alert = self.poco("android:id/content").child("android.widget.FrameLayout").child("android.view.ViewGroup").child("android.view.ViewGroup")[1].offspring("android.widget.TextView")
            self.box_alert = self.poco("android:id/content").child(
                "android.widget.FrameLayout").child(
                    "android.view.ViewGroup").child("android.view.ViewGroup")
        except Exception as e:
            self.log.debug("box_alert 元素报错, {}".format(e))

        self.closeform_img = rootPath + r'testData\testIMG\closeform.png'
        self.backform_img = rootPath + r'testData\testIMG\backform.png'

        self.el_firstSetting_loc = self.poco(
            "io.newtype.eddid.app:id/btn_start")
        self.baropen = self.poco(text="开户")
        self.easyOpenning = self.poco(text="便捷开户")
        self.goLogin = self.poco(text="去登录")
        self.phonenumber = self.poco(text="请输入手机号")

        self.el_chinese = self.poco(text="我是内地居民")
        self.el_idcardNegative = self.poco(text="请上传身份证人像面")
        self.el_idcardpositive = self.poco(text="请上传身份证国徽面")

        # 采用图片识别方式上传身份证
        self.idcardimgpath_img = rootPath + r'testData\\testIMG\\vivo_idcardFolder.png'
        self.idcardimgnegative_img = rootPath + r'testData\\testIMG\\idcardimgnegative.png'
        self.idcardimgpositive_img = rootPath + r'testData\\testIMG\\idcardimgpositive.png'

        # mumu模拟器图片
        self.mumuidcardimgpath_img = rootPath + r'testData\\testIMG\\mumuidcardFolder.png'
        self.mumuidcardimgnegative_img = rootPath + r'testData\\testIMG\\mumuidcardimgnegative.png'
        self.mumuidcardimgpositive_img = rootPath + r'testData\\testIMG\\mumuidcardimgpositive.png'

        # VIVO图片
        self.vivoidcardimgpath_img = rootPath + r'testData\\testIMG\\vivo_idcardFolder.png'
        self.vivoidcardimgnegative_img = rootPath + r'testData\\testIMG\\vivoidcardimgnegative.png'
        self.vivoidcardimgpositive_img = rootPath + r'testData\\testIMG\\vivoidcardimgpositive.png'

        # 个人信息界面
        self.el_title = self.poco(text="称呼").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.el_chinesename = self.poco(
            text="中文姓名").sibling("android.widget.EditText")
        self.el_lastname = self.poco(
            text="姓氏").sibling("android.widget.EditText")
        self.el_firstname = self.poco(
            text="名字").sibling("android.widget.EditText")
        self.el_email = self.poco(text="电邮").sibling("android.widget.EditText")
        self.el_reEmail = self.poco(
            text="再次输入电邮").sibling("android.widget.EditText")
        self.el_phone = self.poco(
            text="电话号码(用于通讯)").sibling("android.widget.EditText")
        self.el_idNumber = self.poco(
            text="证件号码").sibling("android.widget.EditText")
        self.el_birthday = self.poco(text="出生日期").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.el_country = self.poco(
            text="国籍").sibling("android.widget.EditText")
        self.el_countryIssue = self.poco(
            text="签发机关").sibling("android.widget.EditText")
        self.el_validityPeriod = self.poco(text="有效期至").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.el_iDcardAddress = self.poco(
            text="身份证地址(*请确认地址无误,如有误请手动修改)").sibling("android.widget.EditText")
        self.el_isAddress = self.poco(
            text="如住址和身份证地址不一致(请勾选)").sibling("android.widget.ImageView")

        # 地址证明
        self.addressProve = self.poco(text="请上传资料")
        self.Nowaddress = self.poco(
            text="请输入住址").sibling("android.widget.EditText")

        # 银行卡信息
        self.el_bankCardNo = self.poco(
            text="卡号").sibling("android.widget.EditText")
        self.el_bankName = self.poco(
            text="银行名称").sibling("android.widget.EditText")
        self.el_bankPhone = self.poco(
            text="绑定手机号").sibling("android.widget.EditText")

        # 账户信息
        self.el_accountType = self.poco(
            text="账户类型").sibling("android.widget.TextView")
        self.el_accountopeningway = self.poco(
            text="开户方法").sibling("android.widget.TextView")
        self.el_securitiesCash = self.poco(
            text="香港及环球证券账户(现金)").sibling("android.widget.ImageView")
        self.el_securitiesMargin = self.poco(
            text="香港及环球证券账户(保证金)").sibling("android.widget.ImageView")
        self.el_futuresMargin = self.poco(
            text="香港及环球期货账户(保证金)").sibling("android.widget.ImageView")
        self.el_leverMargin = self.poco(
            text="杠杆式外汇账户(保证金)").sibling("android.widget.ImageView")
        self.el_bullionMargin = self.poco(
            text="艾德金业现货黄金账户(保证金)").sibling("android.widget.ImageView")

        # 就业情况
        self.el_employ = self.poco(text="就业情况").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.position = self.poco(text="职位").sibling("android.widget.EditText")
        self.BusinessNature = self.poco(
            text="业务性质").sibling("android.widget.EditText")
        self.companyName = self.poco(
            text="公司名称").sibling("android.widget.EditText")
        self.employmenTime = self.poco(text="受雇年期").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.el_officeaddr = self.poco(
            text="办公室地址").parent().sibling("android.widget.EditText")
        self.totalAnnualCustomerRevenueHK = self.poco(
            text="全年总收入(港元)").sibling("android.view.ViewGroup").offspring(
                "android.widget.TextView")
        self.customerNetAssetValueHK = self.poco(text="资产净值(港元)").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.sourcesfunds = self.poco(text="请注明资金来源(可多选)")
        self.assetsvalue = self.poco(text="请注明资产净值来源(可多选)")
        self.otherfunds = self.poco(
            text="请输入其他资金来源").sibling("android.widget.EditText")
        self.otherassets = self.poco(
            text="请输入其他资产净值来源").sibling("android.widget.EditText")
        self.otherassetsvalue = self.poco(
            text="请输入其他资产净值来源").sibling("android.widget.EditText")

        # 选择交易信息
        self.fundsSourcetext = self.poco(text="交易的资金/财富来源(选择所有适用)")
        self.otherfundsSource = self.poco(
            text="请提供其他财富来源").sibling("android.widget.EditText")
        self.securities_date = self.poco(text="证券").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.CBBC_date = self.poco(text="牛熊证").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.DerivativeWarrant_date = self.poco(text="衍生权证(涡轮)").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.futures_date = self.poco(text="期货").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.Option_date = self.poco(text="期权").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.Optional_date = self.poco(
            text="其他投资(选填)").sibling("android.widget.EditText")
        self.otherInvestment_date = self.poco(text="其他投资").sibling(
            "android.view.ViewGroup").offspring("android.widget.TextView")
        self.personalInfoDeclartionLangsas = self.poco(
            textMatches=".*个人资料之使用声明.*")
        self.personalInfoDeclartionLangsasImgview = self.poco(
            textMatches=".*个人资料之使用声明.*").parent().sibling(
                "android.view.ViewGroup").child("android.widget.ImageView")

        # 相关保证金融资账户
        self.AccountName = self.poco(
            textMatches=".*账户持有人姓名").sibling("android.widget.EditText")
        self.AccountNumber = self.poco(
            textMatches=".*账户号码").sibling("android.widget.EditText")
        self.beneficiaryName = self.poco(
            textMatches=".*受益人名称").sibling("android.widget.EditText")
        self.ordersName = self.poco(
            textMatches=".*最终负责下单人姓名").sibling("android.widget.EditText")

        # 其他资料
        self.investmentTarget = self.poco(text="您的投资目标是")

        # 风险披露
        self.player = self.poco("android.widget.SeekBar").sibling(
            "android.view.ViewGroup").child("android.widget.ImageView")
        self.progressbar = self.poco("android.widget.SeekBar")
        self.isUnderstandRisk = self.poco(
            text="本人已收听风险披露语音,清楚明白并完全接受语音中所声明的全部风险。").sibling(
                "android.view.ViewGroup").child("android.widget.ImageView")

        # 签名
        self.signature = self.poco("android.view.View")
        self.signSubmit = self.poco(text="提").parent()
        self.resign = self.poco(text="重").parent()

    def isElementRadio(self, content, isFlag):
        """
        # 开户表单radio单选框定位方式

        args:
            content: 类型string, 定位栏的标题文本
            isFlag: 类型:Bool

        """
        if isFlag:
            element = self.poco(
                text=content).sibling("android.view.ViewGroup").child(
                    "android.widget.TextView", text="是")
        else:
            element = self.poco(
                text=content).sibling("android.view.ViewGroup").child(
                    "android.widget.TextView", text="否")

        return element

    def isElementCheck(self, content):
        """
        # 开户表单check单个复选框定位方式

        args:
            content: 类型string, 定位栏的标题文本
            isFlag: 类型:Bool

        """
        element = self.poco(text=content).parent().sibling(
            "android.view.ViewGroup").child("android.widget.ImageView")

        return element

    def exists(self, element):
        """
        先等待元素出现, 再判断元素是否显示

        """
        start = time.time()
        while not element.exists():
            self.log.debug("进入exists循环")
            element.invalidate()
            self.poco("android:id/content").invalidate()

            if time.time() - start > 15:
                self.log.debug("循环查找超过15秒, 失败")
                break

            time.sleep(0.5)

        return element

    def disExists_swipe(self, element, orientation=None):
        '''
        元素不在界面上, 滑动界面
        :param element:
        :param orientation: 滑动的方向, 默认向上滑动
        :return: element
        '''

        start = time.time()
        while not element.exists():
            self.log.debug("disExists_swipe进来")
            element.invalidate()
            contentEle = self.poco("android:id/content")
            contentEle.invalidate()
            if not orientation == None:
                contentEle.swipe([0, 0.3])
            elif time.time() - start > 20:
                break
            else:
                contentEle.swipe([0, -0.3])

        element.invalidate()
        return element

    def click_select(self, selectelement, selectText):
        """
        # 选择下拉框的值, 判断与当前值是否一致

        args:
            selectelement : 需要操作的元素
            selectText : 需要选择的, 下拉框的值
        """

        # selectElement = self.exists(selectelement)
        start = time.time()
        while not selectelement.exists():
            selectelement.invalidate()
            self.log.debug("{}不存在".format(str(selectelement)))
            if time.time() - start > 20:
                break

        # 获取就业情况栏位的值
        try:
            employtext = selectelement.get_text()
            self.log.debug("employtext的值为: {}".format(employtext))
        except:
            employtext = None
            self.log.debug("employtext的值为: None")

        # 判断下拉选项当前值是否与当前选中的一致
        if selectText != employtext:
            # 点击就业情况下拉框
            selectelement.click()
            # 下拉框选值:employ
            self.poco(text=selectText).click()

            return True

    def datePickerView(self, element, datestr=None):
        '''
        操作时间组件
        :param element:
        :param datestr: 传入str, '年.月.日'
        :return:
        '''

        # 时间转换
        date_map = {
            '01': '一月',
            '02': '二月',
            '03': '三月',
            '04': '四月',
            '05': '五月',
            '06': '六月',
            '07': '七月',
            '08': '八月',
            '09': '九月',
            '10': '十月',
            '11': '十一月',
            '12': '十二月',
        }

        nowtime = datetime.datetime.now().strftime('%Y.%m.%d')  #获取当前时间
        nowtimelist = nowtime.split('.')

        # 点击弹出时间组件
        element.click()

        # 不用选择日期
        if datestr == None:
            # 定位选择的日期, 并点击该日期
            self.poco("{d} {m} {Y}".format(m=date_map[nowtimelist[1]],
                                           Y=nowtimelist[0],
                                           d=nowtimelist[2])).click()
            self.poco("android:id/button1").click()  # 时间组件, 确定按钮

        # 选择日期
        else:
            # 切割需要选择的日期
            datestrlist = datestr.split('.')
            # 比较两个时间月份
            if int(nowtimelist[1]) > int(datestrlist[1]):
                # 点击上个月
                isdirection = 'last'
            elif int(nowtimelist[1]) == int(datestrlist[1]):
                isdirection = ''
            else:
                # 下个月
                isdirection = 'next'

            self.poco(
                "android:id/date_picker_header_year").click()  # 时间组件, 选择年份
            # 点击, 循环滑动选择年份
            self.disExists_swipe(self.poco(text=datestrlist[0]),
                                 orientation="down").click()

            # 需要点击的日子operating
            operating = self.poco(
                "{d} {m} {Y}".format(m=date_map[datestrlist[1]],
                                     Y=datestrlist[0],
                                     d=datestrlist[2]))

            start = time.time()
            while not operating.exists():
                if isdirection == 'next':
                    self.poco("android:id/next").click()
                elif isdirection == 'last':
                    self.poco("android:id/prev").click()
                elif time.time() - start > 20:
                    break

                operating.invalidate()

            operating.click()
            self.poco("android:id/button1").click()

            element.invalidate()
            assert element.get_text() == datestr, "日期控件时间选择有误"

        return element.get_text()
class Test_derivativeProduct():

    gm = GlobalMap()
    log = Logs()
    fix_routetitle = ["衍生品产品认识"]
    radiovalue = [True, False]

    @allure.story("衍生品产品认识 >> 直接勾选最后一个")
    @pytest.mark.parametrize("buyProduct", radiovalue)
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_derivative_Reversed(self, poco, reloadRoute, buyProduct):
        if self.gm.get_value("derivative") == True:
            pytest.skip("衍生产品选项已经勾选, 跳过")
        pubTool = publicTool(poco)
        derivative = derivativeProductPage(poco)
        print(self.gm.get_value("derivative") != True)
        with allure.step("客户是否申请开通买卖衍生权证、牛熊证及结构性等产品"):
            derivative.click_buyProduct(buyProduct)

        if buyProduct:
            with allure.step("客户已明白买卖衍生权证、牛熊证及结构性产品的风险。并已详细阅读「结构性产品相关风险声明披露」"):
                derivative.click_riskStatement()
        else:
            self.gm.set_bool(knowRisk=False)

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()
            assert_equal(pubTool.get_Routetitle(),
                         "衍生品产品认识",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.story("衍生品产品认识 >> 结构性产品相关风险声明披露不勾选")
    @pytest.mark.parametrize("derivativeCourse", radiovalue)
    @pytest.mark.parametrize("derivativeJobs", radiovalue)
    @pytest.mark.parametrize("tradingFund", radiovalue)
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_derivative_nullriskStatement(self, poco, reloadRoute,
                                          derivativeCourse, derivativeJobs,
                                          tradingFund):
        pubTool = publicTool(poco)
        derivative = derivativeProductPage(poco)
        with allure.step("客户是否曾接受有关衍生产品性质和风险的一般知识培训或修读相关课程"):
            derivative.click_derivativeCourse(derivativeCourse)

        with allure.step("您是否从现在或过去拥有过与衍生产品有关的工作经验?"):
            derivative.click_derivativeJobs(derivativeJobs)

        with allure.step(
                "您是否在过去3年曾执行5次或以上有关衍生产品的交易,例如:衍生证券、牛熊市、股票期权、期货与期权、商品、结构性产品及交易所买卖基金等"
        ):
            derivative.click_tradingFund(tradingFund)

        with allure.step("客户是否申请开通买卖衍生权证、牛熊证及结构性等产品"):
            derivative.click_buyProduct(True)

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()
            assert_equal(pubTool.get_Routetitle(),
                         "衍生品产品认识",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.story("衍生品产品认识 >> 组合勾选")
    @allure.title(
        "derivativeCourse: {derivativeCourse}, derivativeJobs: {derivativeJobs}, tradingFund : {tradingFund}, buyProduct : {buyProduct}"
    )
    @pytest.mark.parametrize("derivativeCourse", radiovalue)
    @pytest.mark.parametrize("derivativeJobs", radiovalue)
    @pytest.mark.parametrize("tradingFund", radiovalue)
    @pytest.mark.parametrize("buyProduct", radiovalue)
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_derivative(self, poco, reloadRoute, derivativeCourse,
                        derivativeJobs, tradingFund, buyProduct):
        self.log.debug("正在执行{} 方法, 参数为: {}".format(
            sys._getframe().f_code.co_name, locals()))
        pubTool = publicTool(poco)
        derivative = derivativeProductPage(poco)
        with allure.step("客户是否曾接受有关衍生产品性质和风险的一般知识培训或修读相关课程"):
            derivative.click_derivativeCourse(derivativeCourse)

        with allure.step("您是否从现在或过去拥有过与衍生产品有关的工作经验?"):
            derivative.click_derivativeJobs(derivativeJobs)

        with allure.step(
                "您是否在过去3年曾执行5次或以上有关衍生产品的交易,例如:衍生证券、牛熊市、股票期权、期货与期权、商品、结构性产品及交易所买卖基金等"
        ):
            derivative.click_tradingFund(tradingFund)

        with allure.step("客户是否申请开通买卖衍生权证、牛熊证及结构性等产品"):
            derivative.click_buyProduct(buyProduct)

        # 当"开通衍生权证"时, 触发隐藏框
        if buyProduct:
            with allure.step("客户已明白买卖衍生权证、牛熊证及结构性产品的风险。并已详细阅读「结构性产品相关风险声明披露」"):
                derivative.click_riskStatement()
        else:
            self.gm.set_bool(knowRisk=False)

        with allure.step("点击下一步"):
            self.log.info("test中knowRisk的值为 : {}".format(
                self.gm.get_value("knowRisk")))
            pubTool.click_NextStepbtn()
            assert_equal(pubTool.get_Routetitle(),
                         "相关保证金融资账户",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))
Exemplo n.º 9
0
class News_Flash(BasePage):

    log = Logs()

    def same_flashData(self, pagelist, apilist):
        print("正在对比数据")

        allure.attach('', 'pagelist的长度为 {}'.format(len(pagelist)),
                      allure.attachment_type.TEXT)
        allure.attach('', 'apilist的长度为 {}'.format(len(apilist)),
                      allure.attachment_type.TEXT)
        assert len(pagelist) == len(apilist)
        reg = re.compile('<[^>]*>')
        for i in range(len(pagelist)):
            self.log.debug("i == {}".format(i))
            self.log.debug("pagelist[i] == {}".format(pagelist[i]))
            self.log.debug("apilist[i] == {}".format(apilist[i]))

            allure.attach(
                '页面的数据 : {} \n\n 接口返回的数据 : {}'.format(pagelist[i], apilist[i]),
                '对比第 {} 条数据'.format(i), allure.attachment_type.TEXT)

            assert pagelist[i]['time'] == apilist[i]['time'][11:]

            try:
                assert pagelist[i]['content'] == reg.sub(
                    '', apilist[i]['data']['content']).replace('\n', '')
            except KeyError:
                assert pagelist[i][
                    'content'] == apilist[i]['data']['country'] + apilist[i][
                        'data']['time_period'] + apilist[i]['data']['name']

            try:
                # previous : 前值
                assert pagelist[i]['previous'] == apilist[i]['data'][
                    'previous'] + (apilist[i]['data']['unit'] or '')

                # consensus : 预测值
                if apilist[i]['data']['consensus'] == None:
                    assert pagelist[i]['consensus'] == '- -'
                else:
                    assert pagelist[i]['consensus'] == apilist[i]['data'][
                        'consensus'] + (apilist[i]['data']['unit'] or '')

                # actual : 公布值
                assert pagelist[i]['actual'] == str(
                    apilist[i]['data']['actual']) + (apilist[i]['data']['unit']
                                                     or '')
                assert pagelist[i]['start'] == apilist[i]['data']['start']
            except KeyError:
                continue

            try:
                # 利空利多
                if apilist[i]['data']['affect'] == 0:
                    if pagelist[i]['actual'] > (pagelist[i]['consensus']
                                                or pagelist[i]['previous']):
                        assert pagelist[i]['affect'] == '利多'
                    elif pagelist[i]['actual'] < (pagelist[i]['consensus']
                                                  or pagelist[i]['previous']):
                        assert pagelist[i]['affect'] == '利空'

                elif apilist[i]['data']['affect'] == 1:
                    if pagelist[i]['actual'] < (pagelist[i]['consensus']
                                                or pagelist[i]['previous']):
                        assert pagelist[i]['affect'] == '利多'
                    elif pagelist[i]['actual'] > (pagelist[i]['consensus']
                                                  or pagelist[i]['previous']):
                        assert pagelist[i]['affect'] == '利空'

            except KeyError:
                continue

    def lxml_parse(self, driver):
        print("解析网页数据")
        soup = BeautifulSoup(driver.page_source, 'lxml')
        pagetext = soup.select(
            "div.md-example-child.news div.md-cell-item-content")
        flashList = []
        for page in pagetext:
            item_dict = {}
            if page.select("p.md-cell-item-brief") != [] or page.select(
                    "p.md-cell-item-title") != []:
                item_dict['time'] = page.select(
                    "p.md-cell-item-brief")[0].get_text()
                item_dict['content'] = page.select(
                    "p.md-cell-item-title")[0].get_text()
            else:
                item_dict['time'] = page.select(
                    "div.calendar-content > span.time")[0].get_text()
                item_dict['content'] = page.select(
                    "div.calendar-content span.title")[0].get_text()
                item_dict['previous'] = page.select(
                    "div.calendar-content span.previous")[0].get_text()[3:]
                item_dict['consensus'] = page.select(
                    "div.calendar-content span.consensus")[0].get_text()[4:]
                item_dict['actual'] = page.select(
                    "div.calendar-content span.actual")[0].get_text()[4:]
                item_dict['start'] = len(
                    page.select("div.calendar-content i.star.stared"))
                item_dict['affect'] = page.select(
                    "div.calendar-content span.status")[0].get_text()[:2]

            # print(item_dict)
            flashList.append(item_dict)

        return flashList

    def get_flash_futures(self):
        driver = self.driver
        # print(driver.page_source)
        self.open()
        wait_loading(driver)
        # 记录打开网页的时间, 传给API, 反正数据刷新
        opentime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        allure.attach('', "快讯期货打开的时间 : {}".format(opentime),
                      allure.attachment_type.TEXT)

        flashList = self.lxml_parse(driver)
        print("页面返回的数据条数为 : {}".format(len(flashList)))

        add_btn = driver.find_element_by_xpath(
            '//button//div[@class="md-button-content"]')

        # 点击加载更多按钮
        print("开始点击加载更多按钮")
        self.scrollinto(add_btn)
        wait_loading(driver)

        addflashList = self.lxml_parse(driver)
        print("点击加载更多按钮后页面返回的数据条数为 : {}".format(len(addflashList)))
        # print("已经要关闭啦!!!!")
        driver.quit()

        self.log.debug("页面初始数据flashList为 : {}".format(flashList, ))
        self.log.debug("页面点击加载更多后的数据addflashList为 : {}".format(addflashList, ))

        return flashList, addflashList, opentime

    def get_flash_HK(self):
        print("开始请求资源网站")
        driver = self.driver
        self.open()
        wait_loading(driver)

        # print(driver.page_source)
        self.find_element(*(By.XPATH, '//a[contains(text(), "港美股")]')).click()
        wait_loading(driver)

        # 记录打开网页的时间, 传给API, 反正数据刷新
        opentime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        allure.attach('', "快讯港美股打开的时间 : {}".format(opentime),
                      allure.attachment_type.TEXT)

        flashList = self.lxml_parse(driver)
        print("快讯-港美股页面返回的数据条数为 : {}".format(len(flashList)))
        add_btn = driver.find_element_by_xpath(
            '//button//div[@class="md-button-inner"]')
        # 点击加载更多按钮
        print("快讯-港美股点击加载更多按钮")

        # 直接点击和使用arguments[0].click()无法点击, 故使用ActionChains, 但需要element先出现在页面上
        self.script("arguments[0].scrollIntoView();", add_btn)
        ActionChains(self.driver).move_to_element(add_btn).click().perform()

        wait_loading(driver)

        addflashList = self.lxml_parse(driver)
        print("快讯-港美股点击加载更多按钮后页面返回的数据条数为 : {}".format(len(addflashList)))
        driver.quit()

        self.log.debug("页面初始数据flashList为 : {}".format(flashList, ))
        self.log.debug("页面点击加载更多后的数据addflashList为 : {}".format(addflashList, ))
        # import pdb; pdb.set_trace
        return flashList, addflashList, opentime
class Test_bankCardInformation():
    log = Logs()
    fix_routetitle = ["银行卡信息"]

    @allure.story("内地银行卡号非空校验")
    @pytest.mark.usefixtures('reloadRoute')
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_bankCardnullvalue(self, poco):
        self.log.debug("正在执行{} 方法".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        bankcard = bankCardInformationPage(poco)
        with allure.step("输入卡号"):
            bankcard.send_bankCardNo(bankNo="")

        with allure.step("输入银行名称"):
            bankcard.send_bankName()

        with allure.step("输入绑定手机号"):
            bankcard.send_bankPhone()

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()

        with allure.step("页面停留在<银行卡信息>界面"):
            assert_equal(pubTool.get_Routetitle(),
                         "银行卡信息",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.story("内地银行卡号输入中文")
    @pytest.mark.usefixtures('reloadRoute')
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_bankCard_sendChinese(self, poco):
        self.log.debug("正在执行{} 方法".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        bankcard = bankCardInformationPage(poco)
        with allure.step("输入卡号"):
            bankcard.send_bankCardNo(bankNo="内地银行卡号")

        with allure.step("输入银行名称"):
            bankcard.send_bankName()

        with allure.step("输入绑定手机号"):
            bankcard.send_bankPhone()

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()

        with allure.step("校验弹框内容"):
            boxtitle, boxcontent = pubTool.get_boxtitle()
            assert_equal(boxtitle, "温馨提示", msg="银行卡信息界面弹框标题有误")
            assert_equal(boxcontent, "卡号只能输入数字", msg="银行卡信息界面弹框内容有误")
            # 关闭弹框
            pubTool.click_box()

        with allure.step("页面停留在<银行卡信息>界面"):
            assert_equal(pubTool.get_Routetitle(),
                         "银行卡信息",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.story("内地银行卡号输入组合字符")
    @pytest.mark.usefixtures('reloadRoute')
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_bankCard_sendAll(self, poco):
        self.log.debug("正在执行{} 方法".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        bankcard = bankCardInformationPage(poco)
        with allure.step("输入卡号"):
            bankcard.send_bankCardNo(bankNo="内地abc123,./")

        with allure.step("输入银行名称"):
            bankcard.send_bankName()

        with allure.step("输入绑定手机号"):
            bankcard.send_bankPhone()

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()

        with allure.step("校验弹框内容"):
            boxtitle, boxcontent = pubTool.get_boxtitle()
            assert_equal(boxtitle, "温馨提示", msg="银行卡信息界面弹框标题有误")
            assert_equal(boxcontent, "卡号只能输入数字", msg="银行卡信息界面弹框内容有误")
            # 关闭弹框
            pubTool.click_box()

        with allure.step("页面停留在<银行卡信息>界面"):
            assert_equal(pubTool.get_Routetitle(),
                         "银行卡信息",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.story("银行名称输入空值")
    @pytest.mark.usefixtures('reloadRoute')
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_bankCardnameNull(self, poco):
        self.log.debug("正在执行{} 方法".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        bankcard = bankCardInformationPage(poco)
        with allure.step("输入卡号"):
            bankcard.send_bankCardNo()

        with allure.step("输入银行名称"):
            bankcard.send_bankName("")

        with allure.step("输入绑定手机号"):
            bankcard.send_bankPhone()

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()

        with allure.step("页面停留在<银行卡信息>界面"):
            assert_equal(pubTool.get_Routetitle(),
                         "银行卡信息",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.story("银行名称输入组合字符")
    @pytest.mark.usefixtures('reloadRoute')
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_bankCardname_sendAll(self, poco):
        self.log.debug("正在执行{} 方法".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        bankcard = bankCardInformationPage(poco)
        with allure.step("输入卡号"):
            bankcard.send_bankCardNo()

        with allure.step("输入银行名称"):
            bankcard.send_bankName("中国银行abc123.,/@")

        with allure.step("输入绑定手机号"):
            bankcard.send_bankPhone()

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()

        with allure.step("页面跳转到人脸识别界面"):
            assert_equal(pubTool.get_Routetitle(),
                         "人脸识别",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

        with allure.step("点击返回按钮返回银行卡信息界面"):
            pubTool.backform()
            assert_equal(pubTool.get_Routetitle(),
                         "银行卡信息",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.story("绑定手机号不填")
    @pytest.mark.usefixtures('reloadRoute')
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_bankCardPhone_Null(self, poco):
        self.log.debug("正在执行{} 方法".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        bankcard = bankCardInformationPage(poco)
        with allure.step("输入卡号"):
            bankcard.send_bankCardNo()

        with allure.step("输入银行名称"):
            bankcard.send_bankName()

        with allure.step("输入绑定手机号"):
            bankcard.send_bankPhone("")

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()

        with allure.step("页面停留在<银行卡信息>界面"):
            assert_equal(pubTool.get_Routetitle(),
                         "银行卡信息",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.story("绑定手机号输入中文")
    @pytest.mark.usefixtures('reloadRoute')
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_bankCardPhone_sendChinese(self, poco):
        self.log.debug("正在执行{} 方法".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        bankcard = bankCardInformationPage(poco)
        with allure.step("输入卡号"):
            bankcard.send_bankCardNo()

        with allure.step("输入银行名称"):
            bankcard.send_bankName()

        with allure.step("输入绑定手机号"):
            bankcard.send_bankPhone("手机号")

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()

        with allure.step("校验弹框内容"):
            boxtitle, boxcontent = pubTool.get_boxtitle()
            assert_equal(boxtitle, "温馨提示", msg="银行卡信息界面弹框标题有误")
            assert_equal(boxcontent, "绑定手机号只能输入数字", msg="银行卡信息界面弹框内容有误")
            # 关闭弹框
            pubTool.click_box()

        with allure.step("页面停留在<银行卡信息>界面"):
            assert_equal(pubTool.get_Routetitle(),
                         "银行卡信息",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))

    @allure.story("绑定手机号输入组合字符")
    @pytest.mark.usefixtures('reloadRoute')
    @pytest.mark.parametrize("reloadRoute", fix_routetitle, indirect=True)
    def test_bankCardPhone_sendAll(self, poco):
        self.log.debug("正在执行{} 方法".format(sys._getframe().f_code.co_name, ))
        pubTool = publicTool(poco)
        bankcard = bankCardInformationPage(poco)
        with allure.step("输入卡号"):
            bankcard.send_bankCardNo()

        with allure.step("输入银行名称"):
            bankcard.send_bankName()

        with allure.step("输入绑定手机号"):
            bankcard.send_bankPhone("手机号123abc,./")

        with allure.step("点击下一步"):
            pubTool.click_NextStepbtn()

        with allure.step("校验弹框内容"):
            boxtitle, boxcontent = pubTool.get_boxtitle()
            assert_equal(boxtitle, "温馨提示", msg="银行卡信息界面弹框标题有误")
            assert_equal(boxcontent, "绑定手机号只能输入数字", msg="银行卡信息界面弹框内容有误")
            # 关闭弹框
            pubTool.click_box()

        with allure.step("页面停留在<银行卡信息>界面"):
            assert_equal(pubTool.get_Routetitle(),
                         "银行卡信息",
                         msg="页面跳转到{}页面".format(pubTool.get_Routetitle()))
Exemplo n.º 11
0
class publicTool(BaseView):

    log = Logs()

    def allow_permissionBox(self):
        """
        处理Android权限弹框
        """
        try:
            # 循环5次, 点击多个弹框
            for i in range(5):
                self.permission_allow_button.invalidate()
                permission_title = self.permission_title.get_text()
                self.log.info("权限 >> {}".format(permission_title,))
                self.permission_allow_button.click()

        except Exception as e:
            self.log.debug("没有出现权限弹框")
            pass


    def click_NextStepbtn(self, title=None):
        """
        开户表单所有的下一步按钮

        """
        self.log.debug("调用此方法的是: {}".format(traceback.extract_stack()[-2][2]))
        # index = 0
        # while index < 10:
        #     self.log.debug("进入下一步循环")
        #     # 获取页面标题内容, 目的是为了刷新页面
        #     # self.nextStepbtn.invalidate()
        #     nextStepbtn = self.disExists_swipe(self.nextStepbtn)
        #     # 判断按钮是否高亮, 通过focusable属性
        #     if nextStepbtn.attr("focusable"):
        #         self.log.debug("'下一步'按钮高亮")
        #         nextStepbtn.click()
        #         break
        #
        #     index += 1

        nextStepbtn = self.disExists_swipe(self.nextStepbtn)
        nextStepbtn.click()



    def click_boxCancel(self):
        """
        开户表单-- 弹出确认框--取消按钮

        """
        self.boxCancel.click()


    def click_boxconfirm(self):
        """
        开户表单-- 弹出确认框--确定按钮

        """
        self.boxconfirm.click()


    def get_boxtitle(self):
        """
        获取弹出框的标题和弹框的内容

        """
        self.log.debug("正在执行get_boxtitle方法")

        start = time.time()
        while True:
            self.log.debug("循环查找")
            if self.poco(text="确定").exists() and self.poco(text="取消").exists():
                box_alert_text = self.poco(text="确定").parent().parent().parent().offspring("android.widget.TextView")
                break
            elif self.poco(text="知道了").exists():
                box_alert_text = self.poco(text="知道了").parent().parent().parent().offspring("android.widget.TextView")
                break

            if time.time() - start > 15:
                self.log.debug("循环查找超过15秒, 失败")
                break

            self.poco("android:id/content").invalidate()

        self.log.debug("提示框的标题是: {}".format(box_alert_text[0].get_text()))
        self.log.debug("提示框的标题是: {}".format(box_alert_text[1].get_text()))

        return box_alert_text[0].get_text(), box_alert_text[1].get_text()




    def wait_loading(self, timeout=30):

        self.get_Routetitle()
        start = time.time()
        # 循环判断loading是否存在
        while self.loading.exists():
            self.log.debug("wait_loading as True, loading存在")
            self.loading.invalidate()
            self.poco("android:id/content").invalidate()

            if time.time() - start > timeout:
                self.log.error("wait_loading超时!!!!")
                break

            time.sleep(1)



    def swipe_to_Up(self):
        """
        # 向上滑动屏幕
        """
        contentEle = self.poco("android:id/content")
        contentEle.invalidate()
        contentEle.swipe([0, -0.4])

    def swipe_to_Down(self):
        """
        # 向下滑动屏幕
        """
        contentEle = self.poco("android:id/content")
        contentEle.invalidate()
        contentEle.swipe([0, 0.4])


    def DragFrom_LeftToRight(self, element):
        """
        # 从左边拖动到右键
        """
        element.long_click()
        element.swipe([1, 0])

    def closeform(self):
        """
        # APP关闭按钮"X"
        """
        # 关闭开户表单
        # touch(Template(self.closeform_img, record_pos=(-0.378, -0.774), resolution=(810, 1440)))


        # import pdb; pdb.set_trace()

        title = self.Routetitle.get_text()
        close_btn = self.poco(text=title).sibling("android.view.ViewGroup")[1]
        close_btn.click()

        # 重复十次
        for i in range(10):
            if self.get_Routetitle() == "艾德证券期货":
                # 点击便捷开户
                self.easyOpenning.click()
                break



    def backform(self):
        """
        # APP返回按钮
        """
        # # 点击返回按钮
        # touch(Template(self.backform_img, record_pos=(-0.42, -0.919), resolution=(1080, 2340)))
        # time.sleep(0.5)

        # import pdb; pdb.set_trace()

        title = self.Routetitle.get_text()
        back_btn = self.poco(text=title).sibling("android.view.ViewGroup")[0]
        back_btn.click()


    def get_appcationNumber(self):
        """
        # 通过申请编号判断客户来源

        textMatches: 模糊匹配
        """
        appcationNumberatext = self.poco(textMatches="申请编号:.*").get_text()
        self.log.debug("申请编号为: {}".format(appcationNumberatext))

        self.gm.set_value(appcationNumber=appcationNumberatext[5:])
        
        return appcationNumberatext[5:]

    # 检验是否全是中文字符
    def is_all_chinese(self, strs):
        for _char in strs:
            if not '\u4e00' <= _char <= '\u9fa5':
                return False
        return True


    # 检验是否含有中文字符
    def is_contains_chinese(self, strs):
        for _char in strs:
            if '\u4e00' <= _char <= '\u9fa5':
                return True
        return False


    def get_Routetitle(self):
        """
        # 获取页面的标题

            # invalidate() : 刷新Android界面
                Android的invalidate与postInvalidate都是用来刷新界面的。
                在UI主线程中,用invalidate(),本质是调用View的onDraw()绘制。
                主线程之外,用postInvalidate()。

                地址:
                https://www.zybuluo.com/natsumi/note/470226
        """

        self.Routetitle.invalidate()
        start = time.time()
        while not self.Routetitle.exists():
            self.log.debug("Routetitle 不存在")
            if time.time() - start > 20:
                break
            pass

        self.log.debug("调用此方法的是: {}".format(traceback.extract_stack()[-2][2]))
        self.log.debug("调用此方法的模块为: {}, 行数为: {}".format(sys._getframe().f_code.co_filename , sys._getframe().f_back.f_lineno))

        try:
            self.log.debug("当前页面的标题为: {}".format(self.Routetitle.get_text(),))
        except PocoNoSuchNodeException:
            self.log.debug("title获取不到")

        return self.Routetitle.get_text()


    def click_box(self):
        start = time.time()
        while not self.poco(text="知道了").exists():
            self.poco(text="知道了").invalidate()
            if time.time() - start > 20:
                break
        self.poco(text="知道了").click()