python UI自动化实战记录五:测试页面2-策略页

该部分记录测试页面2-StrategyPage,所有首页上的元素定位、操作、获取属性等方法都写在该类中。

1 首页类继承自BasePage

2 首页类第一部分写的是所有的定位器

3 首页类第二部分类的方法,包括提取页面元素,页面元素的操作、获取属性、验证元素属性正确性等

4 当用例中需要用到该页面的某元素或操作时,补充方法到该类中,再在用例中调用

#coding:utf-8

"""
策略页面类
LOCATOR : 所有页面元素的定位器
策略页面元素的定位和操作均写在该类中
"""

from .basepage import BasePage
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import Byimport logging;logging.basicConfig(level=logging.INFO)

class StrategyPage(BasePage):
    """
   策略页面类
    """

    #LOCATOR
    _selectedStrategyName_locator = (By.ID, "selectedStrategyName")
    _selectedstragegy_locator  = (By.CSS_SELECTOR, "#strategyList dd.actived")
    _navinfo_locator = (By.CSS_SELECTOR,"#estimationRightInfo .ifund-zf li")
    _groupRiseTbody_locator = (By.ID, "groupRiseTbody")
    _h1_locator = (By.TAG_NAME,"h1")
    _p_locator = (By.TAG_NAME,"p")
    _span_loacator = (By.TAG_NAME,"span")
    _tr_locator = (By.TAG_NAME,"tr")
    _td_locator = (By.CSS_SELECTOR,"td div")
    _dd_locator = (By.TAG_NAME,"dd")
    _pattern_locator = (By.CSS_SELECTOR,"#groupTechContainer .switch-header-i.actived")
    _patterns_locator = (By.CSS_SELECTOR,"#groupTechContainer .switch-header-i")
    _peroid_locator = (By.CSS_SELECTOR,"#groupTechContainer .switch-container li.actived")
    _name_locator = (By.ID,"selectedStrategyName")
    _strategystyle_locator = (By.CSS_SELECTOR, "#poptype li")
    _strategylevel_locator = (By.CSS_SELECTOR, "#strategyList dd")
    _peroids_locator = (By.CSS_SELECTOR,"#groupTechContainer .switch-container .charttype li")
    _startdate_locator = (By.ID,"mdStart")
    _spchart_locator = (By.ID, "spchartType")
    _percentRun_locator = (By.ID, "percentRun")
    _percentDiff_locator = (By.ID, "percentDiff")
    _yield_locator = (By.ID,"yield")
    _mdStartEnd_locator = (By.ID, "mdStart-End")
    _adjustdate_locator = (By.ID,"selAdjustDates")
    _strategyinfo_locator = (By.ID, "strategyinfo")
    _memo_locator = (By.CLASS_NAME, "s-tips")
    _details_locator = (By.CSS_SELECTOR, ".s-details dl")
    _maxretrace_locator = (By.ID, "maxretrace")
    _sharpeRun_locator = (By.ID, "sharpeRun")
    _sharpeDiff_locator = (By.ID, "sharpeDiff")
    _xpRate_locator = (By.ID, "xpRate")
    _js_totop = "scrollTo(0,0)"
    _js_trends = ‘document.getElementsByClassName("ifund-module-i")[1].scrollIntoView()‘
    _js_adjustdate = ‘document.getElementById("selAdjustDates").scrollIntoView()‘
    _js_percents = ‘document.getElementById("groupRiseTbody").scrollIntoView()‘

    def open_strategy_page(self,sso):
        """打开策略页面"""           domain = "http://testdomain"
        strategyurl = ‘/strategy‘
        url = domain + strategyurl + ‘?‘ + sso
        self.openpage(url)

    def get_code(self):
        self.strategycode = self.getelement(*StrategyPage._selectedstragegy_locator).get_attribute("data-code") #获取策略code
        return self.strategycode

    def get_strategyinfo(self):
        """获取页面策略代码、名称信息"""
        self.selectedStrategyName = self.getelement(*StrategyPage._selectedStrategyName_locator).text  # 选中的策略风格名称
        self.selectedstragegy = self.getelement(*StrategyPage._selectedstragegy_locator)

        self.strategystyle = self.selectedstragegy.get_attribute("data-style")  # 选中的策略类型
        self.strategycode = self.selectedstragegy.get_attribute("data-code")  # 选中的策略代码
        self.strategyname = self.selectedstragegy.text  # 选中的策略名称
        logging.info("当前策略:%s_%s"%(self.selectedStrategyName,self.strategycode))
        return  self.strategycode

    def get_navinfo(self):
        """页面净值数据"""
        logging.info("基金净值")
        self.driver.execute_script(StrategyPage._js_totop)  # 返回顶部
        self.getscreenshot("净值")
        navinfo = self.getelements(*StrategyPage._navinfo_locator)  # 净值模块
        nav = self.getchild(navinfo[0],*StrategyPage._h1_locator).text  # 净值
        navDate = self.getchild(navinfo[0],*StrategyPage._p_locator).text[-6:-1]  # 净值日期
        navChange = self.getchild(navinfo[1],*StrategyPage._span_loacator).text[:-1]  # 净值日涨幅
        annualChangeAll = self.getchild(navinfo[2],*StrategyPage._span_loacator).text[:-1]  # 年化回报
        self.navlist = [float(nav), navDate, float(navChange), float(annualChangeAll)]
        return self.navlist

    def get_percents(self):
        """页面组合涨幅数据"""
        self.driver.execute_script(StrategyPage._js_percents) #显示到页面
        logging.info("组合涨幅")
        self.getscreenshot("组合涨幅")
        self.percents_list = []
        groupRiseTbody = self.getelement(*StrategyPage._groupRiseTbody_locator)
        trlist = self.getchilds(groupRiseTbody,*StrategyPage._tr_locator) #获取组合涨幅的数据
        trlen = len(trlist)
        for i in range(trlen):
            tdlist = self.getchilds(trlist[i],*StrategyPage._td_locator)
            tddatalist = [ele.text.replace(‘%‘,‘‘) for ele in tdlist] #取出值并去掉%
            for i in range(len(tddatalist)): #转化成浮点数
                try:
                    tddatalist[i] = float(tddatalist[i])
                except:
                    pass #不能转化成浮点的忽略
            self.percents_list.append(tddatalist)
        return self.percents_list

    def get_actived_pattern(self):
        """获取当前选中的定投方式"""

        pattern = self.getelement(*StrategyPage._pattern_locator)
        self.pattern = pattern.get_attribute("data-type")
        return  self.pattern

    def get_actived_peroid(self):
        """获取当前选中的投资期限"""

        peroid = self.getelement(*StrategyPage._peroid_locator)
        self.peroid = peroid.get_attribute("data-type")
        return self.peroid

    def choose_style(self,styleindex):
        """选择策略风格"""
        strategyListdt = self.getelement(*StrategyPage._name_locator) # 找到当前所选策略
        self.driver.execute_script(StrategyPage._js_totop) #返回顶部
        strategyListdt.click()  # 点击显示下拉列表
        self.wait(0.5)
        strategystylelist = self.getelements(*StrategyPage._strategystyle_locator)  # 下拉框选项列表
        selectstrategy = strategystylelist[styleindex]
        self.selectStrategystyle = selectstrategy.get_attribute("data-style") # 选择的类型
        self.selectStrategyName = selectstrategy.text # 选择的stylename
        selectstrategy.click()  # 点击风格
        self.wait(1)

    def check_chooseresult(self):
        """验证选择的类型与页面显示类型一致"""
        if self.selectedStrategyName == self.selectStrategyName and self.strategystyle == self.selectStrategystyle:
            return True

    def choose_level(self,levelindex):
        """选择策略级别"""
        strategylevellist = self.getelements(*StrategyPage._strategylevel_locator)  # 策略子类型列表
        self.strategylevellist = [item for item in strategylevellist if item.is_displayed()] #移除不显示的元素
        strategylevel = self.strategylevellist[levelindex]
        strategylevel.click() #点击策略子类型
        self.wait(1)
        return

    def choose_strategy(self,styleindex,levelindex):
        """选择策略风格和级别并获取策略信息"""
        self.choose_style(styleindex) # 选择策略风格
        self.choose_level(levelindex) # 选择级别
        self.get_strategyinfo()  # 选择后获取信息
        styleinfo = "益策略选择S00%s00%s"%(styleindex+1,levelindex+1)
        self.getscreenshot(styleinfo)
        logging.info(styleinfo)

    def choose_trends_pattern(self,patternindex):
        """选择组合走势的定投方式"""
        self.driver.execute_script(StrategyPage._js_trends) #定投方式显示到界面,否则无法点击
        self.patternlist = self.getelements(*StrategyPage._patterns_locator)  # 定投方式
        patternele = self.patternlist[patternindex]
        patternele.click()  # 选择定投方式
        self.wait(1)
        self.pattern = patternele.get_attribute("data-type") #获取定投方式K,W
        self.peroidlist = self.getelements(*StrategyPage._peroids_locator) #获取时间区间

    def choose_trends_peroid(self,peroidindex):
        """选择投资期限,获取组合走势开始日期和业绩表现数据"""
        peroidele = self.peroidlist[peroidindex]
        peroidele.click() # 点击时间区间
        self.wait(2)
        self.peroid = peroidele.get_attribute("data-type") #时间区间
        self.get_trends()
        #log和截图
        trendinfo = "组合走势{pattern}_{peroid}".format(pattern=self.pattern,peroid=self.peroid)
        logging.info(trendinfo)
        self.getscreenshot(trendinfo)

    def get_trends(self):
        """获取组合走势起始日期和业绩表现页面数据"""
        self.startdate = self.getelement(*StrategyPage._startdate_locator).text  # 起始日期
        strategycode = self.get_code()

        """业绩表现页面数据"""
        self.spchartType = self.getelement(*StrategyPage._spchart_locator).text #周期
        self.percentRun = self.getelement(*StrategyPage._percentRun_locator).text #收益率超出、跑输
        self.percentDiff = float(self.getelement(*StrategyPage._percentDiff_locator).text[:-1]) #收益率与业绩基准比较的绝对值
        self.yieldp = float(self.getelement(*StrategyPage._yield_locator).text[:-1]) #收益率
        mdStart_End = self.getelement(*StrategyPage._mdStartEnd_locator).text #最大回撤区间
        self.mdstart = mdStart_End[:10].replace(‘/‘, ‘-‘) #转化成与接口一样的格式
        self.mdend = mdStart_End[-10:].replace(‘/‘, ‘-‘) #转化成与接口一样的格式

        self.maxretrace = float(self.getelement(*StrategyPage._maxretrace_locator).text[:-1]) #最大回撤
        self.sharpeRun = self.getelement(*StrategyPage._sharpeRun_locator).text #夏普超出、跑输
        self.sharpeDiff = float(self.getelement(*StrategyPage._sharpeDiff_locator).text[:-1]) #夏普比率比较绝对值
        self.xpRate = self.getelement(*StrategyPage._xpRate_locator).text[:-1] #夏普比率
        try:
            self.xpRate = float(self.xpRate) # 有数值转换,无数值不转换
        except:
            pass

        result = [strategycode,self.startdate, self.percentRun, self.percentDiff, self.yieldp,self.maxretrace,self.sharpeRun,
                  self.sharpeDiff, self.xpRate, self.mdstart,self.mdend]
        return result

    def get_strategy_adjustdate(self):
        """获取策略配置调仓日期"""
        self.selAdjustDatesselect = Select(self.getelement(*StrategyPage._adjustdate_locator)) #调仓日期选择框
        self.adjustDate = self.selAdjustDatesselect.first_selected_option.text #当前选中的日期
        self.adjustDatelist = [opt.get_attribute("value") for opt in self.selAdjustDatesselect.options] #取出所有的调仓日期
        return self.adjustDate

    def choose_adjustdate(self,adjustdate):
        """选择调仓日期并获取配置"""
        self.driver.execute_script(StrategyPage._js_adjustdate) #调仓日期显示到页面
        self.selAdjustDatesselect.select_by_value(adjustdate) #选择调仓日期
        self.wait(0.5)
        #log和截图
        infos = "{adjustdate}配置".format(adjustdate=adjustdate)
        logging.info(infos)
        self.getscreenshot(infos)

    def get_strategy_settings(self):
        """ 获取页面策略配置数据"""
        self.samples = []
        strategyinfo = self.getelement(*StrategyPage._strategyinfo_locator) #策略信息模块
        self.memo = self.getchild(strategyinfo,*StrategyPage._memo_locator).text #memo
        strategydetails = self.getchilds(strategyinfo,*StrategyPage._details_locator) #策略配置列表
        for dl in strategydetails:
            parenttype = self.getchild(dl,*StrategyPage._span_loacator).text #配置大项
            ddlist = self.getchilds(dl,*StrategyPage._dd_locator) #配置子项
            for dd in ddlist:
                sample = [parenttype]
                childtypelist = self.getchilds(dd,*StrategyPage._span_loacator)
                childtype = childtypelist[0].text #子项代码和名称
                name,ticker= childtype.split(" ") #按空格划分
                sample += [ticker,name]
                sample.append(float(childtypelist[1].text[:-1])) #子项权重
                self.samples.append(sample)
        self.samples = sorted(self.samples)

