How to use upd_msg method in yandex-tank

Best Python code snippet using yandex-tank

skilift_checker.py

Source:skilift_checker.py Github

copy

Full Screen

1from lxml import html2import requests3import sys4import os5import re6import sched7import time8import numpy as np9import json10from pprint import pprint11from datetime import date, datetime, timedelta12import dateutil.parser13#reload(sys)14#sys.setdefaultencoding('utf-8')15##################################16## export PYTHONIOENCODING=utf8 ##17##################################18from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)19# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)20from email.mime.text import MIMEText21url = 'https://zillertal.intermaps.com/hochzillertal_spieljoch/data?lang=de'22snapshot_file = 'skilift_snapshot.json'23config_file = 'config.json'24try:25 conf = json.load(open(config_file))26 SMTPserver = conf.get('server')27 USERNAME = conf.get('user')28 PASSWORD = conf.get('password')29 30 sender = conf.get('sender')31 destination = conf.get('destination')32 33 webhook_url = conf.get('webhook_url')34 35except Exception as e:36 print(e)37 #mailout('Could not retrieve stock item')38 print('could not load configuration, please check config.json')39 quit()40def mailout(content):41 # typical values for text_subtype are plain, html, xml42 text_subtype = 'plain'43 content_old="""\44 Test message45 """46 subject="Skilift Update"47 try:48 msg = MIMEText(content, text_subtype)49 msg['Subject']= subject50 msg['From'] = sender51 conn = SMTP(SMTPserver)52 conn.set_debuglevel(False)53 conn.login(USERNAME, PASSWORD)54 try:55 print 'would send mail here'56 conn.sendmail(sender, destination, msg.as_string())57 finally:58 conn.quit()59 except:60 sys.exit( "mail failed; unknown error" ) # give a error message61def send_webhook(content):62 try:63 r = requests.post(webhook_url, json={"type": "message", "text": content})64 except Exception as e:65 print 'could not post to webhook'66 print repr(e)67def url_monitor():68 upd_msg = ""69 today = datetime.now()70 print '--------------------------------------------------------------------'71 print 'running check at '+today.isoformat()72 try:73 prev_snapshot_data = json.load(open(snapshot_file), encoding='utf-8')74 prev_snapshot_datetime = dateutil.parser.isoparse(prev_snapshot_data.get('date'))75 prev_snapshot = prev_snapshot_data.get('snapshot')76 count = prev_snapshot_data.get('count')77 print 'loaded snapshot from '+prev_snapshot_datetime.isoformat()78 #print dateutil.parser.isoparse(prev_snapshot_data.get('date'))79 80 if prev_snapshot_datetime.date() == today.date():81 raise UserWarning('already have a snapshot for '+prev_snapshot_datetime.date().isoformat()+', skipping..')82 83 print ("checking lifts at URL "+url+"...")84 print ("connecting")85 page = requests.get(url, timeout=10)86 print ("connection established")87 print 'page.encoding=', page.encoding88 data = json.loads(page.content)89 90 #print 'data: ', data91 liftsnapshot = {}92 for lift in data['lifts']:93 length = 094 id = lift.get('id')95 status = lift.get('status')96 status_val = float(1) if status == 'open' else float(0)97 if lift.get('popup'):98 title = lift.get('popup').get('title')99 subtitle = lift.get('popup').get('subtitle')100 if lift.get('popup').get('additional-info'):101 if lift.get('popup').get('additional-info').get('length'):102 length = lift.get('popup').get('additional-info').get('length')103 if length > 500:104 prev_lift_snapshot = prev_snapshot.get(id)105 prev_availability = prev_lift_snapshot.get('availability') if prev_lift_snapshot else float(1)106 availability = (float(count) * prev_availability + status_val) / float(count+1) if count > 0 else status_val107 liftsnapshot[id] = {'title': title, 'status':status, 'availability': availability}108 upd_msg+="{:10.2f}".format(availability*100) + "% - "+title+" "+status+" length: "+ str(length)+"\n"109 snapshot_data={'date': today.isoformat(),'count': count+1,'snapshot': liftsnapshot}110 with open(snapshot_file, 'w') as outfile:111 json.dump(snapshot_data, outfile, encoding='utf-8', indent=2)112 except UserWarning as w:113 print(w)114 except Exception as e:115 print(e)116 #mailout('Could not retrieve stock item')117 print('Error processing request')118 #upd_msg += e119 send_webhook("Help, I'm having trouble: " + repr(e))120 #pprint(data)121 if len(upd_msg) > 0:122 print("(not) sending mail:\n"+upd_msg)123 send_webhook(upd_msg)124 #pprint liftsnapshot125 #mailout(upd_msg.encode(sys.stdout.encoding, errors='replace'))126 127sch = sched.scheduler(time.time, time.sleep)128def do_something(sc): 129 # do your stuff130 url_monitor()131 #check every 8 hrs (60 x 60 x 8 = 28800)132 now = datetime.now()133 nextday = now if now.hour < 11 else now +timedelta(days=1)134 nexttime = datetime(nextday.year, nextday.month, nextday.day, 11, 5, 0, 0)135 print "will run again at ", nexttime.isoformat()136 delay = (nexttime - now).total_seconds()137 print "delay=", int(delay)138 sch.enter(delay, 1, do_something, (sch,))139 #sch.enter(10, 1, do_something, (sch,))140# init141print ('jallo')142sch.enter(1, 1, do_something, (sch,))...

