selenium自动化测试例子:
1.安装selenium
pip install selenium
若安装成功之后,在命令行执行 python -m pydoc -p 8080 (-p 是指定端口号) 访问http://127.0.0.1:8888 在页面的最下面site-packages 一栏 会多出一个selenium项,当前python下安装的包和api都能在这边查得到。
2.下载谷歌浏览器驱动(根据浏览器版本)
下载地址:http://chromedriver.storage.googleapis.com/index.html
3.开始项目
日志文件:vlog.py
def record(level, messages):
import logging
logger = logging.getLogger()
logpath = ""
logname = "info.log"
logfile = logpath+logname
if not logger.handlers:
logger.setLevel(logging.ERROR)
w_log = logging.FileHandler(logfile)
formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s: %(message)s')
w_log.setFormatter(formatter)
logger.addHandler(w_log)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
ch.setFormatter(formatter)
logger.addHandler(ch)
if level.lower() == "info":
logger.info(messages)
elif level.lower() == "debug":
logger.debug(messages)
elif level.lower() == "error":
logger.error(messages)
else:
logger.info(messages)
配置文件config.py
# -*- coding:utf-8 -*-
LOGIN = {
'url': 'https://10.21.147.36:7010/xxx/login.html#/',
'user': 'test',
'pass': 'test123123',
'chrome_path': 'D:\d3\chromedriver.exe',
'account_input': '//input[@type="text"][@class="ivu-input"]',
'pass_input': '//input[@type="password"][@class="ivu-input"]'
}
DATA_SOURCE = {
'data_source_user': {
#数据源用户
'mysql': 'root',
'oracle': 'ibdea',
'mppdb': 'dev',
'hive': 'test',
'hdfs': 'test',
'hbase': 'test'
},
'data_source_pass': {
#数据源用户密码
'mysql': 'test123',
'oracle': 'test123',
'mppdb': 'test123'
},
#数据源jdbc
'data_source_jdbc': {
'mysql': 'jdbc:mysql://100.101.19.166:3306/app',
'oracle': 'jdbc:oracle:thin:@100.101.153.41:1521/ora',
'mppdb': 'jdbc:postgresql://100.100.150.166:25308/dev_db'
},
#新建数据源名称
'data_source_name': {'mysql': 'test_mysql',
'oracle': 'test_ora',
'mppdb': 'test_mpp',
'hive': 'test_hive',
'hdfs': 'test_hdfs',
'hbase': 'test_hbase'
},
# 从card进入数据源管理
'data_source_card': '//div[@class="container"]/div/div[@class="index-body"]/div/div/div/a',
# 数据源新增按钮
'data_source_add_btn': '//div[@class="search"]/div/button',
# 文本框
'data_source_input': '//div[@class="ivu-form-item-content"]/div/input',
# 数据源类型选择栏
'data_source_type_span': '//div[@class="ivu-select-selection"]/span',
# 选择类型列表
'data_source_type_li': '//div[@class="ivu-select-dropdown"]/ul/li',
# 按钮
'btn': '//div[@class="ivu-form-item"]/div[@class="ivu-form-item-content"]/button',
}
DATA_TABLE = {
}
autowebtest.py
# -*- coding:utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
from config import LOGIN, DATA_SOURCE
from vlog import record as log
import unittest
from time import sleep
class AutoTest(object): #unittest.TestCase
def __init__(self):
self.chromedriver = LOGIN['chrome_path']
self.browser = webdriver.Chrome(self.chromedriver)
self.browser.implicitly_wait(120)
self.browser.maximize_window()
self.data_source_name = []
def login(self):
self.browser.get(LOGIN['url'])
WebDriverWait(self.browser,10).until(
lambda the_browser: self.browser.find_element_by_xpath(LOGIN['account_input']).is_displayed())
self.browser.find_element_by_xpath(LOGIN['account_input']).send_keys(LOGIN['user']+Keys.TAB)
self.browser.find_element_by_xpath(LOGIN['pass_input']).send_keys(LOGIN['pass']+Keys.ENTER)
self.browser.forward()
def choose_menu_card(self, to_menu):
WebDriverWait(self.browser, 10).until(
lambda the_browser: self.browser.find_element_by_id('menu-iframe').is_displayed())
self.browser.switch_to.frame("menu-iframe")
cards = self.browser.find_elements_by_xpath(
DATA_SOURCE['data_source_card'] + "/div/div/div[@class='item-title']")
for i in cards:
if i.text == to_menu:
i.click()
break
#获取下拉列表元素
def get_li_text(self,database="", authuser="", type="common"):
span = self.browser.find_elements_by_xpath(DATA_SOURCE['data_source_type_span'])
for i in span:
if i.text == u'请选择数据库类型':
i.click()
lis = self.browser.find_elements_by_xpath(DATA_SOURCE['data_source_type_li'])
for i in lis:
if database == str(i.text).lower():
i.click()
if type != 'common':
sleep(1)
for i in self.browser.find_elements_by_xpath(DATA_SOURCE['data_source_type_span']):
if i.text == u'请选择':
i.click()
sleep(1)
for i in self.browser.find_elements_by_xpath(DATA_SOURCE['data_source_type_li']):
if authuser == str(i.text).lower():
i.click()
def judge_opretion_status(self,message):
while True:
if self.browser.find_element_by_xpath('//div[@class="ivu-notice"]').text == message:
break
def search_data_source(self,keys='', times=0):
if times != 0:
self.browser.find_element_by_xpath('//input[@class="ivu-input"][@placeholder="搜索"]').send_keys(Keys.ENTER)
else:
self.browser.find_element_by_xpath('//input[@class="ivu-input"][@placeholder="搜索"]').clear()
self.browser.find_element_by_xpath('//input[@class="ivu-input"][@placeholder="搜索"]').send_keys(keys + Keys.ENTER)
def drop_data_source(self):
#['zwwtest_mysql','zwwtest_ora','zwwtest_mpp','zwwtest_hive','zwwtest_hdfs','zwwtest_hbase']
for name in self.data_source_name:
print name
self.search_data_source(name)
#获取三种操作:删除、修改、测试连接元素
ops = self.browser.find_elements_by_xpath('//div[@class="ivu-table-cell"]/div[@class="datasource-actions"]/a')
for op in ops:
# print op.text
if op.text == u'删除':
op.click()
self.browser.find_element_by_xpath('//div[@class="ivu-modal-confirm"]/div/button[@class="ivu-btn ivu-btn-primary ivu-btn-large"]/span').click()
self.judge_opretion_status(u'删除成功')
break
def test_data_source(self):
log('info',u'开始数据源测试.')
self.login()
try:
#进入数据源管理
self.choose_menu_card(u'数据源管理')
for database_type in ('mysql', 'oracle', 'mppdb', 'hive', 'hdfs', 'hbase'):
sleep(2)
log('info',u'开始创建%s数据源'%database_type)
self.data_source_name.append(DATA_SOURCE['data_source_name'][database_type])
self.browser.find_element_by_xpath(DATA_SOURCE['data_source_add_btn']).click()
self.browser.find_element_by_xpath(DATA_SOURCE['data_source_input']+'[@placeholder="请输入数据源名称"]').send_keys(DATA_SOURCE['data_source_name'][database_type])
if database_type in ('hive', 'hdfs', 'hbase'):
self.get_li_text(database_type , authuser=DATA_SOURCE['data_source_user'][database_type], type='hhh')
if database_type == 'hbase':
self.browser.find_element_by_xpath(DATA_SOURCE['data_source_input']+"[@placeholder='请输入命名空间']").send_keys("default")
elif database_type == 'hive' :
self.browser.find_element_by_xpath(DATA_SOURCE['data_source_input']+"[@placeholder='请输入数据库名']").send_keys("default")
else:
self.browser.find_element_by_xpath(
DATA_SOURCE['data_source_input'] + "[@placeholder='请输入hdfs路径']").send_keys("/zww/tmp/")
else:
self.get_li_text(database_type)
self.browser.find_element_by_xpath(DATA_SOURCE['data_source_input']+'[@placeholder="请输入jdbc连接串"]').clear()
self.browser.find_element_by_xpath(DATA_SOURCE['data_source_input']+'[@placeholder="请输入jdbc连接串"]'
).send_keys(DATA_SOURCE['data_source_jdbc'][database_type] + Keys.TAB)
self.browser.find_element_by_xpath(DATA_SOURCE['data_source_input']+'[@placeholder="请输入用户名"]'
).send_keys(DATA_SOURCE['data_source_user'][database_type] + Keys.TAB)
self.browser.find_element_by_xpath(DATA_SOURCE['data_source_input']+'[@placeholder="请输入密码"]'
).send_keys(DATA_SOURCE['data_source_pass'][database_type] + Keys.TAB)
btns = self.browser.find_elements_by_xpath(DATA_SOURCE['btn']+'/span')
for i in btns:
if i.text == u'测试连接':
i.click()
self.judge_opretion_status(u'连接成功')
break
for i in btns:
if i.text == u'保存':
i.click()
break
self.search_data_source('zww')
sleep(2)
self.drop_data_source()
except Exception as e:
print e
def click_data_table_tree(self, child_dir=""):
tree = self.browser.find_elements_by_xpath('//div[@class="tree-content"]/div[@class="ivu-tree"]/ul')
if tree:
for i in tree:
if i.text == child_dir:
i.click()
break
elif child_dir == "":
# print i.text
i.click()
break
def add_child_dir(self):
self.browser.find_element_by_xpath('//div[@class="header-button-group-main"]/div'
'/button[@title="添加子目录"]').click()
self.browser.find_element_by_xpath('//div[@class="ivu-form-item-content"]/div/'
'input[@placeholder="请输入目录名称,可以输入中文,最多可输入55个字符"]'
).send_keys('zwwtest'+Keys.ENTER)
sleep(1)
def add_data_table(self):
#获取按钮:刷新、新建表、导入外部表
btns = self.browser.find_elements_by_xpath('//div[@class="header-button-group"]/button')
for i in btns:
if i.text == u'新建表':
i.click()
sleep(1)
break
data_source_div = self.browser.find_element_by_xpath('//div[@class="ivu-select-selection"]')
data_source_div.click()
sleep(1)
data_source_lis = self.browser.find_elements_by_xpath('//div[@class="ivu-select-dropdown"]/ul/li')
for i in data_source_lis:
if i.text == "xch_mysql":
i.click()
break
table_name_input = self.browser.find_element_by_xpath('//div[@class="ivu-form-item-content"]/div/input[@placeholder="请输入表名。表名名称只能包含英文字母、数字和下划线,且以英文字母开头。"]')
table_name_input.send_keys('zwwtest_mysql')
netx_btn = self.browser.find_element_by_xpath('/div[@class="button-group"]/button')
if netx_btn.text == u'下一步':
netx_btn.click()
def test_data_table(self):
# self.browser.get('https://10.21.147.36:7010/ide/iam.html#/home')
# 进入数据表
self.choose_menu_card(u'数据表管理')
self.click_data_table_tree()
self.add_child_dir()
self.click_data_table_tree(child_dir='zwwtest')
self.add_data_table()
# ActionChains(self.browser).double_click().perform()
def test(self):
# unittest.main()
self.login()
self.test_data_table()
# print self.browser.find_element_by_xpath('//div/div[@class="datasource-actions"]').text
if __name__ == "__main__":
try:
test = AutoTest()
test.test_data_source()
# test.test_data_table()
except BaseException as e:
print e