the end!

原文地址:https://www.cnblogs.com/dinghanhua/p/10263325.html

时间: 2024-11-09 04:00:28

python UI自动化实战记录五:测试页面2-策略页的相关文章

python UI自动化实战记录三:pageobject-基类

脚本思路:使用pageobject模式,写一个basepage基类,所有页面的通用方法封装到基类中. 项目中的测试页面page1和page2都继承自basepage基类.可使用基类定义的方法.基类里会将webdriver和page合二为一,既将webdriver的操作改写成page的方法. 新建一个包pageclass > 分别新建basepage.page1.page2三个python文件. basepage里定义basepage基类,代码如下: #-*-coding:utf-8-*- "

(appium+python)UI自动化_07_UI自动化实例【拼多多搜索商品为例】

前言 初学UI自动化的小伙伴,在配置好appium+python自动化环境后,往往不知道如何下手实现自动化.小编在初期学习的时候也有这种疑惑,在此以拼多多搜索为实例,展示下appium是如何实现自动化的. 前提:已安装配置好appium+python自动化环境 一.连接手机启动app 1,连接手机 -手机USB连接电脑 -手机打开开发者模式.USB调试功能 2,基础信息配置 基础连接信息如下(以微信app为例): 'platformName': 操作平台'deviceName': 设备名称'pl

