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,19 +31,20 @@ from cloudooo.interfaces.application import IApplication
from cloudooo.utils import logger, socketStatus
from psutil import pid_exists, Process
class Application(object):
"""Base object to create an object that is possible manipulation a
process"""
implements(IApplication)
name = "application"
def start(self):
"""Start Application"""
logger.debug("Process Started %s, Port %s. Pid %s" % (self.name,
self.getAddress()[-1],
self.pid()))
logger.debug("Process Started %s, Port %s. Pid %s" % (self.name,
self.getAddress()[-1],
self.pid()))
def stop(self):
"""Stop the process"""
......@@ -56,10 +57,8 @@ class Application(object):
if pid_exists(process_pid) or self.status():
Process(process_pid).kill()
def loadSettings(self, hostname, port, path_run_dir, display_id, **kwargs):
"""Define attributes for application instance
Keyword arguments:
hostname -- Host to start the instance.
port -- Expected a int number.
......@@ -71,7 +70,7 @@ class Application(object):
self.path_run_dir = path_run_dir
self.display_id = display_id
self.timeout = kwargs.get('start_timeout', 20)
def restart(self):
"""Start and Stop the process"""
self.stop()
......
......@@ -38,9 +38,10 @@ from cloudooo.interfaces.lockable import ILockable
from cloudooo.utils import logger, waitStartDaemon, removeDirectory, \
waitStopDaemon, convertStringToBool
class OpenOffice(Application):
"""Object to control one OOo Instance and all features instance."""
implements(ILockable)
name = "openoffice"
......@@ -56,17 +57,18 @@ class OpenOffice(Application):
def _testOpenOffice(self, host, port):
"""Test if OpenOffice was started correctly"""
logger.debug("Test OpenOffice %s - Pid %s" % (self.getAddress()[-1], self.pid()))
command = [join(self.office_binary_path, "python")
, pkg_resources.resource_filename("cloudooo",
join("helper", "openoffice_tester.py"))
, "'--hostname=%s'" % host
, "'--port=%s'" % port
, "'--uno_path=%s'" % self.uno_path]
logger.debug("Test OpenOffice %s - Pid %s" % (self.getAddress()[-1],
self.pid()))
command = [join(self.office_binary_path, "python"),
pkg_resources.resource_filename("cloudooo",
join("helper", "openoffice_tester.py")),
"'--hostname=%s'" % host,
"'--port=%s'" % port,
"'--uno_path=%s'" % self.uno_path]
logger.debug("Testing Openoffice Instance %s" % port)
stdout, stderr = Popen(" ".join(command), shell=True, stdout=PIPE,
stderr=PIPE, close_fds=True).communicate()
stdout_bool = convertStringToBool(stdout.replace("\n",""))
stdout_bool = convertStringToBool(stdout.replace("\n", ""))
if stdout_bool and stderr != "":
logger.debug("%s\n%s" % (stderr, stdout))
return False
......@@ -81,7 +83,6 @@ class OpenOffice(Application):
def loadSettings(self, hostname, port, path_run_dir, display_id,
office_binary_path, uno_path, **kw):
"""Method to load the configuratio to control one OpenOffice Instance
Keyword arguments:
office_path -- Full Path of the OOo executable.
e.g office_binary_path='/opt/openoffice.org3/program'
......@@ -110,15 +111,15 @@ class OpenOffice(Application):
if exists(self.path_user_installation):
removeDirectory(self.path_user_installation)
# Create command with all parameters to start the instance
self.command = [join(self.office_binary_path, self._bin_soffice)
, '-invisible'
, '-nologo'
, '-nodefault'
, '-norestore'
, '-nofirststartwizard'
, '"-accept=socket,host=%s,port=%d;urp;StarOffice.ComponentContext"' % \
(self.hostname, self.port)
, '-env:UserInstallation=file://%s' % self.path_user_installation]
self.command = [join(self.office_binary_path, self._bin_soffice),
'-invisible',
'-nologo',
'-nodefault',
'-norestore',
'-nofirststartwizard',
'"-accept=socket,host=%s,port=%d;urp;StarOffice.ComponentContext"' % \
(self.hostname, self.port),
'-env:UserInstallation=file://%s' % self.path_user_installation]
# 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
env = environ.copy()
......
......@@ -33,6 +33,7 @@ from application import Application
from cloudooo.interfaces.application import IApplication
from os.path import exists
class Xvfb(Application):
"""Start and control Xvfb. It is used to open/run
instances OpenOffice.
......@@ -50,7 +51,7 @@ class Xvfb(Application):
Application.loadSettings(self, hostname, port, path_run_dir, display_id)
self.virtual_screen = kwargs.get('virtual_screen', '0')
self.process_name = "Xvfb"
def start(self):
"""Method to start Virtual Frame Buffer."""
self.command = ["Xvfb", "-ac", ":%s" % self.display_id, \
......
......@@ -6,15 +6,17 @@ from base64 import encodestring
from xmlrpclib import ServerProxy
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
class CloudoooTestCase(unittest.TestCase):
""" """
def setUp(self):
self.proxy_address = "http://%s:%s" % (HOSTNAME, PORT)
def test_run_generate(self):
data = encodestring(DOCUMENT_STRING)
proxy = ServerProxy(self.proxy_address, allow_none=True)
......@@ -27,9 +29,9 @@ class CloudoooTestCase(unittest.TestCase):
proxy = ServerProxy(self.proxy_address, allow_none=True)
odt_data = proxy.convertFile(data, 'txt', 'odt')
metadata_dict = proxy.getFileMetadataItemList(odt_data, 'odt')
self.assertEquals(metadata_dict["MIMEType"],
self.assertEquals(metadata_dict["MIMEType"],
'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)
response_code, response_dict, response_message = \
proxy.run_convert("t.odt", res[1]['data'])
......@@ -38,20 +40,20 @@ class CloudoooTestCase(unittest.TestCase):
def main():
global PORT, HOSTNAME
global PORT, HOSTNAME
try:
opt_list, arg_list = getopt(sys.argv[1:], "",
["port=","hostname="])
opt_list, arg_list = getopt(sys.argv[1:], "",
["port=", "hostname="])
except GetoptError, e:
print >> sys.stderr, "%s \nUse --port and --hostname" % e
sys.exit(2)
for opt, arg in opt_list:
if opt == "--port":
PORT = arg
elif opt == "--hostname":
HOSTNAME = arg
if not HOSTNAME and not PORT:
print >> sys.stderr, "Use --port and --hostname"
sys.exit(2)
......
from os import path
import pkg_resources
def main():
cloudooo_conf_path = pkg_resources.resource_filename("cloudooo",
path.join("samples", "cloudooo.conf.in"))
......
......@@ -31,12 +31,11 @@ from zope.interface import implements
from cloudooo.interfaces.handler import IHandler
from cloudooo.document import FileSystemDocument
class FFMpegHandler:
"""
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
document at FS, load, export and export.
"""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 document at FS, load, export and export.
"""
implements(IHandler)
......@@ -47,14 +46,13 @@ class FFMpegHandler:
def _getCommand(self, *args, **kw):
"""Transforms all parameters passed in a command"""
return ""
def convert(self, source_format=None, destination_format=None, **kw):
"""Executes a procedure in accordance with parameters passed."""
return ""
def getMetadata(self, converted_data=False):
"""Returns a dictionary with all metadata of document.
Keywords Arguments:
converted_data -- Boolean variable. if true, the document is also returned
along with the metadata."""
......@@ -62,7 +60,6 @@ class FFMpegHandler:
def setMetadata(self, metadata):
"""Returns a document with new metadata.
Keyword arguments:
metadata -- expected an dictionary with metadata.
"""
......
......@@ -31,12 +31,11 @@ from zope.interface import implements
from cloudooo.interfaces.handler import IHandler
from cloudooo.document import FileSystemDocument
class ImageMagickHandler(FileSystemDocument):
"""
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
document at FS, load, export and export.
"""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 document at FS, load, export and export.
"""
implements(IHandler)
......@@ -47,14 +46,13 @@ class ImageMagickHandler(FileSystemDocument):
def _getCommand(self, *args, **kw):
"""Transforms all parameters passed in a command"""
return ""
def convert(self, source_format=None, destination_format=None, **kw):
"""Executes a procedure in accordance with parameters passed."""
return ""
def getMetadata(self, converted_data=False):
"""Returns a dictionary with all metadata of document.
Keywords Arguments:
converted_data -- Boolean variable. if true, the document is also returned
along with the metadata."""
......@@ -62,7 +60,6 @@ class ImageMagickHandler(FileSystemDocument):
def setMetadata(self, metadata):
"""Returns a document with new metadata.
Keyword arguments:
metadata -- expected an dictionary with metadata.
"""
......
......@@ -26,7 +26,8 @@
#
##############################################################################
import jsonpickle, pkg_resources
import jsonpickle
import pkg_resources
from base64 import decodestring, encodestring
from os import environ, path
from subprocess import Popen, PIPE
......@@ -40,9 +41,9 @@ from cloudooo.monitor.timeout import MonitorTimeout
from cloudooo.utils import logger
from psutil import pid_exists
class OOHandler:
"""OOHandler is used to access the one Document and OpenOffice.
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
document at FS, load, export and export.
......@@ -71,20 +72,20 @@ class OOHandler:
"").split("/")[:-1])
kw['hostname'] = hostname
kw['port'] = port
command_list = [path.join(self.office_binary_path, "python")
, pkg_resources.resource_filename("cloudooo",
path.join("helper", "unoconverter.py"))
, "--uno_path='%s'" % self.uno_path
, "--office_binary_path='%s'" % self.office_binary_path
, "--document_url='%s'" % self.document.getUrl()
, "--jsonpickle_path='%s'" % jsonpickle_path]
command_list = [path.join(self.office_binary_path, "python"),
pkg_resources.resource_filename("cloudooo",
path.join("helper", "unoconverter.py")),
"--uno_path='%s'" % self.uno_path,
"--office_binary_path='%s'" % self.office_binary_path,
"--document_url='%s'" % self.document.getUrl(),
"--jsonpickle_path='%s'" % jsonpickle_path]
for arg in args:
command_list.insert(3, "--%s" % arg)
for k, v in kw.iteritems():
command_list.append("--%s='%s'" % (k,v))
command_list.append("--%s='%s'" % (k, v))
return ' '.join(command_list)
def _startTimeout(self):
"""start the Monitor"""
self.monitor = MonitorTimeout(openoffice, self.timeout)
......@@ -143,17 +144,16 @@ class OOHandler:
for extension in mimemapper.extension_list:
for service_type in mimemapper.document_service_list:
if service_type in mimemapper._doc_type_list_by_extension[extension]:
filter_list.append((extension,
service_type,
mimemapper.getFilterName(extension, service_type)))
filter_list.append((extension,
service_type,
mimemapper.getFilterName(extension, service_type)))
return jsonpickle.encode(dict(doc_type_list_by_extension=mimemapper._doc_type_list_by_extension,
filter_list=filter_list,
mimetype_by_filter_type=mimemapper._mimetype_by_filter_type))
def convert(self, destination_format=None, **kw):
"""Convert a document to another format supported by the OpenOffice
Keyword Arguments:
destination_format -- extension of document as String
"""
......@@ -177,7 +177,6 @@ class OOHandler:
def getMetadata(self, base_document=False):
"""Returns a dictionary with all metadata of document.
Keywords Arguments:
base_document -- Boolean variable. if true, the document is also returned
along with the metadata."""
......@@ -194,7 +193,7 @@ class OOHandler:
openoffice.release()
if self.monitor.is_alive():
self._stopTimeout()
metadata=jsonpickle.decode(decodestring(stdout))
metadata = jsonpickle.decode(decodestring(stdout))
if metadata.get("Data"):
self.document.reload(metadata['Data'])
metadata['Data'] = self.document.getContent()
......@@ -202,10 +201,9 @@ class OOHandler:
metadata['Data'] = ''
self.document.trash()
return metadata
def setMetadata(self, metadata):
"""Returns a document with new metadata.
Keyword arguments:
metadata -- expected an dictionary with metadata.
"""
......
......@@ -4,6 +4,7 @@ import helper_utils
from getopt import getopt, GetoptError
from os import environ
def test_openoffice(hostname, port):
try:
helper_utils.getServiceManager(hostname, port)
......@@ -12,14 +13,15 @@ def test_openoffice(hostname, port):
print err
return False
def main():
try:
opt_list, arg_list = getopt(sys.argv[1:], "",
["port=","hostname=","uno_path="])
/bin/bash: q: comando não encontrado
except GetoptError, e:
print >> sys.stderr, "%s \nUse --port and --hostname" % e
sys.exit(2)
for opt, arg in opt_list:
if opt == "--port":
port = arg
......
......@@ -66,6 +66,7 @@ Options:
Dictionary with metadata
"""
class UnoConverter(object):
"""A module to easily work with OpenOffice.org."""
......@@ -249,10 +250,12 @@ class UnoConverter(object):
self.document_loaded.store()
self.document_loaded.dispose()
def help():
print >> sys.stderr, __doc__
sys.exit(1)
def main():
global mimemapper
......
......@@ -49,6 +49,7 @@ Options:
Folter path were is the uno library
"""
class UnoMimemapper(object):
""" """
......@@ -108,10 +109,12 @@ class UnoMimemapper(object):
type_dict = self._getElementNameByService(type_service, ["UINames", "URLPattern"])
return type_dict
def help():
print >> sys.stderr, __doc__
sys.exit(1)
def main():
try:
opt_list, arg_list = getopt(sys.argv[1:], "h", ["help",
......
......@@ -28,6 +28,7 @@
from zope.interface import Interface
class IApplication(Interface):
"""Controls and monitors an application"""
......
......@@ -29,6 +29,7 @@
from zope.interface import Interface
from zope.interface import Attribute
class IDocument(Interface):
"""Manipulates documents in file system"""
......
......@@ -28,6 +28,7 @@
from zope.interface import Interface
class IFilter(Interface):
"""This is a type filter"""
......
......@@ -66,4 +66,3 @@ class ITextGranulator(Interface):
def getChapterItem(file, chapter_id):
"""Return the chapter in the form of (title, level)."""
......@@ -56,7 +56,7 @@ class MonitorMemory(Monitor, Process):
logger.debug("OpenOffice is stopped")
return 0
# 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):
"""Is called by start function. this function is responsible for
......
......@@ -57,7 +57,7 @@ def loadConfig(path):
def startFakeEnvironment(start_openoffice=True, conf_path=None):
"""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]
loadConfig(conf_path)
uno_path = config.get("app:main", "uno_path")
......
......@@ -344,7 +344,6 @@ class TestMimeMapper(cloudoooTestCase):
filtername = self.mimemapper.getFilterName("html", 'com.sun.star.presentation.PresentationDocument')
self.assertEquals(filtername, "impress_html_Export")
def testGetMimetype(self):
"""Test get mimetype according to the filter type"""
self.assertEquals(self.mimemapper.getMimetypeByFilterType("writer8"),\
......
......@@ -196,7 +196,6 @@ class TestServer(cloudoooTestCase):
self.assertEquals(metadata_dict.get("MIMEType"),\
"application/vnd.oasis.opendocument.text")
def testupdateFileMetadata(self):
"""Test server using method updateFileMetadata"""
document_output_url = join(self.tmp_url, "testSetMetadata.odt")
......
......@@ -27,7 +27,8 @@
##############################################################################
import unittest
import jsonpickle, pkg_resources
import jsonpickle
import pkg_resources
from subprocess import Popen, PIPE
from os.path import exists, join
from cloudoooTestCase import cloudoooTestCase, make_suite
......
......@@ -26,7 +26,8 @@
#
##############################################################################
import unittest, pkg_resources
import unittest
import pkg_resources
from cloudooo.application.openoffice import openoffice
from subprocess import Popen, PIPE
from os import environ, path
......@@ -49,7 +50,7 @@ class TestUnoMimeMapper(cloudoooTestCase):
def testCreateLocalAttributes(self):
"""Test if filters returns correctly the filters and types in dict"""
hostname, host = openoffice.getAddress()
hostname, host = openoffice.getAddress()
command = [path.join(self.office_binary_path, "python"),
pkg_resources.resource_filename("cloudooo", "helper/unomimemapper.py"),
"'--uno_path=%s'" % self.uno_path,
......@@ -70,7 +71,7 @@ class TestUnoMimeMapper(cloudoooTestCase):
def testCallUnoMimemapperOnlyHostNameAndPort(self):
""" Test call unomimemapper without uno_path and office_binary_path"""
hostname, host = openoffice.getAddress()
hostname, host = openoffice.getAddress()
command = [path.join(self.office_binary_path, "python"),
pkg_resources.resource_filename("cloudooo",
"helper/unomimemapper.py"),
......@@ -91,7 +92,7 @@ class TestUnoMimeMapper(cloudoooTestCase):
def testWithoutOpenOffice(self):
"""Test when the openoffice is stopped"""
error_msg = "couldn\'t connect to socket (Success)\n"
hostname, host = openoffice.getAddress()
hostname, host = openoffice.getAddress()
openoffice.stop()
command = [path.join(self.office_binary_path, "python"),
pkg_resources.resource_filename("cloudooo",
......
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