Commit 5d1905aa authored by Gabriel Monnerat's avatar Gabriel Monnerat

clean up the code to follow pep08, ignoring 4 spaces to identation

git-svn-id: https://svn.erp5.org/repos/public/erp5/trunk/utils@40432 20353a03-c40f-0410-a6d1-a30d3c3de9de
parent 1c99ce50
...@@ -31,6 +31,7 @@ from cloudooo.interfaces.application import IApplication ...@@ -31,6 +31,7 @@ from cloudooo.interfaces.application import IApplication
from cloudooo.utils import logger, socketStatus from cloudooo.utils import logger, socketStatus
from psutil import pid_exists, Process from psutil import pid_exists, Process
class Application(object): class Application(object):
"""Base object to create an object that is possible manipulation a """Base object to create an object that is possible manipulation a
process""" process"""
...@@ -56,10 +57,8 @@ class Application(object): ...@@ -56,10 +57,8 @@ class Application(object):
if pid_exists(process_pid) or self.status(): if pid_exists(process_pid) or self.status():
Process(process_pid).kill() Process(process_pid).kill()
def loadSettings(self, hostname, port, path_run_dir, display_id, **kwargs): def loadSettings(self, hostname, port, path_run_dir, display_id, **kwargs):
"""Define attributes for application instance """Define attributes for application instance
Keyword arguments: Keyword arguments:
hostname -- Host to start the instance. hostname -- Host to start the instance.
port -- Expected a int number. port -- Expected a int number.
......
...@@ -38,6 +38,7 @@ from cloudooo.interfaces.lockable import ILockable ...@@ -38,6 +38,7 @@ from cloudooo.interfaces.lockable import ILockable
from cloudooo.utils import logger, waitStartDaemon, removeDirectory, \ from cloudooo.utils import logger, waitStartDaemon, removeDirectory, \
waitStopDaemon, convertStringToBool waitStopDaemon, convertStringToBool
class OpenOffice(Application): class OpenOffice(Application):
"""Object to control one OOo Instance and all features instance.""" """Object to control one OOo Instance and all features instance."""
...@@ -56,17 +57,18 @@ class OpenOffice(Application): ...@@ -56,17 +57,18 @@ class OpenOffice(Application):
def _testOpenOffice(self, host, port): def _testOpenOffice(self, host, port):
"""Test if OpenOffice was started correctly""" """Test if OpenOffice was started correctly"""
logger.debug("Test OpenOffice %s - Pid %s" % (self.getAddress()[-1], self.pid())) logger.debug("Test OpenOffice %s - Pid %s" % (self.getAddress()[-1],
command = [join(self.office_binary_path, "python") self.pid()))
, pkg_resources.resource_filename("cloudooo", command = [join(self.office_binary_path, "python"),
join("helper", "openoffice_tester.py")) pkg_resources.resource_filename("cloudooo",
, "'--hostname=%s'" % host join("helper", "openoffice_tester.py")),
, "'--port=%s'" % port "'--hostname=%s'" % host,
, "'--uno_path=%s'" % self.uno_path] "'--port=%s'" % port,
"'--uno_path=%s'" % self.uno_path]
logger.debug("Testing Openoffice Instance %s" % port) logger.debug("Testing Openoffice Instance %s" % port)
stdout, stderr = Popen(" ".join(command), shell=True, stdout=PIPE, stdout, stderr = Popen(" ".join(command), shell=True, stdout=PIPE,
stderr=PIPE, close_fds=True).communicate() stderr=PIPE, close_fds=True).communicate()
stdout_bool = convertStringToBool(stdout.replace("\n","")) stdout_bool = convertStringToBool(stdout.replace("\n", ""))
if stdout_bool and stderr != "": if stdout_bool and stderr != "":
logger.debug("%s\n%s" % (stderr, stdout)) logger.debug("%s\n%s" % (stderr, stdout))
return False return False
...@@ -81,7 +83,6 @@ class OpenOffice(Application): ...@@ -81,7 +83,6 @@ class OpenOffice(Application):
def loadSettings(self, hostname, port, path_run_dir, display_id, def loadSettings(self, hostname, port, path_run_dir, display_id,
office_binary_path, uno_path, **kw): office_binary_path, uno_path, **kw):
"""Method to load the configuratio to control one OpenOffice Instance """Method to load the configuratio to control one OpenOffice Instance
Keyword arguments: Keyword arguments:
office_path -- Full Path of the OOo executable. office_path -- Full Path of the OOo executable.
e.g office_binary_path='/opt/openoffice.org3/program' e.g office_binary_path='/opt/openoffice.org3/program'
...@@ -110,15 +111,15 @@ class OpenOffice(Application): ...@@ -110,15 +111,15 @@ class OpenOffice(Application):
if exists(self.path_user_installation): if exists(self.path_user_installation):
removeDirectory(self.path_user_installation) removeDirectory(self.path_user_installation)
# Create command with all parameters to start the instance # Create command with all parameters to start the instance
self.command = [join(self.office_binary_path, self._bin_soffice) self.command = [join(self.office_binary_path, self._bin_soffice),
, '-invisible' '-invisible',
, '-nologo' '-nologo',
, '-nodefault' '-nodefault',
, '-norestore' '-norestore',
, '-nofirststartwizard' '-nofirststartwizard',
, '"-accept=socket,host=%s,port=%d;urp;StarOffice.ComponentContext"' % \ '"-accept=socket,host=%s,port=%d;urp;StarOffice.ComponentContext"' % \
(self.hostname, self.port) (self.hostname, self.port),
, '-env:UserInstallation=file://%s' % self.path_user_installation] '-env:UserInstallation=file://%s' % self.path_user_installation]
# To run the instance OOo is need a environment. So, the "DISPLAY" of Xvfb # To run the instance OOo is need a environment. So, the "DISPLAY" of Xvfb
# is passed to env and the environment customized is passed to the process # is passed to env and the environment customized is passed to the process
env = environ.copy() env = environ.copy()
......
...@@ -33,6 +33,7 @@ from application import Application ...@@ -33,6 +33,7 @@ from application import Application
from cloudooo.interfaces.application import IApplication from cloudooo.interfaces.application import IApplication
from os.path import exists from os.path import exists
class Xvfb(Application): class Xvfb(Application):
"""Start and control Xvfb. It is used to open/run """Start and control Xvfb. It is used to open/run
instances OpenOffice. instances OpenOffice.
......
...@@ -6,9 +6,11 @@ from base64 import encodestring ...@@ -6,9 +6,11 @@ from base64 import encodestring
from xmlrpclib import ServerProxy from xmlrpclib import ServerProxy
from getopt import getopt, GetoptError from getopt import getopt, GetoptError
DOCUMENT_STRING = "MemoryMonitor - TimeoutMonitor - RequestMonitor\n\nOOHandler\n\nMimemapper\n\nERP5\n" DOCUMENT_STRING = """MemoryMonitor - TimeoutMonitor -
RequestMonitor\n\nOOHandler\n\nMimemapper\n\nERP5\n"""
HOSTNAME = PORT = None HOSTNAME = PORT = None
class CloudoooTestCase(unittest.TestCase): class CloudoooTestCase(unittest.TestCase):
""" """ """ """
...@@ -29,7 +31,7 @@ class CloudoooTestCase(unittest.TestCase): ...@@ -29,7 +31,7 @@ class CloudoooTestCase(unittest.TestCase):
metadata_dict = proxy.getFileMetadataItemList(odt_data, 'odt') metadata_dict = proxy.getFileMetadataItemList(odt_data, 'odt')
self.assertEquals(metadata_dict["MIMEType"], self.assertEquals(metadata_dict["MIMEType"],
'application/vnd.oasis.opendocument.text') 'application/vnd.oasis.opendocument.text')
res = proxy.run_setmetadata("t.odt", odt_data, {"Title":"test"}) res = proxy.run_setmetadata("t.odt", odt_data, {"Title": "test"})
self.assertEquals(res[0], 200) self.assertEquals(res[0], 200)
response_code, response_dict, response_message = \ response_code, response_dict, response_message = \
proxy.run_convert("t.odt", res[1]['data']) proxy.run_convert("t.odt", res[1]['data'])
...@@ -41,7 +43,7 @@ def main(): ...@@ -41,7 +43,7 @@ def main():
global PORT, HOSTNAME global PORT, HOSTNAME
try: try:
opt_list, arg_list = getopt(sys.argv[1:], "", opt_list, arg_list = getopt(sys.argv[1:], "",
["port=","hostname="]) ["port=", "hostname="])
except GetoptError, e: except GetoptError, e:
print >> sys.stderr, "%s \nUse --port and --hostname" % e print >> sys.stderr, "%s \nUse --port and --hostname" % e
sys.exit(2) sys.exit(2)
......
from os import path from os import path
import pkg_resources import pkg_resources
def main(): def main():
cloudooo_conf_path = pkg_resources.resource_filename("cloudooo", cloudooo_conf_path = pkg_resources.resource_filename("cloudooo",
path.join("samples", "cloudooo.conf.in")) path.join("samples", "cloudooo.conf.in"))
......
...@@ -31,12 +31,11 @@ from zope.interface import implements ...@@ -31,12 +31,11 @@ from zope.interface import implements
from cloudooo.interfaces.handler import IHandler from cloudooo.interfaces.handler import IHandler
from cloudooo.document import FileSystemDocument from cloudooo.document import FileSystemDocument
class FFMpegHandler:
"""
For each Document inputed is created on instance of this class to manipulate class FFMpegHandler:
the document. This Document must be able to create and remove a temporary """For each Document inputed is created on instance of this class to
document at FS, load, export and export. manipulate the document. This Document must be able to create and remove a
temporary document at FS, load, export and export.
""" """
implements(IHandler) implements(IHandler)
...@@ -54,7 +53,6 @@ class FFMpegHandler: ...@@ -54,7 +53,6 @@ class FFMpegHandler:
def getMetadata(self, converted_data=False): def getMetadata(self, converted_data=False):
"""Returns a dictionary with all metadata of document. """Returns a dictionary with all metadata of document.
Keywords Arguments: Keywords Arguments:
converted_data -- Boolean variable. if true, the document is also returned converted_data -- Boolean variable. if true, the document is also returned
along with the metadata.""" along with the metadata."""
...@@ -62,7 +60,6 @@ class FFMpegHandler: ...@@ -62,7 +60,6 @@ class FFMpegHandler:
def setMetadata(self, metadata): def setMetadata(self, metadata):
"""Returns a document with new metadata. """Returns a document with new metadata.
Keyword arguments: Keyword arguments:
metadata -- expected an dictionary with metadata. metadata -- expected an dictionary with metadata.
""" """
......
...@@ -31,12 +31,11 @@ from zope.interface import implements ...@@ -31,12 +31,11 @@ from zope.interface import implements
from cloudooo.interfaces.handler import IHandler from cloudooo.interfaces.handler import IHandler
from cloudooo.document import FileSystemDocument from cloudooo.document import FileSystemDocument
class ImageMagickHandler(FileSystemDocument):
"""
For each Document inputed is created on instance of this class to manipulate class ImageMagickHandler(FileSystemDocument):
the document. This Document must be able to create and remove a temporary """For each Document inputed is created on instance of this class to
document at FS, load, export and export. manipulate the document. This Document must be able to create and remove a
temporary document at FS, load, export and export.
""" """
implements(IHandler) implements(IHandler)
...@@ -54,7 +53,6 @@ class ImageMagickHandler(FileSystemDocument): ...@@ -54,7 +53,6 @@ class ImageMagickHandler(FileSystemDocument):
def getMetadata(self, converted_data=False): def getMetadata(self, converted_data=False):
"""Returns a dictionary with all metadata of document. """Returns a dictionary with all metadata of document.
Keywords Arguments: Keywords Arguments:
converted_data -- Boolean variable. if true, the document is also returned converted_data -- Boolean variable. if true, the document is also returned
along with the metadata.""" along with the metadata."""
...@@ -62,7 +60,6 @@ class ImageMagickHandler(FileSystemDocument): ...@@ -62,7 +60,6 @@ class ImageMagickHandler(FileSystemDocument):
def setMetadata(self, metadata): def setMetadata(self, metadata):
"""Returns a document with new metadata. """Returns a document with new metadata.
Keyword arguments: Keyword arguments:
metadata -- expected an dictionary with metadata. metadata -- expected an dictionary with metadata.
""" """
......
...@@ -26,7 +26,8 @@ ...@@ -26,7 +26,8 @@
# #
############################################################################## ##############################################################################
import jsonpickle, pkg_resources import jsonpickle
import pkg_resources
from base64 import decodestring, encodestring from base64 import decodestring, encodestring
from os import environ, path from os import environ, path
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
...@@ -40,9 +41,9 @@ from cloudooo.monitor.timeout import MonitorTimeout ...@@ -40,9 +41,9 @@ from cloudooo.monitor.timeout import MonitorTimeout
from cloudooo.utils import logger from cloudooo.utils import logger
from psutil import pid_exists from psutil import pid_exists
class OOHandler: class OOHandler:
"""OOHandler is used to access the one Document and OpenOffice. """OOHandler is used to access the one Document and OpenOffice.
For each Document inputed is created on instance of this class to manipulate For each Document inputed is created on instance of this class to manipulate
the document. This Document must be able to create and remove a temporary the document. This Document must be able to create and remove a temporary
document at FS, load, export and export. document at FS, load, export and export.
...@@ -71,17 +72,17 @@ class OOHandler: ...@@ -71,17 +72,17 @@ class OOHandler:
"").split("/")[:-1]) "").split("/")[:-1])
kw['hostname'] = hostname kw['hostname'] = hostname
kw['port'] = port kw['port'] = port
command_list = [path.join(self.office_binary_path, "python") command_list = [path.join(self.office_binary_path, "python"),
, pkg_resources.resource_filename("cloudooo", pkg_resources.resource_filename("cloudooo",
path.join("helper", "unoconverter.py")) path.join("helper", "unoconverter.py")),
, "--uno_path='%s'" % self.uno_path "--uno_path='%s'" % self.uno_path,
, "--office_binary_path='%s'" % self.office_binary_path "--office_binary_path='%s'" % self.office_binary_path,
, "--document_url='%s'" % self.document.getUrl() "--document_url='%s'" % self.document.getUrl(),
, "--jsonpickle_path='%s'" % jsonpickle_path] "--jsonpickle_path='%s'" % jsonpickle_path]
for arg in args: for arg in args:
command_list.insert(3, "--%s" % arg) command_list.insert(3, "--%s" % arg)
for k, v in kw.iteritems(): for k, v in kw.iteritems():
command_list.append("--%s='%s'" % (k,v)) command_list.append("--%s='%s'" % (k, v))
return ' '.join(command_list) return ' '.join(command_list)
...@@ -153,7 +154,6 @@ class OOHandler: ...@@ -153,7 +154,6 @@ class OOHandler:
def convert(self, destination_format=None, **kw): def convert(self, destination_format=None, **kw):
"""Convert a document to another format supported by the OpenOffice """Convert a document to another format supported by the OpenOffice
Keyword Arguments: Keyword Arguments:
destination_format -- extension of document as String destination_format -- extension of document as String
""" """
...@@ -177,7 +177,6 @@ class OOHandler: ...@@ -177,7 +177,6 @@ class OOHandler:
def getMetadata(self, base_document=False): def getMetadata(self, base_document=False):
"""Returns a dictionary with all metadata of document. """Returns a dictionary with all metadata of document.
Keywords Arguments: Keywords Arguments:
base_document -- Boolean variable. if true, the document is also returned base_document -- Boolean variable. if true, the document is also returned
along with the metadata.""" along with the metadata."""
...@@ -194,7 +193,7 @@ class OOHandler: ...@@ -194,7 +193,7 @@ class OOHandler:
openoffice.release() openoffice.release()
if self.monitor.is_alive(): if self.monitor.is_alive():
self._stopTimeout() self._stopTimeout()
metadata=jsonpickle.decode(decodestring(stdout)) metadata = jsonpickle.decode(decodestring(stdout))
if metadata.get("Data"): if metadata.get("Data"):
self.document.reload(metadata['Data']) self.document.reload(metadata['Data'])
metadata['Data'] = self.document.getContent() metadata['Data'] = self.document.getContent()
...@@ -205,7 +204,6 @@ class OOHandler: ...@@ -205,7 +204,6 @@ class OOHandler:
def setMetadata(self, metadata): def setMetadata(self, metadata):
"""Returns a document with new metadata. """Returns a document with new metadata.
Keyword arguments: Keyword arguments:
metadata -- expected an dictionary with metadata. metadata -- expected an dictionary with metadata.
""" """
......
...@@ -4,6 +4,7 @@ import helper_utils ...@@ -4,6 +4,7 @@ import helper_utils
from getopt import getopt, GetoptError from getopt import getopt, GetoptError
from os import environ from os import environ
def test_openoffice(hostname, port): def test_openoffice(hostname, port):
try: try:
helper_utils.getServiceManager(hostname, port) helper_utils.getServiceManager(hostname, port)
...@@ -12,10 +13,11 @@ def test_openoffice(hostname, port): ...@@ -12,10 +13,11 @@ def test_openoffice(hostname, port):
print err print err
return False return False
def main(): def main():
try: try:
opt_list, arg_list = getopt(sys.argv[1:], "", opt_list, arg_list = getopt(sys.argv[1:], "",
["port=","hostname=","uno_path="]) /bin/bash: q: comando não encontrado
except GetoptError, e: except GetoptError, e:
print >> sys.stderr, "%s \nUse --port and --hostname" % e print >> sys.stderr, "%s \nUse --port and --hostname" % e
sys.exit(2) sys.exit(2)
......
...@@ -66,6 +66,7 @@ Options: ...@@ -66,6 +66,7 @@ Options:
Dictionary with metadata Dictionary with metadata
""" """
class UnoConverter(object): class UnoConverter(object):
"""A module to easily work with OpenOffice.org.""" """A module to easily work with OpenOffice.org."""
...@@ -249,10 +250,12 @@ class UnoConverter(object): ...@@ -249,10 +250,12 @@ class UnoConverter(object):
self.document_loaded.store() self.document_loaded.store()
self.document_loaded.dispose() self.document_loaded.dispose()
def help(): def help():
print >> sys.stderr, __doc__ print >> sys.stderr, __doc__
sys.exit(1) sys.exit(1)
def main(): def main():
global mimemapper global mimemapper
......
...@@ -49,6 +49,7 @@ Options: ...@@ -49,6 +49,7 @@ Options:
Folter path were is the uno library Folter path were is the uno library
""" """
class UnoMimemapper(object): class UnoMimemapper(object):
""" """ """ """
...@@ -108,10 +109,12 @@ class UnoMimemapper(object): ...@@ -108,10 +109,12 @@ class UnoMimemapper(object):
type_dict = self._getElementNameByService(type_service, ["UINames", "URLPattern"]) type_dict = self._getElementNameByService(type_service, ["UINames", "URLPattern"])
return type_dict return type_dict
def help(): def help():
print >> sys.stderr, __doc__ print >> sys.stderr, __doc__
sys.exit(1) sys.exit(1)
def main(): def main():
try: try:
opt_list, arg_list = getopt(sys.argv[1:], "h", ["help", opt_list, arg_list = getopt(sys.argv[1:], "h", ["help",
......
...@@ -28,6 +28,7 @@ ...@@ -28,6 +28,7 @@
from zope.interface import Interface from zope.interface import Interface
class IApplication(Interface): class IApplication(Interface):
"""Controls and monitors an application""" """Controls and monitors an application"""
......
...@@ -29,6 +29,7 @@ ...@@ -29,6 +29,7 @@
from zope.interface import Interface from zope.interface import Interface
from zope.interface import Attribute from zope.interface import Attribute
class IDocument(Interface): class IDocument(Interface):
"""Manipulates documents in file system""" """Manipulates documents in file system"""
......
...@@ -28,6 +28,7 @@ ...@@ -28,6 +28,7 @@
from zope.interface import Interface from zope.interface import Interface
class IFilter(Interface): class IFilter(Interface):
"""This is a type filter""" """This is a type filter"""
......
...@@ -66,4 +66,3 @@ class ITextGranulator(Interface): ...@@ -66,4 +66,3 @@ class ITextGranulator(Interface):
def getChapterItem(file, chapter_id): def getChapterItem(file, chapter_id):
"""Return the chapter in the form of (title, level).""" """Return the chapter in the form of (title, level)."""
...@@ -56,7 +56,7 @@ class MonitorMemory(Monitor, Process): ...@@ -56,7 +56,7 @@ class MonitorMemory(Monitor, Process):
logger.debug("OpenOffice is stopped") logger.debug("OpenOffice is stopped")
return 0 return 0
# convert bytes to MB # convert bytes to MB
return sum(self.process.get_memory_info())/(1024*1024) return sum(self.process.get_memory_info()) / (1024 * 1024)
def run(self): def run(self):
"""Is called by start function. this function is responsible for """Is called by start function. this function is responsible for
......
...@@ -57,7 +57,7 @@ def loadConfig(path): ...@@ -57,7 +57,7 @@ def loadConfig(path):
def startFakeEnvironment(start_openoffice=True, conf_path=None): def startFakeEnvironment(start_openoffice=True, conf_path=None):
"""Create a fake environment""" """Create a fake environment"""
if not conf_path and len(sys.argv) >=1: if not conf_path and len(sys.argv) >= 1:
conf_path = sys.argv[1] conf_path = sys.argv[1]
loadConfig(conf_path) loadConfig(conf_path)
uno_path = config.get("app:main", "uno_path") uno_path = config.get("app:main", "uno_path")
......
...@@ -344,7 +344,6 @@ class TestMimeMapper(cloudoooTestCase): ...@@ -344,7 +344,6 @@ class TestMimeMapper(cloudoooTestCase):
filtername = self.mimemapper.getFilterName("html", 'com.sun.star.presentation.PresentationDocument') filtername = self.mimemapper.getFilterName("html", 'com.sun.star.presentation.PresentationDocument')
self.assertEquals(filtername, "impress_html_Export") self.assertEquals(filtername, "impress_html_Export")
def testGetMimetype(self): def testGetMimetype(self):
"""Test get mimetype according to the filter type""" """Test get mimetype according to the filter type"""
self.assertEquals(self.mimemapper.getMimetypeByFilterType("writer8"),\ self.assertEquals(self.mimemapper.getMimetypeByFilterType("writer8"),\
......
...@@ -196,7 +196,6 @@ class TestServer(cloudoooTestCase): ...@@ -196,7 +196,6 @@ class TestServer(cloudoooTestCase):
self.assertEquals(metadata_dict.get("MIMEType"),\ self.assertEquals(metadata_dict.get("MIMEType"),\
"application/vnd.oasis.opendocument.text") "application/vnd.oasis.opendocument.text")
def testupdateFileMetadata(self): def testupdateFileMetadata(self):
"""Test server using method updateFileMetadata""" """Test server using method updateFileMetadata"""
document_output_url = join(self.tmp_url, "testSetMetadata.odt") document_output_url = join(self.tmp_url, "testSetMetadata.odt")
......
...@@ -27,7 +27,8 @@ ...@@ -27,7 +27,8 @@
############################################################################## ##############################################################################
import unittest import unittest
import jsonpickle, pkg_resources import jsonpickle
import pkg_resources
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
from os.path import exists, join from os.path import exists, join
from cloudoooTestCase import cloudoooTestCase, make_suite from cloudoooTestCase import cloudoooTestCase, make_suite
......
...@@ -26,7 +26,8 @@ ...@@ -26,7 +26,8 @@
# #
############################################################################## ##############################################################################
import unittest, pkg_resources import unittest
import pkg_resources
from cloudooo.application.openoffice import openoffice from cloudooo.application.openoffice import openoffice
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
from os import environ, path from os import environ, path
......
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