test1

coding=utf-8

‘’’
Created on 2020-4-28
@author: Yanghao
Project:基础类BasePage,封装所有页面都公用的方法,
定义open函数,重定义find_element,switch_frame,send_keys等函数。
在初始化方法中定义驱动driver,基本url,title
WebDriverWait提供了显式等待方式。
‘’’
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class BasePage(object):
“”"
BasePage封装所有页面都公用的方法,例如driver, url ,FindElement等
“”"

# 初始化driver、url、pagetitle等
# 实例化BasePage类时,最先执行的就是__init__方法,该方法的入参,其实就是BasePage类的入参。
# __init__方法不能有返回值,只能返回None
# self只实例本身,相较于类Page而言。
def __init__(self, selenium_driver, base_url, pagetitle):
    self.driver = selenium_driver
    self.base_url = base_url
    self.pagetitle = pagetitle

# 通过title断言进入的页面是否正确。
# 使用title获取当前窗口title,检查输入的title是否在当前title中,返回比较结果(True 或 False)
def on_page(self, pagetitle):
    return pagetitle in self.driver.title

# 打开页面,并校验页面链接是否加载正确
# 以单下划线_开头的方法,在使用import *时,该方法不会被导入,保证该方法为类私有的。
def _open(self, url, pagetitle):
    # 使用get打开访问链接地址
    self.driver.get(url)
    self.driver.maximize_window()
    # 使用assert进行校验,打开的窗口title是否与配置的title一致。调用on_page()方法
    assert self.on_page(pagetitle), u"打开开页面失败 %s" % url

# 定义open方法,调用_open()进行打开链接
def open(self):
    self._open(self.base_url, self.pagetitle)

# 重写元素定位方法
def find_element(self, *loc):
    #        return self.driver.find_element(*loc)
    #try:
        locator =loc[0:2]
        #超时时间默认10秒
        timeout=10
        if len(loc)==3:
            timeout=loc[2]
        # 确保元素是可见的。
        # 注意:以下入参为元组的元素,需要加*。Python存在这种特性,就是将入参放在元组里。
        #            WebDriverWait(self.driver,10).until(lambda driver: driver.find_element(*loc).is_displayed())
        # 注意:以下入参本身是元组,不需要加*
        WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located(locator))
        return self.driver.find_element(*locator)
    #except:
     #   print (u"%s 页面中未能找到 %s 元素" % (self, loc))

# 重写switch_frame方法
def switch_frame(self, loc):
    return self.driver.switch_to_frame(loc)

# 定义script方法,用于执行js脚本,范围执行结果
def script(self, src):
    self.driver.execute_script(src)

# 重写定义send_keys方法
def send_keys(self, loc, vaule, clear_first=True, click_first=True):
    try:
        loc = getattr(self, "_%s" % loc)  # getattr相当于实现self.loc
        if click_first:
            self.find_element(*loc).click()
        if clear_first:
            self.find_element(*loc).clear()
            self.find_element(*loc).send_keys(vaule)

    except AttributeError:
        print
        u"%s 页面中未能找到 %s 元素" % (self, loc)


# 获取元素text
def get_elements_text(self, loc):
    try:
        locator =loc[0:2]
        #超时时间默认10秒
        timeout=10
        if len(loc)==3:
            timeout=loc[2]
        # 确保元素是可见的。
        # 注意:以下入参为元组的元素,需要加*。Python存在这种特性,就是将入参放在元组里。
        #            WebDriverWait(self.driver,10).until(lambda driver: driver.find_element(*loc).is_displayed())
        # 注意:以下入参本身是元组,不需要加*
        WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located(locator))
        return self.driver.find_element(*locator).text
    except:
        return None

class BasetestPage(object):
def init(self, selenium_driver, base_url, pagetitle):
self.pagetitle = pagetitle

# 通过title断言进入的页面是否正确。
# 使用title获取当前窗口title,检查输入的title是否在当前title中,返回比较结果(True 或 False)
def get_classname(self):
    return

from robot.api import TestSuite
from robot.reporting import ResultWriter
from robot.conf import RebotSettings, RobotSettings
import sys
import argparse
import json
import os
import shutil
import time
from src.config import config
import traceback
from importlib import reload

添加脚本执行时的环境变量

from multiprocessing.pool import Pool

ROOT_DIR=os.path.dirname(os.path.abspath(file)).replace(’\’, ‘/’) #当前目录
LIBS_PATH=ROOT_DIR+"/…/…/" #lib库目录
sys.path.append(LIBS_PATH) #添加到系统变量,否则RF无法正确找到关键

reload(sys)
print(sys.path)

def robot_run_(run_list):
‘’’
测试计划执行
:param sql_file_case_list:
:param udf_params 用户定义的原始参数
:param xml_file_name
‘’’
result = []
for pagearr in run_list:
pagename=str(pagearr[0])
print(pagename)
pagefunlist=pagearr[1]
pagefunlist.sort() # 保证同一个文件夹下文件有序

    suite_xml = config.REPORT_PATH_DETAIL  + pagename + ".xml"

    result.append(suite_xml)

    # for fun  in pagefunlist:
    #      pagefunname=fun[0]
    #      pageparam=fun[1]
    #      print(pagefunname)
    #      print(pageparam)
    suite_run(suite_xml,pagename,pagefunlist)