Python核心技术与实战——十五|Python协程

我们在上一章将生成器的时候最后写了,在Python2中生成器还扮演了一个重要的角色——实现Python的协程.那什么是协程呢? 协程 协程是实现并发编程的一种方式.提到并发,肯很多人都会想到多线程/多进程模型,这就是解决并发问题的经典模型之一.在最初的互联网世界中,多线程/多进程就在服务器并发中起到举足轻重的作用. 但是随着互联网的发展,慢慢很多场合都会遇到C10K瓶颈,也就是同时连接到服务器的客户达到1W,于是,很多代码就跑崩溃,因为进程的上下文切换占用了大量的资源,线程也顶不住如此巨大的压力

Selenium2学习-034-WebUI自动化实战实例-032-获取页面 body 大小

获取 body 元素大小的方法,非常简单,直接上码,敬请参阅! 1 /** 2 * Get body size 3 * 4 * @author Aaron.ffp 5 * @version V1.0.0: autoSeleniumDemo main.aaron.sele.core SeleniumCore.java getBrowserBodySize, 2015-8-8 14:12:49 Exp $ 6 * 7 * @return int[width,height] 8 */ 9 public

Selenium2学习-026-WebUI自动化实战实例-024-获取页面元素

非常简单的方法封装,就不啰嗦了,直接上码咯 ^_^ 1 /** 2 * Get element. It will be return null when there is not such element. 3 * 4 * @author Aaron.ffp 5 * @version V1.0.0: autoSeleniumDemo main.aaron.sele.core SeleniumCore.java getWebElement, 2015-7-31 13:56:59 Exp $ 6 *

Selenium2学习-028-WebUI自动化实战实例-026-获取页面元素值或者元素属性值

在自动化脚本编写过程中,经常需要获取页面元素的文本进行判断,以便对于不同的文本进行不同的处理.比如:很多的购物网站,加入购物车的按钮是有多个状态的(加入购物车.到货通知.暂不销售等),那么在实际的操作过程中,需要对此按钮对应的不同的值,执行相应的逻辑. 代码相对比较简单,在此不再详细说明了,直接上码,敬请各位小主参阅,若有不足之处,敬请大神指正,非常感谢! 获取元素值的源码如下所示: 1 /** 2 * @function Get text of element. It will be retu

python UI自动化之js操作

js处理iframe无需先切换到iframe上,再切回来操作.它可以在iframe上和主页面上来回自由操作. switch方法需要先切换到iframe上,操作完之后又的切换回来(很容易忘记切换回来),操作比较繁琐. 1.js处理富文本(富文本格式如禅道中的添加bug页面) 带iframe的元素,用js去操作contentWindow(相当于切换到iframe) body = "这里是通过js发的正文内容" # js处理iframe问题(js代码太长了,我分成两行了) js = 'doc

(appium+python)UI自动化_10_adb常用命令

前言 adb(Android Debug Bridge)工具是android-sdk里的一个工具,是一个命令行窗口,用于通过电脑端与模拟器或者真实设备交互.在app自动化测试过程中,有时要用到adb命令,但是每次都要百度感觉很是繁琐,故总结了下app自动化过程中几个常用的adb命令. adb常用命令 获取设备号 $ adb devices  下载apk 前提:需下载apk至电脑 $ adb install <电脑apk路径> 卸载apk $ adb uninstall <apk包名>

Selenium2学习-034-WebUI自动化实战实例-032-页面快照截图应用之三 -- 区域截图(专业版)

之前有写过两篇博文讲述了 WebUI 自动化测试脚本中常用的截图方法,敬请参阅如下所示链接: 浏览器显示区域截图 浏览器指定区域截图 那么当需要截取的区域不在浏览器显示窗口范围之内时,之前的方法显然无法满足,那么该如何操作呢? 刷新页面,相当于页面归位操作 判断要截取的区域范围与当前浏览器显示区域大小关系,若截取范围大于显示区域,则重置浏览器窗口大小 模拟鼠标操作滚动屏幕,使需要截取的区域显示到浏览器窗口 重新计算截取起始位置相对于当前显示区域的坐标 调用之前的截图方法截图 下面就以获取易迅网首