Skip to content

Commit

Permalink
Pylint enhancements
Browse files Browse the repository at this point in the history
  • Loading branch information
farirat committed Oct 28, 2015
1 parent cfa3b8b commit d3fe8bb
Show file tree
Hide file tree
Showing 16 changed files with 68 additions and 71 deletions.
12 changes: 6 additions & 6 deletions jasmin/interceptor/interceptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ def perspective_run_script(self, pyCode, routable):

try:
self.log.info('Running with a %s (from:%s, to:%s).',
routable.pdu.id,
routable.pdu.params['source_addr'],
routable.pdu.params['destination_addr'])
routable.pdu.id,
routable.pdu.params['source_addr'],
routable.pdu.params['destination_addr'])
self.log.debug('Running [%s]', pyCode)
self.log.debug('... with routable with pdu: %s', routable.pdu)
node = CompiledNode().get(pyCode)
Expand All @@ -53,9 +53,9 @@ def perspective_run_script(self, pyCode, routable):
end = dt.datetime.now()
except Exception, e:
self.log.error('Executing script on routable (from:%s, to:%s) returned: %s',
routable.pdu.params['source_addr'],
routable.pdu.params['destination_addr'],
'%s: %s' % (type(e), e))
routable.pdu.params['source_addr'],
routable.pdu.params['destination_addr'],
'%s: %s' % (type(e), e))
return False
else:
delay = (end - start).seconds
Expand Down
2 changes: 1 addition & 1 deletion jasmin/managers/clients.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ def perspective_load(self, profile='jcli-prod'):
# Add connector
addRet = yield self.perspective_connector_add(
pickle.dumps(loadedConnector['config'],
self.pickleProtocol))
self.pickleProtocol))
if not addRet:
raise ConfigProfileLoadingError('Error adding connector %s' % loadedConnector['id'])

Expand Down
4 changes: 2 additions & 2 deletions jasmin/managers/listeners.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def rejectAndRequeueMessage(self, message, delay=True):

if delay != False:
# Use configured requeue_delay or specific one
if type(delay) != bool:
if not isinstance(delay, bool):
requeue_delay = delay
else:
requeue_delay = self.SMPPClientFactory.config.requeue_delay
Expand Down Expand Up @@ -395,7 +395,7 @@ def submit_sm_resp_event(self, r, amqpMessage):
pickledSmppsMap = yield self.redisClient.get("smppsmap:%s" % msgid)

if pickledDlr is not None:
self.log.debug('There is a HTTP DLR request for msgid[%s] ...' % (msgid))
self.log.debug('There is a HTTP DLR request for msgid[%s] ...', msgid)

dlr = pickle.loads(pickledDlr)
dlr_url = dlr['url']
Expand Down
4 changes: 2 additions & 2 deletions jasmin/protocols/cli/filtersm.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,8 +221,8 @@ def exist_filter_and_call(self, *args, **kwargs):
opts = args[1]
fid = getattr(opts, fid_key)

for _filterId in self.filters.iterkeys():
if fid == _filterId:
for filter_id in self.filters.iterkeys():
if fid == filter_id:
return fCallback(self, *args, **kwargs)

return self.protocol.sendData('Unknown Filter: %s' % fid)
Expand Down
4 changes: 2 additions & 2 deletions jasmin/protocols/cli/httpccm.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ def exist_httpcc_and_call(self, *args, **kwargs):
opts = args[1]
cid = getattr(opts, cid_key)

for _httpccId in self.httpccs.iterkeys():
if cid == _httpccId:
for httpcc_id in self.httpccs.iterkeys():
if cid == httpcc_id:
return fCallback(self, *args, **kwargs)

