def open_browser(self, browser): log1.info('读取浏览器配置') url = Config.config_read('test', 'url') log1.info('读取url:%s' % url) try: if browser == 0: abspath = os.path.abspath(r"F:\m2\chromedriver.exe") self.driver = webdriver.Chrome(abspath) log1.info('打开的浏览器为chrome') elif browser == 1: # abspath = os.path.abspath(r"F:\m2\chromedriver.exe") self.driver = webdriver.Firefox() log1.info('打开的浏览器为Firefox') elif browser == 2: # abspath = os.path.abspath(r"F:\m2\chromedriver.exe") self.driver = webdriver.ie() log1.info('打开的浏览器为ie') self.driver.get(url) self.driver.maximize_window() log1.info('浏览器最大化') self.driver.implicitly_wait(10) log1.info('设置静态等待时间10秒') return self.driver except BaseException: log1.error('浏览器打开报错')
def RecMsg(self, msg): self.__logger.debug('RecMsg from {}:{} '.format( msg['User']['NickName'], msg.text)) if msg['User']['NickName'] == USR_NAME: if msg.text == CMD_CMDINIT: self.Init() elif self.__processer_running != None: self.Send(self.__processer_running.Receive(msg.text)) elif msg.text == CMD_CMDLIST: # 用户请求命令列表 self.Send(self.CmdList()) # 将状态转入到等待用户选择要process self.__state = 'WaitCmdSelection' elif self.__state == 'WaitCmdSelection': config = Config(self.__name + '_config.json').config # 判断用户选择的process序号合法 if int(msg.text) > 0 and int(msg.text) <= len(config): self.SetProcsser(config[int(msg.text) - 1]['ClassName']) self.Send('{} 启动'.format(config[int(msg.text) - 1]['Commnet'])) # 清除状态 self.__state = None else: self.__logger.warning('DiscardMsg: {}'.format(msg.text)) self.Send('对不起,我不懂你的意思。') return
class QP_Api_Test(unittest.TestCase): c = Config() e = Error() datas = _data = ExcelReader(c.data_path + '\\Test_Case1.xls').data def test_api_all(self): '''主运行函数''' for i in self.datas: if i['is_run'].upper() == 'YES': with self.subTest(case=i['CaseName']): url = self.c.test_url + i['api'] data_id = i['data'] method = i['method'] expect_code = i['expect_code'] expect_msg = i['expect_msg'] is_token = i['is_token'] data = OpenIni().get_data(data_id) depend_id = i['depend_id'] query_depend = i['query_depend'] field_depend = i['field_depend'] sql_value = i['sql_value'] expect_data = i['expect_data'] is_coin = i['is_coin'] # 判断是否需要依赖数据,有则替换依赖数据 if depend_id: #判断是否存在逗号,是则是至少有两个key以上,切割组成列表作为keys if ',' in field_depend: field_depend_list = field_depend.split(',') depend = Depend_Data().get_depend_data( depend_id, query_depend, field_depend_list) for key in field_depend_list: #交換兩個字典的值 data[key] = depend[key] else: depend = Depend_Data().get_depend_data( depend_id, query_depend, field_depend) data[field_depend] = depend if is_token == 'YES' and data_id != '': api_token = login() data.update({'api_token': api_token}) response = HTTPClient(url=url, method=method).send(data=data) elif is_token == 'NO' and data_id != '': response = HTTPClient(url=url, method=method).send(data=data) elif is_token == 'YES' and data_id == '': api_token = login() response = HTTPClient( url=url, method=method).send(data={'api_token': api_token}) else: response = HTTPClient(url=url, method=method).send() # 首先进行普通断言 self.e.assertHTTPCode(response, expect_code, expect_msg) # 判断是否查询数据库断言 if sql_value: if is_coin: expect_data = get_user_coin() self.e.assertMysqldata(sql=get_sql_all(sql_value), expect_data=expect_data)
def get_user_coin(): ''' 获取用户信息余额 :return: ''' api_token = login() response = HTTPClient(Config().test_url + 'user/balance', 'get').send(data={'api_token': api_token}) return response['data']['coin']
def CmdList(self): index = 1 result = '' for c in Config(self.__name + '_config.json').config: if index > 1: result = result + '\n' result = result + '{} {}'.format(index, c['Commnet']) index = index + 1 return result
def __init__(self): ''' 构造方法 ''' # 加载配置 # 请求头 self.config = Config('./config.json') self.mongo = pymongo.MongoClient(self.config.get('mongo_host')) self.headers = { "Host": "www.1905.com", "Connection": "keep-alive", "Pragma": "no-cache", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.1021.400 QQBrowser/9.0.2524.400", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9" } self.sleep_time = self.config.get('sleep_time') self.table = None
def login(): c = Config() username = c.username password = c.password try: url = c.test_url + 'pub/login' response = HTTPClient(url, 'post').send(data={'username': username, 'password': password}) api_token = response['data'] return api_token except Exception as e: logger.error('获取api_token失败! {}'.format(e))
def __init__(self): '''数据库配置''' self.c = Config() self.host = self.c.host self.port = self.c.port self.user = self.c.user self.passwd = self.c.dbpassword self.db = self.c.db self.DB = pymysql.connect( host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db )
def test_weather(self): '''查询天气''' case_name = '查询天气' log1.info("执行测试用例:%s" % case_name) try: weather = test_requests() # 初始化测试基类的实例 url = Config.config_read('weathere', 'url') # 获取配置文件中的url city = Config.config_read('weathere', 'city') # 获取配置文件中的crty status_code, response_json, reurl = weather.get( url + city) # 调用封装的get方法,接收状态码和相应内容 message = weather.getdict(response_json, 'message') # 调用迭代字典方法,获得message字段的值 test1 = self.assertEqual(status_code, 200) # 断言状态码等于200 print(test1) test2 = self.assertEqual(message, 'Success !') # 断言message字段的值等于'Success !' print(test2) if test1 == None and test2 == None: # 如果两个断言结果都等于None log1.info("测试通过") except BaseException as f: log1.error("测试用例执行出错: %s" % case_name, exc_info=1) raise
def __init__(self, logger_name='Auto_frame'): self.logger = logging.getLogger(logger_name) logging.root.setLevel(logging.NOTSET) # 引入配置文件log c = Config() # 日志文件名 self.log_file_name = c.log_file_name # 日志名 self.backup_count = c.backup # 保留日志数量 # 日志输出级别 self.console_output_level = c.console_level self.file_output_level = c.file_level # 日志输出格式 self.formatter = c.pattern if c and c.pattern else logging.Formatter( '%(asctime)s -- %(name)s -- %(filename)s -- %(lineno)d -- %(levelname)s -- %(message)s' )
class Controller(MakesmithInitFuncs): """ NonVisibleWidgets is a home for widgets which do not have a visible representation like the serial connection, but which still need to be tied in to the rest of the program. """ actions = Actions() gracefulKiller = GracefulKiller() logger = Logger() config = Config() watchdog = WatchDog() ui_queue = queue.Queue() message_queue = LoggingQueue(logger) def setUpData(self, data): """ The setUpData function is called when a widget is first created to give that widget access to the global data object. This should be replaced with a supper classed version of the __init__ function. """ self.data = data self.data.actions = self.actions self.data.gracefulKiller = self.gracefulKiller self.data.logger = self.logger self.data.config = self.config self.data.ui_queue = self.ui_queue self.data.message_queue = self.message_queue self.data.watchdog = self.watchdog self.actions.setUpData(data) self.gracefulKiller.setUpData(data) self.logger.setUpData(data) self.config.setUpData(data) self.watchdog.setUpData(data) self.watchdog.checkForRunningContainer()
def get_sql_all(sql_value): ''' 根据传入的方法和字段数据返回出sql :param sql_value: excel上获取的value :return: ''' # 格式化当前时间 _time = str(time.strftime('%Y-%m-%d', time.localtime(time.time()))) id_name = sql_value.split('>')[0] field = sql_value.split('>')[1] id_value = sql_value.split('>')[2] if id_name == 'user_info': return '''select {} from gygy_members WHERE username = '******';'''.format( field, Config().username) elif id_name == 'activity': return '''select {} from gygy_activity_apply WHERE apply_date = '{}' and activity_id = {}'''.format( field, _time, id_value) else: return None
def run(testname): '''集合所有用例运行发送报告''' c = Config() with open(c.report_path, 'wb') as f: suite = unittest.defaultTestLoader.discover(start_dir=c.case_path, pattern='Api_*.py') runner = HTMLTestRunner(stream=f, verbosity=2, title='API测试报告', description='接口html测试报告', tester=testname, test_user=str(c.username)) runner.run(suite) e = Email(server=c.server, sender=c.sender, password=c.empassword, receiver=c.receiver, title='老马发送的今天的API自动化报告又来了,请注意查看!', message='来了来了,你的测试API自动化报告!!,注意如果收不到邮件注意查看垃圾箱还是退信了!', path=[c.report_path, c.log_file_name]) e.send()
def Receive(self, msg): self.logger.info('Processer {} rec {}'.format(self.name, msg)) if msg == CMD_CMDLIST: # 将状态转入到等待用户选择要process self.state = 'WaitCmdSelection' # 用户请求命令列表 return self.CmdList() elif self.state == 'WaitCmdSelection': config = Config(self.name + '_config.json').config # 判断用户选择的process序号合法 if int(msg) > 0 and int(msg) <= len(config): # 清除状态 self.__state = None result = eval('self.{}()'.format(config[int(msg) - 1]['FunName'])) return '{} 启动\n{}'.format(config[int(msg) - 1]['Commnet'], result) else: return None else: self.logger.warning('DiscardMsg: {}'.format(msg)) return '对不起,我不懂你的意思。'
def __init__(self): super().__init__() self.config = Config() self.bridge = Bridge() self.bridge.gamePickSignal.connect(self.gamePickHandler) self.bridge.localGameStageEndSignal.connect( self.localGameStageEndHandler) self.bridge.onlineGameStageEndSignal.connect( self.onlineGameStageEndHandler) self.bridge.localGameOverSignal.connect(self.localGameOverHandler) self.bridge.onlineGameOverSignal.connect(self.onlineGameOverHandler) self.mainMenu = MainMenu(self.config, self.bridge) self.board = None self.numOfMaps = len(self.config.maps) self.currentMap = 1 self.currentStage = 1 self.currentGameTypeData = None # this holds initial data for a local game self.initialLocalGameData = LocalGameData() self.initialLocalGameData.firstPlayerDetails = PlayerDetails( 1, 0, 2, 1, True) self.initialLocalGameData.secondPlayerDetails = PlayerDetails( 2, 0, 2, 1, True) # this will hold either local game data or online game data self.currentGameData = None self.endOfStageOnePlayer = None self.endOfStageTwoPlayers = None self.winnerScreen = WinnerScreen(self.config, 1, 0, 0, 0) self.winnerScreen.winnerAnimationOverSignal.connect(self.goToMainMenu) self.gameStartSound = oalOpen(self.config.sounds["gameStart"]) self.newStageTimer = QTimer() self.newStageTimer.setTimerType(Qt.PreciseTimer) self.newStageTimer.setInterval(3000) self.newStageTimer.timeout.connect(self.newStage) self.__init_ui__() self.show()
def __init__(self): platformName=Config.config_read('appium', 'platformName') deviceName=Config.config_read('appium', 'deviceName') platformVersion=Config.config_read('appium', 'platformVersion') apkpath = Config.config_read('appium', 'app') appPackage = Config.config_read('appium', 'appPackage') appActivity = Config.config_read('appium', 'appActivity') path = getcwd.get_cwd() apk_path = os.path.join(path, apkpath) desired_caps = { 'platformName': platformName, 'deviceName': deviceName, # 手机设备名称,通过adb devices查看 'platformVersion': platformVersion, # android系统的版本号 'app': apk_path, 'appPackage': appPackage, # apk包名 'appActivity': appActivity, # apk的launcherActivity 'noRset':'true', 'automationNname':'uiautomator2' } self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) self.driver.implicitly_wait(3)
#!/usr/bin/python3 import os import time import smtplib from email.mime.text import MIMEText from email.utils import formataddr from email.mime.multipart import MIMEMultipart import getcwd from Config.config import Config from Logs.log import log1 config = Config() rq = time.strftime('%Y%m%d', time.localtime(time.time())) # 获取本地时间 转换成日期 email = config.config_read('sender', 'email') # 发件人邮箱账号 password = config.config_read('sender', 'password') # 发件人邮箱密码 usernmae = config.config_read('sender', 'username') # 发件人姓名 users = config.config_options('addressed') # 收件人 addressed_eamils = config.get_addkey(users) # 收件人邮箱 path = getcwd.get_cwd() file = os.path.join(path, 'report/兰州电网PC端部分功能自动化测试报告.html') def sent_mail(): try: # 创建一个带附件的实例 message = MIMEMultipart() message['From'] = formataddr([usernmae, email]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
class Query: table: None def __init__(self): ''' 构造方法 ''' # 加载配置 # 请求头 self.config = Config('./config.json') self.mongo = pymongo.MongoClient(self.config.get('mongo_host')) self.headers = { "Host": "www.1905.com", "Connection": "keep-alive", "Pragma": "no-cache", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.1021.400 QQBrowser/9.0.2524.400", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9" } self.sleep_time = self.config.get('sleep_time') self.table = None # 请求指定地址,自动携带请求头 def query(self, url): ''' 请求指定地址 :param url: :return: ''' req = requests.get(url, headers=self.headers) if req.status_code == 200: return True, req print('请求失败:%s' % url) return False, req # 获取电影列表页信息 def get_move_list_info(self, url): ''' 获取电影列表页信息 :return: ''' # 请求电影列表页 status, res = self.query(url) if status == False: return False, [] # 使用PyQuery解析网页 doc = PyQuery(res.text) # 获取电影列表页的类.inqList下的li元素列表 li = doc('.inqList li').items() # 保存电影列表信息的列表变量 info_list = [] # 循环遍历li元素列表,解析提取每个元素的有效信息 for item in li: # 保存电影信息的字典变量 info = { # 电影名称 'title': item('div p a').attr.title, # 电影详情页uri 'moveUrl': item('a').attr.href, # 缩略图地址 'imgUrl': item('a img').attr.src, # 相关属性 'attr': [] } # 循环取出电影的相关属性 for p in item('div p').items(): info['attr'].append(p.text()) # 将本次循环中获取到的电影信息添加到保存电影列表信息的列表变量 info_list.append(info) return True, info_list # 保存电影列表页信息到mongo def save_info(self, info): table = self.get_database_table() # 保存电影信息表 table.insert_many(info, ordered=False) # 遍历中国2019年电影列表页 并将信息保存到数据库 def loop_move_list_page_of_cn2019(self): base_url = 'https://www.1905.com/mdb/film/list/country-China/year-2019/o0d0p' info_list = [] # 一共44页 for i in range(2, 45): time.sleep(self.sleep_time) url = '%s%d.html' % (base_url, i) print('正在访问:', url) status, res = self.get_move_list_info(url) if status: info_list = info_list + res self.save_info(info_list) # 获取电影的海报地址列表 def get_move_image_url(self, move_uri): ''' 电影详情页中点击图片可以发现,图片版块url如下: https://www.1905.com{/mdb/film/2245264/}still/?fr=mdbypsy_dh_tp 其中 {/mdb/film/2245264/} 部分为 电影列表页中获取到的moveUrl 1. 判断是否有图片 浏览多个页面可以发现 部分电影的图片tab是不能点击的 右键查看元素可以发现 可以点击的tab class为active 不能点击的tab class为gray-style 因此,可以通过class的判断当前电影是否有图片,没有的可以跳过 2. 判断是否有海报 图片判断通过后,需要继续判断图片tab中是否有海报模块 多浏览几个页面观察可以发现 部分电影同时存在 “剧照” 和 “海报” 模块 部分电影只有 "剧照" ,部分电影只有 "海报" 如何判断有海报呢? 先分析 “剧照” 和 “海报” 的html 以 https://www.1905.com/mdb/film/2245264/still/?fr=mdbypsy_dh_tp 为例 可以发现 两个元素都在父级div的class均为 secPag-pics, 其中海报 的 h3元素的class 比剧照的class 多了一个 paddng-top-none 因此,可以通过判断是否存在 class为paddng-top-none的元素来判断是否有海报模块 3. 获取海报页地址 因为部分电影海报较多,点击海报可以发现还有专门的海报页面,会显示所有海报,因此先获取到海报页地址,在去海报页获取所有海报地址 4. 获取所有海报地址 :return: ''' # 获取图片tab页地址 注意中间的 %s 为字符串替换 image_tab_url = 'https://www.1905.com%sstill/?fr=mdbypsy_dh_tp' % move_uri # 请求地址 status, res = self.query(image_tab_url) if not status: print('请求%s异常,状态码:%d' % (image_tab_url, res.status_code)) return False, '' doc = PyQuery(res.text) # 判断图片tab class是否为active li = doc('.layout-menu ul li').eq(2).attr('class') if li != 'active': print("当前页面图片tab不可点击") return True, '' # 判断是否有海报 sec = doc('.secPag-pics .paddng-top-none') if not sec: print('没有海报模块') return True, '' # 获取海报详情页地址 .secPag-pics:last 代表 class为secPag-pics 的最后一个元素 li:first 代表前置条件元素内的第一个li元素 image_page_url = doc('.secPag-pics:last ul li:first a').attr('href') return True, image_page_url # 请求电影详情 def get_image_list(self, image_page_url): # 参数校验,如果地址为空 if image_page_url == '': return False, [] status, res = self.query(image_page_url) if not status: return False, [] images_doc = PyQuery(res.text) # 创建一个保存海报的列表变量 image_list = [] # 获取 class 为 pic_img_gallery 的元素 下的 所有li元素,items()方法获得一个可遍历的对象 li = images_doc('.pic_img_gallery li').items() for elem in li: # 取出一张图片的地址 image_url = elem('div a').attr('href') # 将这个地址添加到列表中 image_list.append(image_url) print('成功获得%d张海报' % (len(image_list))) return True, image_list # 保存海报列表信息 def save_image_list(self, key, image_list): table = self.get_database_table() # 组装需要保存到数据的数据 update_dict = {'image_list': image_list, 'image_list_status': True} # 更新mongodb 数据表中的一条数据 条件为_id = key ,$set 表示直更新局部,即表中的image_list字段 table.update_one({'_id': key}, {'$set': update_dict}) # 读取电影列表 def read_move_list(self,number = 10): table = self.get_database_table() # 取出image_list_status 不等于 true的记录 , limit 指定取出条数 info_list = table.find({'image_list_status': {'$ne': True}}).limit(number) for info in info_list: # 取出信息后,获取海报列表,并写入数据中, print("当前请求的是《%s》" % info['title']) status, image_page_url = self.get_move_image_url(info['moveUrl']) # 如果返回接口正常且获取到url if status and image_page_url != '': get_image_list_status,image_list = self.get_image_list(image_page_url) if get_image_list_status: print("获取到海报列表") self.save_image_list(info['_id'],image_list) # 如果返回接口正常且没有获取到url elif status and image_page_url == '': print("没有海报") self.save_image_list(info['_id'],[]) else: print("请求异常") # 获取mongo数据库表对象 def get_database_table(self): if self.table is None: database = self.mongo[self.config.get('database')] self.table = database['move_info'] return self.table
from bottle import Bottle, request from orator import DatabaseManager, Model from Config.config import Config from FileHelper.file_helper import FileHelper #import controllers# from Controllers.users_controller import UsersController import logging import sys db = DatabaseManager(Config.get_config(self=0)) Model.set_connection_resolver(db) bottle = Bottle() def exec_command(controller, method, other="", input=None): try: if input is None: if other != "": return eval(controller + "." + method + "('" + other + "')") else: return eval(controller + "." + method + "()") else: return eval(controller + "." + method + "(" + input + ")") except: logging.error('%s', sys.exc_info()) #examples of routing @bottle.route('/<controller>/<method>', method='GET') def show_multiple(controller="", method=""): return exec_command(controller=controller, method=method)
from bottle import Bottle, request from orator import DatabaseManager, Model from Config.config import Config from FileHelper.file_helper import FileHelper # import controllers# from Controllers.users_controller import UsersController import logging import sys db = DatabaseManager(Config.get_config(self=0)) Model.set_connection_resolver(db) bottle = Bottle() def exec_command(controller, method, other="", input=None): try: if input is None: if other != "": return eval(controller + "." + method + "('" + other + "')") else: return eval(controller + "." + method + "()") else: return eval(controller + "." + method + "(" + input + ")") except: logging.error("%s", sys.exc_info()) # examples of routing @bottle.route("/<controller>/<method>", method="GET") def show_multiple(controller="", method=""):
print("Process ID {}, Process Parent ID {}".format(os.getpid(), os.getppid())) # gpu gpu = torch.cuda.is_available() if gpu: print('The train will be using GPU.') else: print('The train will be using CPU.') print('CuDNN', torch.backends.cudnn.enabled) # config arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--config_file', type=str, default='./Config/config.ini') args = arg_parser.parse_args() config = Config(args.config_file) if gpu: config.add_args('Train', 'use_cuda', 'True') # data_loader sem_data_loader = ReadSenData(config) tra_sen_data, dev_sen_data = sem_data_loader.read_data() word_data_loader = ReadData(config) tra_data, dev_data = word_data_loader.read_data() # vocab if os.path.isfile(config.fact_word_vocab): tra_fact_word_vocab = read_pkl(config.fact_word_vocab) tra_fact_char_vocab = read_pkl(config.fact_char_vocab) if config.read_sen: tra_fact_sen_vocab = read_pkl(config.fact_sen_vocab)
from Config.config import Config section = 'selenium' username = '******' password = '******' test = Config() test.config_write(section) test.config_write(section, 'username', username) test.config_write(section, 'password', password) get_username = test.config_read(section, 'username') get_password = test.config_read(section, 'password') test.config_delete( section, 'usrename', ) test.config_delete(section, 'password') test.config_delete(section)
def Driver(): driver = Webdriver() driver.maximize_window() driver.get(Config().base_url) yield driver driver.quit()
# -*- coding: UTF-8 -*- from Config.config import Config #可以写入初始化数据以及浏览器引擎 section = 'selenium' username = '******' password = '******' a = Config.config_read('DB', 'dbhost') print(a)
def __init__(self): self.c = Config() self.ini = OpenIni() self.j = JMESPathExtractor()
# coding=utf-8 import os import time import xlrd from selenium.common.exceptions import NoSuchElementException from selenium import webdriver import getcwd from Logs.log import log1 from Config.config import Config path = getcwd.get_cwd() config = Config() class BasePage: """测试基类""" def __init__(self, driver): self.driver = driver # 截图 def get_img(self): jt_path = os.path.join(getcwd.get_cwd(), 'img/') #拼接截图保存路径 rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time())) #按格式获取当前时间 img_name = jt_path + rq + '.png' #拼接截图文件名 # noinspection PyBroadException try: self.driver.get_screenshot_as_file(img_name) log1.info('截图保存成功') except BaseException:
def __init__(self): self.c = Config()