return  result

def suite_run(suite_xml,page_obeject,funlist):
‘’’
构建suite_list
:param suite_xml:报告目录
:param page_obeject:页面类地址
:param case_list:
:return:
‘’’

#创建suite
suite_name=suite_xml.split(".")[-2]

new_suite = TestSuite(suite_name)
new_suite.resource.imports.library(page_obeject)
for fun in funlist:
    funname=fun[0]
    print("funname :" +funname)
    #print("funlist : "+len(funlist))
    #创建用例
    for sql_file in fun[1]:
        #
        case_name=sql_file[0]
        case_par=sql_file[1]
        print(case_name)
        new_case = new_suite.tests.create(case_name, tags=None)
        #new_case.tag("sss"")
         # kw处理
        new_case.keywords.create(funname, args=case_par, assign=("${res}",))
        new_case.keywords.create("should be true", args=["${res}"])

#执行suite
try:
    #执行
    settings = RobotSettings(output=suite_xml,consolewidth=200)
    new_suite.run(settings)
    return True
except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    traceback.print_exception(exc_type, exc_value, exc_traceback, limit=10, file=sys.stdout)
    return False

def make_report(log_dir,xml_list,log_level=‘TRACE’):
log_file=log_dir+‘rebot_log.html’
report_file=log_dir+‘rebot_report.html’
if os.path.exists(log_file):
os.remove(log_file)
if os.path.exists(report_file):
os.remove(report_file)
for file in xml_list:#检查日志文件是否存在,并且是xml文件,如果不是,则移除并打印日志
if os.path.isfile(file) and file.split(’.’)[-1].lower() == ‘xml’:
continue
else:
print(“sss :”+file)
xml_list.remove(file)
settings = RebotSettings(log=log_file,report=report_file,loglevel=log_level,name=“rebot”)
try:

    ResultWriter(*xml_list).write_results(settings=settings)
except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    traceback.print_exception(exc_type, exc_value, exc_traceback, limit=1, file=sys.stdout)

if name == ‘main’:
allpo = []
po1 = [‘gitRepo.dbaservices.PageObject.LoginPageTest.LoginPageTest’]
po2 = [‘gitRepo.dbaservices.PageObject.CreateDatabaseTest.CreateDatabaseTest’]

func1 = ['login']
params = [['简单模式登录',['172.22.7.33:10000']]]

func1.append(params)


funlist=[]
funlist.append(func1)
po1.append(funlist)




func32 = ['createData']
params32 = [['测试已存在',['Database already exists','zz4']],['测试成功',['Create database success','ritian66']],['测试失败',['Create database success','zz4']]]

func32.append(params32)
funlist2 = []
funlist2.append(func32)
po2.append(funlist2)

allpo.append(po1)
allpo.append(po2)
print("-------------------------")
print(allpo)
print("-------------------------")
kafka=robot_run_(allpo)
print(allpo)
make_report('',kafka)

#继承BasePage类
import time

from selenium.webdriver.common.by import By

from Basepage import BasePage
from src.tools.InitWebdriver import InitWebdriver

class CreateDatabase(BasePage):
# 定位器,通过元素属性定位元素对象
# username_loc = (By.ID, ‘kw’, 10)
# password_loc = (By.NAME, ‘password’)
# submit_loc = (By.ID, ‘dologin’)
# span_loc = (By.CSS_SELECTOR, “div.error-tt>p”)
b_newdatabase=(By.XPATH,’//[@id=“root”]/section/div/div[3]/section/div/div/main/div/div/main/div[1]/div[2]/div/a/button’)
i_databasename = (By.XPATH, '//
[@id=“root”]/section/div/div[3]/section/div/div/main/div/main/div/div[3]/div[1]/div[2]/div[2]/input’)

t_submit=(By.XPATH,'//*[@id="root"]/section/div/div[3]/section/div/div/main/div/main/div/div[1]/div/div/div/div/div[1]/div[4]')
b_preview = (By.XPATH, '//*[@id="root"]/section/div/div[3]/section/div/div/main/div/main/div/div[3]/div[4]/div[2]/button[1]')
b_submit=(By.XPATH, '//*[@id="root"]/section/div/div[3]/section/div/div/main/div/main/div/div[3]/div[4]/div[2]/button[2]')
a_index_page = (By.XPATH, '//*[@id="root"]/section/div/div[1]/div/ul/li[2]/span[2]/span[2]/div/a', 10)

def click_b_newdatabase(self):
    self.find_element(*self.b_newdatabase).click()

def input_databasename(self, databasename):
    #    self.find_element(*self.username_loc).clear()
    self.find_element(*self.i_databasename).send_keys(databasename)
def submit_sql(self):

    self.find_element(*self.t_submit).click()
    time.sleep(1)
    self.find_element(*self.b_preview).click()
    time.sleep(3)
    self.find_element(*self.b_submit).click()

def go_back_indexpage(self):
    self.find_element(*self.a_index_page).click()

def judge_result(self, messages):
    loc_text = (By.XPATH,"//*[contains(text(),'%s')]"%messages)
    text=self.get_elements_text(loc_text)
    if text is None:
        print("not found")
        return  False
    else:
        print(loc_text)
        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值