Commit 78a697c2 authored by Hartmut Goebel's avatar Hartmut Goebel
Browse files

Cleanup: pep8ifying sources.

This changes have been applied to all python files using
https://github.com/htgoebel/pep8ify and the result has been checked.
parent ea63dfa2
......@@ -9,14 +9,15 @@ setup(
long_description="""In preparation""",
author="Michael Weinrich",
author_email='testsuite@michael-weinrich.de',
license = "MIT",
license="MIT",
packages=find_packages(),
scripts = ['bin/upntest', 'bin/upntest-gui'],
url = "http://coherence.beebits.net",
scripts=['bin/upntest', 'bin/upntest-gui'],
install_requires=['Coherence', 'lxml', 'Twisted', 'Louie', 'pygtk'],
url="http://coherence.beebits.net",
#download_url = 'https://coherence.beebits.net/download/Coherence-%s.tar.gz' % __version__,
download_url = '',
download_url='',
keywords=['UPnP'],
classifiers = ['Development Status :: 4 - Beta',
classifiers=['Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'License :: OSI Approved :: MIT License',
......@@ -26,7 +27,7 @@ setup(
entry_points="""""",
package_data = {
package_data={
'coherence': ['xmlfiles/device/*.xml',
'xmlfiles/service/*.xml',
'schemas/*.xsd']
......
......@@ -5,7 +5,7 @@ try:
xmlschema_doc = etree.parse('/home/micxer/development/UPnT/testresources/service.xsd')
except Exception, e:
print e.error_log
try:
xmlschema = etree.XMLSchema(xmlschema_doc)
except Exception, e:
......
......@@ -14,7 +14,8 @@ import os
from twisted.internet import reactor, task, defer
from twisted.python.filepath import FilePath
import gtk, gtk.glade, gobject
import gtk
import gobject
from coherence import log
......@@ -56,15 +57,15 @@ class UPnTGUI(log.Loggable):
self.window = self.wTree.get_widget(self.windowname)
dic = {
"onDestroy" : self.shutdown,
"onExecuteTest": self.executeTests,
"onToolButtonQuit": self.shutdown,
"onDestroy": self.shutdown,
"onExecuteTest": self.executeTests,
"onToolButtonQuit": self.shutdown,
"onActivateDeviceRow": self.showDetails
}
self.wTree.signal_autoconnect(dic)
# TreView for the devices
gfx_dir = config.get('gfx_dir', FilePath(__file__).parent().parent().path);
gfx_dir = config.get('gfx_dir', FilePath(__file__).parent().parent().path)
if not gfx_dir.endswith('/'):
gfx_dir += '/'
self.device_icon = gtk.gdk.pixbuf_new_from_file_at_size(gfx_dir + 'gnome-fs-client.svg', 24, 24)
......@@ -177,7 +178,6 @@ class UPnTGUI(log.Loggable):
self.addSubDevicesToTree(model, subdevice_iter, subdevice)
self.addServicesToTree(model, subdevice_iter, subdevice)
def addServicesToTree(self, model, device_iter, device):
"""
Add all services of a device to the tree
......
#: C{tuple} with version information
__version_info__ = (0,5,0)
__version_info__ = (0, 5, 0)
#: A C{str} variable that shows the actual version of this software.
__version__ = '%d.%d.%d' % (__version_info__[0],__version_info__[1],__version_info__[2],)
__version__ = '%d.%d.%d' % (__version_info__[0], __version_info__[1], __version_info__[2], )
......@@ -16,6 +16,7 @@ from coherence import log
# local includes
from upntest.host import Host
class UPnT(log.Loggable):
"""
Main class of the test tool. All messages from UPnP devices are send to
......@@ -53,7 +54,7 @@ class UPnT(log.Loggable):
"""Stores the given config options to pass it on to other objects who
need it."""
self._coherence = Coherence(self._config);
self._coherence = Coherence(self._config)
"""The C{Coherence} instance that is created based on the given config
C{dict}."""
......@@ -69,7 +70,6 @@ class UPnT(log.Loggable):
louie.connect(self.addDeferredToList, 'UPnT.running_deferred', louie.Any, weak=False)
louie.connect(self.removeDeferredFromList, 'UPnT.ending_deferred', louie.Any, weak=False)
self.info('signals connected, waiting for signals...')
#reactor.addSystemEventTrigger('before', 'shutdown', self.waitForShutdown)
def eventMessage(self, message, list):
......@@ -103,7 +103,7 @@ class UPnT(log.Loggable):
#try:
self._knownHosts[ip].dispatchDiscoveryPacketData(data)
#except Exception, error:
# self.warning(error)
# self.warning(error)
def hostRemoved(self, ip):
"""
......
......@@ -20,6 +20,7 @@ from coherence import log
# local includes
from upntest.soap_proxy import SOAPProxy
class ServerControl(log.Loggable):
"""
This class contains methods to invoke all actions that a service offers and
......@@ -207,7 +208,6 @@ class ServerControl(log.Loggable):
d.addErrback(self.callFailed, action, url, in_args, testcase['ActionName'])
is_looped = self.loop_tests
#self.test_deferred.callback(test_result)
def stopTesting(self):
......@@ -431,4 +431,4 @@ class ClientControl(log.Loggable):
return False
return True
self.debug('Control call ok')
\ No newline at end of file
self.debug('Control call ok')
......@@ -25,6 +25,7 @@ from upntest.controlling import ClientControl
from upntest.eventing import ClientEventMessageChecks
from upntest.service import MissingUrlException
class ClientDevice(log.Loggable):
"""
This class keeps track of messages sent by a client device (most likely an
......@@ -181,6 +182,7 @@ class ServerDevice(log.Loggable):
@return: The parent as L{ServerDevice}.
"""
return self._parent
def setParent(self, parent_device):
"""
Set the parent device of this device.
......@@ -199,6 +201,7 @@ class ServerDevice(log.Loggable):
@return: A L{Host} object.
"""
return self._host
def setHost(self, host):
"""
Set the L{Host} where this device resides.
......@@ -257,7 +260,7 @@ class ServerDevice(log.Loggable):
if new:
self.info('Creating new device for %s' % usn_split[0][5:])
self._uuid = usn_split[0][5:] # UUID is uuid:1234567890
self._uuid = usn_split[0][5:] # UUID is uuid:1234567890
self._expirationNotificationFunc = \
reactor.callLater(int(cache_control[1].strip()),
self.deviceExpired)
......@@ -265,7 +268,6 @@ class ServerDevice(log.Loggable):
self.info('Updating device for %s' % usn_split[0][5:])
self._expirationNotificationFunc.reset(int(cache_control[1].strip()))
self._descLocation = headers['location']
self.debug(self._descLocation)
......@@ -541,9 +543,8 @@ class ServerDevice(log.Loggable):
self.info(error)
self.checkServiceAnnouncement(device, device_list, service_list, xpath_exp='upnp:deviceList/upnp:device')
#if d is not None:
#louie.send('UPnT.ending_deferred', None, d)
# louie.send('UPnT.ending_deferred', None, d)
return doc
......@@ -565,7 +566,6 @@ class ServerDevice(log.Loggable):
self.debug(failure)
#louie.send('UPnT.ending_deferred', None, d)
def removeUnknownTags(self, xmldoc):
"""
Removes unknown elements from tree before validating.
......@@ -582,13 +582,13 @@ class ServerDevice(log.Loggable):
"""The main UPnP namespace used to filter tags of other namespaces
(like DLNA)."""
unknown_elements = [MAIN_NS+'INMPR03']
unknown_elements = [MAIN_NS + 'INMPR03']
"""Other non-standard elements known for being send by certain devices."""
for el in xmldoc.getiterator('*'):
if not el.tag.startswith(MAIN_NS) or el.tag in unknown_elements:
parent = el.getparent()
if parent is not None: # not the root element
if parent is not None: # not the root element
parent.remove(el)
return xmldoc
......@@ -613,6 +613,7 @@ class ServerDevice(log.Loggable):
self._services[headers['usn']].eventchecker.removeEventSeq()
del self._services[headers['usn']]
class InvalidDescriptionException(StandardError):
"""
Error representing an invalid device description.
......@@ -635,4 +636,3 @@ class InvalidDescriptionException(StandardError):
"""
return 'Device-Description not valid! (UUID %s)' % (self.uuid)
......@@ -26,6 +26,7 @@ control_point = None
event_server = None
"""Global variable for a single instance of an C{EventServer}."""
class ServerEventMessageChecks(log.Loggable):
"""
This class contains event message checks for server devices like
......@@ -165,7 +166,6 @@ class ServerEventMessageChecks(log.Loggable):
self.notifySeq[service_ident][service_sid] += 1
if self.notifySeq[service_ident][service_sid] > 429496729:
self.notifySeq[service_ident][service_sid] = 1
#self.debug('calcNextEventSeq (%r, %r, %r, %r)' % (service_host, service_url, service_sid, self.notifySeq[service_ident][service_sid]))
def removeEventSeq(self):
......@@ -661,4 +661,3 @@ class ClientEventMessageChecks(log.Loggable):
)
self.debug('checkUnsubscribeMessage-Finished')
This diff is collapsed.
......@@ -25,6 +25,7 @@ from coherence.upnp.core import utils
from upntest.controlling import ServerControl
from upntest.eventing import ServerEventMessageChecks
class Service(log.Loggable):
"""
This class checks information of a service that is retrieved from the
......@@ -178,6 +179,7 @@ class Service(log.Loggable):
@return: The type of this service (C{str}).
"""
return self._parentDevice
def setParentDevice(self, parentDevice):
"""
Set the parent device of this service.
......@@ -203,6 +205,7 @@ class Service(log.Loggable):
@return: A URL (C{str}).
"""
return self._eventSubURL
def setEventSubUrl(self, eventSubURL):
"""
Set the URL where to send messages to subscribe and unsubscribe.
......@@ -224,6 +227,7 @@ class Service(log.Loggable):
@return: A URL (C{str}).
"""
return self._SCPDURL
def setScpdUrl(self, scpdUrl):
"""
Set the URL where to send messages to subscribe and unsubscribe.
......@@ -244,6 +248,7 @@ class Service(log.Loggable):
@return: A URL (C{str}).
"""
return self._controlURL
def setControlUrl(self, controlUrl):
"""
Set the URL where the control messages have to be send to.
......@@ -294,7 +299,7 @@ class Service(log.Loggable):
executed to check the validity of the description.
"""
uuid = self.parentDevice.UUID;
uuid = self.parentDevice.UUID
if len(self._SCPDURL) == 0:
raise MissingUrlException('Service %s/%s has no SCPDURL' % (self.parentDevice.host.ip, uuid))
if len(self._controlURL) == 0:
......@@ -463,7 +468,7 @@ class Service(log.Loggable):
action_name = action_node.xpath('upnp:name', ns)[0].text.strip()
if tpl_actions.has_key(action_name):
for argument in action_node.xpath('upnp:argumentList/upnp:argument', ns):
argument_name = argument.xpath('upnp:name',ns)[0].text.strip()
argument_name = argument.xpath('upnp:name', ns)[0].text.strip()
#self.debug('Checking argument %s for of action %s' % (argument_name, action_name))
if tpl_actions[action_name]['Arguments'].has_key(argument_name):
......@@ -778,10 +783,8 @@ class Service(log.Loggable):
self.info('startControlTestingFailed')
self.info(failure)
#louie.send('UPnT.ending_deferred', None, d)
def serviceExpired(self):
"""
Print a message that the announcement of this service has expired.
......@@ -795,6 +798,7 @@ class MissingUrlException(StandardError):
"""
Exception that represents a missing URL in a device or service description.
"""
def __init__(self, error):
"""
Initialise the exception and set the error message.
......@@ -819,6 +823,7 @@ class MissingRequiredActionException(StandardError):
"""
Exception that represents a missing action in a service description.
"""
def __init__(self, missingAction, serviceName):
"""
Initialise the exception and set the name of the missing action and
......@@ -848,6 +853,7 @@ class SyntaxError(StandardError):
Exception that represents wrong syntax in action description. The concrete
message about why the exception was raised is stored in L{message}.
"""
def __init__(self, message, actionName, serviceName):
"""
Initialise the exception.
......@@ -879,6 +885,7 @@ class MissingRequiredStateVariableException(StandardError):
"""
Exception that represents a missing state variable in a service description.
"""
def __init__(self, missingVariable, serviceName):
"""
Initialise the exception and set the name of the missing variable and
......@@ -902,10 +909,12 @@ class MissingRequiredStateVariableException(StandardError):
"""
return 'Required state variable %s not implemented by %s' % (self.missingVariable, self.serviceName)
class MissingTemplateException(StandardError):
"""
Exception that represents a missing template file.
"""
def __init__(self, error):
"""
Initialise the exception and set the error message.
......@@ -924,4 +933,3 @@ class MissingTemplateException(StandardError):
@return: A string representation of this exception.
"""
return repr(self.error)
......@@ -22,37 +22,39 @@ NS_XSD = "{http://www.w3.org/1999/XMLSchema}"
SOAP_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/"
"""Namespace of SOAP message encoding."""
UPNPERRORS = {401:'Invalid Action',
402:'Invalid Args',
501:'Action Failed',
600:'Argument Value Invalid',
601:'Argument Value Out of Range',
602:'Optional Action Not Implemented',
603:'Out Of Memory',
604:'Human Intervention Required',
605:'String Argument Too Long',
606:'Action Not Authorized',
607:'Signature Failure',
608:'Signature Missing',
609:'Not Encrypted',
610:'Invalid Sequence',
611:'Invalid Control URL',
612:'No Such Session'}
UPNPERRORS = {401: 'Invalid Action',
402: 'Invalid Args',
501: 'Action Failed',
600: 'Argument Value Invalid',
601: 'Argument Value Out of Range',
602: 'Optional Action Not Implemented',
603: 'Out Of Memory',
604: 'Human Intervention Required',
605: 'String Argument Too Long',
606: 'Action Not Authorized',
607: 'Signature Failure',
608: 'Signature Missing',
609: 'Not Encrypted',
610: 'Invalid Sequence',
611: 'Invalid Control URL',
612: 'No Such Session'}
"""Listing of error codes predefined by the UPnP Device Architecture."""
def build_soap_error(status,description='without words'):
def build_soap_error(status, description='without words'):
""" builds an UPnP SOAP error msg
"""
root = ET.Element('s:Fault')
ET.SubElement(root,'faultcode').text='s:Client'
ET.SubElement(root,'faultstring').text='UPnPError'
e = ET.SubElement(root,'detail')
ET.SubElement(root, 'faultcode').text = 's:Client'
ET.SubElement(root, 'faultstring').text = 'UPnPError'
e = ET.SubElement(root, 'detail')
e = ET.SubElement(e, 'UPnPError')
e.attrib['xmlns']='urn:schemas-upnp-org:control-1-0'
ET.SubElement(e,'errorCode').text=str(status)
ET.SubElement(e,'errorDescription').text=UPNPERRORS.get(status,description)
e.attrib['xmlns'] = 'urn:schemas-upnp-org:control-1-0'
ET.SubElement(e, 'errorCode').text = str(status)
ET.SubElement(e, 'errorDescription').text = UPNPERRORS.get(status, description)
return build_soap_call(None, root, encoding=None)
def build_soap_call(method, arguments, is_response=False,
encoding=SOAP_ENCODING,
envelope_attrib=None,
......@@ -65,10 +67,10 @@ def build_soap_call(method, arguments, is_response=False,
envelope = ET.Element("s:Envelope")
if envelope_attrib:
for n in envelope_attrib:
envelope.attrib.update({n[0] : n[1]})
envelope.attrib.update({n[0]: n[1]})
else:
envelope.attrib.update({'s:encodingStyle' : "http://schemas.xmlsoap.org/soap/encoding/"})
envelope.attrib.update({'xmlns:s' :"http://schemas.xmlsoap.org/soap/envelope/"})
envelope.attrib.update({'s:encodingStyle': "http://schemas.xmlsoap.org/soap/encoding/"})
envelope.attrib.update({'xmlns:s': "http://schemas.xmlsoap.org/soap/envelope/"})
body = ET.SubElement(envelope, "s:Body")
......@@ -76,14 +78,14 @@ def build_soap_call(method, arguments, is_response=False,
# append the method call
if is_response is True:
method += "Response"
re = ET.SubElement(body,method)
re = ET.SubElement(body, method)
if encoding:
re.set(NS_SOAP_ENV + "encodingStyle", encoding)
else:
re = body
# append the arguments
if isinstance(arguments,dict):
if isinstance(arguments, dict):
for arg_name, arg_val in arguments.iteritems():
#arg_type = type_map[type(arg_val)]
......@@ -103,7 +105,5 @@ def build_soap_call(method, arguments, is_response=False,
else:
re.append(arguments)
preamble = """<?xml version="1.0" encoding="utf-8"?>"""
return preamble + ET.tostring(envelope,'utf-8')
return preamble + ET.tostring(envelope, 'utf-8')
......@@ -17,6 +17,7 @@ from coherence.upnp.core.utils import getPage, parse_xml
from upntest import soap_lite
from coherence import log
class SOAPProxy(log.Loggable):
logCategory = 'UPnT_SOAPProxy'
""" A Proxy for making remote SOAP calls.
......@@ -56,14 +57,13 @@ class SOAPProxy(log.Loggable):
@param soapmethod:
@param in_args:
"""
soapaction = self.soapaction or soapmethod
self.action = soapmethod
ns = self.namespace
payload = soap_lite.build_soap_call("{%s}%s" % (ns[1], soapmethod), in_args,
encoding=None)
#self.debug("soapaction: %r" % soapaction)
#self.debug("callRemote: %r" % payload)
#self.debug("url: %r" % self.url)
......@@ -118,7 +118,7 @@ class SOAPProxy(log.Loggable):
for elem in response:
result[elem.tag] = self.decode_result(elem)
#print "_cbGotResult 3", result
return result
def decode_result(self, element):
......@@ -166,5 +166,5 @@ class SOAPProxy(log.Loggable):
result[e_elem.tag] = e_elem.text
else:
result[elem.tag] = elem.text
return result
\ No newline at end of file
return result
......@@ -11,4 +11,3 @@ from lxml import etree
from coherence.extern.logger import Logger
log = Logger('UPnT.utils')
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment