def login_production(self): """selenium+chromeheadless获取Token""" logger = Logger.get_logger() config = ReadConfig() # 获取配置 vcc = config.get_userinfo("vcc").split(",") username = config.get_userinfo("username").split(",") password = config.get_userinfo("password") production_url = config.get_url("production_url") day = time.strftime("%d") chrome_options = Options() chrome_options.add_argument('--headless') driver = webdriver.Chrome(options=chrome_options) driver.implicitly_wait(10) driver.get(production_url) driver.find_element_by_id("vcc").send_keys(vcc[0]) # 登录 driver.find_element_by_id("username").send_keys(username[0]) driver.find_element_by_id("password").send_keys(password) driver.find_element_by_id('btn').click() manage_cookie = driver.get_cookie('manage_access_token') driver.quit() manage_cookies = json.dumps(manage_cookie) config.update_token("day", day) # 写入日期和token config.update_token("manage_access_token", manage_cookies) logger.info("获取线上manage_access_token到配置文件")
def __init__(self): self.data = ReadConfig() self.host = self.data.get_db("host") self.user = self.data.get_db("user") self.password = self.data.get_db("password") self.database = self.data.get_db("database") self.port = self.data.get_db("port")
class Clean: def __init__(self): self.words = ReadConfig() def dataclean(self, datas): d_list = [] noword = self.words.get_input("noword") word = self.words.get_input("word") for data in datas: data = data[0] #转换为字符串 try: data1 = data.replace("(", "(").replace(")", ")") # 全角括号替换为半角符号 l = len(data1) #字符长度 m = len(re.findall(u'[\u0800-\u4e00]+', data1)) # 匹配日文,至少两个日文 n = len(re.findall(u'[\u4e00-\u9fa5]+', data1)) # 匹配中文 if l <= 4 or m >= 2 or n == 0: data1 = '' data_all = (data, data1) d_list.append(data_all) else: data1 = re.sub(r'公司.*$', '公司', data1) # 删去公司后面 data1 = re.sub(r';.*$', '', data1) # 删去;后面的内容 data1 = re.sub(r'\(原.*', '', data1) # 删去(原后面的内容 data1 = re.sub(r'/.*', '', data1) # 删去/后面的内容 # 补整 data1 = re.sub(r'有$', '有限公司', data1) data1 = re.sub(r'有限公$', '有限公司', data1) data1 = re.sub(r'有限责$', '有限责任公司', data1) data1 = re.sub(r'有限责任公$', '有限责任公司', data1) data1 = re.sub(r'有限$', '有限公司', data1) data1 = re.sub(r'股份有$', '股份有限公司', data1) # 正则匹配公司名称中不包括->'公司,集团,制药'关键字 name_l = len(re.findall(noword, data1)) name_2 = len(re.findall(word, data1)) if name_l > 0: data1 = '' data_all = (data, data1) d_list.append(data_all) else: if name_2 == 0: data1 = '' data_all = (data, data1) d_list.append(data_all) else: data1 = re.sub(u'[^\u4e00-\u9fa5\(\)]+', '', data1) #去除不包括中文和半角括号的其他一切字符 data_all = (data, data1) d_list.append(data_all) except Exception as e: print('警告->字符类型中含有None类型') data1 = '' data_all = (data, data1) d_list.append(data_all) continue return d_list
def getSSHConnection(self): ssh = paramiko.SSHClient() key = paramiko.AutoAddPolicy() ssh.set_missing_host_key_policy(key) rc = ReadConfig() host, port, user, password, timeout = rc.readDockerweb() ssh.connect(host, int(port), user, password, timeout=int(timeout)) return ssh
def test_login(self,case_id, case_name, precondition, method, url, request_data, expect_result, test_result): config = ReadConfig() fxchat_test_host = config.get_host("hostname") config_request = ConfigRequest() res = config_request.post_method(fxchat_test_host + url, data=request_data, headers=headers) # content = res.json() if res.status_code !=200: assert not True else: if res['message'] == expect_result: assert True # self.assertEqual(content['message'], expect_result)
def __init__(self, *args, **kwargs): config = ReadConfig().getConfig() self._dburl = "mysql+pymysql://" + config['mysql'][ 'user'] + ":" + config['mysql']['passwd'] + "@" + config['mysql'][ 'host'] + ":3306/" + config['mysql']['db'] + "?charset=utf8mb4" self._conn = records.Database(self._dburl) self._writeEngine = create_engine(self._dburl, echo=True)
class MyMySQL: def __init__(self): self.conn = None self.cur = None self.data = ReadConfig() self.conn_mysql() def __enter__(self): return self def conn_mysql(self): '''连接数据库''' host = self.data.get_db("MySQL", "host") user = self.data.get_db("MySQL", "user") password = self.data.get_db("MySQL", "password") db = self.data.get_db("MySQL", "db") port = self.data.get_db("MySQL", "port") charset = self.data.get_db("MySQL", "charset") self.conn = pymysql.connect(host=host, user=user, password=password, port=int(port),db=db,charset=charset) self.cur = self.conn.cursor() def execute_sql(self, sql, data=None): self.conn_mysql() if data: self.cur.execute(sql, data) else: self.cur.execute(sql) self.conn.commit() def search(self, sql): self.conn_mysql() self.cur.execute(sql) return self.cur.fetchall() def __exit__(self, exc_type, exc_val, exc_tb): self.cur.close() self.conn.close() print("mysql 正常退出")
def setUpClass(cls): cls.config = ReadConfig() # 读取配置 cls.logger = Logger.get_logger() vcc = cls.config.get_userinfo("vcc").split(",") username = cls.config.get_userinfo("username").split(",") password = cls.config.get_userinfo("password") d = Driver("Chrome") cls.driver = d.selenium_driver() t = LoginTestPage(cls.driver) t.open() t.login_test(vcc[1], username[1], password) # 登录,切换token cls.work_config_page = WorkConfigPage(cls.driver) # 进入职场配置页面 cls.work_config_page.enter_work_config_page()
def test_read_config_file(self): test_data = "Abbracadabra" file = "config.yml" cf = ReadConfig(file) assert cf.config['data']['test'] == test_data
from readconfig import ReadConfig from readexcel import ReadExcel readconfig = ReadConfig() path = ReadExcel().get_xlsx('interface_usecases.xlsx', 'login')[0][3] # print(path) class GetUrlParams(): # 定义一个方法,将从配置文件中读取的进行拼接 def get_url(self): config_url = readconfig.get_http("baseurl") if config_url != 'https://api.aircourses.com': new_url = readconfig.get_http('baseurl') + ":" + readconfig.get_http('port') + path+"?" else: new_url = config_url+"?" # logger.info('new_url'+new_url) return new_url if __name__ == '__main__': # 验证拼接后的正确性 print(__file__) print(GetUrlParams().get_url())
class Login: def __init__(self): self.data = ReadConfig() self.host = self.data.get_db("host") self.user = self.data.get_db("user") self.password = self.data.get_db("password") self.database = self.data.get_db("database") self.port = self.data.get_db("port") def obtain_connect(self): #连接数据库 connect = False try: connect = psycopg2.connect(host=self.host, user=self.user, password=self.password, database=self.database, port=self.port) except Exception as e: print("连接数据库失败->%s" % e) finally: return connect def query(self, sql): #执行查询类操作 results = '' try: db = self.obtain_connect() cursor = db.cursor() cursor.execute(sql) results = cursor.fetchall() db.commit() cursor.close() db.close() except Exception as e: print("查询失败->%s" % e) finally: return results def insert(self, sql, data): #执行插入数据操作 flag = False try: db = self.obtain_connect() cursor = db.cursor() cursor.executemany(sql, data) db.commit() cursor.close() db.close() flag = True except Exception as e: flag = False db.rollback() print("执行失败->%s" % e) finally: return flag def nonquery(self, sql): #执行非查询类操作 flag = False try: db = self.obtain_connect() cursor = db.cursor() cursor.execute(sql) db.commit() cursor.close() db.close() flag = True except Exception as e: flag = False db.rollback() print("执行失败->%s" % e) finally: return flag
#!/usr/bin/env python # -*- coding: utf-8 -*- import os try: import datetime from Login import Login from readconfig import ReadConfig from clean import Clean lj = Login() dc = Clean() _info = ReadConfig() except Exception as e: print('配置文件缺失%s' %e) print('输入enter停止') _k= input() os._exit(0) def main(): try: print('该程序用于清洗公司名称数据->修改配置文件即可运行') print('版本:1.3') print('输入enter开始') k1=input() #读取数据库原始数据 print('正在清洗数据->请稍后..') info1 = _info.get_input("col_name") #字段名称 info2 = _info.get_input("table_name") #表名->有模式需要加.配置完整表名 sql1 = ''' select {}
#!/usr/bin/python # coding=utf-8 import logger as logger import logging import os from datetime import datetime from readconfig import ReadConfig from configbackup import GetNetworkConfig cf = ReadConfig('config.ini') # 获取备份目录 backupdir = cf.get('backup_dir','backupdir') # 获取IP地址(存储成列表) network_huawei_telnet_ip = cf.get('network_huawei_telnet', 'network_huawei_ip').split(',') network_huawei_ssh_ip = cf.get('network_huawei_ssh', 'network_huawei_ip').split(',') network_cisco_telnet_ip = cf.get('network_cisco_telnet', 'network_cisco_ip').split(',') network_dp_ssh_ip = cf.get('network_dp_ssh', 'network_dp_ip').split(',') network_juniper_ssh_ip = cf.get('network_juniper_ssh', 'network_juniper_ip').split(',') # 获取用户 network_user = cf.get('network_user','network_user') # 获取密码 network_password = cf.get('network_user','network_password') if __name__ == '__main__': mylogger = logger.Logger() s = GetNetworkConfig() # 获取当天日期 now=datetime.now() today = datetime.strftime(now, '%Y%m%d')
#coding=utf-8 from django.http import HttpResponse from readconfig import ReadConfig from execcmd import Exec def test(request): return HttpResponse("hello test") if __name__ == "__main__": rc = ReadConfig() host, port, user, password, timeout = rc.readDockerweb() print host print port print user print password print timeout e = Exec() e.execCommand("l /root")
import smtplib from email.mime.text import MIMEText #填写文本 from email.header import Header #标题 from email.mime.multipart import MIMEMultipart #编写文件 from readconfig import ReadConfig from loging_a import mig_logger from newReport import new_file from location import result_path #实例化html存储路径 result_path = result_path() #实例化日志 logger = mig_logger() # 获取配置文件 e = ReadConfig() mail_host, mail_user, mail_pass, sender, receiver = e.email_a() def send(): msg = MIMEMultipart() msg['From'] = Header('*****@*****.**') # 编辑邮件头 msg['To'] = Header('*****@*****.**') msg['Subject'] = Header('禾贝管理系统', 'utf-8') # html1 = 'D:\python3\UI自动化\\test_html\test_runner.html' new_file1 = new_file(result_path) with open(new_file1, 'rb') as f: with_html = f.read() # f.close() msg.attach(MIMEText(with_html, 'html', 'utf-8')) # 把正文附在邮件上 att = MIMEText(with_html, 'base64', 'utf-8') att['Content-Type'] = 'application/octet-stream'
def __init__(self, *args, **kwargs): config = ReadConfig().getConfig() self._token = config['tushare']['token'] ts.set_token(self._token) self.tusharePro = ts.pro_api()
def __init__(self, selenium_driver): self.config = ReadConfig() self.logger = Logger.get_logger() self.driver = selenium_driver self.base_url = self.config.get_url("test_url")
# coding=utf-8 import os from readconfig import ReadConfig # 读取配置文件 # config_file_path = os.path.split(os.path.realpath(__file__))[0] # read_config = ReadConfig(os.path.join(config_file_path, 'config.ini')) read_config = ReadConfig() # 项目参数设置 prj_path = read_config.getValue('projectConfig', 'project_path') # 日志路径 log_path = os.path.join(prj_path, 'report', 'log') # 测试报告路径 report_path = os.path.join(prj_path, 'report', 'testreport') # 测试数据路径 data_path = os.path.join(prj_path, 'data', 'testdata')
def test_ReadConfig_with_None(self): file = "./config/config.yml" cf = ReadConfig(None) assert cf.file == file
import os import time from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # 导入鼠标事件 from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from log import Log from readconfig import ReadConfig logger = Log() read_config = ReadConfig() url = read_config.getValue('testServer', 'URL') browserName = read_config.getValue('browserType', 'browserName') _timeout = read_config.getIntValue('waitTime', 'timeout') _t = read_config.getFloatValue('waitTime', 'time') class Base(object): def __init__(self, browser=browserName, base_url=url): t1 = time.time() if browser == "Firefox" or browser == "firefox": driver = webdriver.Firefox() elif browser == "Chrome" or browser == "chrome": driver = webdriver.Chrome() elif browser == "ie" or browser == "IE": driver = webdriver.Ie()
import smtplib import os import sys from email.mime.text import MIMEText from readconfig import ReadConfig import datetime import getpathinfo # 读取配置文件 read_conf = ReadConfig() # 从配置文件中读取,smtp服务器、端口、发件人、密码、收件人、抄送人 smtp = read_conf.get_email("host") port = read_conf.get_email("port") user = read_conf.get_email("user") pwd = read_conf.get_email("pwd") addressee = read_conf.get_email("addressee") # addressee=list(addressee.split(";")) chaosong = read_conf.get_email("chaosong") # 从配置文件中读取,邮件主题 now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") subject = "hello,这是" + now + read_conf.get_email("subject") print(subject) mail_path = os.path.join(getpathinfo.get_path(), 'result', 'report.html') # 获取测试报告路径 content = "<h1>测试报告来咯!</h1>" class SendEmail(object):
def __init__(self): self.words = ReadConfig()
def test_ReadConfig_with_file(self): file = "config.yml" cf = ReadConfig(file) assert cf.file == file
import requests import ssl import operator import unittest ssl._create_default_https_context = ssl._create_unverified_context from readconfig import ReadConfig from log import MyLog as Log from common.functions import * import json localReadConfig = ReadConfig() class ConfigHttp: def __init__(self): global timeout #host = #localReadConfig.get_http("baseurl") #port = localReadConfig.get_http("port") #timeout = localReadConfig.get_http("timeout") #for i in case_array: # print(i) # print("OKOK") self.host = {} self.log = Log.get_log() self.logger = self.log.logger self.headers = {} self.params = {} self.data = {} self.url = {} self.files = {} self.timeout = 0
def __init__(self): self.conn = None self.cur = None self.data = ReadConfig() self.conn_mysql()
class BasePage: """基类""" def __init__(self, selenium_driver): self.config = ReadConfig() self.logger = Logger.get_logger() self.driver = selenium_driver self.base_url = self.config.get_url("test_url") def _open(self, url): """以——为开头的方法,在使用import *时,该方法不会被导入,返回比较结果(True or False)""" self.driver.maximize_window() self.driver.get(url) def open(self): """调用——open()打开链接""" self._open(self.base_url) def find_element(self, *loc): """寻找元素""" try: # 元素可见时,返回查找到的元素;以下入参为元组的元素,需要加* WebDriverWait(self.driver, 10).until(lambda driver: driver.find_element(*loc).is_displayed()) return self.driver.find_element(*loc) except NoSuchElementException: # print('找不到定位元素: %s' % loc[1]) self.logger.warning('找不到定位元素: %s' % loc[1]) raise except TimeoutException: # print('查找元素超时: %s' % loc[1]) self.logger.warning('查找元素超时: %s' % loc[1]) raise def find_element_presence(self, *loc): """元素存在dom中,即被找到""" try: WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(loc)) # 显示等待 return self.driver.find_element(*loc) except: # print(loc, '页面未找到元素') self.logger.warning(loc, '页面未找到元素') def find_elements(self, *loc): """寻找多个元素""" try: WebDriverWait(self.driver,10).until(EC.visibility_of_element_located(loc)) #显示等待 return self.driver.find_elements(*loc) except NoSuchElementException: # print('%s页面未找到元素', loc) self.logger.warning('%s页面未找到元素', loc) except TimeoutException: self.logger.warning('查找元素超时: %s' % loc[1]) def send_keys(self, value, *loc , clear_first=True, click_first=True): """ 输入文本框 :param value: 输入的文本 :param clear_first: 是否清空文本框 :param click_first: 是否点击文本框""" try: 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(value) # 输入文本 except AttributeError: # print("页面中未能找到元素", loc) self.logger.error("页面中未能找到元素", loc) def switch_frame(self, loc): """切换frame""" return self.driver.switch_to.frame(loc) def switch_default_frame(self): """返回默认iframe""" self.driver.switch_to_default_content() self.logger.info("返回默认iframe") def click(self, *loc): self.logger.info('点击元素 by {}'.format(loc[1])) try: self.find_element(*loc).click() time.sleep(0.5) except AttributeError as e: # print("无法点击元素: ", e) self.logger.error("无法点击元素: ", e) def wait(self, seconds): """隐式等待""" self.driver.implicitly_wait(seconds) # print("等待 %d 秒" % seconds) self.logger.info("等待 %d 秒" % seconds) def get_text(self, *loc): """获取文本""" element = self.find_element(*loc) return element.text def get_attribute(self, loc, name): '''获取属性''' element = self.find_element(*loc) return element.get_attribute(name) def is_element_exist(self, *loc): try: element = self.driver.find_element(*loc) if element==None: return False else: return True except: return False
import unittest from xird_a import xlrd_rb from ddt import ddt, unpack, data from openpyxl_a import open_wb import os import json from requests_a import requests_main from loging_a import mig_logger from readconfig import ReadConfig # report_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + r'\接口数据.xlsx' #获取配置文件 c = ReadConfig() report_path = c.config('PATH','path') #实例化日志类 logger = mig_logger() #实例化读取excel,获取接口数据 rb = xlrd_rb() line =rb.line(report_path) #实例化测试报告写入excel r = requests_main() #实例化requests发送请求 wb = open_wb(report_path) @ddt class MyTest(unittest.TestCase): @classmethod