return self.protocol.sendData('Unknown Httpcc: %s' % cid)
Expand Down
2 changes: 1 addition & 1 deletion jasmin/protocols/cli/mointerceptorm.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def parse_args_and_call_with_instance(self, *args, **kwargs):
return self.protocol.sendData(
'Interceptor order forced to 0 since it is a DefaultInterceptor')
elif (arg == '0' and 'type' in self.sessBuffer and
self.sessBuffer['type'] != 'DefaultInterceptor'):
self.sessBuffer['type'] != 'DefaultInterceptor'):
return self.protocol.sendData(
'This interceptor order (0) is reserved for DefaultInterceptor only')
elif not arg.isdigit() or int(arg) < 0:
Expand Down
2 changes: 1 addition & 1 deletion jasmin/protocols/cli/mtinterceptorm.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def parse_args_and_call_with_instance(self, *args, **kwargs):
return self.protocol.sendData(
'Interceptor order forced to 0 since it is a DefaultInterceptor')
elif (arg == '0' and 'type' in self.sessBuffer and
self.sessBuffer['type'] != 'DefaultInterceptor'):
self.sessBuffer['type'] != 'DefaultInterceptor'):
return self.protocol.sendData(
'This interceptor order (0) is reserved for DefaultInterceptor only')
elif not arg.isdigit() or int(arg) < 0:
Expand Down
2 changes: 1 addition & 1 deletion jasmin/protocols/cli/smppccm.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def castInputToBuiltInType(key, value):
elif (key == 'loglevel' and
value not in [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]):
raise KeyError('loglevel must be numeric value of 10, 20, 30, 40 or 50.')
elif type(value) == str and value.lower() == 'none':
elif isinstance(value, str) == str and value.lower() == 'none':
value = None
except KeyError:
raise UnknownValue('Unknown value for key %s: %s' % (key, value))
Expand Down
8 changes: 4 additions & 4 deletions jasmin/protocols/cli/statsm.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,11 @@ def smppcs(self, arg, opts):
row.append(formatDateTime(sc.get(connector['id']).get('connected_at')))
row.append(formatDateTime(sc.get(connector['id']).get('bound_at')))
row.append(formatDateTime(sc.get(connector['id']).get('disconnected_at')))
row.append('%s/%s' % (sc.get(connector['id']).get(
'submit_sm_request_count'),
row.append('%s/%s' % (
sc.get(connector['id']).get('submit_sm_request_count'),
sc.get(connector['id']).get('submit_sm_count')))
row.append('%s/%s' % (sc.get(connector['id']).get(
'deliver_sm_count'),
row.append('%s/%s' % (
sc.get(connector['id']).get('deliver_sm_count'),
sc.get(connector['id']).get('data_sm_count')))
row.append(sc.get(connector['id']).get('throttling_error_count'))
row.append(sc.get(connector['id']).get('other_submit_error_count'))
Expand Down
6 changes: 3 additions & 3 deletions jasmin/protocols/http/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ def render(self, request):
'priority' : {'optional': True, 'pattern': re.compile(r'^[0-3]$')},
# Validity period validation pattern can be validated/filtered further more
# through HttpAPICredentialValidator
'validity-period' : {'optional': True , 'pattern': re.compile(r'^\d+$')},
'validity-period' : {'optional': True, 'pattern': re.compile(r'^\d+$')},
'dlr' : {'optional': False, 'pattern': re.compile(r'^(yes|no)$')},
'dlr-url' : {'optional': True, 'pattern': re.compile(r'^(http|https)\://.*$')},
# DLR Level validation pattern can be validated/filtered further more
Expand Down Expand Up @@ -388,8 +388,8 @@ def route_routable(self, request):
self.log.error(
"Authentication failure for username:%s",
request.args['username'][0])
raise AuthenticationError('Authentication failure for username:%s' %
request.args['username'][0])
raise AuthenticationError(
'Authentication failure for username:%s' % request.args['username'][0])

# Update CnxStatus
user.getCnxStatus().httpapi['connects_count'] += 1
Expand Down
66 changes: 31 additions & 35 deletions jasmin/protocols/smpp/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,11 @@ def PDUReceived(self, pdu):
self.log.debug("Complete PDU dump: %s", pdu)
self.factory.stats.set('last_received_pdu_at', datetime.now())

"""A better version than vendor's PDUReceived method:
- Dont re-encode pdu !
if self.log.isEnabledFor(logging.DEBUG):
encoded = self.encoder.encode(pdu)
self.log.debug("Receiving data [%s]" % _safelylogOutPdu(encoded))
"""
#A better version than vendor's PDUReceived method:
#- Dont re-encode pdu !
#if self.log.isEnabledFor(logging.DEBUG):
# encoded = self.encoder.encode(pdu)
# self.log.debug("Receiving data [%s]" % _safelylogOutPdu(encoded))

#Signal SMPP operation
self.onSMPPOperation()
Expand Down Expand Up @@ -135,9 +134,7 @@ def endOutboundTransaction(self, respPDU):
if not isinstance(respPDU, txn.request.requireAck):
txn.ackDeferred.errback(
SMPPProtocolError("Invalid PDU response type [%s] returned for request type [%s]" % (
type(respPDU), type(txn.request)
)
))
type(respPDU), type(txn.request))))
return
#Do callback
txn.ackDeferred.callback(SMPPOutboundTxnResult(self, txn.request, respPDU))
Expand All @@ -149,20 +146,20 @@ def endOutboundTransaction(self, respPDU):

txn.ackDeferred.errback(SMPPTransactionError(respPDU, txn.request))

def cancelOutboundTransactions(self, error):
def cancelOutboundTransactions(self, err):
"""Cancels LongSubmitSmTransactions when cancelling OutboundTransactions
"""
twistedSMPPClientProtocol.cancelOutboundTransactions(self, error)
self.cancelLongSubmitSmTransactions(error)
twistedSMPPClientProtocol.cancelOutboundTransactions(self, err)
self.cancelLongSubmitSmTransactions(err)

def cancelLongSubmitSmTransactions(self, error):
def cancelLongSubmitSmTransactions(self, err):
for item in self.longSubmitSmTxns.values():
reqPDU = item['txn'].request

self.log.exception(error)
self.log.exception(err)
txn = self.closeLongSubmitSmTransaction(reqPDU.LongSubmitSm['msg_ref_num'])
#Do errback
txn.ackDeferred.errback(error)
txn.ackDeferred.errback(err)

def startLongSubmitSmTransaction(self, reqPDU, timeout):
if reqPDU.LongSubmitSm['msg_ref_num'] in self.longSubmitSmTxns:
Expand Down Expand Up @@ -243,7 +240,7 @@ def preSubmitSm(self, pdu):
intVal = pdu.params['data_coding']
if intVal in data_coding_default_value_map:
name = data_coding_default_value_map[intVal]
pdu.params['data_coding'] = DataCoding(schemeData = getattr(DataCodingDefault, name))
pdu.params['data_coding'] = DataCoding(schemeData=getattr(DataCodingDefault, name))
else:
pdu.params['data_coding'] = None

Expand Down Expand Up @@ -351,12 +348,11 @@ def PDUReceived(self, pdu):
self.log.debug("Complete PDU dump: %s", pdu)
self.factory.stats.set('last_received_pdu_at', datetime.now())

"""A better version than vendor's PDUReceived method:
- Dont re-encode pdu !
if self.log.isEnabledFor(logging.DEBUG):
encoded = self.encoder.encode(pdu)
self.log.debug("Receiving data [%s]" % _safelylogOutPdu(encoded))
"""
#A better version than vendor's PDUReceived method:
#- Dont re-encode pdu !
#if self.log.isEnabledFor(logging.DEBUG):
# encoded = self.encoder.encode(pdu)
# self.log.debug("Receiving data [%s]" % _safelylogOutPdu(encoded))

#Signal SMPP operation
self.onSMPPOperation()
Expand Down Expand Up @@ -394,7 +390,7 @@ def onPDURequest_enquire_link(self, reqPDU):
self.factory.stats.set('last_received_elink_at', datetime.now())
self.factory.stats.inc('elink_count')
if self.user is not None:
self.user.getCnxStatus().smpps['elink_count']+= 1
self.user.getCnxStatus().smpps['elink_count'] += 1

def doPDURequest(self, reqPDU, handler):
twistedSMPPServerProtocol.doPDURequest(self, reqPDU, handler)
Expand All @@ -418,31 +414,31 @@ def sendPDU(self, pdu):
self.user.uid,
pdu.params['source_addr'],
pdu.params['destination_addr'],
re.sub(r'[^\x20-\x7E]+','.', pdu.params['short_message']))
self.user.getCnxStatus().smpps['deliver_sm_count']+= 1
re.sub(r'[^\x20-\x7E]+', '.', pdu.params['short_message']))
self.user.getCnxStatus().smpps['deliver_sm_count'] += 1
elif pdu.commandId == CommandId.data_sm:
self.factory.stats.inc('data_sm_count')
if self.user is not None:
self.log.info('DATA_SM [uid:%s] [from:%s] [to:%s] [content:%s]',
self.user.uid,
pdu.params['source_addr'],
pdu.params['destination_addr'],
re.sub(r'[^\x20-\x7E]+','.', pdu.params['short_message']))
self.user.uid,
pdu.params['source_addr'],
pdu.params['destination_addr'],
re.sub(r'[^\x20-\x7E]+','.', pdu.params['short_message']))
self.user.getCnxStatus().smpps['data_sm_count']+= 1
elif pdu.commandId == CommandId.submit_sm_resp:
if pdu.status == CommandStatus.ESME_RTHROTTLED:
self.factory.stats.inc('throttling_error_count')
if self.user is not None:
self.user.getCnxStatus().smpps['throttling_error_count']+= 1
self.user.getCnxStatus().smpps['throttling_error_count'] += 1
elif pdu.status != CommandStatus.ESME_ROK:
self.factory.stats.inc('other_submit_error_count')
if self.user is not None:
self.user.getCnxStatus().smpps['other_submit_error_count']+= 1
self.user.getCnxStatus().smpps['other_submit_error_count'] += 1
else:
# We got a ESME_ROK
self.factory.stats.inc('submit_sm_count')
if self.user is not None:
self.user.getCnxStatus().smpps['submit_sm_count']+= 1
self.user.getCnxStatus().smpps['submit_sm_count'] += 1


