Commit b2bf7ce9 authored by Jérome Perrin's avatar Jérome Perrin

*: trivial code modernisation

using 2to3 -f asserts -f except and a few manual
changes
parent a09d87af
...@@ -21,30 +21,30 @@ class CloudoooTestCase(unittest.TestCase): ...@@ -21,30 +21,30 @@ class CloudoooTestCase(unittest.TestCase):
data = encodestring(DOCUMENT_STRING) data = encodestring(DOCUMENT_STRING)
proxy = ServerProxy(self.proxy_address, allow_none=True) proxy = ServerProxy(self.proxy_address, allow_none=True)
res = proxy.run_generate("t.text", data, None, 'pdf', 'text/plain') res = proxy.run_generate("t.text", data, None, 'pdf', 'text/plain')
self.assertEquals(res[1]['mime'], "application/pdf") self.assertEqual(res[1]['mime'], "application/pdf")
self.assertEquals(res[0], 200) self.assertEqual(res[0], 200)
def test_set_metadata(self): def test_set_metadata(self):
data = encodestring(DOCUMENT_STRING) data = encodestring(DOCUMENT_STRING)
proxy = ServerProxy(self.proxy_address, allow_none=True) proxy = ServerProxy(self.proxy_address, allow_none=True)
odt_data = proxy.convertFile(data, 'txt', 'odt') odt_data = proxy.convertFile(data, 'txt', 'odt')
metadata_dict = proxy.getFileMetadataItemList(odt_data, 'odt') metadata_dict = proxy.getFileMetadataItemList(odt_data, 'odt')
self.assertEquals(metadata_dict["MIMEType"], self.assertEqual(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.assertEqual(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'])
self.assertEquals(response_code, 200) self.assertEqual(response_code, 200)
self.assertEquals(response_dict['meta']['Title'], "test") self.assertEqual(response_dict['meta']['Title'], "test")
def main(): def main():
global PORT, HOSTNAME global PORT, HOSTNAME
try: try:
opt_list, arg_list = getopt(sys.argv[1:], "", opt_list, _ = getopt(sys.argv[1:], "",
["port=", "hostname="]) ["port=", "hostname="])
except GetoptError, e: except GetoptError as 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)
......
...@@ -45,12 +45,12 @@ class TestHandler(HandlerTestCase): ...@@ -45,12 +45,12 @@ class TestHandler(HandlerTestCase):
"""Test coversion of video to another format""" """Test coversion of video to another format"""
output_data = self.input.convert("mpeg") output_data = self.input.convert("mpeg")
file_format = self.file_detector.from_buffer(output_data) file_format = self.file_detector.from_buffer(output_data)
self.assertEquals(file_format, 'video/mpeg') self.assertEqual(file_format, 'video/mpeg')
def testgetMetadata(self): def testgetMetadata(self):
"""Test if metadata is extracted from""" """Test if metadata is extracted from"""
output_metadata = self.input.getMetadata() output_metadata = self.input.getMetadata()
self.assertEquals(output_metadata, {'Encoder': 'Lavf52.64.2'}) self.assertEqual(output_metadata, {'Encoder': 'Lavf52.64.2'})
def testsetMetadata(self): def testsetMetadata(self):
""" Test if metadata are inserted correclty """ """ Test if metadata are inserted correclty """
...@@ -58,8 +58,8 @@ class TestHandler(HandlerTestCase): ...@@ -58,8 +58,8 @@ class TestHandler(HandlerTestCase):
output = self.input.setMetadata(metadata_dict) output = self.input.setMetadata(metadata_dict)
handler = Handler(self.tmp_url, output, "ogv", **self.kw) handler = Handler(self.tmp_url, output, "ogv", **self.kw)
metadata = handler.getMetadata() metadata = handler.getMetadata()
self.assertEquals(metadata["Title"], "Set Metadata Test") self.assertEqual(metadata["Title"], "Set Metadata Test")
self.assertEquals(metadata["Creator"], "cloudooo") self.assertEqual(metadata["Creator"], "cloudooo")
def testConvertAudio(self): def testConvertAudio(self):
"""Test coversion of audio to another format""" """Test coversion of audio to another format"""
...@@ -68,6 +68,6 @@ class TestHandler(HandlerTestCase): ...@@ -68,6 +68,6 @@ class TestHandler(HandlerTestCase):
output_data = self.input.convert("wav") output_data = self.input.convert("wav")
file_format = self.file_detector.from_buffer(output_data) file_format = self.file_detector.from_buffer(output_data)
# XXX this might expect 'audio/vnd.wave' but magic only got 'audio/x-wav' # XXX this might expect 'audio/vnd.wave' but magic only got 'audio/x-wav'
self.assertEquals(file_format, 'audio/x-wav') self.assertEqual(file_format, 'audio/x-wav')
...@@ -39,10 +39,10 @@ class TestInterface(unittest.TestCase): ...@@ -39,10 +39,10 @@ class TestInterface(unittest.TestCase):
def testIHandler(self): def testIHandler(self):
"""Test if Handlers implements IHandler""" """Test if Handlers implements IHandler"""
self.assertTrue(IHandler.implementedBy(Handler)) self.assertTrue(IHandler.implementedBy(Handler))
self.assertEquals(IHandler.get('convert').required, ('destination_format',)) self.assertEqual(IHandler.get('convert').required, ('destination_format',))
self.assertEquals(IHandler.get('getMetadata').required, self.assertEqual(IHandler.get('getMetadata').required,
('converted_data',)) ('converted_data',))
self.assertEquals(IHandler.get('setMetadata').required, self.assertEqual(IHandler.get('setMetadata').required,
('metadata_dict',)) ('metadata_dict',))
...@@ -46,16 +46,16 @@ class TestHandler(HandlerTestCase): ...@@ -46,16 +46,16 @@ class TestHandler(HandlerTestCase):
jpg_file = handler.convert("jpg") jpg_file = handler.convert("jpg")
mime = magic.Magic(mime=True) mime = magic.Magic(mime=True)
jpg_mimetype = mime.from_buffer(jpg_file) jpg_mimetype = mime.from_buffer(jpg_file)
self.assertEquals("image/jpeg", jpg_mimetype) self.assertEqual("image/jpeg", jpg_mimetype)
def testgetMetadataFromImage(self): def testgetMetadataFromImage(self):
"""Test if metadata is extracted from image correctly""" """Test if metadata is extracted from image correctly"""
png_file = open("data/test.png").read() png_file = open("data/test.png").read()
handler = Handler(self.tmp_url, png_file, "png", **self.kw) handler = Handler(self.tmp_url, png_file, "png", **self.kw)
metadata = handler.getMetadata() metadata = handler.getMetadata()
self.assertEquals(metadata.get("Compression"), "Zip") self.assertEqual(metadata.get("Compression"), "Zip")
self.assertEquals(metadata.get("Colorspace"), "sRGB") self.assertEqual(metadata.get("Colorspace"), "sRGB")
self.assertEquals(metadata.get("Alpha color"), "grey74") self.assertEqual(metadata.get("Alpha color"), "grey74")
def testsetMetadata(self): def testsetMetadata(self):
""" Test if metadata are inserted correclty """ """ Test if metadata are inserted correclty """
......
...@@ -126,7 +126,7 @@ class OOGranulator(object): ...@@ -126,7 +126,7 @@ class OOGranulator(object):
odf_document.close() odf_document.close()
odf_document_as_string.seek(0) odf_document_as_string.seek(0)
return odf_document_as_string.read() return odf_document_as_string.read()
except Exception, e: except Exception as e:
logger.error(e) logger.error(e)
return None return None
......
...@@ -70,7 +70,7 @@ class TestAllFormatsERP5Compatibility(TestCase): ...@@ -70,7 +70,7 @@ class TestAllFormatsERP5Compatibility(TestCase):
file_type = self._getFileType(data_output) file_type = self._getFileType(data_output)
if file_type.endswith(": empty"): if file_type.endswith(": empty"):
fault_list.append((source_format, extension, file_type)) fault_list.append((source_format, extension, file_type))
except Fault, err: except Fault as err:
fault_list.append((source_format, extension, err.faultString)) fault_list.append((source_format, extension, err.faultString))
if fault_list: if fault_list:
template_message = 'input_format: %r\noutput_format: %r\n traceback:\n%s' template_message = 'input_format: %r\noutput_format: %r\n traceback:\n%s'
......
...@@ -41,23 +41,23 @@ class TestApplication(unittest.TestCase): ...@@ -41,23 +41,23 @@ class TestApplication(unittest.TestCase):
def testLoadSettings(self): def testLoadSettings(self):
"""Test if settings are defined correctly""" """Test if settings are defined correctly"""
self.assertEquals(self.application.hostname, 'localhost') self.assertEqual(self.application.hostname, 'localhost')
self.assertEquals(self.application.port, 9999) self.assertEqual(self.application.port, 9999)
self.assertEquals(self.application.path_run_dir, '/tmp/') self.assertEqual(self.application.path_run_dir, '/tmp/')
def testStartTimeout(self): def testStartTimeout(self):
"""Test if the attribute timeout is defined correctly""" """Test if the attribute timeout is defined correctly"""
self.assertEquals(self.application.timeout, 20) self.assertEqual(self.application.timeout, 20)
application = Application() application = Application()
application.loadSettings('localhost', 9999, '/', start_timeout=25) application.loadSettings('localhost', 9999, '/', start_timeout=25)
self.assertEquals(application.timeout, 25) self.assertEqual(application.timeout, 25)
def testgetAddress(self): def testgetAddress(self):
"""Test if getAddress() returns tuple with address correctly """ """Test if getAddress() returns tuple with address correctly """
self.assertEquals(self.application.getAddress(), ('localhost', 9999)) self.assertEqual(self.application.getAddress(), ('localhost', 9999))
def testPid(self): def testPid(self):
"""As the application do not have the pid() should return None""" """As the application do not have the pid() should return None"""
self.assertEquals(self.application.pid(), None) self.assertEqual(self.application.pid(), None)
...@@ -60,19 +60,19 @@ class TestFileSystemDocument(unittest.TestCase): ...@@ -60,19 +60,19 @@ class TestFileSystemDocument(unittest.TestCase):
document_filename) document_filename)
open(document_test_url, 'wb').write(decodestring("Test Document")) open(document_test_url, 'wb').write(decodestring("Test Document"))
self.fsdocument.reload(document_test_url) self.fsdocument.reload(document_test_url)
self.assertEquals(path.exists(old_document_url), False) self.assertEqual(path.exists(old_document_url), False)
self.assertNotEquals(self.fsdocument.original_data, self.assertNotEqual(self.fsdocument.original_data,
self.fsdocument.getContent()) self.fsdocument.getContent())
old_document_url = self.fsdocument.getUrl() old_document_url = self.fsdocument.getUrl()
self.fsdocument.restoreOriginal() self.fsdocument.restoreOriginal()
self.assertEquals(path.exists(old_document_url), False) self.assertEqual(path.exists(old_document_url), False)
self.assertNotEquals(old_document_url, self.fsdocument.getUrl()) self.assertNotEqual(old_document_url, self.fsdocument.getUrl())
self.assertTrue(path.exists(self.fsdocument.getUrl())) self.assertTrue(path.exists(self.fsdocument.getUrl()))
self.assertEquals(self.fsdocument.getContent(), self.data) self.assertEqual(self.fsdocument.getContent(), self.data)
def testgetContent(self): def testgetContent(self):
"""Test if returns the data correctly""" """Test if returns the data correctly"""
self.assertEquals(self.fsdocument.getContent(), self.data) self.assertEqual(self.fsdocument.getContent(), self.data)
def testgetUrl(self): def testgetUrl(self):
"""Check if the url is correct""" """Check if the url is correct"""
...@@ -83,9 +83,9 @@ class TestFileSystemDocument(unittest.TestCase): ...@@ -83,9 +83,9 @@ class TestFileSystemDocument(unittest.TestCase):
"""Test if the document is created correctly""" """Test if the document is created correctly"""
url = self.fsdocument.getUrl() url = self.fsdocument.getUrl()
tmp_document = open(url, 'r').read() tmp_document = open(url, 'r').read()
self.assertEquals(self.data, tmp_document) self.assertEqual(self.data, tmp_document)
self.fsdocument.trash() self.fsdocument.trash()
self.assertEquals(path.exists(url), False) self.assertEqual(path.exists(url), False)
def testReload(self): def testReload(self):
"""Change url and check if occurs correctly""" """Change url and check if occurs correctly"""
...@@ -96,10 +96,10 @@ class TestFileSystemDocument(unittest.TestCase): ...@@ -96,10 +96,10 @@ class TestFileSystemDocument(unittest.TestCase):
open(document_test_url, 'wb').write(self.data) open(document_test_url, 'wb').write(self.data)
self.fsdocument.reload(document_test_url) self.fsdocument.reload(document_test_url)
url = self.fsdocument.getUrl() url = self.fsdocument.getUrl()
self.assertEquals(path.exists(old_document_url), False) self.assertEqual(path.exists(old_document_url), False)
self.assertEquals(self.fsdocument.getContent(), self.data) self.assertEqual(self.fsdocument.getContent(), self.data)
self.fsdocument.trash() self.fsdocument.trash()
self.assertEquals(path.exists(url), False) self.assertEqual(path.exists(url), False)
def testZipDocumentList(self): def testZipDocumentList(self):
"""Tests if the zip file is returned correctly""" """Tests if the zip file is returned correctly"""
...@@ -107,14 +107,14 @@ class TestFileSystemDocument(unittest.TestCase): ...@@ -107,14 +107,14 @@ class TestFileSystemDocument(unittest.TestCase):
zip_file = self.fsdocument.getContent(True) zip_file = self.fsdocument.getContent(True)
mime = magic.Magic(mime=True) mime = magic.Magic(mime=True)
mimetype = mime.from_buffer(zip_file) mimetype = mime.from_buffer(zip_file)
self.assertEquals(mimetype, 'application/zip') self.assertEqual(mimetype, 'application/zip')
ziptest = ZipFile(StringIO(zip_file), 'r') ziptest = ZipFile(StringIO(zip_file), 'r')
self.assertEquals(len(ziptest.filelist), 2) self.assertEqual(len(ziptest.filelist), 2)
for file in ziptest.filelist: for file in ziptest.filelist:
if file.filename.endswith("document2"): if file.filename.endswith("document2"):
self.assertEquals(file.file_size, 4) self.assertEqual(file.file_size, 4)
else: else:
self.assertEquals(file.file_size, 9) self.assertEqual(file.file_size, 9)
def testSendZipFile(self): def testSendZipFile(self):
"""Tests if the htm is extrated from zipfile""" """Tests if the htm is extrated from zipfile"""
...@@ -123,11 +123,11 @@ class TestFileSystemDocument(unittest.TestCase): ...@@ -123,11 +123,11 @@ class TestFileSystemDocument(unittest.TestCase):
zipdocument = FileSystemDocument(self.tmp_url, data, 'zip') zipdocument = FileSystemDocument(self.tmp_url, data, 'zip')
mime = magic.Magic(mime=True) mime = magic.Magic(mime=True)
mimetype = mime.from_buffer(zipdocument.getContent(True)) mimetype = mime.from_buffer(zipdocument.getContent(True))
self.assertEquals(mimetype, "application/zip") self.assertEqual(mimetype, "application/zip")
mimetype = mime.from_buffer(zipdocument.getContent()) mimetype = mime.from_buffer(zipdocument.getContent())
self.assertEquals(mimetype, "text/html") self.assertEqual(mimetype, "text/html")
zipfile = ZipFile(StringIO(zipdocument.getContent(True))) zipfile = ZipFile(StringIO(zipdocument.getContent(True)))
self.assertEquals(sorted(zipfile.namelist()), self.assertEqual(sorted(zipfile.namelist()),
sorted(['logo.gif', 'test.htm'])) sorted(['logo.gif', 'test.htm']))
...@@ -48,10 +48,10 @@ class TestFilter(unittest.TestCase): ...@@ -48,10 +48,10 @@ class TestFilter(unittest.TestCase):
def testFilter(self): def testFilter(self):
"""Tests filter gets""" """Tests filter gets"""
self.assertEquals(self.filter.getExtension(), 'pdf') self.assertEqual(self.filter.getExtension(), 'pdf')
self.assertEquals(self.filter.getName(), 'writer_pdf_Export') self.assertEqual(self.filter.getName(), 'writer_pdf_Export')
self.assertEquals(self.filter.getMimetype(), 'application/pdf') self.assertEqual(self.filter.getMimetype(), 'application/pdf')
self.assertEquals(self.filter.getSortIndex(), 1000) self.assertEqual(self.filter.getSortIndex(), 1000)
self.assertTrue(self.filter.isPreferred()) self.assertTrue(self.filter.isPreferred())
...@@ -61,7 +61,7 @@ class TestOOGranulator(HandlerTestCase): ...@@ -61,7 +61,7 @@ class TestOOGranulator(HandlerTestCase):
table_list = [('Developers', ''), table_list = [('Developers', ''),
('Prices', 'Table 1: Prices table from Mon Restaurant'), ('Prices', 'Table 1: Prices table from Mon Restaurant'),
('SoccerTeams', 'Tabela 2: Soccer Teams')] ('SoccerTeams', 'Tabela 2: Soccer Teams')]
self.assertEquals(table_list, oogranulator.getTableItemList()) self.assertEqual(table_list, oogranulator.getTableItemList())
def testGetTable(self): def testGetTable(self):
"""Test if getTable() returns on odf file with the right table""" """Test if getTable() returns on odf file with the right table"""
...@@ -72,23 +72,23 @@ class TestOOGranulator(HandlerTestCase): ...@@ -72,23 +72,23 @@ class TestOOGranulator(HandlerTestCase):
content_xml = etree.fromstring(content_xml_str) content_xml = etree.fromstring(content_xml_str)
table_list = content_xml.xpath('//table:table', table_list = content_xml.xpath('//table:table',
namespaces=content_xml.nsmap) namespaces=content_xml.nsmap)
self.assertEquals(1, len(table_list)) self.assertEqual(1, len(table_list))
table = table_list[0] table = table_list[0]
name_key = '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}name' name_key = '{urn:oasis:names:tc:opendocument:xmlns:table:1.0}name'
self.assertEquals('Developers', table.attrib[name_key]) self.assertEqual('Developers', table.attrib[name_key])
def testGetTableItemWithoutSuccess(self): def testGetTableItemWithoutSuccess(self):
"""Test if getTable() returns None for an non existent table name""" """Test if getTable() returns None for an non existent table name"""
data = open('./data/granulate_table_test.odt').read() data = open('./data/granulate_table_test.odt').read()
oogranulator = OOGranulator(data, 'odt') oogranulator = OOGranulator(data, 'odt')
table_data = oogranulator.getTable('NonExistentTable') table_data = oogranulator.getTable('NonExistentTable')
self.assertEquals(table_data, None) self.assertEqual(table_data, None)
def testGetColumnItemList(self): def testGetColumnItemList(self):
"""Test if getColumnItemList() returns the right table columns list""" """Test if getColumnItemList() returns the right table columns list"""
data = open('./data/granulate_table_test.odt').read() data = open('./data/granulate_table_test.odt').read()
oogranulator = OOGranulator(data, 'odt') oogranulator = OOGranulator(data, 'odt')
self.assertEquals([[0, 'Name'], [1, 'Country']], self.assertEqual([[0, 'Name'], [1, 'Country']],
oogranulator.getColumnItemList('SoccerTeams')) oogranulator.getColumnItemList('SoccerTeams'))
def testGetLineItemList(self): def testGetLineItemList(self):
...@@ -98,20 +98,20 @@ class TestOOGranulator(HandlerTestCase): ...@@ -98,20 +98,20 @@ class TestOOGranulator(HandlerTestCase):
matrix = [['Name', 'Phone', 'Email'], matrix = [['Name', 'Phone', 'Email'],
['Hugo', '+55 (22) 8888-8888', 'hugomaia@tiolive.com'], ['Hugo', '+55 (22) 8888-8888', 'hugomaia@tiolive.com'],
['Rafael', '+55 (22) 9999-9999', 'rafael@tiolive.com']] ['Rafael', '+55 (22) 9999-9999', 'rafael@tiolive.com']]
self.assertEquals(matrix, oogranulator.getTableMatrix('Developers')) self.assertEqual(matrix, oogranulator.getTableMatrix('Developers'))
matrix = [['Product', 'Price'], matrix = [['Product', 'Price'],
['Pizza', 'R$ 25,00'], ['Pizza', 'R$ 25,00'],
['Petit Gateau', 'R$ 10,00'], ['Petit Gateau', 'R$ 10,00'],
['Feijoada', 'R$ 30,00']] ['Feijoada', 'R$ 30,00']]
self.assertEquals(matrix, oogranulator.getTableMatrix('Prices')) self.assertEqual(matrix, oogranulator.getTableMatrix('Prices'))
self.assertEquals(None, oogranulator.getTableMatrix('Non existent')) self.assertEqual(None, oogranulator.getTableMatrix('Non existent'))
def testGetImageItemList(self): def testGetImageItemList(self):
"""Test if getImageItemList() returns the right images list""" """Test if getImageItemList() returns the right images list"""
image_list = self.oogranulator.getImageItemList() image_list = self.oogranulator.getImageItemList()
self.assertEquals([('10000000000000C80000009C38276C51.jpg', ''), self.assertEqual([('10000000000000C80000009C38276C51.jpg', ''),
('10000201000000C80000004E7B947D46.png', 'TioLive Logo'), ('10000201000000C80000004E7B947D46.png', 'TioLive Logo'),
('10000201000000C80000004E7B947D46.png', ''), ('10000201000000C80000004E7B947D46.png', ''),
# XXX The svg image are stored into odf as svm # XXX The svg image are stored into odf as svm
...@@ -126,12 +126,12 @@ class TestOOGranulator(HandlerTestCase): ...@@ -126,12 +126,12 @@ class TestOOGranulator(HandlerTestCase):
image_id = '10000000000000C80000009C38276C51.jpg' image_id = '10000000000000C80000009C38276C51.jpg'
original_image = zip.read('Pictures/%s' % image_id) original_image = zip.read('Pictures/%s' % image_id)
geted_image = self.oogranulator.getImage(image_id) geted_image = self.oogranulator.getImage(image_id)
self.assertEquals(original_image, geted_image) self.assertEqual(original_image, geted_image)
def testGetImageWithoutSuccess(self): def testGetImageWithoutSuccess(self):
"""Test if getImage() returns an empty string for not existent id""" """Test if getImage() returns an empty string for not existent id"""
obtained_image = self.oogranulator.getImage('anything.png') obtained_image = self.oogranulator.getImage('anything.png')
self.assertEquals('', obtained_image) self.assertEqual('', obtained_image)
def testGetParagraphItemList(self): def testGetParagraphItemList(self):
"""Test if getParagraphItemList() returns the right paragraphs list, with """Test if getParagraphItemList() returns the right paragraphs list, with
...@@ -140,31 +140,31 @@ class TestOOGranulator(HandlerTestCase): ...@@ -140,31 +140,31 @@ class TestOOGranulator(HandlerTestCase):
data = open('./data/granulate_test.odt').read() data = open('./data/granulate_test.odt').read()
oogranulator = OOGranulator(data, 'odt') oogranulator = OOGranulator(data, 'odt')
paragraph_list = oogranulator.getParagraphItemList() paragraph_list = oogranulator.getParagraphItemList()
self.assertEquals((0, 'P3'), paragraph_list[0]) self.assertEqual((0, 'P3'), paragraph_list[0])
self.assertEquals((1, 'P1'), paragraph_list[1]) self.assertEqual((1, 'P1'), paragraph_list[1])
self.assertEquals((2, 'P12'), paragraph_list[2]) self.assertEqual((2, 'P12'), paragraph_list[2])
self.assertEquals((8, 'P13'), paragraph_list[8]) self.assertEqual((8, 'P13'), paragraph_list[8])
self.assertEquals((19, 'Standard'), paragraph_list[19]) self.assertEqual((19, 'Standard'), paragraph_list[19])
def testGetParagraphItemSuccessfully(self): def testGetParagraphItemSuccessfully(self):
"""Test if getParagraphItem() returns the right paragraph""" """Test if getParagraphItem() returns the right paragraph"""
self.assertEquals(('Some images without title', 'P13'), self.assertEqual(('Some images without title', 'P13'),
self.oogranulator.getParagraph(8)) self.oogranulator.getParagraph(8))
big_paragraph = self.oogranulator.getParagraph(5) big_paragraph = self.oogranulator.getParagraph(5)
self.assertEquals('P8', big_paragraph[1]) self.assertEqual('P8', big_paragraph[1])
self.assertTrue(big_paragraph[0].startswith(u'A prática cotidiana prova')) self.assertTrue(big_paragraph[0].startswith(u'A prática cotidiana prova'))
self.assertTrue(big_paragraph[0].endswith(u'corresponde às necessidades.')) self.assertTrue(big_paragraph[0].endswith(u'corresponde às necessidades.'))
def testGetParagraphItemWithoutSuccess(self): def testGetParagraphItemWithoutSuccess(self):
"""Test if getParagraphItem() returns None for not existent id""" """Test if getParagraphItem() returns None for not existent id"""
self.assertEquals(None, self.oogranulator.getParagraph(200)) self.assertEqual(None, self.oogranulator.getParagraph(200))
def testGetChapterItemList(self): def testGetChapterItemList(self):
"""Test if getChapterItemList() returns the right chapters list""" """Test if getChapterItemList() returns the right chapters list"""
data = open('./data/granulate_chapters_test.odt').read() data = open('./data/granulate_chapters_test.odt').read()
oogranulator = OOGranulator(data, 'odt') oogranulator = OOGranulator(data, 'odt')
self.assertEquals([(0, 'Title 0'), (1, 'Title 1'), (2, 'Title 2'), self.assertEqual([(0, 'Title 0'), (1, 'Title 1'), (2, 'Title 2'),
(3, 'Title 3'), (4, 'Title 4'), (5, 'Title 5'), (3, 'Title 3'), (4, 'Title 4'), (5, 'Title 5'),
(6, 'Title 6'), (7, 'Title 7'), (8, 'Title 8'), (6, 'Title 6'), (7, 'Title 7'), (8, 'Title 8'),
(9, 'Title 9'), (10, 'Title 10')], (9, 'Title 9'), (10, 'Title 10')],
...@@ -174,5 +174,5 @@ class TestOOGranulator(HandlerTestCase): ...@@ -174,5 +174,5 @@ class TestOOGranulator(HandlerTestCase):
"""Test if getChapterItem() returns the right chapter""" """Test if getChapterItem() returns the right chapter"""
data = open("./data/granulate_chapters_test.odt").read() data = open("./data/granulate_chapters_test.odt").read()
oogranulator = OOGranulator(data, 'odt') oogranulator = OOGranulator(data, 'odt')
self.assertEquals(['Title 1', 1], oogranulator.getChapterItem(1)) self.assertEqual(['Title 1', 1], oogranulator.getChapterItem(1))
...@@ -47,8 +47,8 @@ class TestLegacyInterface(TestCase): ...@@ -47,8 +47,8 @@ class TestLegacyInterface(TestCase):
None, None,
'text/html') 'text/html')
self.assertEquals(response_dict['mime'], 'text/html') self.assertEqual(response_dict['mime'], 'text/html')
self.assertEquals(self._getFileType(response_dict['data']), self.assertEqual(self._getFileType(response_dict['data']),
'text/html') 'text/html')
def testHtmlToOdt(self): def testHtmlToOdt(self):
...@@ -61,7 +61,7 @@ class TestLegacyInterface(TestCase): ...@@ -61,7 +61,7 @@ class TestLegacyInterface(TestCase):
None, None,
'odt', 'odt',
'text/html') 'text/html')
self.assertEquals(response_dict['mime'], 'application/vnd.oasis.opendocument.text') self.assertEqual(response_dict['mime'], 'application/vnd.oasis.opendocument.text')
self.assertEquals(self._getFileType(response_dict['data']), self.assertEqual(self._getFileType(response_dict['data']),
'application/vnd.oasis.opendocument.text') 'application/vnd.oasis.opendocument.text')
...@@ -161,50 +161,50 @@ class TestMimeMapper(HandlerTestCase): ...@@ -161,50 +161,50 @@ class TestMimeMapper(HandlerTestCase):
def testGetFilterWhenExtensionNotExist(self): def testGetFilterWhenExtensionNotExist(self):
"""Test the case that the user passes extension which does not exist.""" """Test the case that the user passes extension which does not exist."""
empty_list = self.mimemapper.getFilterList('xxx') empty_list = self.mimemapper.getFilterList('xxx')
self.assertEquals(empty_list, []) self.assertEqual(empty_list, [])
def testIfThereIsDuplicateData(self): def testIfThereIsDuplicateData(self):
"""Test if there is duplicate data.""" """Test if there is duplicate data."""
# XXX It can not exists multiple keys inside a dictionary # XXX It can not exists multiple keys inside a dictionary
extension_list = self.mimemapper._doc_type_list_by_extension.keys() extension_list = self.mimemapper._doc_type_list_by_extension.keys()
self.assertEquals(len(extension_list), len(set(extension_list))) self.assertEqual(len(extension_list), len(set(extension_list)))
for type_list in self.mimemapper._doc_type_list_by_extension.values(): for type_list in self.mimemapper._doc_type_list_by_extension.values():
self.assertEquals(len(type_list), len(set(type_list))) self.assertEqual(len(type_list), len(set(type_list)))
document_type_list = self.mimemapper._document_type_dict.keys() document_type_list = self.mimemapper._document_type_dict.keys()
self.assertEquals(len(document_type_list), len(set(document_type_list))) self.assertEqual(len(document_type_list), len(set(document_type_list)))
document_service_list = self.mimemapper._document_type_dict.values() document_service_list = self.mimemapper._document_type_dict.values()
self.assertEquals(len(document_service_list), len(set(document_service_list))) self.assertEqual(len(document_service_list), len(set(document_service_list)))
document_service_list = self.mimemapper._extension_list_by_type.keys() document_service_list = self.mimemapper._extension_list_by_type.keys()
self.assertEquals(len(document_service_list), len(set(document_service_list))) self.assertEqual(len(document_service_list), len(set(document_service_list)))
extension_list = self.mimemapper._extension_list_by_type.values() extension_list = self.mimemapper._extension_list_by_type.values()
for extension in extension_list: for extension in extension_list:
self.assertEquals(len(extension), len(set(extension)), self.assertEqual(len(extension), len(set(extension)),
"extension_list_by_type has duplicate data") "extension_list_by_type has duplicate data")
def testGetFilterByExt(self): def testGetFilterByExt(self):
"""Test if passing the extension the filter returns corretcly.""" """Test if passing the extension the filter returns corretcly."""
pdf_filter_list = self.mimemapper.getFilterList('pdf') pdf_filter_list = self.mimemapper.getFilterList('pdf')
self.assertEquals(len(pdf_filter_list), 5) self.assertEqual(len(pdf_filter_list), 5)
xls_filter_list = self.mimemapper.getFilterList('xls') xls_filter_list = self.mimemapper.getFilterList('xls')
self.assertEquals(len(xls_filter_list), 1) self.assertEqual(len(xls_filter_list), 1)
doc_filter_list = self.mimemapper.getFilterList('doc') doc_filter_list = self.mimemapper.getFilterList('doc')
self.assertEquals(len(doc_filter_list), 1) self.assertEqual(len(doc_filter_list), 1)
def testGetDocumentTypeDict(self): def testGetDocumentTypeDict(self):
"""Test if dictonary document type returns type correctly.""" """Test if dictonary document type returns type correctly."""
document_type_dict = self.mimemapper._document_type_dict document_type_dict = self.mimemapper._document_type_dict
type = document_type_dict.get("text") type = document_type_dict.get("text")
self.assertEquals(type, 'com.sun.star.text.TextDocument') self.assertEqual(type, 'com.sun.star.text.TextDocument')
type = document_type_dict.get("chart") type = document_type_dict.get("chart")
self.assertEquals(type, 'com.sun.star.chart2.ChartDocument') self.assertEqual(type, 'com.sun.star.chart2.ChartDocument')
type = document_type_dict.get("drawing") type = document_type_dict.get("drawing")
self.assertEquals(type, 'com.sun.star.drawing.DrawingDocument') self.assertEqual(type, 'com.sun.star.drawing.DrawingDocument')
type = document_type_dict.get("presentation") type = document_type_dict.get("presentation")
self.assertEquals(type, 'com.sun.star.presentation.PresentationDocument') self.assertEqual(type, 'com.sun.star.presentation.PresentationDocument')
type = document_type_dict.get("spreadsheet") type = document_type_dict.get("spreadsheet")
self.assertEquals(type, 'com.sun.star.sheet.SpreadsheetDocument') self.assertEqual(type, 'com.sun.star.sheet.SpreadsheetDocument')
type = document_type_dict.get("web") type = document_type_dict.get("web")
self.assertEquals(type, 'com.sun.star.text.WebDocument') self.assertEqual(type, 'com.sun.star.text.WebDocument')
def testGetAllowedExtensionListByExtension(self): def testGetAllowedExtensionListByExtension(self):
"""Test if function getAllowedExtensionList returns correctly a list with """Test if function getAllowedExtensionList returns correctly a list with
...@@ -243,7 +243,7 @@ class TestMimeMapper(HandlerTestCase): ...@@ -243,7 +243,7 @@ class TestMimeMapper(HandlerTestCase):
got_list.sort() got_list.sort()
global_expected_list = list(global_expected_tuple) global_expected_list = list(global_expected_tuple)
global_expected_list.sort() global_expected_list.sort()
self.assertEquals(got_list, global_expected_list) self.assertEqual(got_list, global_expected_list)
def testGetAllAllowedExtensionListForDrawing(self): def testGetAllAllowedExtensionListForDrawing(self):
"""Passing document_type equal to 'drawing', the return must be equal """Passing document_type equal to 'drawing', the return must be equal
...@@ -262,7 +262,7 @@ class TestMimeMapper(HandlerTestCase): ...@@ -262,7 +262,7 @@ class TestMimeMapper(HandlerTestCase):
got_tuple.sort() got_tuple.sort()
web_expected_list = list(web_expected_tuple) web_expected_list = list(web_expected_tuple)
web_expected_list.sort() web_expected_list.sort()
self.assertEquals(got_tuple, web_expected_list) self.assertEqual(got_tuple, web_expected_list)
def testGetAllAllowedExtensionListForPresentation(self): def testGetAllAllowedExtensionListForPresentation(self):
"""Passing document_type equal to 'presentation', the return must be equal """Passing document_type equal to 'presentation', the return must be equal
...@@ -290,21 +290,21 @@ class TestMimeMapper(HandlerTestCase): ...@@ -290,21 +290,21 @@ class TestMimeMapper(HandlerTestCase):
got_list.sort() got_list.sort()
chart_expected_list = list(chart_expected_tuple) chart_expected_list = list(chart_expected_tuple)
chart_expected_list.sort() chart_expected_list.sort()
self.assertEquals(got_list, chart_expected_list) self.assertEqual(got_list, chart_expected_list)
def testGetFilterName(self): def testGetFilterName(self):
"""Test if passing extension and document_type, the filter is correct.""" """Test if passing extension and document_type, the filter is correct."""
filtername = self.mimemapper.getFilterName("xls", filtername = self.mimemapper.getFilterName("xls",
'com.sun.star.sheet.SpreadsheetDocument') 'com.sun.star.sheet.SpreadsheetDocument')
self.assertEquals(filtername, "MS Excel 97") self.assertEqual(filtername, "MS Excel 97")
filtername = self.mimemapper.getFilterName("pdf", filtername = self.mimemapper.getFilterName("pdf",
'com.sun.star.text.TextDocument') 'com.sun.star.text.TextDocument')
self.assertEquals(filtername, "writer_pdf_Export") self.assertEqual(filtername, "writer_pdf_Export")
filtername = self.mimemapper.getFilterName('ppt', filtername = self.mimemapper.getFilterName('ppt',
'com.sun.star.presentation.PresentationDocument') 'com.sun.star.presentation.PresentationDocument')
self.assertEquals(filtername, "MS PowerPoint 97") self.assertEqual(filtername, "MS PowerPoint 97")
filtername = self.mimemapper.getFilterName("html", filtername = self.mimemapper.getFilterName("html",
'com.sun.star.presentation.PresentationDocument') 'com.sun.star.presentation.PresentationDocument')
self.assertEquals(filtername, "impress_html_Export") self.assertEqual(filtername, "impress_html_Export")
...@@ -53,13 +53,13 @@ class TestMonitorInit(HandlerTestCase): ...@@ -53,13 +53,13 @@ class TestMonitorInit(HandlerTestCase):
def testMonitorInitGlobalAttributes(self): def testMonitorInitGlobalAttributes(self):
"""Test the global attributes""" """Test the global attributes"""
self.assertEquals(monitor.monitor_request, None) self.assertEqual(monitor.monitor_request, None)
self.assertEquals(monitor.monitor_memory, None) self.assertEqual(monitor.monitor_memory, None)
def testMonitorLoadOnlyMonitorRequest(self): def testMonitorLoadOnlyMonitorRequest(self):
"""Check if the monitors are started""" """Check if the monitors are started"""
monitor.load(self.load_config) monitor.load(self.load_config)
self.assertEquals(isinstance(monitor.monitor_request, self.assertEqual(isinstance(monitor.monitor_request,
MonitorRequest), MonitorRequest),
True) True)
...@@ -67,10 +67,10 @@ class TestMonitorInit(HandlerTestCase): ...@@ -67,10 +67,10 @@ class TestMonitorInit(HandlerTestCase):
"""Check if the MemoryMemory is started""" """Check if the MemoryMemory is started"""
self.load_config['enable_memory_monitor'] = 'true' self.load_config['enable_memory_monitor'] = 'true'
monitor.load(self.load_config) monitor.load(self.load_config)
self.assertEquals(isinstance(monitor.monitor_request, self.assertEqual(isinstance(monitor.monitor_request,
MonitorRequest), MonitorRequest),
True) True)
self.assertEquals(isinstance(monitor.monitor_memory, self.assertEqual(isinstance(monitor.monitor_memory,
MonitorMemory), MonitorMemory),
True) True)
......
...@@ -74,7 +74,7 @@ class TestMonitorMemory(unittest.TestCase): ...@@ -74,7 +74,7 @@ class TestMonitorMemory(unittest.TestCase):
self.monitor = MonitorMemory(openoffice, 2, 10) self.monitor = MonitorMemory(openoffice, 2, 10)
self.monitor.start() self.monitor.start()
sleep(self.interval) sleep(self.interval)
self.assertEquals(openoffice.status(), False) self.assertEqual(openoffice.status(), False)
finally: finally:
self.monitor.terminate() self.monitor.terminate()
...@@ -94,17 +94,17 @@ class TestMonitorMemory(unittest.TestCase): ...@@ -94,17 +94,17 @@ class TestMonitorMemory(unittest.TestCase):
self.monitor = MonitorMemory(openoffice, 2, 400) self.monitor = MonitorMemory(openoffice, 2, 400)
self.monitor.create_process() self.monitor.create_process()
self.assertTrue(hasattr(self.monitor, 'process')) self.assertTrue(hasattr(self.monitor, 'process'))
self.assertEquals(type(self.monitor.process), Process) self.assertEqual(type(self.monitor.process), Process)
def testGetMemoryUsage(self): def testGetMemoryUsage(self):
"""Test memory usage""" """Test memory usage"""
self.monitor = MonitorMemory(openoffice, 2, 400) self.monitor = MonitorMemory(openoffice, 2, 400)
openoffice.stop() openoffice.stop()
memory_usage_int = self.monitor.get_memory_usage() memory_usage_int = self.monitor.get_memory_usage()
self.assertEquals(memory_usage_int, 0) self.assertEqual(memory_usage_int, 0)
if not openoffice.status(): if not openoffice.status():
openoffice.start() openoffice.start()
memory_usage_int = self.monitor.get_memory_usage() memory_usage_int = self.monitor.get_memory_usage()
self.assertEquals(type(memory_usage_int), IntType) self.assertEqual(type(memory_usage_int), IntType)
...@@ -47,18 +47,18 @@ class TestMonitorRequest(HandlerTestCase): ...@@ -47,18 +47,18 @@ class TestMonitorRequest(HandlerTestCase):
monitor_request.terminate() monitor_request.terminate()
sleep(4) sleep(4)
try: try:
self.assertEquals(monitor_request.is_alive(), False) self.assertEqual(monitor_request.is_alive(), False)
finally: finally:
monitor_request.terminate() monitor_request.terminate()
def testMonitorRequest(self): def testMonitorRequest(self):
"""Test if openoffice is monitored correclty""" """Test if openoffice is monitored correclty"""
openoffice.request = 3 openoffice.request = 3
self.assertEquals(openoffice.request, 3) self.assertEqual(openoffice.request, 3)
monitor_request = MonitorRequest(openoffice, 1, 2) monitor_request = MonitorRequest(openoffice, 1, 2)
monitor_request.start() monitor_request.start()
sleep(4) sleep(4)
self.assertEquals(openoffice.request, 0) self.assertEqual(openoffice.request, 0)
monitor_request.terminate() monitor_request.terminate()
...@@ -52,7 +52,7 @@ class TestMonitorTimeout(unittest.TestCase): ...@@ -52,7 +52,7 @@ class TestMonitorTimeout(unittest.TestCase):
monitor_timeout = self._createMonitor(1) monitor_timeout = self._createMonitor(1)
monitor_timeout.start() monitor_timeout.start()
sleep(2) sleep(2)
self.assertEquals(monitor_timeout.is_alive(), False) self.assertEqual(monitor_timeout.is_alive(), False)
monitor_timeout.terminate() monitor_timeout.terminate()
def testStopOpenOffice(self): def testStopOpenOffice(self):
...@@ -62,7 +62,7 @@ class TestMonitorTimeout(unittest.TestCase): ...@@ -62,7 +62,7 @@ class TestMonitorTimeout(unittest.TestCase):
monitor_timeout = self._createMonitor(1) monitor_timeout = self._createMonitor(1)
monitor_timeout.start() monitor_timeout.start()
sleep(2) sleep(2)
self.assertEquals(openoffice.status(), False) self.assertEqual(openoffice.status(), False)
openoffice.restart() openoffice.restart()
self.assertTrue(openoffice.status()) self.assertTrue(openoffice.status())
finally: finally:
...@@ -76,17 +76,17 @@ class TestMonitorTimeout(unittest.TestCase): ...@@ -76,17 +76,17 @@ class TestMonitorTimeout(unittest.TestCase):
monitor_timeout = self._createMonitor(1) monitor_timeout = self._createMonitor(1)
monitor_timeout.start() monitor_timeout.start()
sleep(2) sleep(2)
self.assertEquals(openoffice.status(), False) self.assertEqual(openoffice.status(), False)
monitor_timeout.terminate() monitor_timeout.terminate()
openoffice.restart() openoffice.restart()
self.assertTrue(openoffice.status()) self.assertTrue(openoffice.status())
monitor_timeout = self._createMonitor(1) monitor_timeout = self._createMonitor(1)
monitor_timeout.start() monitor_timeout.start()
sleep(2) sleep(2)
self.assertEquals(openoffice.status(), False) self.assertEqual(openoffice.status(), False)
monitor_timeout.terminate() monitor_timeout.terminate()
sleep(1) sleep(1)
self.assertEquals(monitor_timeout.is_alive(), False) self.assertEqual(monitor_timeout.is_alive(), False)
finally: finally:
monitor_timeout.terminate() monitor_timeout.terminate()
openoffice.release() openoffice.release()
......
...@@ -52,12 +52,12 @@ class TestOdfDocument(HandlerTestCase): ...@@ -52,12 +52,12 @@ class TestOdfDocument(HandlerTestCase):
def testGetExistentFile(self): def testGetExistentFile(self):
"""Test if the getFile method returns the requested file""" """Test if the getFile method returns the requested file"""
requested_file = self.oodocument.getFile('content.xml') requested_file = self.oodocument.getFile('content.xml')
self.assertEquals(requested_file, self.oodocument.getContentXml()) self.assertEqual(requested_file, self.oodocument.getContentXml())
def testGetNotPresentFile(self): def testGetNotPresentFile(self):
"""Test if the getFile method returns None for not present file request""" """Test if the getFile method returns None for not present file request"""
requested_file = self.oodocument.getFile('not_present.xml') requested_file = self.oodocument.getFile('not_present.xml')
self.assertEquals(requested_file, '') self.assertEqual(requested_file, '')
def testParseContent(self): def testParseContent(self):
"""Test if the _parsed_content attribute is the parsed content.xml""" """Test if the _parsed_content attribute is the parsed content.xml"""
......
...@@ -56,10 +56,10 @@ class TestOpenOffice(HandlerTestCase): ...@@ -56,10 +56,10 @@ class TestOpenOffice(HandlerTestCase):
def testPid(self): def testPid(self):
"""Test pid function to validate if the return is correctly""" """Test pid function to validate if the return is correctly"""
self.assertNotEquals(self.openoffice.pid(), None) self.assertNotEqual(self.openoffice.pid(), None)
self.openoffice.stop() self.openoffice.stop()
self.assertEquals(self.openoffice.pid(), None) self.assertEqual(self.openoffice.pid(), None)
self.assertEquals(self.openoffice.status(), False) self.assertEqual(self.openoffice.status(), False)
def testOpenOfficeStart(self): def testOpenOfficeStart(self):
"""Test if the start method works correclty""" """Test if the start method works correclty"""
...@@ -69,12 +69,12 @@ class TestOpenOffice(HandlerTestCase): ...@@ -69,12 +69,12 @@ class TestOpenOffice(HandlerTestCase):
"""Test if the stop method works correctly""" """Test if the stop method works correctly"""
self.openoffice.stop() self.openoffice.stop()
waitStopDaemon(self.openoffice) waitStopDaemon(self.openoffice)
self.assertEquals(self.openoffice.status(), False) self.assertEqual(self.openoffice.status(), False)
def testOpenOfficeRequest(self): def testOpenOfficeRequest(self):
"""Test if the requisition amount is increasing right""" """Test if the requisition amount is increasing right"""
self.openoffice.acquire() self.openoffice.acquire()
self.assertEquals(self.openoffice.request, 1) self.assertEqual(self.openoffice.request, 1)
self.openoffice.release() self.openoffice.release()
def testOpenOfficeRestart(self): def testOpenOfficeRestart(self):
...@@ -87,7 +87,7 @@ class TestOpenOffice(HandlerTestCase): ...@@ -87,7 +87,7 @@ class TestOpenOffice(HandlerTestCase):
self.openoffice.acquire() self.openoffice.acquire()
self.assertTrue(self.openoffice.isLocked()) self.assertTrue(self.openoffice.isLocked())
self.openoffice.release() self.openoffice.release()
self.assertEquals(self.openoffice.isLocked(), False) self.assertEqual(self.openoffice.isLocked(), False)
def testStartTwoOpenOfficeWithTheSameAddress(self): def testStartTwoOpenOfficeWithTheSameAddress(self):
"""Check if starting two openoffice using the same address, the second """Check if starting two openoffice using the same address, the second
...@@ -100,7 +100,7 @@ class TestOpenOffice(HandlerTestCase): ...@@ -100,7 +100,7 @@ class TestOpenOffice(HandlerTestCase):
'en', 'en',
self.environment_dict) self.environment_dict)
second_openoffice.start() second_openoffice.start()
self.assertEquals(self.openoffice.status(), False) self.assertEqual(self.openoffice.status(), False)
self.assertTrue(second_openoffice.status()) self.assertTrue(second_openoffice.status())
second_openoffice.stop() second_openoffice.stop()
......
This diff is collapsed.
...@@ -80,12 +80,12 @@ class TestUnoConverter(HandlerTestCase): ...@@ -80,12 +80,12 @@ class TestUnoConverter(HandlerTestCase):
stdout, stderr = Popen(command, stdout, stderr = Popen(command,
stdout=PIPE, stdout=PIPE,
stderr=PIPE).communicate() stderr=PIPE).communicate()
self.assertEquals(stderr, '') self.assertEqual(stderr, '')
output_url = stdout.replace('\n', '') output_url = stdout.replace('\n', '')
self.assertTrue(exists(output_url), stdout) self.assertTrue(exists(output_url), stdout)
mime = magic.Magic(mime=True) mime = magic.Magic(mime=True)
self.assertEquals(mime.from_file(output_url), 'application/msword') self.assertEqual(mime.from_file(output_url), 'application/msword')
self.document.trash() self.document.trash()
self.assertEquals(exists(output_url), False) self.assertEqual(exists(output_url), False)
...@@ -68,15 +68,15 @@ class TestUnoMimeMapper(HandlerTestCase): ...@@ -68,15 +68,15 @@ class TestUnoMimeMapper(HandlerTestCase):
stdout, stderr = Popen(command, stdout, stderr = Popen(command,
stdout=PIPE, stdout=PIPE,
stderr=PIPE).communicate() stderr=PIPE).communicate()
self.assertEquals(stderr, '') self.assertEqual(stderr, '')
filter_dict, type_dict = json.loads(stdout) filter_dict, type_dict = json.loads(stdout)
self.assertTrue('filter_dict' in locals()) self.assertTrue('filter_dict' in locals())
self.assertTrue('type_dict' in locals()) self.assertTrue('type_dict' in locals())
self.assertNotEquals(filter_dict.get('writer8'), None) self.assertNotEqual(filter_dict.get('writer8'), None)
self.assertEquals(type_dict.get('writer8').get('Name'), 'writer8') self.assertEqual(type_dict.get('writer8').get('Name'), 'writer8')
self.assertNotEquals(filter_dict.get('writer8'), None) self.assertNotEqual(filter_dict.get('writer8'), None)
self.assertEquals(type_dict.get('writer8').get('PreferredFilter'), 'writer8') self.assertEqual(type_dict.get('writer8').get('PreferredFilter'), 'writer8')
self.assertEquals(stderr, '') self.assertEqual(stderr, '')
def testCallUnoMimemapperOnlyHostNameAndPort(self): def testCallUnoMimemapperOnlyHostNameAndPort(self):
""" Test call unomimemapper without uno_path and office_binary_path""" """ Test call unomimemapper without uno_path and office_binary_path"""
...@@ -89,15 +89,15 @@ class TestUnoMimeMapper(HandlerTestCase): ...@@ -89,15 +89,15 @@ class TestUnoMimeMapper(HandlerTestCase):
stdout, stderr = Popen(command, stdout, stderr = Popen(command,
stdout=PIPE, stdout=PIPE,
stderr=PIPE).communicate() stderr=PIPE).communicate()
self.assertEquals(stderr, '') self.assertEqual(stderr, '')
filter_dict, type_dict = json.loads(stdout) filter_dict, type_dict = json.loads(stdout)
self.assertTrue('filter_dict' in locals()) self.assertTrue('filter_dict' in locals())
self.assertTrue('type_dict' in locals()) self.assertTrue('type_dict' in locals())
self.assertNotEquals(filter_dict.get('writer8'), None) self.assertNotEqual(filter_dict.get('writer8'), None)
self.assertEquals(type_dict.get('writer8').get('Name'), 'writer8') self.assertEqual(type_dict.get('writer8').get('Name'), 'writer8')
self.assertNotEquals(filter_dict.get('writer8'), None) self.assertNotEqual(filter_dict.get('writer8'), None)
self.assertEquals(type_dict.get('writer8').get('PreferredFilter'), 'writer8') self.assertEqual(type_dict.get('writer8').get('PreferredFilter'), 'writer8')
self.assertEquals(stderr, '') self.assertEqual(stderr, '')
def testWithoutOpenOffice(self): def testWithoutOpenOffice(self):
"""Test when the openoffice is stopped""" """Test when the openoffice is stopped"""
...@@ -118,7 +118,7 @@ class TestUnoMimeMapper(HandlerTestCase): ...@@ -118,7 +118,7 @@ class TestUnoMimeMapper(HandlerTestCase):
stdout, stderr = Popen(command, stdout, stderr = Popen(command,
stdout=PIPE, stdout=PIPE,
stderr=PIPE).communicate() stderr=PIPE).communicate()
self.assertEquals(stdout, '') self.assertEqual(stdout, '')
self.assertTrue(stderr.endswith(error_msg), stderr) self.assertTrue(stderr.endswith(error_msg), stderr)
openoffice.start() openoffice.start()
......
...@@ -48,10 +48,10 @@ class TestUtil(unittest.TestCase): ...@@ -48,10 +48,10 @@ class TestUtil(unittest.TestCase):
def testLoadMimetypelist(self): def testLoadMimetypelist(self):
"""Test if the file with mimetypes is loaded correctly""" """Test if the file with mimetypes is loaded correctly"""
self.assertEquals(mimetypes.types_map.get(".ogv"), None) self.assertEqual(mimetypes.types_map.get(".ogv"), None)
self.assertEquals(mimetypes.types_map.get(".3gp"), None) self.assertEqual(mimetypes.types_map.get(".3gp"), None)
util.loadMimetypeList() util.loadMimetypeList()
self.assertEquals(mimetypes.types_map.get(".ogv"), "video/ogg") self.assertEqual(mimetypes.types_map.get(".ogv"), "video/ogg")
self.assertEquals(mimetypes.types_map.get(".3gp"), "video/3gpp") self.assertEqual(mimetypes.types_map.get(".3gp"), "video/3gpp")
...@@ -40,7 +40,7 @@ def removeDirectory(path): ...@@ -40,7 +40,7 @@ def removeDirectory(path):
"""Remove directory""" """Remove directory"""
try: try:
rmtree(path) rmtree(path)
except OSError, msg: except OSError as msg:
logger.error(msg) logger.error(msg)
...@@ -50,8 +50,8 @@ def socketStatus(hostname, port): ...@@ -50,8 +50,8 @@ def socketStatus(hostname, port):
socket().bind((hostname, port),) socket().bind((hostname, port),)
# False if the is free # False if the is free
return False return False
except error, (num, err): except error as err:
if num == EADDRINUSE: if err.errno == EADDRINUSE:
# True if the isn't free # True if the isn't free
return True return True
...@@ -79,5 +79,5 @@ def waitStopDaemon(daemon, attempts=5): ...@@ -79,5 +79,5 @@ def waitStopDaemon(daemon, attempts=5):
def remove_file(filepath): def remove_file(filepath):
try: try:
remove(filepath) remove(filepath)
except OSError, msg: except OSError as msg:
print msg.strerror print(msg.strerror)
...@@ -51,9 +51,9 @@ class TestHandler(HandlerTestCase): ...@@ -51,9 +51,9 @@ class TestHandler(HandlerTestCase):
pdf_document = open("data/test.pdf").read() pdf_document = open("data/test.pdf").read()
handler = Handler(self.tmp_url, pdf_document, "pdf", **self.kw) handler = Handler(self.tmp_url, pdf_document, "pdf", **self.kw)
metadata = handler.getMetadata() metadata = handler.getMetadata()
self.assertEquals(type(metadata), DictType) self.assertEqual(type(metadata), DictType)
self.assertNotEquals(metadata, {}) self.assertNotEqual(metadata, {})
self.assertEquals(metadata["title"], 'Free Cloud Alliance Presentation') self.assertEqual(metadata["title"], 'Free Cloud Alliance Presentation')
def testsetMetadata(self): def testsetMetadata(self):
"""Test if the metadata is inserted correctly""" """Test if the metadata is inserted correctly"""
...@@ -63,8 +63,8 @@ class TestHandler(HandlerTestCase): ...@@ -63,8 +63,8 @@ class TestHandler(HandlerTestCase):
new_document = handler.setMetadata(metadata_dict) new_document = handler.setMetadata(metadata_dict)
handler = Handler(self.tmp_url, new_document, "pdf", **self.kw) handler = Handler(self.tmp_url, new_document, "pdf", **self.kw)
metadata = handler.getMetadata() metadata = handler.getMetadata()
self.assertEquals(metadata["title"], 'Set Metadata Test') self.assertEqual(metadata["title"], 'Set Metadata Test')
self.assertEquals(metadata['creator'], 'gabriel\'@') self.assertEqual(metadata['creator'], 'gabriel\'@')
def testGetAllowedConversionFormatList(self): def testGetAllowedConversionFormatList(self):
"""Test all combination of mimetype """Test all combination of mimetype
...@@ -73,10 +73,10 @@ class TestHandler(HandlerTestCase): ...@@ -73,10 +73,10 @@ class TestHandler(HandlerTestCase):
""" """
get = Handler.getAllowedConversionFormatList get = Handler.getAllowedConversionFormatList
# Handled mimetypes # Handled mimetypes
self.assertEquals(get("application/pdf;ignored=param"), self.assertEqual(get("application/pdf;ignored=param"),
[("text/plain", "Plain Text")]) [("text/plain", "Plain Text")])
# Unhandled mimetypes # Unhandled mimetypes
self.assertEquals(get("text/plain;ignored=param"), []) self.assertEqual(get("text/plain;ignored=param"), [])
self.assertEquals(get("text/plain;charset=UTF-8;ignored=param"), []) self.assertEqual(get("text/plain;charset=UTF-8;ignored=param"), [])
...@@ -45,7 +45,7 @@ class TestHandler(HandlerTestCase): ...@@ -45,7 +45,7 @@ class TestHandler(HandlerTestCase):
pdf_file = handler.convert("pdf", **conversion_kw) pdf_file = handler.convert("pdf", **conversion_kw)
mime = magic.Magic(mime=True) mime = magic.Magic(mime=True)
pdf_mimetype = mime.from_buffer(pdf_file) pdf_mimetype = mime.from_buffer(pdf_file)
self.assertEquals("application/pdf", pdf_mimetype) self.assertEqual("application/pdf", pdf_mimetype)
def testConvertHtmlWithPngDataUrlToPdf(self): def testConvertHtmlWithPngDataUrlToPdf(self):
"""Test conversion of html with png data url to pdf""" """Test conversion of html with png data url to pdf"""
...@@ -86,9 +86,9 @@ class TestHandler(HandlerTestCase): ...@@ -86,9 +86,9 @@ class TestHandler(HandlerTestCase):
""" """
get = Handler.getAllowedConversionFormatList get = Handler.getAllowedConversionFormatList
# Handled mimetypes # Handled mimetypes
self.assertEquals(get("text/html;ignored=param"), self.assertEqual(get("text/html;ignored=param"),
[("application/pdf", "PDF - Portable Document Format")]) [("application/pdf", "PDF - Portable Document Format")])
# Unhandled mimetypes # Unhandled mimetypes
self.assertEquals(get("application/pdf;ignored=param"), []) self.assertEqual(get("application/pdf;ignored=param"), [])
...@@ -89,7 +89,7 @@ class TestHandler(HandlerTestCase): ...@@ -89,7 +89,7 @@ class TestHandler(HandlerTestCase):
def testgetMetadata(self): def testgetMetadata(self):
"""Test getMetadata from yformats""" """Test getMetadata from yformats"""
handler = Handler(self.tmp_url, "", "xlsy", **self.kw) handler = Handler(self.tmp_url, "", "xlsy", **self.kw)
self.assertEquals(handler.getMetadata(), { self.assertEqual(handler.getMetadata(), {
u'CreationDate': u'00/00/0000 00:00:00', u'CreationDate': u'00/00/0000 00:00:00',
u'ImplementationName': u'com.sun.star.comp.comphelper.OPropertyBag', u'ImplementationName': u'com.sun.star.comp.comphelper.OPropertyBag',
u'MIMEType': u'text/plain', u'MIMEType': u'text/plain',
...@@ -98,7 +98,7 @@ class TestHandler(HandlerTestCase): ...@@ -98,7 +98,7 @@ class TestHandler(HandlerTestCase):
u'TemplateDate': u'00/00/0000 00:00:00', u'TemplateDate': u'00/00/0000 00:00:00',
}) })
handler = Handler(self.tmp_url, open("data/test_with_metadata.xlsy").read(), "xlsy", **self.kw) handler = Handler(self.tmp_url, open("data/test_with_metadata.xlsy").read(), "xlsy", **self.kw)
self.assertEquals(handler.getMetadata(), { self.assertEqual(handler.getMetadata(), {
u'CreationDate': u'31/01/2018 21:09:10', u'CreationDate': u'31/01/2018 21:09:10',
u'Keywords': [u'\u0442\u0435\u0441\u0442', u'\u0441\u0430\u0431\u0436\u0435\u043a\u0442'], u'Keywords': [u'\u0442\u0435\u0441\u0442', u'\u0441\u0430\u0431\u0436\u0435\u043a\u0442'],
'MIMEType': 'application/x-asc-spreadsheet', 'MIMEType': 'application/x-asc-spreadsheet',
...@@ -117,7 +117,7 @@ class TestHandler(HandlerTestCase): ...@@ -117,7 +117,7 @@ class TestHandler(HandlerTestCase):
"Keywords": "test keywords", "Keywords": "test keywords",
}) })
handler = Handler(self.tmp_url, new_mime_data, "xlsy", **self.kw) handler = Handler(self.tmp_url, new_mime_data, "xlsy", **self.kw)
self.assertEquals(handler.getMetadata(), {u'Keywords': u'test keywords', 'MIMEType': 'application/x-asc-spreadsheet', u'Title': u'test title', u'Subject': u'test subject'}) self.assertEqual(handler.getMetadata(), {u'Keywords': u'test keywords', 'MIMEType': 'application/x-asc-spreadsheet', u'Title': u'test title', u'Subject': u'test subject'})
def testGetAllowedConversionFormatList(self): def testGetAllowedConversionFormatList(self):
"""Test all combination of mimetype """Test all combination of mimetype
...@@ -125,13 +125,13 @@ class TestHandler(HandlerTestCase): ...@@ -125,13 +125,13 @@ class TestHandler(HandlerTestCase):
None of the types below define any mimetype parameter to not ignore so far. None of the types below define any mimetype parameter to not ignore so far.
""" """
get = Handler.getAllowedConversionFormatList get = Handler.getAllowedConversionFormatList
self.assertEquals(get("application/x-asc-text;ignored=param"), self.assertEqual(get("application/x-asc-text;ignored=param"),
[("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Word 2007 Document"), [("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Word 2007 Document"),
('application/vnd.oasis.opendocument.text', 'ODF Text Document')]) ('application/vnd.oasis.opendocument.text', 'ODF Text Document')])
self.assertEquals(get("application/x-asc-spreadsheet;ignored=param"), self.assertEqual(get("application/x-asc-spreadsheet;ignored=param"),
[("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Excel 2007 Spreadsheet"), [("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Excel 2007 Spreadsheet"),
('application/vnd.oasis.opendocument.spreadsheet', 'ODF Spreadsheet Document')]) ('application/vnd.oasis.opendocument.spreadsheet', 'ODF Spreadsheet Document')])
self.assertEquals(get("application/x-asc-presentation;ignored=param"), self.assertEqual(get("application/x-asc-presentation;ignored=param"),
[("application/vnd.openxmlformats-officedocument.presentationml.presentation", "PowerPoint 2007 Presentation"), [("application/vnd.openxmlformats-officedocument.presentationml.presentation", "PowerPoint 2007 Presentation"),
('application/vnd.oasis.opendocument.presentation', 'ODF Presentation Document')]) ('application/vnd.oasis.opendocument.presentation', 'ODF Presentation Document')])
...@@ -274,7 +274,7 @@ class Manager(object): ...@@ -274,7 +274,7 @@ class Manager(object):
response_dict['mime'] = response_dict['meta']['MIMEType'] response_dict['mime'] = response_dict['meta']['MIMEType']
del response_dict['meta']['Data'] del response_dict['meta']['Data']
return (200, response_dict, "") return (200, response_dict, "")
except Exception, e: except Exception as e:
import traceback; import traceback;
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
return (402, {}, e.args[0]) return (402, {}, e.args[0])
...@@ -291,7 +291,7 @@ class Manager(object): ...@@ -291,7 +291,7 @@ class Manager(object):
try: try:
response_dict['data'] = self.updateFileMetadata(data, extension, meta) response_dict['data'] = self.updateFileMetadata(data, extension, meta)
return (200, response_dict, '') return (200, response_dict, '')
except Exception, e: except Exception as e:
import traceback; import traceback;
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
return (402, {}, e.args[0]) return (402, {}, e.args[0])
...@@ -311,7 +311,7 @@ class Manager(object): ...@@ -311,7 +311,7 @@ class Manager(object):
# we use 'Title'" # we use 'Title'"
response_dict['meta']['title'] = response_dict['meta']['Title'] response_dict['meta']['title'] = response_dict['meta']['Title']
return (200, response_dict, '') return (200, response_dict, '')
except Exception, e: except Exception as e:
import traceback; import traceback;
logger.error('run_getmetadata: ' + traceback.format_exc()) logger.error('run_getmetadata: ' + traceback.format_exc())
return (402, {}, e.args[0]) return (402, {}, e.args[0])
...@@ -353,7 +353,7 @@ class Manager(object): ...@@ -353,7 +353,7 @@ class Manager(object):
response_dict['mime'] = mimetypes.types_map.get('.%s' % extension, response_dict['mime'] = mimetypes.types_map.get('.%s' % extension,
mimetypes.types_map.get('.%s' % extension.split('.')[-1])) mimetypes.types_map.get('.%s' % extension.split('.')[-1]))
return (200, response_dict, "") return (200, response_dict, "")
except Exception, e: except Exception as e:
import traceback; import traceback;
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
return (402, response_dict, str(e)) return (402, response_dict, str(e))
...@@ -373,7 +373,7 @@ class Manager(object): ...@@ -373,7 +373,7 @@ class Manager(object):
extension_list.append((ext.lstrip('.'), t)) extension_list.append((ext.lstrip('.'), t))
response_dict['response_data'] = extension_list response_dict['response_data'] = extension_list
return (200, response_dict, '') return (200, response_dict, '')
except Exception, e: except Exception as e:
logger.error(e) logger.error(e)
return (402, {}, e.args[0]) return (402, {}, e.args[0])
......
...@@ -123,11 +123,11 @@ class TestCase(unittest.TestCase): ...@@ -123,11 +123,11 @@ class TestCase(unittest.TestCase):
success = False success = False
try: try:
self.setUp() self.setUp()
except SkipTest, e: except SkipTest as e:
result.addSkip(self, str(e)) result.addSkip(self, str(e))
except SetupSiteError, e: except SetupSiteError as e:
result.errors.append(None) result.errors.append(None)
except BaseException, e: except BaseException as e:
result.addError(self, sys.exc_info()) result.addError(self, sys.exc_info())
if isinstance(e, (KeyboardInterrupt, SystemExit)): if isinstance(e, (KeyboardInterrupt, SystemExit)):
raise raise
...@@ -136,13 +136,13 @@ class TestCase(unittest.TestCase): ...@@ -136,13 +136,13 @@ class TestCase(unittest.TestCase):
testMethod() testMethod()
except self.failureException: except self.failureException:
result.addFailure(self, sys.exc_info()) result.addFailure(self, sys.exc_info())
except _ExpectedFailure, e: except _ExpectedFailure as e:
result.addExpectedFailure(self, e.exc_info) result.addExpectedFailure(self, e.exc_info)
except _UnexpectedSuccess: except _UnexpectedSuccess:
result.addUnexpectedSuccess(self) result.addUnexpectedSuccess(self)
except SkipTest, e: except SkipTest as e:
result.addSkip(self, str(e)) result.addSkip(self, str(e))
except BaseException, e: except BaseException as e:
result.addError(self, sys.exc_info()) result.addError(self, sys.exc_info())
if isinstance(e, (KeyboardInterrupt, SystemExit)): if isinstance(e, (KeyboardInterrupt, SystemExit)):
raise raise
...@@ -151,7 +151,7 @@ class TestCase(unittest.TestCase): ...@@ -151,7 +151,7 @@ class TestCase(unittest.TestCase):
try: try:
self.tearDown() self.tearDown()
except BaseException, e: except BaseException as e:
result.addError(self, sys.exc_info()) result.addError(self, sys.exc_info())
if isinstance(e, (KeyboardInterrupt, SystemExit)): if isinstance(e, (KeyboardInterrupt, SystemExit)):
raise raise
......
...@@ -81,11 +81,11 @@ class TestCase(backportUnittest.TestCase): ...@@ -81,11 +81,11 @@ class TestCase(backportUnittest.TestCase):
zip) zip)
file_type = self._getFileType(output_data) file_type = self._getFileType(output_data)
if destination_mimetype != None: if destination_mimetype != None:
self.assertEquals(file_type, destination_mimetype) self.assertEqual(file_type, destination_mimetype)
else: else:
if file_type.endswith(": empty"): if file_type.endswith(": empty"):
fault_list.append((source_format, destination_format, file_type)) fault_list.append((source_format, destination_format, file_type))
except Fault, err: except Fault as err:
fault_list.append((source_format, destination_format, err.faultString)) fault_list.append((source_format, destination_format, err.faultString))
if fault_list: if fault_list:
template_message = 'input_format: %r\noutput_format: %r\n traceback:\n%s' template_message = 'input_format: %r\noutput_format: %r\n traceback:\n%s'
...@@ -106,7 +106,7 @@ class TestCase(backportUnittest.TestCase): ...@@ -106,7 +106,7 @@ class TestCase(backportUnittest.TestCase):
source_format, source_format,
base_document) base_document)
for key,value in expected_metadata.iteritems(): for key,value in expected_metadata.iteritems():
self.assertEquals(metadata_dict[key], value) self.assertEqual(metadata_dict[key], value)
def _testFaultGetMetadata(self, data, source_format): def _testFaultGetMetadata(self, data, source_format):
""" Generic test for fail converting""" """ Generic test for fail converting"""
...@@ -123,7 +123,7 @@ class TestCase(backportUnittest.TestCase): ...@@ -123,7 +123,7 @@ class TestCase(backportUnittest.TestCase):
source_format, source_format,
False) False)
for key,value in metadata_dict.iteritems(): for key,value in metadata_dict.iteritems():
self.assertEquals(new_metadata_dict[key], value) self.assertEqual(new_metadata_dict[key], value)
def _testRunConvert(self, filename, data, expected_response_code, def _testRunConvert(self, filename, data, expected_response_code,
response_dict_data,response_dict_keys, response_dict_data,response_dict_keys,
...@@ -131,17 +131,17 @@ class TestCase(backportUnittest.TestCase): ...@@ -131,17 +131,17 @@ class TestCase(backportUnittest.TestCase):
"""Generic test for run_convert""" """Generic test for run_convert"""
response_code, response_dict, response_message = \ response_code, response_dict, response_message = \
self.proxy.run_convert(filename, encodestring(data)) self.proxy.run_convert(filename, encodestring(data))
self.assertEquals(response_code, expected_response_code) self.assertEqual(response_code, expected_response_code)
self.assertEquals(type(response_dict), DictType) self.assertEqual(type(response_dict), DictType)
if expected_response_code == 402: if expected_response_code == 402:
self.assertEquals(response_dict, {}) self.assertEqual(response_dict, {})
self.assertTrue(response_message.endswith(expected_response_message), self.assertTrue(response_message.endswith(expected_response_message),
"%s != %s" % (response_message, expected_response_message)) "%s != %s" % (response_message, expected_response_message))
else: else:
self.assertNotEquals(response_dict['data'], response_dict_data) self.assertNotEqual(response_dict['data'], response_dict_data)
self.assertEquals(sorted(response_dict.keys()), response_dict_keys) self.assertEqual(sorted(response_dict.keys()), response_dict_keys)
self.assertEquals(response_message, expected_response_message) self.assertEqual(response_message, expected_response_message)
self.assertEquals(response_dict['meta']['MIMEType'], response_dict_meta) self.assertEqual(response_dict['meta']['MIMEType'], response_dict_meta)
def ConversionScenarioList(self): def ConversionScenarioList(self):
""" """
......
...@@ -53,7 +53,7 @@ class TestSuite(BaseTestSuite): ...@@ -53,7 +53,7 @@ class TestSuite(BaseTestSuite):
'runUnitTest') 'runUnitTest')
args = tuple(shlex.split(runUnitTest)) + args args = tuple(shlex.split(runUnitTest)) + args
status_dict = self.spawn(*args, **kw) status_dict = self.spawn(*args, **kw)
except SubprocessError, e: except SubprocessError as e:
status_dict = e.status_dict status_dict = e.status_dict
test_log = status_dict['stderr'] test_log = status_dict['stderr']
search = self.RUN_RE.search(test_log) search = self.RUN_RE.search(test_log)
......
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