seleniumA
import os
import unittest
import HTMLTestRunner # 仅提供html文字报告
import STHTMLTestRunner # 可提供带html的饼图及截图报告
# 用例路径
case_path = os.path.join(".\\ljk_app")
def all_case():
runner1 = unittest.defaultTestLoader.discover(case_path,
pattern='test_*.py',
top_level_dir=None)
print(runner1)
return runner1
if __name__ == "__main__":
# 报告存放路径
report_path = os.path.join(".\\report", "report.html")
fp = open(report_path, "wb")
runner2 = STHTMLTestRunner.HTMLTestRunner(stream=fp,
title=U'自动化测试报告',
description=u'用例执行情况:')
# runner2 = unittest.TextTestRunner()
runner2.run(all_case())
fp.close()
2
from selenium import webdriver
from common.Excel import ExcelUtil
from common.logger import Log
import ddt
import unittest
import time
import warnings
log = Log()
warnings.simplefilter("ignore", ResourceWarning)
@ddt.ddt
class TestLogin(unittest.TestCase):
@classmethod
def setUp(cls):
log.info('----测试开始------')
cls.driver = webdriver.Firefox()
cls.driver.get("https://192.168.3.56/login")
cls.driver.maximize_window()
cls.driver.find_element('xpath', '//*[@id="account"]').send_keys('wangping')
cls.driver.find_element('xpath', '//*[@id="password"]').send_keys('000000')
cls.driver.find_element('xpath', '//*[@id="login_btn"]').click()
cls.driver.find_element('xpath', '//*[@id="loginNavigateBox"]/div[2]/div[2]/div[2]/div[2]/div[2]').click()
time.sleep(3)
cls.driver.find_element('xpath', '//*[@id="app"]/div/div[2]/div[2]/aside/div[1]/div/div/ul/li[2]/div').click()
cls.driver.find_element('xpath', '//*[@id="sub_menu_1_$$_sub_Cssd-popup"]/li[1]/span').click()
cls.driver.find_element('xpath', '//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[2]/div/div/div[2]/div[3]/div/span').click()
cls.driver.find_element('xpath', '//*[@id="rc_select_2"]').click()
cls.driver.find_element('xpath','/html/body/div[10]/div/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div[1]/div/div/div/div/span[2]').click()
cls.driver.find_element('xpath', '/html/body/div[10]/div/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div[2]/div/div/div[2]/div[1]/div[2]/table/tbody/tr[1]/td[6]/div/div/div[1]/span[1]/span').click()
cls.driver.find_element('xpath', '/html/body/div[10]/div/div[2]/div/div/div[2]/div/div[2]/div/div[3]/div[2]/div/div/div[2]/div[1]/div[1]/table/thead/tr/th[1]/div[1]/span').click()
cls.driver.find_element('xpath', '/html/body/div[10]/div/div[2]/div/div/div[1]/div/div/div/div[2]/button/span').click()
cls.driver.find_element('xpath', '//*[@id="app"]/div/div[2]/div[2]/div/div[2]/div/div[2]/div/div/div[2]/div[1]/div/div/div/div').click()
def test_login(self):
pass
@classmethod
def tearDown(cls):
log.info('------测试结束------')
cls.driver.quit()
if __name__ == "__main__":
unittest.main()
from rediscluster import StrictRedisCluster
import json
def query(key):
startup_nodes = [
{"host": "192.168.0.111", "port": 6379},
{"host": "192.168.0.112", "port": 6379},
{"host": "192.168.0.113", "port": 6379},
{"host": "192.168.0.114", "port": 6379},
{"host": "192.168.0.115", "port": 6379},
{"host": "192.168.0.116", "port": 6379}]
rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True,
skip_full_coverage_check=True) # skip_full_coverage_check 跳过检测配置
print(rc.type(key))
print(rc.ttl(key))
if rc.type(key) == 'hash':
t = rc.hgetall('%s' % str(key))
print(json.dumps(t, indent=2, ensure_ascii=False))
elif rc.type(key) == 'string':
t = rc.get('%s' % str(key))
print(json.dumps(json.loads(t), indent=1, ensure_ascii=False))
elif rc.type(key) == 'list':
t = rc.lrange('%s' % str(key), 0, -1)
print(json.dumps(tuple(t), indent=2, ensure_ascii=False))
print(type(t))
elif rc.type(key) == 'set':
t = rc.smembers('%s' % str(key))
print(t)
elif rc.type(key) == 'zset':
t = rc.zrange('%s' % str(key), 0, -1, 0, -1)
print(t)
else:
print('暂不支持查询的类型')
if __name__ == '__main__':
key = 'th:pk:daily:room:result:1713'
query(key)
# coding:utf-8
import xlrd
import json
class ExcelUtil():
def __init__(self, excelPath, sheetName):
self.data = xlrd.open_workbook(excelPath)
self.table = self.data.sheet_by_name(sheetName)
# 获取第一行作为key值
self.keys = self.table.row_values(0)
# 获取总行数
self.rowNum = self.table.nrows
print(u"总行数:", self.rowNum)
# 获取总列数
self.colNum = self.table.ncols
print(u"总列数:", self.colNum)
def dict_data(self):
if self.rowNum <= 1:
print("总行数小于1")
else:
r = []
j = 1
for i in range(self.rowNum - 1):
s = {}
# 从第二行取对应values值
values = self.table.row_values(j)
for x in range(self.colNum):
s[self.keys[x]] = values[x]
r.append(s)
j += 1
return r
if __name__ == "__main__":
filePath = "F:\\Selenium_qmflh_app\\excel\\test.xlsx"
sheetName = "Sheet1"
data = ExcelUtil(filePath, sheetName).dict_data()
# print(data)
# qq = []
# for i in data:
# qq.append(i['qq'])
# print(data)
#!/user/bin/env python
# -*-coding:utf-8 -*-
import logging, time, os
# 日志保存本地的路径
log_path = "D:\\Selenium_ljk_app\\Logger"
class Log:
def __init__(self):
# 文件的命名
self.logname = os.path.join(log_path, '%s.log' % time.strftime('%Y_%m_%d'))
self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)
# 日志输出格式
self.formatter = logging.Formatter('[%(asctime)s] - %(filename)s] - %(levelname)s: %(message)s')
def __console(self, level, message):
# 创建一个FileHandler,用于写到本地
fh = logging.FileHandler(self.logname, 'a', encoding='utf-8') # 这个是python3的
fh.setLevel(logging.DEBUG)
fh.setFormatter(self.formatter)
self.logger.addHandler(fh)
# 创建一个StreamHandler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(self.formatter)
self.logger.addHandler(ch)
if level == 'info':
self.logger.info(message)
elif level == 'debug':
self.logger.debug(message)
elif level == 'warning':
self.logger.warning(message)
elif level == 'error':
self.logger.error(message)
# 这两行代码是为了避免日志输出重复问题
self.logger.removeHandler(ch)
self.logger.removeHandler(fh)
# 关闭文件
fh.close()
def debug(self, message):
self.__console('debug', message)
def info(self, message):
self.__console('info', message)
def warning(self, message):
self.__console('warning', message)
def error(self, message):
self.__console('error', message)
if __name__ == "__main__":
log = Log()
log.info("---测试开始----")
log.warning("----测试结束----")
import pymysql
import os
def mysql_connect(sql):
# 连接mysql数据库
try:
# conn = pymysql.connect(host="134.175.103.124", port=3306, user="wapn", password="123456", db="czth")
config = {
'host': '192.168.0.36',
'port': 3306,
'user': 'root',
'password': 'rTo0CesHi2018Qx',
'db': 'xxxr',
'charset': 'utf8',
'cursorclass': pymysql.cursors.DictCursor
}
conn = pymysql.connect(**config)
cur = conn.cursor()
rr = cur.execute(sql)
print(rr)
conn.commit()
except Exception as a:
print("数据库连接异常:%s" % a)
if __name__ == "__main__":
sql = 'select * from user_info'
mysql_connect(sql)
# coding:utf-8
import cx_Oracle
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
u'''Oracle数据库相关操作
连接数据库名称如:xxx
查询一组数据:oracle_getrows
查询某个字段对应的字符串:oracle_getstring
执行sql语句:oracle_sql
关闭oracle连接:oracle_close
'''
dbname = {"user": "czth_sales",
"pwd": "123456",
"dsn": "192.168.0.136:1521/ORCL136"}
class OracleUtil():
def __init__(self):
''' 连接池方式'''
self.db_info = dbname
self.conn = OracleUtil.__getConnect(self.db_info)
@staticmethod
def __getConnect(db_info):
''' 静态方法,从连接池中取出连接'''
try:
con = cx_Oracle.connect(db_info['user'], db_info['pwd'], db_info['dsn'])
return con
except Exception as a:
print("数据库连接异常:%s" % a)
def oracle_getrows(self, sql):
''' 执行查询sql'''
try:
cursor = self.conn.cursor()
try:
cursor.execute(sql)
rows = cursor.fetchall()
return rows
except Exception as a:
print("执行sql出现异常:%s" % a)
finally:
cursor.close()
except Exception as a:
print("数据库连接异常:%s" % a)
def oracle_getstring(self, sql):
''' 查询某个字段的对应值'''
rows = self.oracle_getrows(sql)
if rows != None:
for row in rows:
for i in row:
return i
def oracle_sql(self, sql):
''' 执行sql语句'''
try:
cursor = self.conn.cursor()
try:
cursor.execute(sql)
except Exception as a:
print("执行sql出现异常:%s" % a)
finally:
cursor.close()
except Exception as a:
print("数据库连接异常:%s" % a)
def orcle_close(self):
''' 关闭orcle连接'''
try:
self.conn.close()
except Exception as a:
print("数据库关闭时异常:%s" % a)
if __name__ == "__main__":
oracl = OracleUtil()
sql = '''select t.* from th_wx_payment t
where t.create_time =( select max(t.create_time) from th_wx_payment t)
'''
r = oracl.oracle_getrows(sql)
# print(r)
# r2 = json.dumps(r, default=lambda obj: obj.__dict__, sort_keys=True, indent=4)
# print(r2)
# oracl.orcle_close()
r1 = ['user_id', 'ext_order_no']
print(r[0])
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# -----------1、发件相关的参数---------------
smtpserver = "smtp.163.com" # 发件服务器
port = 0 # 端口
sender = "m18581893850@163.com" # 发件人
psw = "VJZPKJQWYTEQUFJN" # 密码
receiver = "wangping@100bm.com" # 收件人
# receiver = ['639889832@qq.com', '727593930@qq.com'] # 群发用列表
# -----------2、编辑邮件内容---------------
# # -----------2、1只发送邮件---------------
# subject1 = "测试用例报告"
# body = '<p>浏览器打开http://134.175.103.124/rhfg.html</p>' # 邮件正文用html格式
# msg = MIMEText(body, "html", "utf-8")
# msg['from'] = sender
# msg['to'] = receiver
# msg['subject'] = subject1
# -----------发送附件-------------------
# 读文件
subject2 = "发送Appium测试报告html"
file_path = "..\\report\\report.html"
with open(file_path, "rb") as fp:
mail_body = fp.read()
msg = MIMEMultipart()
msg["from"] = sender # 发件人
msg["to"] = receiver # 收件人
# msg["to"] = ";".join(receiver) # 群发收件人
msg["subject"] = subject2 # 主题
# 正文
body = MIMEText(mail_body, "html", "utf-8")
msg.attach(body)
# 附件
att = MIMEText(mail_body, "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
att["Content-Disposition"] = 'attachment; filename="test_report.html"'
msg.attach(att)
# ----------3、发送邮件---------------------
try:
smtp = smtplib.SMTP()
smtp.connect(smtpserver) # 连服务器
smtp.login(sender, psw)
except:
smtp = smtplib.SMTP_SSL(smtpserver, port)
smtp.login(sender, psw) # 登录
smtp.sendmail(sender, receiver, msg.as_string()) # 发送
smtp.quit() # 关闭
# 封装一个滑动方法
class Swipe:
# def __init__(self):
# pass
def swipeUp(driver, t=500, n=1):
l = driver.get_window_size()
x1 = l['width'] * 0.5 # 起始x坐标
y1 = l['height'] * 0.75 # 起始y坐标
y2 = l['heigth'] * 0.25 # 终点y坐标
for i in range(n):
driver.swipe(x1, y1, x1, y2, t)
def swipeDown(driver, t=500, n=1):
l = driver.get_window_size()
x1 = l['width'] * 0.5 # 起始x坐标
y1 = l['height'] * 0.25 # 起始y坐标
y2 = l['height'] * 0.75 # 终点y坐标
for i in range(n):
driver.swipe(x1, y1, x1, y2, t)
def swipeLeft(driver, t=500, n=1):
l = driver.get_window_size()
x1 = l['width'] * 0.75 # 起始x坐标
y1 = l['height'] * 0.5 # 起始y坐标
x2 = l['width'] * 0.05 # 终点y坐标
for i in range(n):
driver.swipe(x1, y1, x2, y1, t)
def swipeRigth(driver, t=500, n=1):
l = driver.get_window_size()
x1 = l['width'] * 0.05 # 起始x坐标
y1 = l['height'] * 0.5 # 起始y坐标
x2 = l['width'] * 0.75 # 终点y坐标
for i in range(n):
driver.swipe(x1, y1, x2, y1, t)
if __name__ == "__main__":
print(driver.get_window_size())
# coding:utf-8
from kazoo.client import KazooClient
import json
import requests
def login():
# 登录获取jwt
url1 = 'http://192.168.106.211:8100/sys/sso/loginon?method=sso.login&systemno=CZTH?'
payload1 = {'username': 'admin',
'password': '123456',
'validcode': '999999'}
r = requests.post(url1, data=payload1).cookies
# print(r['jwt'])
# 链接zk查看DebugSession
zk = KazooClient(hosts='192.168.0.104:2181') # 如果是本地那就写127.0.0.1
zk.start() # 与zookeeper连接
# node = zk.get_children('/wapn/test/')
data = {"RecvURL": "http://user.100bm.cn/activityRecv/%s?activityId=%d&destoken=%s",
"PacketPoolInsert": "https://xiaowei.100bm.cn/packet/pool/insert",
"CbsQcodeUrl": "wxapp.qrcode.request#cbs_core.cbs",
"SaveImgUrl": "/home/xia/gopath/src/czth/adminservice/czthadmin/web/dist/qrcode/%s",
"ImageUrl": "/qrcode/",
"FileUrl": "file",
"DomainUrl": "http://192.168.136.141:8000",
"ImageManaUrl": "http://192.168.136.141:8000/image/",
"ResetLandUrl": "/user/delete/session",
"AdocAppId": "wx8290550a632226b3",
"SSOPath": "sso.vps",
"IsDebug": bool('true'),
"DebugSession": "",
"KingCardDeliveryUrl": "kingcard.order.delivery#czthservice.czthserver",
"KingCardRefundUrl": "kingcard.order.refund#czthservice.czthserver",
"OrderRechargeUrl": "/order/vis/delivery#czthservice.czthserver",
"FileUploadPath": "/home/xia/go/files/"}
print('zk')
data['DebugSession'] = r['jwt']
zk.set('/czthadmin/var/conf/czthadmin', bytes(str(json.dumps(data, indent=2)), encoding='utf-8'))
print(json.dumps(data, indent=2))
login()