def onPDURequest_unbind(self, reqPDU):
Expand All @@ -468,9 +464,9 @@ def PDUDataRequestReceived(self, reqPDU):
def PDURequestReceived(self, reqPDU):
# Handle only accepted command ids
acceptedPDUs = [CommandId.submit_sm, CommandId.bind_transmitter,
CommandId.bind_receiver, CommandId.bind_transceiver,
CommandId.unbind, CommandId.unbind_resp,
CommandId.enquire_link, CommandId.data_sm]
CommandId.bind_receiver, CommandId.bind_transceiver,
CommandId.unbind, CommandId.unbind_resp,
CommandId.enquire_link, CommandId.data_sm]
if reqPDU.commandId not in acceptedPDUs:
errMsg = 'Received unsupported pdu type: %s' % reqPDU.commandId
self.cancelOutboundTransactions(SessionStateError(errMsg, CommandStatus.ESME_RSYSERR))
Expand Down
1 change: 1 addition & 0 deletions jasmin/queues/factory.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#pylint: disable=E0203
import logging
from logging.handlers import TimedRotatingFileHandler
from twisted.internet.protocol import ClientFactory
Expand Down
2 changes: 1 addition & 1 deletion jasmin/routing/Interceptors.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class Interceptor(object):
def __init__(self, filters, script):
if not isinstance(script, InterceptorScript):
raise InvalidInterceptorParameterError("script is not an instance of InterceptorScript")
if type(filters) is not list:
if not isinstance(filters, list):
raise InvalidInterceptorParameterError("filters must be a list")
for _filter in filters:
if not isinstance(_filter, Filter):
Expand Down
12 changes: 6 additions & 6 deletions jasmin/routing/Routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ class Route(object):
def __init__(self, filters, connector, rate):
if not isinstance(connector, Connector):
raise InvalidRouteParameterError("connector is not an instance of Connector")
if type(rate) is not float:
if not isinstance(rate, float):
raise InvalidRouteParameterError("rate is not float")
if rate < 0:
raise InvalidRouteParameterError("rate can not be a negative value")
if type(filters) is not list:
if not isinstance(filters, list):
raise InvalidRouteParameterError("filters must be a list")
for _filter in filters:
if not isinstance(_filter, Filter):
Expand Down Expand Up @@ -128,7 +128,7 @@ def __init__(self, connector, rate=0.0):
"""
if not isinstance(connector, Connector):
raise InvalidRouteParameterError("connector is not an instance of Connector")
if type(rate) is not float:
if not isinstance(rate, float):
raise InvalidRouteParameterError("rate is not float")
if rate < 0:
raise InvalidRouteParameterError("rate can not be a negative value")
Expand Down Expand Up @@ -172,12 +172,12 @@ class RoundrobinRoute(object):
"""Generick RoundrobinRoute
"""
def __init__(self, filters, connectors):
if type(connectors) is not list:
if not isinstance(connectors, list):
raise InvalidRouteParameterError("connectors must be a list")
for _connector in connectors:
if not isinstance(_connector, Connector):
raise InvalidRouteParameterError("connector is not an instance of Connector")
if type(filters) is not list:
if not isinstance(filters, list):
raise InvalidRouteParameterError("filters must be a list")
for _filter in filters:
if not isinstance(_filter, Filter):
Expand Down Expand Up @@ -219,7 +219,7 @@ class RandomRoundrobinMTRoute(RoundrobinRoute, MTRoute):
def __init__(self, filters, connectors, rate):
"Overriding RoundrobinRoute's __init__ to add rate parameter as it is only used for MT Routes"

if type(rate) is not float:
if not isinstance(rate, float):
raise InvalidRouteParameterError("rate is not float")
if rate < 0:
raise InvalidRouteParameterError("rate can not be a negative value")
Expand Down
4 changes: 2 additions & 2 deletions jasmin/routing/RoutingTables.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ def add(self, route, order):

# Ensure connector type is correct for given route
if self.type == 'mo':
if type(route.connector) is not list:
if not isinstance(route.connector, list):
if route.connector.type not in ['http', 'smpps']:
raise InvalidRoutingTableParameterError("connector '%s' type '%s' is not valid for MO Route" % (route.connector.cid, route.connector.type))
else:
for connector in route.connector:
if connector.type not in ['http', 'smpps']:
raise InvalidRoutingTableParameterError("connector '%s' type '%s' is not valid for MO Route" % (connector.cid, connector.type))
elif self.type == 'mt':
if type(route.connector) is not list:
if not isinstance(route.connector, list):
if route.connector.type not in ['smppc']:
raise InvalidRoutingTableParameterError("connector '%s' type '%s' is not valid for MT Route" % (route.connector.cid, route.connector.type))
else:
Expand Down
8 changes: 4 additions & 4 deletions jasmin/tools/singleton.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class Singleton(type):
_instances = {}

def __call__(mcs, *args, **kwargs):
if mcs not in mcs._instances:
mcs._instances[mcs] = super(Singleton, mcs).__call__(*args, **kwargs)
return mcs._instances[mcs]
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]

0 comments on commit d3fe8bb

Please sign in to comment.