Full Screen

Full Screen

te_controller.py

Source:te_controller.py Github

copy

Full Screen

1__author__ = 'dipsingh'2import socket3import mpls_lsp_pb24import struct5class TEController(object):6 def __init__(self):7 self._lsp_dict = dict()8 self._lsp_delg_dict = dict()9 self._srpid = 110 def ip2int(self, addr):11 return struct.unpack_from("!I", socket.inet_aton(addr))[0]12 def handle_pce_message(self, pcc_ip, message):13 if message[0] == 'State_Report':14 result = self.handle_state_report_od(pcc_ip, message)15 return result16 return (None,)17 def handle_state_report_od(self,pcc_ip,message):18 lsp=mpls_lsp_pb2.LSP()19 first_lsp = 120 for report_object in message[1]:21 if (report_object[0] == 'LSP_Object'):22 if (report_object[1][0] != 0):23 lsp.pcc_ip = pcc_ip[0]24 lsp.lsp_obj.plsp_id = report_object[1][0]25 lsp.lsp_obj.delegated = report_object[1][1]26 lsp.lsp_obj.sync = report_object[1][2]27 lsp.lsp_obj.remove = report_object[1][3]28 lsp.lsp_obj.administrative = report_object[1][4]29 lsp.lsp_obj.operational = report_object[1][5]30 lsp.lsp_obj.create = report_object[1][6]31 if report_object[1][7][0][0] == 'Symbolic_Name':32 lsp.lsp_obj.symbolic_name = report_object[1][7][0][2]33 if report_object[1][7][1][0] == 'LSP_IDENTIFIER':34 lsp.lsp_obj.tunnel_source = report_object[1][7][1][2]35 lsp.lsp_obj.tunnel_endpoint= report_object[1][7][1][5]36 lsp.lsp_obj.tunnel_id = report_object[1][7][1][4]37 lsp.lsp_obj.lsp_id = report_object[1][7][1][3]38 if report_object[0] == "Bandwidth_Object" :39 lsp.bandwidth = report_object[1][0]40 if report_object[0] == "ERO_LIST_EMPTY":41 lsp.ero_list_empty = True42 if report_object[0] == "SRP_ID":43 lsp.srp.srp_id = report_object[1][0]44 if report_object[0] == "LSPA":45 lsp.lspa_obj.setup_prio= report_object[1][0]46 lsp.lspa_obj.hold_prio = report_object[1][1]47 lsp.lspa_obj.local_protection = report_object[1][2]48 if report_object[0] == "ERO_List" :49 if len(report_object[1]) > 0 :50 for ero_node in report_object[1]:51 ero=lsp.ero.add()52 ero.loose= ero_node[1]53 ero.node_ip = ero_node[2]54 ero.node_mask= ero_node[3]55 if report_object[0] == "SR_ERO_lIST":56 if len(report_object[1]) > 0:57 for ero_node in report_object[1]:58 srero = lsp.srero.add()59 srero.loose = ero_node[1]60 srero.node_label = ero_node[2]61 srero.node_ip = ero_node[3]62 if report_object[0] == "RRO_List":63 if len (report_object[1]) > 0 :64 for rro_node in report_object[1]:65 rro=lsp.rro.add()66 rro.loose=rro_node[1]67 rro.node_ip = rro_node[2]68 rro.node_mask = rro_node[3]69 if report_object[0] == "SRP_ID":70 lsp.srp.srp_id = report_object[1][0]71 else:72 lsp.srp.srp_id = 073 lsp_dict_index = (self.ip2int(pcc_ip[0]),lsp.lsp_obj.plsp_id)74 self._lsp_dict[lsp_dict_index] = lsp75 delegate_lsps = list()76 for key in self._lsp_dict:77 lsp = self._lsp_dict[key]78 if (lsp.lsp_obj.delegated) & (lsp.lsp_obj.tunnel_id > 100):79 if lsp.lsp_obj.operational == 0:80 delegate_lsps.append(lsp)81 print ("Delegated LSP ", lsp)82 if len (delegate_lsps) > 0:83 for lsp in delegate_lsps:84 lsp_dict_delg_index = lsp.lsp_obj.tunnel_id85 self._lsp_delg_dict[lsp_dict_delg_index] = (self.generate_lsp_upd_msg_od(lsp))86 #print ("Delegated LSP Dict",self._lsp_delg_dict)87 return ("lsp_update",self._lsp_delg_dict)88 return (None)89 def generate_lsp_upd_msg_od(self,lsp):90 upd_msg = list()91 upd_msg.append(('LSP_Object',(lsp.lsp_obj.plsp_id,lsp.lsp_obj.delegated,lsp.lsp_obj.sync,lsp.lsp_obj.remove,lsp.lsp_obj.administrative,lsp.lsp_obj.operational,lsp.lsp_obj.symbolic_name)))92 upd_msg.append(('ENDPOINT_Object',(lsp.lsp_obj.tunnel_source,lsp.lsp_obj.tunnel_endpoint,lsp.lsp_obj.tunnel_id)))93 if lsp.ero:94 ero_list = list()95 for ero in lsp.ero:96 ero_list.append((ero.loose,self.ip2int(ero.node_ip),ero.node_mask))97 upd_msg.append(("ERO_List",ero_list))98 else:99 upd_msg.append (("ERO_List_EMPTY",((0,0,0),)))100 upd_msg.append (("LSPA",(lsp.lspa_obj.setup_prio,lsp.lspa_obj.hold_prio,lsp.lspa_obj.local_protection)))101 upd_msg.append (("Bandwidth_Object",(lsp.bandwidth,)))...

