def click(self, locator): try: self.find_element(locator).click() logger.info(u'点击%s成功' % (list(locator))) except Exception as msg: logger.error(u'点击%s失败' % (list(locator))) logger.error("报错信息是:%s" % msg)
def find_elements(self, locator, loc_time=10): try: elements = WebDriverWait(self.driver, loc_time).until( ec.presence_of_all_elements_located(locator)) logger.info(u'找到元素' + '%s' % (list(locator))) return elements except Exception as msg: logger.error('未找到元素' + '%s' % list(locator)) logger.error("报错信息是:%s" % msg)
def get_ele_attribute(self, locator, ele_type): try: element = self.find_element(locator) if ele_type == 'text': return element.text else: return element.get_attribute(ele_type) except Exception as msg: logger.error(u"获取%s失败" % list(locator)) logger.effor("报错信息是:%s" % msg) else: logger.info(u"获取%s成功,值为:%s" % (list(locator), element.text))
def check_loginStatus(self): logger.info('====check_loginStatus======') time.sleep(2) try: element = self.driver.find_element(*self.loginCheck) except NoSuchElementException: logger.error('login Fail!') self.getScreenShot('login') return False else: logger.info('login success!') return True
def switch_to_context(self, con_type): try: if con_type == '1': self.driver.switch_to.context('NATIVE_APP') logger.info(u'切换到NATIVE_APP成功') else: contexts = self.get_contexts() self.driver.switch_tocontent(contexts[1]) logger.info(u'切换到%s成功' % contexts[1]) except Exception as msg: logger.error(u'切换content失败') logger.error("报错信息是:%s" % msg)
def get_credentials(api): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. :param api: api - API from which we want to obtain the credentials. :return: Credentials, the obtained credential. """ logger.info("Get Google credential for API {}".format(api)) # If modifying these scopes, delete your previously saved credentials # at ./.credentials/sheets.googleapis.com.json scope = { 'sheets': 'https://www.googleapis.com/auth/spreadsheets', 'analytics': 'https://www.googleapis.com/auth/analytics.readonly', 'analyticsreporting': 'https://www.googleapis.com/auth/analytics.readonly' } credential_folder = os.path.join(CODE_HOME, CREDENTIAL_DIR) logger.debug("Credential dir: {}".format(credential_folder)) if not os.path.exists(credential_folder): try: os.makedirs(credential_folder) except OSError as e: logger.error( "Unable to create the corresponding directory: {}".format( e.message)) credential_path = os.path.join(credential_folder, CREDENTIAL_FILE) if api == 'sheets': store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CREDENTIAL, scope[api]) flow.user_agent = APPLICATION_NAME credentials = tools.run_flow(flow, store, flags) else: credentials = ServiceAccountCredentials.from_json_keyfile_name( os.path.join(SERVICE_ACCOUNT_KEY_HOME, SERVICE_ACCOUNT_KEY), scopes=scope[api]) return credentials
def send_meassurements(self, meassurements): logger.info('Sending meassurements to Monasca...') d = list() d = [ self.payload_meassure(row) for row in meassurements.values ] flatten_payload = [item for sublist in d for item in sublist] logger.debug('Payload: {}'.format(flatten_payload)) try: r = requests.post(self.url, json=flatten_payload, headers=self.headers) r.raise_for_status() except requests.exceptions.HTTPError as errh: logger.error("Http Error: {}".format(errh)) sys.exit(1) except requests.exceptions.ConnectionError as errc: logger.error("Error Connecting: {}".format(errc)) sys.exit(1) except requests.exceptions.Timeout as errt: logger.error("Timeout Error: {}".format(errt)) sys.exit(1) except requests.exceptions.RequestException as err: logger.error("OOps: Something Else: {}".format(err)) sys.exit(1) logger.info( 'Meassurements sent to Monasca, status code: {}'.format(r.status_code))
def get_token(self): logger.info('Requesting token to Keytone...') try: r = requests.post(self.url, json=self.payload, headers=self.headers) r.raise_for_status() except requests.exceptions.HTTPError as errh: logger.error("Http Error: {}".format(errh)) sys.exit(1) except requests.exceptions.ConnectionError as errc: logger.error("Error Connecting: {}".format(errc)) sys.exit(1) except requests.exceptions.Timeout as errt: logger.error("Timeout Error: {}".format(errt)) sys.exit(1) except requests.exceptions.RequestException as err: logger.error("OOps: Something Else: {}".format(err)) sys.exit(1) token = r.headers['X-Subject-Token'] logger.info('Token obtained, status code: {}'.format(r.status_code)) logger.debug('Token: {}'.format(token)) return token
def find_element(self, locator, loc_time=10): """ 查找元素 :param locator: 元素的元祖参数 :param loc_time: 查找时间,默认超时时间10s :return: """ try: element = WebDriverWait(self.driver, loc_time).until( ec.presence_of_element_located(locator)) return element except WebDriverException: logger.error('未找到元素' + '%s' % list(locator)) else: logger.info(u'找到元素%s' % (list(locator)))
def send_text(self, locator, text): """ :param locator: 定位元素 :param text: 输入的文本信息 :return: """ try: element = self.find_element(locator) element.clear() element.send_keys(text) except Exception as msg: logger.error(u'输入%s失败,原因是%s' % (text, msg)) else: logger.info(u'输入%s成功' % text)
def add_application_action_nz(self, product_name, product_type, product_cast, unit, picture, manufacturer, product_specification, number, trademark, other, description): file = os.path.abspath(os.path.join(os.getcwd(), "../..")) picture_file = file + "\shhfw\data\%s" % picture self.driver.find_element(*self.fwxz).click() self.driver.find_element(*self.nzBtn).click() self.driver.find_element(*self.addBtn).click() self.driver.find_element(*self.cpmc).send_keys(product_name) self.driver.find_element(*self.fwlx1).click() element_type1 = self.driver.find_element(*self.fwlx2) element_type2 = element_type1.find_elements_by_xpath('li') ###找到所有li for values in element_type2: if product_type in values.text: values.click() break self.driver.find_element(*self.cpdj).send_keys(product_cast) time.sleep(1) self.driver.find_element(*self.jgdw1).click() element_cast1 = self.driver.find_element(*self.jgdw2) element_cast2 = element_cast1.find_elements_by_xpath('li') ###找到所有li for values in element_cast2: if unit in values.text: values.click() break # logging.info('上传图片 is:%s' %picture) self.driver.find_element(*self.update).send_keys(picture_file) self.driver.find_element(*self.sccj).send_keys(manufacturer) self.driver.find_element(*self.cpgg).send_keys(product_specification) self.driver.find_element(*self.cpbm).send_keys(number) self.driver.find_element(*self.cppp).send_keys(trademark) self.driver.find_element(*self.qtcs).send_keys(other) self.driver.find_element(*self.cpms).send_keys(description) self.driver.find_element(*self.qdBtn).click() time.sleep(1.5) try: self.driver.find_element(*self.checkBox).click() except WebDriverException as e: logger.error('add application Fail!') self.getScreenShot('add application fail') self.driver.find_element(*self.tjBtn).click() time.sleep(2)
def select(self, locator1, locator2, locator3): """ :param locator1: 第一个点击的元素,点击进入弹框页面 :param locator2: 定位弹框里的一组元素,任意选择其中的一个点击 :param locator3: 弹框中的确定按钮 :return: """ try: self.find_element(locator1).click() elements = self.find_elements(locator2) num = random.randint(0, len(elements) - 1) elements[num].click() self.find_element(locator3).click() logger.info(u'选择%s成功' % list(locator2)) except Exception as msg: logger.info(u'选择%s失败' % list(locator2)) logger.error("报错信息是:%s" % msg)
def send_to_text(self, locator1, locator2, text, locator3): """ 定位到元素后,点击在新的页面填写内容,保存后再回到之前页面 :param locator1: 定位的元素 :param locator2: 输入内容框的元素 :param locator3: 保存按钮 :param text: 输入的内筒 :return: """ try: self.find_element(locator1).click() self.send_text(locator2, text) self.find_element(locator3).click() logger.info(u'输入%s成功' % text) except Exception as msg: logger.error(u'输入%s失败' % text) logger.error("报错信息是:%s" % msg)
def process_tweets_by_username(username, until_date=None): """ Consulta log do usuário para checar ultima atualização Cria intervalo de datas de captura dos tweets Consulta os tweets via crawler do usuário para o intervalo de datas Salva os tweets e atualiza o log para o usuário ---------- username : str username do perfil no Twitter until_date : datetime Data final do intervalo de captura """ try: log_user = select_log_update_tweets(user=username) except NoResultFound as e: log_user = Log_update_tweets(username=username, updated=None) if log_user.updated is None: since_date = datetime.strptime(SINCE_DEFAULT, '%Y-%m-%d %H:%M:%S') else: since_date = log_user.updated since_date = pytz.timezone('America/Recife').localize(since_date) if until_date is None: until_date = datetime.now(tz=TZ) if (until_date > since_date): try: log_user = dict(username=log_user.username, updated=until_date) tweets = get_tweets_by_username(username, since_date, until_date) upsert_tweets_username(log_user, tweets) except Exception as e: logger.error(e) return(False) return(True)
def obtain(self): for source in db.query(Source): logger.info(source.name) # if source.name != 'Academy': continue metrics = db.query(Metric).filter_by(source_id=source.id).all() try: op_source = eval('{}()'.format(source.name)) except Exception as e: logger.error('source {} is not implemented'.format( source.name)) logger.error(e) continue for metric in metrics: try: value = op_source.get_measurement(metric) except NotDefined: value = 'Not Defined' except NotImplemented: value = 'No Impl' except InvalidConection: value = 'No Connect' except Exception as e: logger.error(e) value = 'No Access' params = { 'metric_id': metric.id, 'date': datetime.now(), 'value': value.replace(',', '') } logger.debug(params) measurement = Measurement(**params) db.add(measurement) else: db.commit()
#设置测试用例、测试报告路径 test_dir='../test_case_business' report_dir='../reports' logger.info('start run test case...') #加载测试用例 suite = unittest.TestSuite() # suite.addTest(unittest.makeSuite(test_appDemand.TestAppDemand)) # suite.addTest(unittest.makeSuite(test_processingDemand.TestprocessingDemand)) suite.addTest(unittest.makeSuite(test_processing_order_xq.TestprocessingOderXq)) suite.addTest(unittest.makeSuite(test_booking.TestBooking)) # suite.addTest(unittest.makeSuite(test_processing_order_booking.TestprocessingOder)) # suite.addTest(unittest.makeSuite(test_check.TestCheck)) ##设置测试报告名称 now=time.strftime('%Y-%m-%d %H_%M_%S') report_name=report_dir+'/'+now+'report.html' #执行测试用例生成测试报告 with open(report_name,'wb') as file: HTMLTestRunner(stream=file,title='社会化服务测试报告',description='社会化服务测试报告',retry=1,save_last_try=False).run(suite) # 通过邮件发送测试报告的 logger.info("start send email......") try: rep = send_email.get_report('../reports') send_email.send_email(rep) except: logger.error("send_email failed") finally: logger.info("send_email success")
def add_application_action_nj(self, number, application_name, application_type, application_cast, unit, picture, region): ###向excel中写入服务编号,方便监管端查询 workbook = xlrd.open_workbook('../data/application.xls') excel = copy(workbook) table = excel.get_sheet(0) table.write(int(number), 2, '') excel.save('../data/application.xls') logger.info('-----clean excel finished------') file = os.path.abspath(os.path.join(os.getcwd(), "../..")) picture_file = file + "\shhfw\data\%s" % picture logger.info('============add_application_action==============') self.driver.find_element(*self.fwxz).click() self.driver.find_element(*self.applicationBtn).click() logger.info('服务名称 is:%s' % application_name) self.driver.find_element( *self.applicationName).send_keys(application_name) application_Number = random.randint(000000000000000, 9999999999999999) logger.info('服务编号 is:%s' % application_Number) self.driver.find_element( *self.applicationNumber).send_keys(application_Number) ###向excel中写入服务编号,方便监管端查询 workbook = xlrd.open_workbook('../data/application.xls') excel = copy(workbook) table = excel.get_sheet(0) table.write(int(number), 2, str(application_Number)) excel.save('../data/application.xls') logger.info('-----write excel finished------') logger.info('服务类型 is:%s' % application_type) self.driver.find_element(*self.applicationType_1).click() element = self.driver.find_element(*self.applicationType_2) element1 = element.find_elements_by_xpath('li') for values in element1: if application_type in values.text: values.click() break logger.info('服务单价(元) is:%s' % application_cast) self.driver.find_element( *self.applicationCast).send_keys(application_cast) time.sleep(1) self.driver.find_element(*self.applicationUnit1).click() element3 = self.driver.find_element(*self.applicationUnit2) element4 = element3.find_elements_by_xpath('li') for values in element4: if unit in values.text: values.click() break # logging.info('上传图片 is:%s' %picture) self.driver.find_element(*self.updateBtn).send_keys(picture_file) logger.info('select sever area') li1 = str(region).split("-") logger.info("------region is %s------" % region) if len(li1) == 1: pass elif len(li1) == 2: self.driver.find_element(*self.serviceArea_Btn).click() element_area1 = self.driver.find_element(*self.serviceArea_1) element_area2 = element_area1.find_elements_by_xpath('li') ###找到所有li for values in element_area2: if li1[1] in values.text: values.click() break elif len(li1) == 3: self.driver.find_element(*self.serviceArea_Btn).click() element_area1 = self.driver.find_element(*self.serviceArea_1) element_area2 = element_area1.find_elements_by_xpath('li') ###找到所有li for values in element_area2: if li1[1] in values.text: values.click() break element_area3 = self.driver.find_element(*self.serviceArea_2) element_area4 = element_area1.find_elements_by_xpath('li') for values in element_area4: if li1[2] in values.text: values.click() break else: pass logger.error("area erorr") self.driver.find_element(*self.jxmc).send_keys("机械名称") self.driver.find_element(*self.jxxh).send_keys("dqeq112312") self.driver.find_element(*self.zyms).send_keys("作业描述") self.driver.find_element(*self.bz).send_keys("备注") self.driver.find_element(*self.msnr).send_keys("描述内容") logger.info('click savebutton') self.driver.find_element(*self.application_submit).click() logger.info('add_application_action finished!') time.sleep(5)