Commit 6015079d authored by Arnaud Fontaine's avatar Arnaud Fontaine

WIP: 2to3: cStringIO.

parent 94e54af7
...@@ -438,7 +438,7 @@ class TestERP5DumbHTTPExtractionPlugin(AccessTokenTestCase): ...@@ -438,7 +438,7 @@ class TestERP5DumbHTTPExtractionPlugin(AccessTokenTestCase):
env['GATEWAY_INTERFACE']='CGI/1.1 ' env['GATEWAY_INTERFACE']='CGI/1.1 '
env['SCRIPT_NAME']='Main' env['SCRIPT_NAME']='Main'
env.update(headers) env.update(headers)
return HTTPRequest(io.StringIO(), env, HTTPResponse()) return HTTPRequest(io.BytesIO(), env, HTTPResponse())
def test_working_authentication(self): def test_working_authentication(self):
request = self.do_fake_request("GET", {"HTTP_AUTHORIZATION": "Basic " + base64.b64encode("login:password")}) request = self.do_fake_request("GET", {"HTTP_AUTHORIZATION": "Basic " + base64.b64encode("login:password")})
......
...@@ -32,7 +32,7 @@ from functools import partial ...@@ -32,7 +32,7 @@ from functools import partial
import unittest import unittest
import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.parse, urllib.error
import urllib.parse import urllib.parse
from io import StringIO from io import BytesIO
import time import time
import http.client import http.client
import mock import mock
...@@ -756,7 +756,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -756,7 +756,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
response = self.publish( response = self.publish(
portal.absolute_url_path() + '/logged_in', portal.absolute_url_path() + '/logged_in',
basic='test-05:used_ALREADY_1234', basic='test-05:used_ALREADY_1234',
stdin=StringIO(urllib.parse.urlencode({'came_from': 'https://www.erp5.com'})), stdin=BytesIO(urllib.parse.urlencode({'came_from': 'https://www.erp5.com'})),
request_method='POST', request_method='POST',
) )
redirect_url = urllib.parse.urlparse(response.getHeader("Location")) redirect_url = urllib.parse.urlparse(response.getHeader("Location"))
...@@ -819,7 +819,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -819,7 +819,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
def submit_reset_password_dialog(new_password): def submit_reset_password_dialog(new_password):
return self.publish( return self.publish(
'%s/portal_password' % self.portal.getPath(), '%s/portal_password' % self.portal.getPath(),
stdin=StringIO(urllib.parse.urlencode({ stdin=BytesIO(urllib.parse.urlencode({
'Base_callDialogMethod:method': '', 'Base_callDialogMethod:method': '',
'dialog_id': 'PasswordTool_viewResetPassword', 'dialog_id': 'PasswordTool_viewResetPassword',
'dialog_method': 'PasswordTool_changeUserPassword', 'dialog_method': 'PasswordTool_changeUserPassword',
...@@ -874,7 +874,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -874,7 +874,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
return self.publish( return self.publish(
'%s/portal_preferences' % self.portal.getPath(), '%s/portal_preferences' % self.portal.getPath(),
basic='%s:current' % self.id(), basic='%s:current' % self.id(),
stdin=StringIO(urllib.parse.urlencode({ stdin=BytesIO(urllib.parse.urlencode({
'Base_callDialogMethod:method': '', 'Base_callDialogMethod:method': '',
'dialog_id': 'PreferenceTool_viewChangePasswordDialog', 'dialog_id': 'PreferenceTool_viewChangePasswordDialog',
'dialog_method': 'PreferenceTool_setNewPassword', 'dialog_method': 'PreferenceTool_setNewPassword',
......
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
############################################################################## ##############################################################################
from functools import partial from functools import partial
from io import StringIO from io import BytesIO
import unittest import unittest
import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.parse, urllib.error
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
...@@ -81,7 +81,7 @@ class TestAuoLogout(ERP5TypeTestCase): ...@@ -81,7 +81,7 @@ class TestAuoLogout(ERP5TypeTestCase):
portal.absolute_url_path() + '/view', portal.absolute_url_path() + '/view',
request_method='POST', request_method='POST',
) )
response = publish(stdin=StringIO(stdin)) response = publish(stdin=BytesIO(stdin))
self.assertIn('Welcome to ERP5', response.getBody()) self.assertIn('Welcome to ERP5', response.getBody())
# check '__ac' cookie has set an expire timeout # check '__ac' cookie has set an expire timeout
...@@ -96,7 +96,7 @@ class TestAuoLogout(ERP5TypeTestCase): ...@@ -96,7 +96,7 @@ class TestAuoLogout(ERP5TypeTestCase):
self.tic() self.tic()
portal.portal_caches.clearAllCache() portal.portal_caches.clearAllCache()
response = publish(stdin=StringIO(stdin)) response = publish(stdin=BytesIO(stdin))
self.assertIn('Welcome to ERP5', response.getBody()) self.assertIn('Welcome to ERP5', response.getBody())
ac_cookie = response.getCookie('__ac') ac_cookie = response.getCookie('__ac')
self.assertNotEqual(ac_cookie, None) self.assertNotEqual(ac_cookie, None)
......
...@@ -31,7 +31,6 @@ from hashlib import sha1 ...@@ -31,7 +31,6 @@ from hashlib import sha1
from DateTime import DateTime from DateTime import DateTime
from zLOG import LOG, WARNING, ERROR from zLOG import LOG, WARNING, ERROR
from ZODB.POSException import ConflictError from ZODB.POSException import ConflictError
from io import BytesIO as StringIO
# Time global parameters # Time global parameters
MAX_PROCESSING_TIME = 900 # in seconds MAX_PROCESSING_TIME = 900 # in seconds
......
...@@ -27,7 +27,7 @@ import _thread ...@@ -27,7 +27,7 @@ import _thread
from sys import _current_frames from sys import _current_frames
import traceback import traceback
import time import time
from io import BytesIO as StringIO from io import BytesIO
from zLOG import LOG, DEBUG, ERROR from zLOG import LOG, DEBUG, ERROR
from App.config import getConfiguration from App.config import getConfiguration
...@@ -76,7 +76,7 @@ def dump_threads(): ...@@ -76,7 +76,7 @@ def dump_threads():
except ImportError: except ImportError:
pass pass
output = StringIO() output = BytesIO()
traceback.print_stack(frame, file=output) traceback.print_stack(frame, file=output)
res.append("Thread %s%s:\n%s%s" % res.append("Thread %s%s:\n%s%s" %
(thread_id, reqinfo, output.getvalue(), mysql_info)) (thread_id, reqinfo, output.getvalue(), mysql_info))
......
...@@ -75,7 +75,7 @@ from Products.ERP5Type.TransactionalVariable import getTransactionalVariable ...@@ -75,7 +75,7 @@ from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
from OFS.Traversable import NotFound from OFS.Traversable import NotFound
from OFS import SimpleItem from OFS import SimpleItem
from OFS.Image import Pdata from OFS.Image import Pdata
from io import BytesIO as StringIO from io import BytesIO
from copy import deepcopy from copy import deepcopy
from zExceptions import BadRequest from zExceptions import BadRequest
from Products.ERP5Type.XMLExportImport import exportXML from Products.ERP5Type.XMLExportImport import exportXML
...@@ -355,7 +355,7 @@ class BusinessTemplateArchive(object): ...@@ -355,7 +355,7 @@ class BusinessTemplateArchive(object):
else: else:
if isinstance(obj, str): if isinstance(obj, str):
self.revision.hash(path, obj) self.revision.hash(path, obj)
obj = StringIO(obj) obj = BytesIO(obj)
else: else:
obj.seek(0) obj.seek(0)
self.revision.hash(path, obj.read()) self.revision.hash(path, obj.read())
...@@ -420,7 +420,7 @@ class BusinessTemplateTarball(BusinessTemplateArchive): ...@@ -420,7 +420,7 @@ class BusinessTemplateTarball(BusinessTemplateArchive):
def __init__(self, path, creation=0, importing=0, **kw): def __init__(self, path, creation=0, importing=0, **kw):
super(BusinessTemplateTarball, self).__init__(path, **kw) super(BusinessTemplateTarball, self).__init__(path, **kw)
if creation: if creation:
self.fobj = StringIO() self.fobj = BytesIO()
self.tar = tarfile.open('', 'w:gz', self.fobj) self.tar = tarfile.open('', 'w:gz', self.fobj)
self.time = time.time() self.time = time.time()
elif importing: elif importing:
...@@ -849,7 +849,7 @@ class ObjectTemplateItem(BaseTemplateItem): ...@@ -849,7 +849,7 @@ class ObjectTemplateItem(BaseTemplateItem):
if not extension: if not extension:
extension = self.guessExtensionOfDocument(obj, key, extension = self.guessExtensionOfDocument(obj, key,
data if record_id == 'data' else None) data if record_id == 'data' else None)
bta.addObject(StringIO(data), key, path=path, bta.addObject(BytesIO(data), key, path=path,
ext='._xml' if extension == 'xml' else '.' + extension) ext='._xml' if extension == 'xml' else '.' + extension)
break break
# since we get the obj from context we should # since we get the obj from context we should
...@@ -857,7 +857,7 @@ class ObjectTemplateItem(BaseTemplateItem): ...@@ -857,7 +857,7 @@ class ObjectTemplateItem(BaseTemplateItem):
obj = self.removeProperties(obj, 1, keep_workflow_history = True) obj = self.removeProperties(obj, 1, keep_workflow_history = True)
transaction.savepoint(optimistic=True) transaction.savepoint(optimistic=True)
f = StringIO() f = BytesIO()
exportXML(obj._p_jar, obj._p_oid, f) exportXML(obj._p_jar, obj._p_oid, f)
bta.addObject(f, key, path=path) bta.addObject(f, key, path=path)
...@@ -1010,7 +1010,7 @@ class ObjectTemplateItem(BaseTemplateItem): ...@@ -1010,7 +1010,7 @@ class ObjectTemplateItem(BaseTemplateItem):
key = '%s:%s' % (name, mtime) key = '%s:%s' % (name, mtime)
try: try:
return StringIO(cache_database.db[key]) return BytesIO(cache_database.db[key])
except: except:
pass pass
...@@ -1018,7 +1018,7 @@ class ObjectTemplateItem(BaseTemplateItem): ...@@ -1018,7 +1018,7 @@ class ObjectTemplateItem(BaseTemplateItem):
from Products.ERP5Type.XMLExportImport import (ppml, from Products.ERP5Type.XMLExportImport import (ppml,
start_zopedata, save_record, save_zopedata) start_zopedata, save_record, save_zopedata)
import xml.parsers.expat import xml.parsers.expat
outfile=StringIO() outfile=BytesIO()
try: try:
data=file.read() data=file.read()
F=ppml.xmlPickler() F=ppml.xmlPickler()
...@@ -1067,8 +1067,8 @@ class ObjectTemplateItem(BaseTemplateItem): ...@@ -1067,8 +1067,8 @@ class ObjectTemplateItem(BaseTemplateItem):
for path, old_object in upgrade_list: for path, old_object in upgrade_list:
# compare object to see it there is changes # compare object to see it there is changes
new_object = self._objects[path] new_object = self._objects[path]
new_io = StringIO() new_io = BytesIO()
old_io = StringIO() old_io = BytesIO()
exportXML(new_object._p_jar, new_object._p_oid, new_io) exportXML(new_object._p_jar, new_object._p_oid, new_io)
new_obj_xml = new_io.getvalue() new_obj_xml = new_io.getvalue()
try: try:
...@@ -1107,7 +1107,7 @@ class ObjectTemplateItem(BaseTemplateItem): ...@@ -1107,7 +1107,7 @@ class ObjectTemplateItem(BaseTemplateItem):
for subobject_id in obj.objectIds(): for subobject_id in obj.objectIds():
subobject = obj[subobject_id] subobject = obj[subobject_id]
subobject_dict[subobject_id] = subobject._p_jar.exportFile( subobject_dict[subobject_id] = subobject._p_jar.exportFile(
subobject._p_oid, StringIO()) subobject._p_oid, BytesIO())
return subobject_dict return subobject_dict
# XXX btsave is for backward compatibility # XXX btsave is for backward compatibility
if action in ('backup', 'btsave', 'save_and_remove',): if action in ('backup', 'btsave', 'save_and_remove',):
...@@ -6161,8 +6161,8 @@ Business Template is a set of definitions, such as skins, portal types and categ ...@@ -6161,8 +6161,8 @@ Business Template is a set of definitions, such as skins, portal types and categ
'_test_item', '_message_translation_item',] '_test_item', '_message_translation_item',]
if item_name in item_list_1: if item_name in item_list_1:
f1 = StringIO() # for XML export of New Object f1 = BytesIO() # for XML export of New Object
f2 = StringIO() # For XML export of Installed Object f2 = BytesIO() # For XML export of Installed Object
# Remove unneeded properties # Remove unneeded properties
new_object = new_item.removeProperties(new_object, 1) new_object = new_item.removeProperties(new_object, 1)
installed_object = installed_item.removeProperties(installed_object, 1) installed_object = installed_item.removeProperties(installed_object, 1)
......
...@@ -48,7 +48,7 @@ from Products.ERP5.genbt5list import generateInformation ...@@ -48,7 +48,7 @@ from Products.ERP5.genbt5list import generateInformation
from Acquisition import aq_base from Acquisition import aq_base
from tempfile import mkstemp, mkdtemp from tempfile import mkstemp, mkdtemp
from Products.ERP5 import _dtmldir from Products.ERP5 import _dtmldir
from io import StringIO from io import BytesIO
from urllib.request import pathname2url, urlopen, urlretrieve from urllib.request import pathname2url, urlopen, urlretrieve
from urllib.parse import splittype from urllib.parse import splittype
import urllib.request, urllib.error, urllib.parse import urllib.request, urllib.error, urllib.parse
...@@ -305,7 +305,7 @@ class TemplateTool (BaseTool): ...@@ -305,7 +305,7 @@ class TemplateTool (BaseTool):
bt = Resource(url) bt = Resource(url)
export_string = bt.get().get_body() export_string = bt.get().get_body()
self.deleteContent(id) self.deleteContent(id)
self._importObjectFromFile(StringIO(export_string), id=id) self._importObjectFromFile(BytesIO(export_string), id=id)
security.declareProtected( Permissions.ManagePortal, 'manage_download' ) security.declareProtected( Permissions.ManagePortal, 'manage_download' )
def manage_download(self, url, id=None, REQUEST=None): def manage_download(self, url, id=None, REQUEST=None):
...@@ -395,7 +395,7 @@ class TemplateTool (BaseTool): ...@@ -395,7 +395,7 @@ class TemplateTool (BaseTool):
""" """
Import Business Template from passed base64 encoded text. Import Business Template from passed base64 encoded text.
""" """
import_file = StringIO(decodestring(file_data)) import_file = BytesIO(decodestring(file_data))
return self.importFile(import_file = import_file, id = id, REQUEST = REQUEST, return self.importFile(import_file = import_file, id = id, REQUEST = REQUEST,
batch_mode = batch_mode, **kw) batch_mode = batch_mode, **kw)
......
...@@ -38,7 +38,7 @@ from zExceptions import BadRequest ...@@ -38,7 +38,7 @@ from zExceptions import BadRequest
from zLOG import LOG, WARNING from zLOG import LOG, WARNING
from DateTime import DateTime from DateTime import DateTime
from Acquisition import aq_base from Acquisition import aq_base
from io import BytesIO as StringIO from io import BytesIO
class TrashTool(BaseTool): class TrashTool(BaseTool):
""" """
...@@ -146,7 +146,7 @@ class TrashTool(BaseTool): ...@@ -146,7 +146,7 @@ class TrashTool(BaseTool):
for subobject_id in list(obj.objectIds()): for subobject_id in list(obj.objectIds()):
subobject = obj[subobject_id] subobject = obj[subobject_id]
subobjects_dict[subobject_id] = subobject._p_jar.exportFile( subobjects_dict[subobject_id] = subobject._p_jar.exportFile(
subobject._p_oid, StringIO()) subobject._p_oid, BytesIO())
if save: # remove subobjecs from backup object if save: # remove subobjecs from backup object
obj._delObject(subobject_id) obj._delObject(subobject_id)
......
...@@ -174,7 +174,7 @@ class TextDocument(CachedConvertableMixin, BaseConvertableFileMixin, TextContent ...@@ -174,7 +174,7 @@ class TextDocument(CachedConvertableMixin, BaseConvertableFileMixin, TextContent
# Include extra parameter for image conversions # Include extra parameter for image conversions
temp_image = self.portal_contributions.newContent( temp_image = self.portal_contributions.newContent(
portal_type='Image', portal_type='Image',
file=io.StringIO(), file=io.BytesIO(),
filename=self.getId(), filename=self.getId(),
temp_object=1) temp_object=1)
temp_image._setData(result) temp_image._setData(result)
......
...@@ -31,7 +31,7 @@ from AccessControl import ClassSecurityInfo ...@@ -31,7 +31,7 @@ from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Globals import InitializeClass from Products.ERP5Type.Globals import InitializeClass
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
from OFS.Image import Pdata from OFS.Image import Pdata
from io import StringIO from io import BytesIO
_MARKER = object() _MARKER = object()
class BaseConvertableFileMixin: class BaseConvertableFileMixin:
...@@ -96,7 +96,7 @@ class BaseConvertableFileMixin: ...@@ -96,7 +96,7 @@ class BaseConvertableFileMixin:
"""Wrap value into Pdata """Wrap value into Pdata
""" """
if not isinstance(data, Pdata) and data is not None: if not isinstance(data, Pdata) and data is not None:
file_ = StringIO(data) file_ = BytesIO(data)
data, _ = self._read_data(file_) data, _ = self._read_data(file_)
self._baseSetBaseData(data) self._baseSetBaseData(data)
......
...@@ -23,7 +23,7 @@ from Products.ERP5Type.Globals import InitializeClass ...@@ -23,7 +23,7 @@ from Products.ERP5Type.Globals import InitializeClass
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
from Products.CMFCore.PortalContent import ResourceLockedError from Products.CMFCore.PortalContent import ResourceLockedError
from zExceptions import Forbidden from zExceptions import Forbidden
from io import StringIO from io import BytesIO
security = ModuleSecurityInfo(__name__) security = ModuleSecurityInfo(__name__)
...@@ -77,7 +77,7 @@ class TextContent: ...@@ -77,7 +77,7 @@ class TextContent:
headers = self.parseHeadersFromText(body) headers = self.parseHeadersFromText(body)
content_type = REQUEST.get_header('Content-Type', '') content_type = REQUEST.get_header('Content-Type', '')
headers.setdefault('content_type', content_type) headers.setdefault('content_type', content_type)
headers['file'] = StringIO(body) headers['file'] = BytesIO(body)
self._edit(**headers) self._edit(**headers)
except ResourceLockedError: except ResourceLockedError:
transaction.abort() transaction.abort()
......
...@@ -168,7 +168,7 @@ class ContributionTool(BaseTool): ...@@ -168,7 +168,7 @@ class ContributionTool(BaseTool):
except KeyError: except KeyError:
raise ValueError('data must be provided') raise ValueError('data must be provided')
if data is not None: if data is not None:
file_object = io.StringIO() file_object = io.BytesIO()
file_object.write(data) file_object.write(data)
file_object.seek(0) file_object.seek(0)
kw['file'] = file_object kw['file'] = file_object
...@@ -638,7 +638,7 @@ class ContributionTool(BaseTool): ...@@ -638,7 +638,7 @@ class ContributionTool(BaseTool):
url_file = urllib.request.urlopen(urllib.request.Request(url, url_file = urllib.request.urlopen(urllib.request.Request(url,
headers={'Accept':'*/*'})) headers={'Accept':'*/*'}))
data = url_file.read() # time out must be set or ... too long XXX data = url_file.read() # time out must be set or ... too long XXX
file_object = io.StringIO() file_object = io.BytesIO()
file_object.write(data) file_object.write(data)
file_object.seek(0) file_object.seek(0)
# if a content-disposition header is present, # if a content-disposition header is present,
......
...@@ -220,7 +220,7 @@ if ReportTool: ...@@ -220,7 +220,7 @@ if ReportTool:
from Products.CMFReportTool.RenderPDF.Parser import TemplateParser,DocumentParser from Products.CMFReportTool.RenderPDF.Parser import TemplateParser,DocumentParser
from Products.PageTemplates.Expressions import boboAwareZopeTraverse from Products.PageTemplates.Expressions import boboAwareZopeTraverse
from io import StringIO from io import BytesIO
import xml.dom.minidom import xml.dom.minidom
import urllib.request, urllib.parse, urllib.error,os.path import urllib.request, urllib.parse, urllib.error,os.path
...@@ -254,7 +254,7 @@ if ReportTool: ...@@ -254,7 +254,7 @@ if ReportTool:
elif hasattr(obj,'data'): elif hasattr(obj,'data'):
obj = obj.data obj = obj.data
return StringIO(str(obj)) return BytesIO(str(obj))
else: else:
class ERP5ResourceHandler(ResourceHandler): class ERP5ResourceHandler(ResourceHandler):
''' Wrapper for ZODB Resources and files''' ''' Wrapper for ZODB Resources and files'''
...@@ -287,7 +287,7 @@ if ReportTool: ...@@ -287,7 +287,7 @@ if ReportTool:
elif hasattr(obj,'data'): elif hasattr(obj,'data'):
obj = obj.data obj = obj.data
return StringIO(str(obj)) return BytesIO(str(obj))
...@@ -329,7 +329,7 @@ if ReportTool: ...@@ -329,7 +329,7 @@ if ReportTool:
document = DocumentParser(document_dom,encoding,resourceHandler=rhandler) document = DocumentParser(document_dom,encoding,resourceHandler=rhandler)
# create the PDF itself using the document and the template # create the PDF itself using the document and the template
buf = StringIO() buf = BytesIO()
document(template,buf) document(template,buf)
buf.seek(0) buf.seek(0)
return buf.read() return buf.read()
......
...@@ -43,7 +43,7 @@ from Acquisition import aq_base ...@@ -43,7 +43,7 @@ from Acquisition import aq_base
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from .OOoUtils import OOoBuilder from .OOoUtils import OOoBuilder
from zipfile import ZipFile, ZIP_DEFLATED from zipfile import ZipFile, ZIP_DEFLATED
from io import StringIO from io import BytesIO
import re import re
import itertools import itertools
import six import six
...@@ -225,7 +225,7 @@ class OOoTemplate(ZopePageTemplate): ...@@ -225,7 +225,7 @@ class OOoTemplate(ZopePageTemplate):
self.OLE_documents_zipstring = None self.OLE_documents_zipstring = None
# create a zip archive and store it # create a zip archive and store it
if attached_files_list: if attached_files_list:
memory_file = StringIO() memory_file = BytesIO()
try: try:
zf = ZipFile(memory_file, mode='w', compression=ZIP_DEFLATED) zf = ZipFile(memory_file, mode='w', compression=ZIP_DEFLATED)
except RuntimeError: except RuntimeError:
......
...@@ -37,7 +37,7 @@ from xml.dom import Node ...@@ -37,7 +37,7 @@ from xml.dom import Node
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Globals import InitializeClass, get_request from Products.ERP5Type.Globals import InitializeClass, get_request
from zipfile import ZipFile, ZIP_DEFLATED from zipfile import ZipFile, ZIP_DEFLATED
from io import StringIO from io import BytesIO
import imghdr import imghdr
import random import random
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
...@@ -73,7 +73,7 @@ class OOoBuilder(Implicit): ...@@ -73,7 +73,7 @@ class OOoBuilder(Implicit):
def __init__(self, document): def __init__(self, document):
if hasattr(document, 'data') : if hasattr(document, 'data') :
self._document = StringIO() self._document = BytesIO()
if isinstance(document.data, Pdata): if isinstance(document.data, Pdata):
# Handle image included in the style # Handle image included in the style
...@@ -88,7 +88,7 @@ class OOoBuilder(Implicit): ...@@ -88,7 +88,7 @@ class OOoBuilder(Implicit):
elif hasattr(document, 'read') : elif hasattr(document, 'read') :
self._document = document self._document = document
else : else :
self._document = StringIO() self._document = BytesIO()
self._document.write(document) self._document.write(document)
self._image_count = 0 self._image_count = 0
self._manifest_additions_list = [] self._manifest_additions_list = []
...@@ -143,7 +143,7 @@ class OOoBuilder(Implicit): ...@@ -143,7 +143,7 @@ class OOoBuilder(Implicit):
- indent the xml - indent the xml
""" """
content_xml = self.extract(ooo_xml_file_id) content_xml = self.extract(ooo_xml_file_id)
output = StringIO() output = BytesIO()
content_doc = etree.XML(content_xml) content_doc = etree.XML(content_xml)
root = content_doc.getroottree().getroot() root = content_doc.getroottree().getroot()
#Declare zope namespaces #Declare zope namespaces
...@@ -232,7 +232,7 @@ class OOoParser(Implicit): ...@@ -232,7 +232,7 @@ class OOoParser(Implicit):
self.filename = None self.filename = None
def openFromString(self, text_content): def openFromString(self, text_content):
return self.openFile(StringIO(text_content)) return self.openFile(BytesIO(text_content))
def openFile(self, file_descriptor): def openFile(self, file_descriptor):
""" """
......
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManagement import newSecurityManager
from io import StringIO from io import BytesIO
class TestFormPrintoutMixin(ERP5TypeTestCase): class TestFormPrintoutMixin(ERP5TypeTestCase):
run_all_test = 1 run_all_test = 1
...@@ -55,7 +55,7 @@ class TestFormPrintoutMixin(ERP5TypeTestCase): ...@@ -55,7 +55,7 @@ class TestFormPrintoutMixin(ERP5TypeTestCase):
'''return odf document from the printout '''return odf document from the printout
''' '''
document_file = getattr(self.portal, printout_form.template, None) document_file = getattr(self.portal, printout_form.template, None)
document_file = StringIO(document_file).read() document_file = BytesIO(document_file).read()
if document_file is not None: if document_file is not None:
return document_file return document_file
raise ValueError ('%s template not found' % printout_form.template) raise ValueError ('%s template not found' % printout_form.template)
......
...@@ -2108,7 +2108,7 @@ class Base_contributeMixin: ...@@ -2108,7 +2108,7 @@ class Base_contributeMixin:
""" """
person = self.portal.person_module.newContent(portal_type='Person') person = self.portal.person_module.newContent(portal_type='Person')
empty_file_upload = ZPublisher.HTTPRequest.FileUpload(FieldStorage( empty_file_upload = ZPublisher.HTTPRequest.FileUpload(FieldStorage(
fp=io.StringIO(), fp=io.BytesIO(),
environ=dict(REQUEST_METHOD='PUT'), environ=dict(REQUEST_METHOD='PUT'),
headers={"content-disposition": headers={"content-disposition":
"attachment; filename=empty;"})) "attachment; filename=empty;"}))
......
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
import os import os
import unittest import unittest
from io import StringIO from io import BytesIO
from zipfile import ZipFile from zipfile import ZipFile
from Products.ERP5Type.tests.utils import FileUpload from Products.ERP5Type.tests.utils import FileUpload
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
...@@ -237,7 +237,7 @@ return getattr(context, "%s_%s" % (parameter, current_language)) ...@@ -237,7 +237,7 @@ return getattr(context, "%s_%s" % (parameter, current_language))
response.getHeader('content-type').split(';')[0]) response.getHeader('content-type').split(';')[0])
self.assertEqual('attachment; filename="Base_viewIncludeImageAsOdt.odt"', self.assertEqual('attachment; filename="Base_viewIncludeImageAsOdt.odt"',
response.getHeader('content-disposition')) response.getHeader('content-disposition'))
cs = StringIO() cs = BytesIO()
cs.write(body) cs.write(body)
zip_document = ZipFile(cs) zip_document = ZipFile(cs)
picture_list = [x for x in zip_document.infolist() if "Pictures" in x.filename] picture_list = [x for x in zip_document.infolist() if "Pictures" in x.filename]
......
...@@ -40,7 +40,7 @@ import tempfile ...@@ -40,7 +40,7 @@ import tempfile
import zipfile import zipfile
import popen2 import popen2
import urllib.request, urllib.error, urllib.parse import urllib.request, urllib.error, urllib.parse
from io import StringIO from io import BytesIO
try: try:
import lxml import lxml
...@@ -65,14 +65,14 @@ if lxml: ...@@ -65,14 +65,14 @@ if lxml:
def validate(self, odf_file_content): def validate(self, odf_file_content):
error_list = [] error_list = []
odf_file = StringIO(odf_file_content) odf_file = BytesIO(odf_file_content)
for f in ('content.xml', 'meta.xml', 'styles.xml', 'settings.xml'): for f in ('content.xml', 'meta.xml', 'styles.xml', 'settings.xml'):
error_list.extend(self._validateXML(odf_file, f)) error_list.extend(self._validateXML(odf_file, f))
return error_list return error_list
def _validateXML(self, odf_file, content_file_name): def _validateXML(self, odf_file, content_file_name):
zfd = zipfile.ZipFile(odf_file) zfd = zipfile.ZipFile(odf_file)
doc = lxml.etree.parse(StringIO(zfd.read(content_file_name))) doc = lxml.etree.parse(BytesIO(zfd.read(content_file_name)))
return [] return []
# The following is the past implementation that validates with # The following is the past implementation that validates with
# RelaxNG schema. But recent LibreOffice uses extended odf # RelaxNG schema. But recent LibreOffice uses extended odf
......
...@@ -94,7 +94,6 @@ from zope.interface import classImplementsOnly, implementedBy ...@@ -94,7 +94,6 @@ from zope.interface import classImplementsOnly, implementedBy
import sys, re import sys, re
from io import BytesIO as StringIO
from socket import gethostname, gethostbyaddr from socket import gethostname, gethostbyaddr
import random import random
...@@ -2158,7 +2157,7 @@ class Base( ...@@ -2158,7 +2157,7 @@ class Base(
# We must do an ordered list so we can not use the previous method # We must do an ordered list so we can not use the previous method
# self._setValue(id, self.portal_catalog.getObjectList(uids), spec=spec) # self._setValue(id, self.portal_catalog.getObjectList(uids), spec=spec)
references = [self.getPortalObject().portal_catalog.getObject(x) references = [self.getPortalObject().portal_catalog.getObject(x)
for x in ((uids,) if isinstance(uids, int) else uids)] for x in ((uids,) if isinstance(uids, six.integer_types) else uids)]
self._setValue(id, references, spec=spec, filter=filter, portal_type=portal_type, self._setValue(id, references, spec=spec, filter=filter, portal_type=portal_type,
keep_default=keep_default, checked_permission=checked_permission) keep_default=keep_default, checked_permission=checked_permission)
......
...@@ -37,7 +37,7 @@ except ImportError: ...@@ -37,7 +37,7 @@ except ImportError:
DeprecationWarning) DeprecationWarning)
import zope.interface import zope.interface
from Products.ERP5Type import XMLExportImport from Products.ERP5Type import XMLExportImport
from io import BytesIO as StringIO from io import BytesIO
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type.interfaces.json_representable import IJSONRepresentable from Products.ERP5Type.interfaces.json_representable import IJSONRepresentable
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
...@@ -71,7 +71,7 @@ class JSONRepresentableMixin: ...@@ -71,7 +71,7 @@ class JSONRepresentableMixin:
Gets the dict representation of the object Gets the dict representation of the object
""" """
# Use OFS exportXML to first export to xml # Use OFS exportXML to first export to xml
f = StringIO() f = BytesIO()
XMLExportImport.exportXML(self._p_jar, self._p_oid, f) XMLExportImport.exportXML(self._p_jar, self._p_oid, f)
# Get the value of exported XML # Get the value of exported XML
...@@ -88,7 +88,7 @@ class JSONRepresentableMixin: ...@@ -88,7 +88,7 @@ class JSONRepresentableMixin:
# Convert the dict_value to XML representation # Convert the dict_value to XML representation
xml_value = xmltodict.unparse(dict_value) xml_value = xmltodict.unparse(dict_value)
f = StringIO(xml_value) f = BytesIO(xml_value)
return XMLExportImport.importXML(self._p_jar, f) return XMLExportImport.importXML(self._p_jar, f)
InitializeClass(JSONRepresentableMixin) InitializeClass(JSONRepresentableMixin)
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
""" """
import OFS.Image import OFS.Image
import struct import struct
from io import BytesIO as StringIO from io import BytesIO
from zExceptions import Forbidden from zExceptions import Forbidden
def getImageInfo_with_svg_fix(data): def getImageInfo_with_svg_fix(data):
...@@ -57,7 +57,7 @@ def getImageInfo_with_svg_fix(data): ...@@ -57,7 +57,7 @@ def getImageInfo_with_svg_fix(data):
# handle JPEGs # handle JPEGs
elif (size >= 2) and (data[:2] == '\377\330'): elif (size >= 2) and (data[:2] == '\377\330'):
content_type = 'image/jpeg' content_type = 'image/jpeg'
jpeg = StringIO(data) jpeg = BytesIO(data)
jpeg.read(2) jpeg.read(2)
b = jpeg.read(1) b = jpeg.read(1)
try: try:
......
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
# Install openers # Install openers
# -> testTemplateTool.TestTemplateTool.test_getBusinessTemplateUrl # -> testTemplateTool.TestTemplateTool.test_getBusinessTemplateUrl
import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.parse, urllib.error
from io import BytesIO as StringIO from io import BytesIO
import socket import socket
import os import os
import mimetypes import mimetypes
...@@ -72,7 +72,7 @@ class DirectoryFileHandler(urllib.request.FileHandler): ...@@ -72,7 +72,7 @@ class DirectoryFileHandler(urllib.request.FileHandler):
size = stats.st_size size = stats.st_size
modified = formatdate(stats.st_mtime, usegmt=True) modified = formatdate(stats.st_mtime, usegmt=True)
mtype = mimetypes.guess_type(file)[0] mtype = mimetypes.guess_type(file)[0]
headers = message_from_bytes(StringIO( headers = message_from_bytes(BytesIO(
'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
(mtype or 'text/plain', size, modified))) (mtype or 'text/plain', size, modified)))
if host: if host:
...@@ -81,14 +81,14 @@ class DirectoryFileHandler(urllib.request.FileHandler): ...@@ -81,14 +81,14 @@ class DirectoryFileHandler(urllib.request.FileHandler):
(not port and socket.gethostbyname(host) in self.get_names()): (not port and socket.gethostbyname(host) in self.get_names()):
try: try:
file_list = os.listdir(localfile) file_list = os.listdir(localfile)
s = StringIO() s = BytesIO()
s.write('<html><head><base href="%s"/></head><body>' % ('file:' + file)) s.write('<html><head><base href="%s"/></head><body>' % ('file:' + file))
s.write('<p>Directory Content:</p>') s.write('<p>Directory Content:</p>')
for f in file_list: for f in file_list:
s.write('<p><a href="%s">%s</a></p>\n' % (urllib.parse.quote(f), f)) s.write('<p><a href="%s">%s</a></p>\n' % (urllib.parse.quote(f), f))
s.write('</body></html>') s.write('</body></html>')
s.seek(0) s.seek(0)
headers = message_from_bytes(StringIO( headers = message_from_bytes(BytesIO(
'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
('text/html', size, modified))) ('text/html', size, modified)))
return urllib2.addinfourl(s, headers, 'file:' + file) return urllib2.addinfourl(s, headers, 'file:' + file)
......
...@@ -20,7 +20,7 @@ import time ...@@ -20,7 +20,7 @@ import time
import traceback import traceback
import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.parse, urllib.error
from contextlib import contextmanager from contextlib import contextmanager
from io import StringIO from io import BytesIO
from six.moves import configparser from six.moves import configparser
from six.moves.cPickle import dumps from six.moves.cPickle import dumps
from glob import glob from glob import glob
...@@ -824,9 +824,9 @@ class ERP5TypeTestCaseMixin(ProcessingNodeTestCase, PortalTestCase): ...@@ -824,9 +824,9 @@ class ERP5TypeTestCaseMixin(ProcessingNodeTestCase, PortalTestCase):
return orig_extractUserIds(pas, request, plugins) return orig_extractUserIds(pas, request, plugins)
if stdin is None: if stdin is None:
stdin = StringIO() stdin = BytesIO()
outstream = StringIO() outstream = BytesIO()
response = Response(stdout=outstream, stderr=sys.stderr) response = Response(stdout=outstream, stderr=sys.stderr)
try: try:
......
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
import os, sys import os, sys
import unittest import unittest
from subprocess import check_output, CalledProcessError from subprocess import check_output, CalledProcessError
from io import StringIO from io import BytesIO
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from lib2to3.main import main from lib2to3.main import main
...@@ -67,7 +67,7 @@ class Python3StyleTest(ERP5TypeTestCase): ...@@ -67,7 +67,7 @@ class Python3StyleTest(ERP5TypeTestCase):
path = os.path.normpath(path + os.environ['TESTED_PRODUCT']) path = os.path.normpath(path + os.environ['TESTED_PRODUCT'])
orig_stdout = sys.stdout orig_stdout = sys.stdout
try: # XXX: not thread-safe try: # XXX: not thread-safe
sys.stdout = stdout = StringIO() sys.stdout = stdout = BytesIO()
returncode = main("lib2to3.fixes", ["--fix", fixer_name, path]) returncode = main("lib2to3.fixes", ["--fix", fixer_name, path])
finally: finally:
sys.stdout = orig_stdout sys.stdout = orig_stdout
......
...@@ -2781,8 +2781,8 @@ class TestGC(XMLObject): ...@@ -2781,8 +2781,8 @@ class TestGC(XMLObject):
import gc import gc
initial_gc_debug_flags = gc.get_debug() initial_gc_debug_flags = gc.get_debug()
initial_stderr = sys.stderr initial_stderr = sys.stderr
from io import StringIO from io import BytesIO
stderr = StringIO() stderr = BytesIO()
try: try:
gc.disable() gc.disable()
......
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