Full Screen

Full Screen

reject_pending_message.py

Source:reject_pending_message.py Github

copy

Full Screen

1from intergov.monitoring import statsd_timer2from intergov.use_cases.common import BaseUseCase3class RejectPendingMessageUseCase(BaseUseCase):4 """5 Gets a single message from rejected message repo6 If rejected message payload is valid - has sender, sender_ref fields7 updates message metadata by changing status to rejected via message lake repo8 update_metadata method9 Fails if:10 1. unable to update message status11 2. rejected message payload is invalid12 """13 def __init__(self, rejected_message_repo, message_lake_repo):14 self.rejected_messages = rejected_message_repo15 self.message_lake = message_lake_repo16 def execute(self):17 update = self.rejected_messages.get()18 if not update:19 return None20 (upd_id, upd_msg) = update21 super().execute()22 return self.process(upd_id, upd_msg)23 @statsd_timer("usecase.RejectPendingMessageUseCase.process")24 def process(self, upd_id, upd_msg):25 delta = {'status': 'rejected'}26 # right now only reason of failure is a critical error27 # NOTE: we need to decide what to do if message not found28 # is it success or critical failure29 try:30 self.message_lake.update_metadata(upd_msg.sender, upd_msg.sender_ref, delta)31 except Exception as e:32 raise Exception(f"Unable to update message status. Reason: {e}") from e33 deleted = self.rejected_messages.delete(upd_id)34 if not deleted:35 return False...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run yandex-tank automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful