How to use __terminate method in yandex-tank

Best Python code snippet using yandex-tank

brandwatch.py

Source:brandwatch.py Github

copy

Full Screen

1from bcr_api.bwproject import BWProject, BWUser2from bcr_api.bwresources import BWQueries, BWGroups, BWAuthorLists, BWSiteLists, BWLocationLists, BWTags, BWCategories, BWRules, BWMentions, BWSignals3from datetime import datetime4from pytz import timezone5from time import sleep6import pandas as pd7import logging8logger = logging.getLogger("bcr_api")9logger.setLevel(logging.ERROR)10class Brandwatch:11 12 version = "1.0"13 14 # Set default parameter15 def __init__(self, token = None, token_path = 'tokens.txt', username = None, password = None, terminate = False, logger = None):16 self.__token = token17 self.__token_path = token_path18 self.__username = username19 self.__password = password20 self.__user = None21 self.__projects = None22 self.__project = None23 self.__groups = None24 self.__queries = None25 self.__groups_queries = None26 self.__mentions = None27 self.__delay = 3028 self.__terminate = terminate29 self.__logger = logger30 31 # Allow pandas dataframe display all rows and columns, default to 60 rows and 20 columns32 def set_display_all(self, flag = True):33 if flag is True:34 pd.set_option('display.max_rows', None)35 pd.set_option('display.max_columns', None)36 else:37 pd.set_option('display.max_rows', 60)38 pd.set_option('display.max_columns', 20)39 # Set delay time to retry if rate limit reach, default to 30 seconds40 def set_delay(self, delay = 30):41 self.__delay = delay42 43 # Set terminate signal when using GUI to interrupt44 def terminate(self, flag):45 self.__terminate = flag46 # Set logger to update log info to GUI47 def setLogger(self, logger):48 self.__logger = logger49 # Get user object with username/password or token50 def getUser(self):51 self.__user = None52 if self.__terminate:53 return self.__user54 try:55 self.__user = BWUser(username = self.__username, password = self.__password, token = self.__token, token_path = self.__token_path)56 self.__token = self.__user.token57 except Exception as e:58 if 'Invalid access token' in str(e):59 logging.info('Token is invalid or expired')60 if self.__logger is not None:61 self.__logger.emit('Token is invalid or expired')62 self.__user = None63 elif 'rate limit exceeded' in str(e):64 logging.info('Rate limit exceeded, please wait '+str(self.__delay)+'s ...')65 print('Rate limit exceeded, please wait '+str(self.__delay)+'s ...')66 if self.__logger is not None:67 self.__logger.emit('Rate limit exceeded, please wait '+str(self.__delay)+'s...')68 self.__user = None69 sleep(self.__delay)70 self.getUser()71 else:72 logging.info('Error: '+ str(e))73 if self.__logger is not None:74 self.__logger.emit('Error: '+str(e))75 return self.__user76 77 # Get BWProject object list, need to extract 'name' attr78 def getProjects(self):79 self.__projects = None80 if self.__terminate:81 return self.__projects82 if self.__user is None or self.__user.token != self.__token:83 self.getUser()84 if self.__user is not None:85 try:86 projects = self.__user.get_projects()87 if 'rate limit exceeded' in str(projects) or 'Invalid access token' in str(projects):88 raise Exception(projects)89 else:90 self.__projects = projects91 except Exception as e:92 if 'Invalid access token' in str(e):93 logging.info('Token is invalid or expired')94 if self.__logger is not None:95 self.__logger.emit('Token is invalid or expired')96 self.__user = None97 elif 'rate limit exceeded' in str(e):98 logging.info('Rate limit exceeded, please wait '+str(self.__delay)+'s ...')99 if self.__logger is not None:100 self.__logger.emit('Rate limit exceeded, please wait '+str(self.__delay)+'s...')101 self.__projects = None102 sleep(self.__delay)103 self.getProjects()104 else:105 logging.info('Error: '+ str(e))106 if self.__logger is not None:107 self.__logger.emit('Error: '+str(e))108 return self.__projects109 110 # Get BWProject object111 def getProject(self, project):112 self.__project = None113 if self.__terminate:114 return self.__project115 try:116 self.__project = BWProject(project=project, username = self.__username, password = self.__password, token = self.__token, token_path = self.__token_path)117 except Exception as e:118 if 'Invalid access token' in str(e):119 logging.info('Token is invalid or expired')120 if self.__logger is not None:121 self.__logger.emit('Token is invalid or expired')122 self.__user = None123 elif 'rate limit exceeded' in str(e):124 logging.info('Rate limit exceeded, please wait '+str(self.__delay)+'s ...')125 if self.__logger is not None:126 self.__logger.emit('Rate limit exceeded, please wait '+str(self.__delay)+'s...')127 self.__project = None128 sleep(self.__delay)129 self.getProject(project)130 else:131 logging.info('Error: '+ str(e))132 if self.__logger is not None:133 self.__logger.emit('Error: '+str(e))134 return self.__project135 # Get BWGroup object based on BWProject136 def getGroupInst(self, project):137 self.__groups = None138 if self.__terminate:139 return self.__groups140 try:141 self.__groups = BWGroups(project)142 except Exception as e:143 if 'Invalid access token' in str(e):144 logging.info('Token is invalid or expired')145 if self.__logger is not None:146 self.__logger.emit('Token is invalid or expired')147 self.__user = None148 elif 'rate limit exceeded' in str(e):149 logging.info('Rate limit exceeded, please wait '+str(self.__delay)+'s ...')150 if self.__logger is not None:151 self.__logger.emit('Rate limit exceeded, please wait '+str(self.__delay)+'s ...')152 self.__groups = None153 sleep(self.__delay)154 self.getGroupInst(project)155 else:156 logging.info('Error: '+ str(e))157 if self.__logger is not None:158 self.__logger.emit('Error: '+str(e))159 return self.__groups160 161 # Get BWGroup object list, need to extract 'name' attr162 def getGroups(self, project):163 self.__groups = None164 if self.__terminate:165 return self.__groups166 if self.__project is None or self.__project.project_name != project:167 self.getProject(project)168 if self.__project is not None:169 self.getGroupInst(self.__project)170 return self.__groups171 172 # Get BWQuery object173 def getQueryInst(self, project):174 self.__queries = None175 if self.__terminate:176 return self.__queries177 try:178 self.__queries = BWQueries(project)179 except Exception as e:180 if 'Invalid access token' in str(e):181 logging.info('Token is invalid or expired')182 if self.__logger is not None:183 self.__logger.emit('Token is invalid or expired')184 self.__user = None185 elif 'rate limit exceeded' in str(e):186 logging.info('Rate limit exceeded, please wait '+str(self.__delay)+'s ...')187 if self.__logger is not None:188 self.__logger.emit('Rate limit exceeded, please wait '+str(self.__delay)+'s...')189 self.__queries = None190 sleep(self.__delay)191 self.getQueryInst(project)192 else:193 logging.info('Error: '+ str(e))194 if self.__logger is not None:195 self.__logger.emit('Error: '+str(e))196 return self.__queries197 198 # Get BWQueries object list, need to extract 'name' attr199 def getQueries(self, project):200 self.__queries = None201 if self.__terminate:202 return self.__queries203 if self.__project is None or self.__project.project_name != project:204 self.getProject(project)205 if self.__project is not None:206 self.getQueryInst(self.__project)207 return self.__queries208 # Get BWQueries object list by group name, need to extract 'name' attr209 def getQueriesByGroup(self, group):210 self.__groups_queries = None211 if self.__terminate:212 return self.__groups_queries213 if self.__groups is not None:214 try:215 groups_queries = self.__groups.get_group_queries(name=group)216 if 'rate limit exceeded' in str(groups_queries) or 'Invalid access token' in str(groups_queries):217 raise Exception(groups_queries)218 else:219 self.__groups_queries = groups_queries220 except Exception as e:221 if 'Invalid access token' in str(e):222 logging.info('Token is invalid or expired')223 if self.__logger is not None:224 self.__logger.emit('Token is invalid or expired')225 self.__user = None226 elif 'rate limit exceeded' in str(e):227 logging.info('Rate limit exceeded, please wait '+str(self.__delay)+'s ...')228 if self.__logger is not None:229 self.__logger.emit('Rate limit exceeded, please wait '+str(self.__delay)+'s...')230 self.__groups_queries = None231 sleep(self.__delay)232 self.getQueriesByGroup(group)233 else:234 logging.info('Error: '+ str(e))235 if self.__logger is not None:236 self.__logger.emit('Error: '+str(e))237 else:238 logging.info('Please retrieve groups by project first ...')239 return self.__groups_queries240 241 # Get mentions with project name, query name, start and end time242 def getMentions(self, project, name, start, end):243 self.__mentions = None244 if self.__terminate:245 return self.__mentions246 if self.__queries is None:247 self.getQueries(project)248 if self.__queries is not None:249 try:250 mentions = self.__queries.get_mentions(name = name, startDate = start, endDate = end, __logger = self.__logger, __delay = self.__delay)251 if 'rate limit exceeded' in str(mentions) or 'Invalid access token' in str(mentions):252 raise Exception(mentions)253 else:254 self.__mentions = mentions255 except Exception as e:256 if 'Invalid access token' in str(e):257 logging.info('Token is invalid or expired')258 if self.__logger is not None:259 self.__logger.emit('Token is invalid or expired')260 self.__user = None261 elif 'rate limit exceeded' in str(e):262 logging.info('Rate limit exceeded, please wait '+str(self.__delay)+'s ...')263 if self.__logger is not None:264 self.__logger.emit('Rate limit exceeded, please wait '+str(self.__delay)+'s...')265 self.__mentions = None266 sleep(self.__delay)267 self.getMentions(project, name, start, end)268 else:269 logging.info('Error: '+ str(e))270 if self.__logger is not None:271 self.__logger.emit('Error: '+str(e))272 return self.__mentions273 # Convert projects raw data from json to dataframe274 def ProjectsDF(self):275 df = pd.DataFrame(self.__projects)276 return df277 # Convert groups raw data from json to dataframe 278 def GroupsDF(self):279 if self.__groups is not None:280 df = pd.DataFrame([[k,v] for k, v in self.__groups.names.items()], columns = ["id", "name"])281 else:282 df = pd.DataFrame(self.__groups)283 return df284 # Convert queries raw data from json to dataframe 285 def QueriesDF(self):286 if self.__queries is not None:287 df = pd.DataFrame([[k, v] for k, v in self.__queries.names.items()], columns = ["id", "name"])288 else:289 df = pd.DataFrame(self.__queries)290 return df291 292 # Convert queries raw data from json to dataframe293 def GroupQueriesDF(self):294 if self.__groups_queries is not None:295 df = pd.DataFrame([[v, k] for k, v in self.__groups_queries.items()], columns = ["id", "name"])296 else:297 df = pd.DataFrame(self.__groups_queries)298 return df299 # Convert mentions raw data from json to dataframe 300 def MentionsDF(self):301 df = pd.DataFrame(self.__mentions)302 return df303 304 # Print groups 305 def displayGroups(self):306 print(self.GroupsDF())307 308 # Print projects309 def displayProjects(self):310 print(self.ProjectsDF())311 312 # Print queries313 def displayQueries(self):314 print(self.QueryDF())315 # Print queries316 def displayGroupQueries(self):317 print(self.QueryDF())318 # Print mentions 319 def displayMentions(self):320 print(self.ProjectsDF())321 322 # Convert time with timezone to UTC323 def timeconvertToUTC(self, timestr, tz):324 original = timezone(tz).localize(datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S'))325 utc = original.astimezone(timezone('UTC'))326 return utc.strftime('%Y-%m-%dT%H:%M:%S')327 # Convert time with timezone from UTC328 def timeconvertFromUTC(self, timestr, tz):329 utc = timezone('UTC').localize(datetime.strptime(timestr, '%Y-%m-%dT%H:%M:%S'))330 dest = utc.astimezone(timezone(tz))331 return dest.strftime('%Y-%m-%d %H:%M:%S')332 # Convert NZT to UTC333 def NZT2UTC(self, timestr):334 return self.timeconvertToUTC(timestr, 'Pacific/Auckland')335 # Convert UTC to NZT336 def UTC2NZT(self, timestr):...

Full Screen

Full Screen

satif.py

Source:satif.py Github

copy

Full Screen

1#!/usr/bin/env python32#3# satif.py4# 5# Copyright (C) 2017 by G3UKB Bob Cowdery6# This program is free software; you can redistribute it and/or modify7# it under the terms of the GNU General Public License as published by8# the Free Software Foundation; either version 2 of the License, or9# (at your option) any later version.10# 11# This program is distributed in the hope that it will be useful,12# but WITHOUT ANY WARRANTY; without even the implied warranty of13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14# GNU General Public License for more details.15# 16# You should have received a copy of the GNU General Public License17# along with this program; if not, write to the Free Software18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA19# 20# The author can be reached by email at: 21# bob@bobcowdery.plus.com22#2324# Application imports25from imports import *26from defs import *27import defs2829"""30 Interface to the Satellite control program antenna interface.3132"""3334"""35 Main class of the satellite interface36"""37class SatIf(threading.Thread):38 39 def __init__(self, statusCallback, positionCallback, cmdq, msgq):40 """41 Constructor42 43 Arguments:44 statusCallback -- sat control status callback45 positionCallback -- send position updates46 cmdq -- Q to rotator interface thread47 msgq -- add messages for output here48 49 """50 51 super(SatIf, self).__init__()52 53 self.__statusCallback = statusCallback54 self.__positionCallback = positionCallback55 self.__cmdq = cmdq56 self.__msgq = msgq57 58 # Class variables59 self.__antListenerThread = None60 self.__terminate = False61 self.__restart = False62 self.__azimuth = 063 self.__elevation = 064 65 # Create the send q66 self.__sendq = deque()67 68 # A socket to listen on69 self.__sock = None70 71 def run(self):72 """ Thread entry point """73 74 75 # We require one socket to listen for connects from the satellite program antenna interface 76 if self.__openSocket():77 # Create the listener thread for Hamlib antctld commands78 self.__antListenerThread = AntListenerThread(self.__sock, self.__sendq, self.__msgq, self.__statusCallback, self.__listenCallback)79 self.__antListenerThread.start()80 81 # Loop until terminated by the user82 self.__msgq.append( 'Antenna Interface running')83 while not self.__terminate:84 if self.__restart:85 break86 sleep(1.0)87 88 # Exit thread89 if self.__sock != None:90 self.__sock.close()91 self.__msgq.append('Antenna interface thread exiting')92 self.__statusCallback(OFFLINE)93 94 def __openSocket(self):95 96 # We require one socket to listen for connects from the satellite program rig interface 97 retry = 598 r = False99 self.__sock = None100 while True:101 try:102 self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)103 self.__sock.bind((defs.SAT_IP, defs.SAT_PORT))104 self.__sock.settimeout(1)105 r = True106 break107 except Exception as e:108 if '10048' in str(e):109 # Socket not available110 self.__sock.close()111 retry -= 1112 if retry == 0:113 self.__msgq.append('Failed to bind sat control antenna interface socket!')114 self.__statusCallback(FAILED)115 break116 sleep(1)117 sleep(0.1)118 return r119 120 def terminate(self):121 """ Terminating """122 123 self.__terminate = True124 if self.__antListenerThread != None:125 self.__antListenerThread.terminate()126 self.__antListenerThread.join()127128 def __listenCallback(self, msg):129 """130 Callback from Satellite control program131 132 Arguments:133 msg -- callback message134 """135 136 # There is a basic set of commands that form the comms protocol137 # We are only interested in the 'p', 'P' and 'q' commands.138 # If we encounter others we will add them139 # p\n - get position as b'azimuth\nelevation\n'140 # where azimuth = 0.0 to 360.0 (nominal but can be changed in Gpredict)141 # P azimuth elevation\n -142 # set position143 # S stop rotator144 # q\n quit connection145 #146 # x request to quit from thread147 148 try:149 if len(msg) == 0: return150 toks = msg.split()151 if toks[0] == 'p':152 # Get command153 # Ask rotator interface to send position to sat program154 self.__cmdq.append(("getPos", [self.__azimuth, self.__elevation, self.__sendq]))155 elif toks[0] == 'P':156 # Set command157 if len(toks) == 3:158 try:159 self.__azimuth = int(float(toks[1]))160 self.__elevation = int(float(toks[2]))161 self.__cmdq.append(("setPosAz", [self.__azimuth]))162 self.__cmdq.append(("setPosEl", [self.__elevation]))163 self.__positionCallback(self.__azimuth, self.__elevation)164 # Send an ack165 self.__sendq.append('RPRT 0\n')166 except ValueError:167 self.__msgq.append('Invalid position parameters, not floats! ', paramList)168 else:169 self.__msgq.append('Invalid number of parameters for position command! [%s]' % msg)170 elif toks[0] == 'S':171 # Stop rotator, null effect as we move as directed172 self.__sendq.append('RPRT 0\n')173 elif toks[0] == 'q':174 self.__msgq.append('Request to quit listening')175 # Connection quit176 self.__sendq.append('RPRT 0\n')177 self.__restart = True178 elif toks[0] == 'x':179 self.__msgq.append('Antenna listner requested exit!')180 # Connection quit181 self.__restart = True182 else:183 # Oops184 self.__msgq.append('Unknown command from satellite program! [%s]' % msg)185 self.__sendq.append('RPRT 0\n')186 except Exception as e:187 self.__msgq.append('Problem with sat control, error in callback [%s,%s]' % (str(e),traceback.format_exc()))188 self.__restart = True189 190"""191 Listener thread for rotator commands192"""193class AntListenerThread(threading.Thread):194 195 def __init__(self, sock, sendq, msgq, statusCallback, evntCallback):196 """197 Constructor198 199 Arguments:200 sock -- open bound socket201 sendq -- queue to receive data to send202 msgq -- queue to send messages on203 statusCallback -- callback with connect status204 evntCallback -- callback here with event data205 206 """207 super(AntListenerThread, self).__init__()208 self.__sock = sock209 self.__sendq = sendq210 self.__msgq = msgq211 self.__statusCallback = statusCallback212 self.__evntCallback = evntCallback213 214 # Class vars215 self.__terminate = False216 self.__conn = None217 self.__addr = None218 219 def terminate(self):220 """ Thread terminating """221 222 self.__terminate = True223 224 def run(self):225 """ Thread entry point """226 227 self.__sock.listen(1)228 229 tries = 5230 self.__statusCallback(WAITING)231 while not self.__terminate:232 try:233 self.__conn, self.__addr = self.__sock.accept()234 break235 except socket.timeout:236 # No connection237 if self.__terminate: return238 continue239 except Exception as e:240 if self.__terminate: return241 tries -= 1242 self.__msgq.append('Exception while attempting a connect at try %d' % (5-tries))243 if tries < 0:244 self.__msgq.append('Connect exception [%s]' % (str(e)))245 self.__statusCallback(FAILED)246 return247 248 self.__msgq.append('Satellite antenna control connected at %s' % str(self.__addr))249 self.__statusCallback(ONLINE)250 251 self.__conn.settimeout(defs.SAT_TIMEOUT)252 while not self.__terminate:253 # Any data to send254 success = True255 while len(self.__sendq) > 0:256 data = self.__sendq.pop()257 # Wait a bit as Gpredict seems to miss the response otherwise and waits for ever258 try:259 self.__conn.send(bytes(data, 'UTF-8'))260 except Exception as e:261 if '10053' in str(e) or '10054' in str(e) or '32' in str(e):262 # Host disconnected, we will try and restart263 self.__msgq.append('Satelite control disconnected!')264 else:265 # Something else went wrong266 self.__msgq.append('Failure in antenna listener thread: [%s][%s]' % (format(e), traceback.format_exc()))267 # Request to restart thread268 self.__evntCallback ('x\n')269 self.__terminate = True270 self.__statusCallback(FAILED)271 success = False272 break273 274 if not self.__terminate and success: 275 try:276 data = self.__conn.recv(SAT_BUFFER)277 self.__evntCallback (data.decode(encoding='UTF-8'))278 except socket.timeout:279 # No data280 if self.__terminate: break281 continue282 except Exception as e:283 if '10053' in str(e) or '10054' in str(e) or '32' in str(e):284 # Host disconnected285 self.__msgq.append('Satelite control disconnected!')286 else:287 # Something else went wrong288 self.__msgq.append('Failure in listener thread: [%s][%s]' %(format(e), traceback.format_exc()))289 # Request to restart290 self.__evntCallback ('x\n')291 break292 293 self.__conn.close() 294 self.__msgq.append('Satellite Antenna Control Listener thread exiting...') ...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

...29 logger.addHandler(log_handler)30 if "log_level" in config:31 level = getattr(logging, config["log_level"].upper(), logging.NOTSET)32 logger.setLevel(level)33def __terminate(signum, frame):34 global daemon35 logger.debug("Got signal %i. Stopping...", signum)36 daemon.terminate()37 release_database()38def main():39 global daemon40 config = IniConfig.from_common_locations()41 setup_logging(config.DAEMON)42 signal(SIGTERM, __terminate)43 signal(SIGINT, __terminate)44 init_database(config.BASE["database_uri"])45 daemon = Daemon(config)46 daemon.run()47 release_database()

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