Commit de24bae0 authored by Kazuhiko Shiozaki's avatar Kazuhiko Shiozaki Committed by Arnaud Fontaine

py2/py3: modernize -f imports_six.

parent 09981803
...@@ -32,7 +32,7 @@ from ZPublisher.HTTPResponse import HTTPResponse ...@@ -32,7 +32,7 @@ from ZPublisher.HTTPResponse import HTTPResponse
from Products.PluggableAuthService.interfaces.plugins import IAuthenticationPlugin from Products.PluggableAuthService.interfaces.plugins import IAuthenticationPlugin
from DateTime import DateTime from DateTime import DateTime
import urllib import urllib
import httplib import six.moves.http_client
import base64 import base64
from six.moves import cStringIO as StringIO from six.moves import cStringIO as StringIO
import mock import mock
...@@ -143,7 +143,7 @@ class TestERP5AccessTokenSkins(AccessTokenTestCase): ...@@ -143,7 +143,7 @@ class TestERP5AccessTokenSkins(AccessTokenTestCase):
urllib.urlencode({ urllib.urlencode({
'access_token': access_token.getId(), 'access_token': access_token.getId(),
'access_token_secret': access_token.getReference()}))) 'access_token_secret': access_token.getReference()})))
self.assertEqual(response.getStatus(), httplib.OK) self.assertEqual(response.getStatus(), six.moves.http_client.OK)
# XXX caption currently shows plugin id and relative URL of the token, # XXX caption currently shows plugin id and relative URL of the token,
# that's not ideal. # that's not ideal.
self.assertEqual( self.assertEqual(
......
from urlparse import urlparse from six.moves.urllib.parse import urlparse
from urlparse import parse_qsl from six.moves.urllib.parse import parse_qsl
context.REQUEST.RESPONSE.setCookie("loyalty_reward", "disable", path='/') context.REQUEST.RESPONSE.setCookie("loyalty_reward", "disable", path='/')
......
from urlparse import urlparse from six.moves.urllib.parse import urlparse
from urlparse import parse_qsl from six.moves.urllib.parse import parse_qsl
context.REQUEST.RESPONSE.setCookie("loyalty_reward", "enable", path='/') context.REQUEST.RESPONSE.setCookie("loyalty_reward", "enable", path='/')
......
...@@ -33,7 +33,7 @@ import unittest ...@@ -33,7 +33,7 @@ import unittest
import six.moves.urllib.parse import six.moves.urllib.parse
from six.moves import cStringIO as StringIO from six.moves import cStringIO as StringIO
import time import time
import httplib import six.moves.http_client
import mock import mock
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
...@@ -711,9 +711,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -711,9 +711,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
basic='test-05:used_ALREADY_1234', basic='test-05:used_ALREADY_1234',
) )
response = publish() response = publish()
redirect_url = urlparse.urlparse(response.getHeader("Location")) redirect_url = six.moves.urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, '{}/login_form'.format(portal.absolute_url_path())) self.assertEqual(redirect_url.path, '{}/login_form'.format(portal.absolute_url_path()))
redirect_url_params = urlparse.parse_qsl(redirect_url.query) redirect_url_params = six.moves.urllib.parse.parse_qsl(redirect_url.query)
self.assertEqual(redirect_url_params, [('portal_status_message', 'Account is blocked.')] ) self.assertEqual(redirect_url_params, [('portal_status_message', 'Account is blocked.')] )
# test expire password message, first unblock it # test expire password message, first unblock it
...@@ -722,9 +722,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -722,9 +722,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
self.tic() self.tic()
self._clearCache() self._clearCache()
response = publish() response = publish()
redirect_url = urlparse.urlparse(response.getHeader("Location")) redirect_url = six.moves.urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, '{}/login_form'.format(portal.absolute_url_path())) self.assertEqual(redirect_url.path, '{}/login_form'.format(portal.absolute_url_path()))
redirect_url_params = urlparse.parse_qsl(redirect_url.query) redirect_url_params = six.moves.urllib.parse.parse_qsl(redirect_url.query)
self.assertEqual(redirect_url_params, [('portal_status_message', 'Password is expired.')] ) self.assertEqual(redirect_url_params, [('portal_status_message', 'Password is expired.')] )
self.assertTrue(login.isPasswordExpired()) self.assertTrue(login.isPasswordExpired())
...@@ -734,9 +734,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -734,9 +734,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
self.tic() self.tic()
self._clearCache() self._clearCache()
response = publish() response = publish()
redirect_url = urlparse.urlparse(response.getHeader("Location")) redirect_url = six.moves.urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, '{}/ERP5Site_viewNewPersonCredentialUpdateDialog'.format(portal.absolute_url_path())) self.assertEqual(redirect_url.path, '{}/ERP5Site_viewNewPersonCredentialUpdateDialog'.format(portal.absolute_url_path()))
redirect_url_params = urlparse.parse_qs(redirect_url.query) redirect_url_params = six.moves.urllib.parse.parse_qs(redirect_url.query)
# status message contain the password expiration date # status message contain the password expiration date
self.assertIn('Your password will expire at 20', redirect_url_params['portal_status_message'][0]) self.assertIn('Your password will expire at 20', redirect_url_params['portal_status_message'][0])
self.assertIn('You are advised to change it as soon as possible', redirect_url_params['portal_status_message'][0]) self.assertIn('You are advised to change it as soon as possible', redirect_url_params['portal_status_message'][0])
...@@ -758,9 +758,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -758,9 +758,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
stdin=StringIO(urllib.urlencode({'came_from': 'https://www.erp5.com'})), stdin=StringIO(urllib.urlencode({'came_from': 'https://www.erp5.com'})),
request_method='POST', request_method='POST',
) )
redirect_url = urlparse.urlparse(response.getHeader("Location")) redirect_url = six.moves.urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, portal.absolute_url_path()) self.assertEqual(redirect_url.path, portal.absolute_url_path())
redirect_url_params = urlparse.parse_qsl(redirect_url.query) redirect_url_params = six.moves.urllib.parse.parse_qsl(redirect_url.query)
self.assertEqual(redirect_url_params, [('portal_status_message', 'Redirection to an external site prevented.')] ) self.assertEqual(redirect_url_params, [('portal_status_message', 'Redirection to an external site prevented.')] )
def test_ExpireOldAuthenticationEventList(self): def test_ExpireOldAuthenticationEventList(self):
...@@ -831,7 +831,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -831,7 +831,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
handle_errors=False) handle_errors=False)
ret = submit_reset_password_dialog('alice') ret = submit_reset_password_dialog('alice')
self.assertEqual(httplib.OK, ret.getStatus()) self.assertEqual(six.moves.http_client.OK, ret.getStatus())
self.assertIn( self.assertIn(
'<span class="error">You can not use any parts of your ' '<span class="error">You can not use any parts of your '
'first and last name in password.</span>', 'first and last name in password.</span>',
...@@ -847,14 +847,14 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -847,14 +847,14 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
with mock.patch.object(self.portal.Localizer.erp5_ui.__class__, 'gettext', side_effect=gettext): with mock.patch.object(self.portal.Localizer.erp5_ui.__class__, 'gettext', side_effect=gettext):
ret = submit_reset_password_dialog('alice') ret = submit_reset_password_dialog('alice')
self.assertEqual(httplib.OK, ret.getStatus()) self.assertEqual(six.moves.http_client.OK, ret.getStatus())
self.assertIn( self.assertIn(
'<span class="error">Yöü can not ... translated</span>', '<span class="error">Yöü can not ... translated</span>',
ret.getBody()) ret.getBody())
# now with a password complying to the policy # now with a password complying to the policy
ret = submit_reset_password_dialog('ok') ret = submit_reset_password_dialog('ok')
self.assertEqual(httplib.FOUND, ret.getStatus()) self.assertEqual(six.moves.http_client.FOUND, ret.getStatus())
self.assertTrue(ret.getHeader('Location').endswith( self.assertTrue(ret.getHeader('Location').endswith(
'/login_form?portal_status_message=Password+changed.')) '/login_form?portal_status_message=Password+changed.'))
...@@ -886,7 +886,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -886,7 +886,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
# too short password is refused # too short password is refused
ret = submit_change_password_dialog('short') ret = submit_change_password_dialog('short')
self.assertEqual(httplib.OK, ret.getStatus()) self.assertEqual(six.moves.http_client.OK, ret.getStatus())
self.assertIn( self.assertIn(
'<span class="error">Too short.</span>', '<span class="error">Too short.</span>',
ret.getBody()) ret.getBody())
...@@ -901,7 +901,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -901,7 +901,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
with mock.patch.object(self.portal.Localizer.erp5_ui.__class__, 'gettext', side_effect=gettext): with mock.patch.object(self.portal.Localizer.erp5_ui.__class__, 'gettext', side_effect=gettext):
ret = submit_change_password_dialog('short') ret = submit_change_password_dialog('short')
self.assertEqual(httplib.OK, ret.getStatus()) self.assertEqual(six.moves.http_client.OK, ret.getStatus())
self.assertIn( self.assertIn(
'<span class="error">Töü short ... translated</span>', '<span class="error">Töü short ... translated</span>',
ret.getBody()) ret.getBody())
...@@ -918,7 +918,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase): ...@@ -918,7 +918,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
# long enough password is accepted # long enough password is accepted
ret = submit_change_password_dialog('long_enough_password') ret = submit_change_password_dialog('long_enough_password')
# When password reset is succesful, user is logged out # When password reset is succesful, user is logged out
self.assertEqual(httplib.FOUND, ret.getStatus()) self.assertEqual(six.moves.http_client.FOUND, ret.getStatus())
self.assertEqual(self.portal.portal_preferences.absolute_url(), self.assertEqual(self.portal.portal_preferences.absolute_url(),
ret.getHeader("Location")) ret.getHeader("Location"))
......
...@@ -150,7 +150,7 @@ class OOoDocument(OOoDocumentExtensibleTraversableMixin, BaseConvertableFileMixi ...@@ -150,7 +150,7 @@ class OOoDocument(OOoDocumentExtensibleTraversableMixin, BaseConvertableFileMixi
return [] return []
def cached_getTargetFormatItemList(content_type): def cached_getTargetFormatItemList(content_type):
from xmlrpclib import Fault from six.moves.xmlrpc_client import Fault
server_proxy = DocumentConversionServerProxy(self) server_proxy = DocumentConversionServerProxy(self)
try: try:
allowed_target_item_list = server_proxy.getAllowedTargetItemList( allowed_target_item_list = server_proxy.getAllowedTargetItemList(
......
...@@ -26,7 +26,7 @@ ...@@ -26,7 +26,7 @@
# #
############################################################################## ##############################################################################
import urllib2 import six.moves.urllib.request
from lxml import etree from lxml import etree
from erp5.component.document.Document import ConversionError from erp5.component.document.Document import ConversionError
...@@ -34,7 +34,7 @@ SVG_DEFAULT_NAMESPACE = "http://www.w3.org/2000/svg" ...@@ -34,7 +34,7 @@ SVG_DEFAULT_NAMESPACE = "http://www.w3.org/2000/svg"
def getDataURI(url): def getDataURI(url):
try: try:
data = urllib2.urlopen(url) data = six.moves.urllib.request.urlopen(url)
except Exception as e: except Exception as e:
raise ConversionError("Error to transform url (%s) into data uri. ERROR = %s" % (url, Exception(e))) raise ConversionError("Error to transform url (%s) into data uri. ERROR = %s" % (url, Exception(e)))
return 'data:%s;base64,%s' % (data.info()["content-type"], return 'data:%s;base64,%s' % (data.info()["content-type"],
......
...@@ -36,7 +36,7 @@ import email, re ...@@ -36,7 +36,7 @@ import email, re
from email.header import decode_header, make_header from email.header import decode_header, make_header
from email.utils import parseaddr from email.utils import parseaddr
import cgi import cgi
import urlparse import six.moves.urllib.parse
use_verbose_security = 0 use_verbose_security = 0
if use_verbose_security: if use_verbose_security:
...@@ -780,7 +780,7 @@ class TestERP5Credential(ERP5TypeTestCase): ...@@ -780,7 +780,7 @@ class TestERP5Credential(ERP5TypeTestCase):
url = url.strip() url = url.strip()
self.assertNotEqual(url, None) self.assertNotEqual(url, None)
self.publish(url) self.publish(url)
parameters = cgi.parse_qs(urlparse.urlparse(url)[4]) parameters = cgi.parse_qs(six.moves.urllib.parse.urlparse(url)[4])
self.assertTrue( self.assertTrue(
'reset_key' in parameters, 'reset_key' in parameters,
'reset_key not found in mail message : %s' % body_message 'reset_key not found in mail message : %s' % body_message
...@@ -1265,7 +1265,7 @@ class TestERP5Credential(ERP5TypeTestCase): ...@@ -1265,7 +1265,7 @@ class TestERP5Credential(ERP5TypeTestCase):
self.portal.ERP5Site_viewNewPersonCredentialUpdateDialog() self.portal.ERP5Site_viewNewPersonCredentialUpdateDialog()
ret = self.portal.ERP5Site_newPersonCredentialUpdate(password='new_password') ret = self.portal.ERP5Site_newPersonCredentialUpdate(password='new_password')
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
['Password changed.'], ['Password changed.'],
) )
self.tic() self.tic()
...@@ -1433,7 +1433,7 @@ class TestERP5Credential(ERP5TypeTestCase): ...@@ -1433,7 +1433,7 @@ class TestERP5Credential(ERP5TypeTestCase):
ret = self.portal.ERP5Site_newCredentialRecovery(reference=self._testMethodName) ret = self.portal.ERP5Site_newCredentialRecovery(reference=self._testMethodName)
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
['We have sent you an email to enable you to reset your password. Please check your inbox and your junk/spam mail for this email and follow the link to reset your password.'], ['We have sent you an email to enable you to reset your password. Please check your inbox and your junk/spam mail for this email and follow the link to reset your password.'],
) )
person.setDefaultEmailCoordinateText(None) person.setDefaultEmailCoordinateText(None)
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
############################################################################## ##############################################################################
import unittest import unittest
import urlparse import six.moves.urllib.parse
import os import os
import textwrap import textwrap
from unittest import expectedFailure from unittest import expectedFailure
...@@ -548,7 +548,7 @@ class TestCRM(BaseTestCRM): ...@@ -548,7 +548,7 @@ class TestCRM(BaseTestCRM):
# This action checks everything is properly defined # This action checks everything is properly defined
ret = campaign.Ticket_createEventFromDefaultEventPath() ret = campaign.Ticket_createEventFromDefaultEventPath()
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
["Recipients must be defined"]) ["Recipients must be defined"])
campaign.setDefaultEventPathDestination( campaign.setDefaultEventPathDestination(
"portal_domains/%s" % person_domain.getRelativeUrl()) "portal_domains/%s" % person_domain.getRelativeUrl())
...@@ -556,38 +556,38 @@ class TestCRM(BaseTestCRM): ...@@ -556,38 +556,38 @@ class TestCRM(BaseTestCRM):
campaign.setDefaultEventPathEventPortalType(None) campaign.setDefaultEventPathEventPortalType(None)
ret = campaign.Ticket_createEventFromDefaultEventPath() ret = campaign.Ticket_createEventFromDefaultEventPath()
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
["Event Type must be defined"]) ["Event Type must be defined"])
campaign.setDefaultEventPathEventPortalType('Mail Message') campaign.setDefaultEventPathEventPortalType('Mail Message')
ret = campaign.Ticket_createEventFromDefaultEventPath() ret = campaign.Ticket_createEventFromDefaultEventPath()
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
["Sender must be defined"]) ["Sender must be defined"])
campaign.setDefaultEventPathSource(sender.getRelativeUrl()) campaign.setDefaultEventPathSource(sender.getRelativeUrl())
ret = campaign.Ticket_createEventFromDefaultEventPath() ret = campaign.Ticket_createEventFromDefaultEventPath()
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
["Notification Message must be defined"]) ["Notification Message must be defined"])
campaign.setDefaultEventPathResource(notification_message.getRelativeUrl()) campaign.setDefaultEventPathResource(notification_message.getRelativeUrl())
ret = campaign.Ticket_createEventFromDefaultEventPath() ret = campaign.Ticket_createEventFromDefaultEventPath()
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
["Notification Message must be validated"]) ["Notification Message must be validated"])
notification_message.setReference(notification_message_reference) notification_message.setReference(notification_message_reference)
ret = campaign.Ticket_createEventFromDefaultEventPath() ret = campaign.Ticket_createEventFromDefaultEventPath()
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
["Notification Message must be validated"]) ["Notification Message must be validated"])
notification_message.validate() notification_message.validate()
self.tic() self.tic()
ret = campaign.Ticket_createEventFromDefaultEventPath() ret = campaign.Ticket_createEventFromDefaultEventPath()
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
["Events are being created in background"]) ["Events are being created in background"])
self.tic() self.tic()
event_list = [event for event in campaign.getFollowUpRelatedValueList() event_list = [event for event in campaign.getFollowUpRelatedValueList()
......
...@@ -6,7 +6,7 @@ from six.moves import cStringIO as StringIO ...@@ -6,7 +6,7 @@ from six.moves import cStringIO as StringIO
from erp5.portal_type import Image from erp5.portal_type import Image
from types import ModuleType from types import ModuleType
from ZODB.serialize import ObjectWriter from ZODB.serialize import ObjectWriter
import cPickle import six.moves.cPickle
import sys import sys
import traceback import traceback
import ast import ast
...@@ -589,7 +589,7 @@ def canSerialize(obj): ...@@ -589,7 +589,7 @@ def canSerialize(obj):
# for example: if the user defines a dict with an object of a class # for example: if the user defines a dict with an object of a class
# that he created the dump will stil work, but the load will fail. # that he created the dump will stil work, but the load will fail.
try: try:
cPickle.loads(cPickle.dumps(obj)) six.moves.cPickle.loads(six.moves.cPickle.dumps(obj))
# By unknowing reasons, trying to catch cPickle.PicklingError in the "normal" # By unknowing reasons, trying to catch cPickle.PicklingError in the "normal"
# way isn't working. This issue might be related to some weirdness in # way isn't working. This issue might be related to some weirdness in
# pickle/cPickle that is reported in this issue: http://bugs.python.org/issue1457119. # pickle/cPickle that is reported in this issue: http://bugs.python.org/issue1457119.
...@@ -599,7 +599,7 @@ def canSerialize(obj): ...@@ -599,7 +599,7 @@ def canSerialize(obj):
# #
# Even though the issue seems complicated, this quickfix should be # Even though the issue seems complicated, this quickfix should be
# properly rewritten in a better way as soon as possible. # properly rewritten in a better way as soon as possible.
except (cPickle.PicklingError, TypeError, NameError, AttributeError): except (six.moves.cPickle.PicklingError, TypeError, NameError, AttributeError):
return False return False
else: else:
return True return True
......
...@@ -28,7 +28,7 @@ ...@@ -28,7 +28,7 @@
############################################################################## ##############################################################################
from Products.ERP5Form.FormBox import FormBox from Products.ERP5Form.FormBox import FormBox
from urlparse import urlparse from six.moves.urllib.parse import urlparse
def Base_updatePropertyMapListWithFieldLabel(self, property_map_list): def Base_updatePropertyMapListWithFieldLabel(self, property_map_list):
"""Try to get the title of field which edit the given inside property_map_list """Try to get the title of field which edit the given inside property_map_list
......
...@@ -26,7 +26,7 @@ ...@@ -26,7 +26,7 @@
############################################################################## ##############################################################################
import zipfile, cStringIO, re import zipfile, cStringIO, re
import xmlrpclib, base64 import six.moves.xmlrpc_client, base64
from Products.CMFCore.utils import getToolByName from Products.CMFCore.utils import getToolByName
def extractContent(data): def extractContent(data):
...@@ -68,7 +68,7 @@ def mkProxy(self): ...@@ -68,7 +68,7 @@ def mkProxy(self):
nr = pref.getPreferredDmsOoodocServerPortNumber() nr = pref.getPreferredDmsOoodocServerPortNumber()
if adr is None or nr is None: if adr is None or nr is None:
raise Exception('you should set conversion server coordinates in preferences') raise Exception('you should set conversion server coordinates in preferences')
sp = xmlrpclib.ServerProxy('http://%s:%d' % (adr,nr), allow_none=True) sp = six.moves.xmlrpc_client.ServerProxy('http://%s:%d' % (adr,nr), allow_none=True)
return sp return sp
def generateFile(self, name, data, format): # pylint: disable=redefined-builtin def generateFile(self, name, data, format): # pylint: disable=redefined-builtin
......
from erp5.component.document.Document import ConversionError from erp5.component.document.Document import ConversionError
from erp5.component.module.Log import log from erp5.component.module.Log import log
from ZODB.POSException import ConflictError from ZODB.POSException import ConflictError
from xmlrpclib import Fault from six.moves.xmlrpc_client import Fault
from socket import error as SocketError from socket import error as SocketError
message = None message = None
......
...@@ -63,7 +63,7 @@ from Products.ERP5Type.tests.utils import createZODBPythonScript ...@@ -63,7 +63,7 @@ from Products.ERP5Type.tests.utils import createZODBPythonScript
from Products.ERP5Type.Globals import get_request from Products.ERP5Type.Globals import get_request
import os import os
from threading import Thread from threading import Thread
import httplib import six.moves.http_client
import urllib import urllib
import difflib import difflib
import re import re
...@@ -1848,7 +1848,7 @@ document.write('<sc'+'ript type="text/javascript" src="http://somosite.bg/utb.ph ...@@ -1848,7 +1848,7 @@ document.write('<sc'+'ript type="text/javascript" src="http://somosite.bg/utb.ph
</html> </html>
""" """
web_page.edit(text_content=html_content) web_page.edit(text_content=html_content)
from HTMLParser import HTMLParseError from six.moves.html_parser import HTMLParseError
try: try:
web_page.asStrippedHTML() web_page.asStrippedHTML()
except HTMLParseError: except HTMLParseError:
...@@ -1916,7 +1916,7 @@ document.write('<sc'+'ript type="text/javascript" src="http://somosite.bg/utb.ph ...@@ -1916,7 +1916,7 @@ document.write('<sc'+'ript type="text/javascript" src="http://somosite.bg/utb.ph
assert response.getHeader('content-type') == 'image/png', \ assert response.getHeader('content-type') == 'image/png', \
response.getHeader('content-type') response.getHeader('content-type')
assert response.getStatus() == httplib.OK assert response.getStatus() == six.moves.http_client.OK
# assume there is no password # assume there is no password
credential = '%s:' % (getSecurityManager().getUser().getId(),) credential = '%s:' % (getSecurityManager().getUser().getId(),)
......
...@@ -98,7 +98,7 @@ class TestWebDavSupport(ERP5TypeTestCase): ...@@ -98,7 +98,7 @@ class TestWebDavSupport(ERP5TypeTestCase):
request_method='PUT', request_method='PUT',
stdin=file_object, stdin=file_object,
basic=self.authentication) basic=self.authentication)
self.assertEqual(response.getStatus(), httplib.CREATED) self.assertEqual(response.getStatus(), six.moves.http_client.CREATED)
image = person['erp5_logo.png'] image = person['erp5_logo.png']
self.assertEqual(image.getPortalType(), 'Embedded File') self.assertEqual(image.getPortalType(), 'Embedded File')
self.assertEqual(image.getContentType(), 'image/png') self.assertEqual(image.getContentType(), 'image/png')
...@@ -118,7 +118,7 @@ class TestWebDavSupport(ERP5TypeTestCase): ...@@ -118,7 +118,7 @@ class TestWebDavSupport(ERP5TypeTestCase):
stdin=file_object, stdin=file_object,
basic=self.authentication) basic=self.authentication)
self.assertEqual(response.getStatus(), httplib.CREATED) self.assertEqual(response.getStatus(), six.moves.http_client.CREATED)
document_module = self.getDocumentModule() document_module = self.getDocumentModule()
self.assertIn(filename, document_module.objectIds()) self.assertIn(filename, document_module.objectIds())
self.assertEqual(document_module[filename].getPortalType(), 'Presentation') self.assertEqual(document_module[filename].getPortalType(), 'Presentation')
...@@ -140,7 +140,7 @@ class TestWebDavSupport(ERP5TypeTestCase): ...@@ -140,7 +140,7 @@ class TestWebDavSupport(ERP5TypeTestCase):
stdin=file_object, stdin=file_object,
basic=self.authentication) basic=self.authentication)
self.assertEqual(response.getStatus(), httplib.CREATED) self.assertEqual(response.getStatus(), six.moves.http_client.CREATED)
self.tic() self.tic()
# check Document fetching # check Document fetching
...@@ -153,7 +153,7 @@ class TestWebDavSupport(ERP5TypeTestCase): ...@@ -153,7 +153,7 @@ class TestWebDavSupport(ERP5TypeTestCase):
request_method='GET', request_method='GET',
stdin=StringIO(), stdin=StringIO(),
basic=self.authentication) basic=self.authentication)
self.assertEqual(response.getStatus(), httplib.OK) self.assertEqual(response.getStatus(), six.moves.http_client.OK)
self.assertEqual(response.getBody(), document.getData(), self.assertEqual(response.getBody(), document.getData(),
'Error in getting data, get:%r' % response.getHeader('content-type')) 'Error in getting data, get:%r' % response.getHeader('content-type'))
...@@ -168,7 +168,7 @@ class TestWebDavSupport(ERP5TypeTestCase): ...@@ -168,7 +168,7 @@ class TestWebDavSupport(ERP5TypeTestCase):
request_method='PUT', request_method='PUT',
basic=self.authentication) basic=self.authentication)
self.assertEqual(response.getStatus(), httplib.CREATED) self.assertEqual(response.getStatus(), six.moves.http_client.CREATED)
web_page_module = self.getWebPageModule() web_page_module = self.getWebPageModule()
self.assertIn(filename, web_page_module.objectIds()) self.assertIn(filename, web_page_module.objectIds())
self.assertEqual(web_page_module[filename].getPortalType(), 'Web Page') self.assertEqual(web_page_module[filename].getPortalType(), 'Web Page')
...@@ -192,7 +192,7 @@ class TestWebDavSupport(ERP5TypeTestCase): ...@@ -192,7 +192,7 @@ class TestWebDavSupport(ERP5TypeTestCase):
request_method='PUT', request_method='PUT',
stdin=StringIO(iso_text_content), stdin=StringIO(iso_text_content),
basic=self.authentication) basic=self.authentication)
self.assertEqual(response.getStatus(), httplib.NO_CONTENT) self.assertEqual(response.getStatus(), six.moves.http_client.NO_CONTENT)
self.assertEqual(web_page_module[filename].getData(), iso_text_content) self.assertEqual(web_page_module[filename].getData(), iso_text_content)
# Convert to base format and run conversion into utf-8 # Convert to base format and run conversion into utf-8
self.tic() self.tic()
...@@ -223,7 +223,7 @@ class TestWebDavSupport(ERP5TypeTestCase): ...@@ -223,7 +223,7 @@ class TestWebDavSupport(ERP5TypeTestCase):
stdin=StringIO(), stdin=StringIO(),
basic=self.authentication) basic=self.authentication)
self.assertEqual(response.getStatus(), httplib.OK) self.assertEqual(response.getStatus(), six.moves.http_client.OK)
self.assertEqual(response.getBody(), document.getData(), self.assertEqual(response.getBody(), document.getData(),
'Error in getting data, get:%r' % response.getHeader('content-type')) 'Error in getting data, get:%r' % response.getHeader('content-type'))
...@@ -247,7 +247,7 @@ class TestWebDavSupport(ERP5TypeTestCase): ...@@ -247,7 +247,7 @@ class TestWebDavSupport(ERP5TypeTestCase):
stdin=StringIO(), stdin=StringIO(),
basic=self.authentication) basic=self.authentication)
self.assertEqual(response.getStatus(), httplib.MULTI_STATUS) self.assertEqual(response.getStatus(), six.moves.http_client.MULTI_STATUS)
xml_metadata_string = response.getBody() xml_metadata_string = response.getBody()
xml_metadata = etree.fromstring(xml_metadata_string) xml_metadata = etree.fromstring(xml_metadata_string)
self.assertEqual(xml_metadata.find('{DAV:}response/{DAV:}href').text, self.assertEqual(xml_metadata.find('{DAV:}response/{DAV:}href').text,
...@@ -285,7 +285,7 @@ class TestWebDavSupport(ERP5TypeTestCase): ...@@ -285,7 +285,7 @@ class TestWebDavSupport(ERP5TypeTestCase):
stdin=StringIO(), stdin=StringIO(),
basic=self.authentication) basic=self.authentication)
self.assertEqual(response.getStatus(), httplib.MULTI_STATUS) self.assertEqual(response.getStatus(), six.moves.http_client.MULTI_STATUS)
xml_metadata_string = response.getBody() xml_metadata_string = response.getBody()
xml_metadata = etree.fromstring(xml_metadata_string) xml_metadata = etree.fromstring(xml_metadata_string)
self.assertEqual(xml_metadata.find( self.assertEqual(xml_metadata.find(
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
############################################################################## ##############################################################################
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
import urlparse import six.moves.urllib.parse
class TestBusinessTemplateScripts(ERP5TypeTestCase): class TestBusinessTemplateScripts(ERP5TypeTestCase):
...@@ -46,10 +46,10 @@ class TestBusinessTemplateScripts(ERP5TypeTestCase): ...@@ -46,10 +46,10 @@ class TestBusinessTemplateScripts(ERP5TypeTestCase):
skin_folder=self.skin_folder.getId(), skin_folder=self.skin_folder.getId(),
use_from_date_at_date=None) use_from_date_at_date=None)
resp_url = urlparse.urlparse(resp) resp_url = six.moves.urllib.parse.urlparse(resp)
self.assertEqual( self.assertEqual(
['Report created.'], ['Report created.'],
urlparse.parse_qs(resp_url.query)['portal_status_message']) six.moves.urllib.parse.parse_qs(resp_url.query)['portal_status_message'])
# report is usable (also in ERP5JS) # report is usable (also in ERP5JS)
action, = [ action, = [
...@@ -60,7 +60,7 @@ class TestBusinessTemplateScripts(ERP5TypeTestCase): ...@@ -60,7 +60,7 @@ class TestBusinessTemplateScripts(ERP5TypeTestCase):
self.assertEqual('dummy_report_report', action['id']) self.assertEqual('dummy_report_report', action['id'])
self.assertEqual( self.assertEqual(
'FooModule_viewDummyReportReportDialog', 'FooModule_viewDummyReportReportDialog',
urlparse.urlparse(action['url']).path.split('/')[-1]) six.moves.urllib.parse.urlparse(action['url']).path.split('/')[-1])
self.assertIn( self.assertIn(
'FooModule_viewDummyReportReportDialog', self.skin_folder.objectIds()) 'FooModule_viewDummyReportReportDialog', self.skin_folder.objectIds())
...@@ -90,10 +90,10 @@ class TestBusinessTemplateScripts(ERP5TypeTestCase): ...@@ -90,10 +90,10 @@ class TestBusinessTemplateScripts(ERP5TypeTestCase):
skin_layer_priority=None, skin_layer_priority=None,
skin_layer_list=self.portal.portal_skins.getSkinSelections(), skin_layer_list=self.portal.portal_skins.getSkinSelections(),
) )
resp_url = urlparse.urlparse(resp) resp_url = six.moves.urllib.parse.urlparse(resp)
self.assertEqual( self.assertEqual(
['Skin folder created.'], ['Skin folder created.'],
urlparse.parse_qs(resp_url.query)['portal_status_message']) six.moves.urllib.parse.parse_qs(resp_url.query)['portal_status_message'])
self.assertIn('dummy_skin_folder', self.portal.portal_skins.objectIds()) self.assertIn('dummy_skin_folder', self.portal.portal_skins.objectIds())
# skin is added to business template # skin is added to business template
...@@ -107,10 +107,10 @@ class TestBusinessTemplateScripts(ERP5TypeTestCase): ...@@ -107,10 +107,10 @@ class TestBusinessTemplateScripts(ERP5TypeTestCase):
skin_layer_priority=99, skin_layer_priority=99,
skin_layer_list=self.portal.portal_skins.getSkinSelections(), skin_layer_list=self.portal.portal_skins.getSkinSelections(),
) )
resp_url = urlparse.urlparse(resp) resp_url = six.moves.urllib.parse.urlparse(resp)
self.assertEqual( self.assertEqual(
['Skin folder created.'], ['Skin folder created.'],
urlparse.parse_qs(resp_url.query)['portal_status_message']) six.moves.urllib.parse.parse_qs(resp_url.query)['portal_status_message'])
self.assertIn('dummy_skin_folder', self.portal.portal_skins.objectIds()) self.assertIn('dummy_skin_folder', self.portal.portal_skins.objectIds())
self.assertEqual( self.assertEqual(
...@@ -130,10 +130,10 @@ class TestBusinessTemplateScripts(ERP5TypeTestCase): ...@@ -130,10 +130,10 @@ class TestBusinessTemplateScripts(ERP5TypeTestCase):
skin_folder_name='dummy_skin_folder', skin_folder_name='dummy_skin_folder',
skin_layer_priority=99, skin_layer_priority=99,
skin_layer_list=['View', 'SelectedSkinSelection']) skin_layer_list=['View', 'SelectedSkinSelection'])
resp_url = urlparse.urlparse(resp) resp_url = six.moves.urllib.parse.urlparse(resp)
self.assertEqual( self.assertEqual(
['Skin folder created.'], ['Skin folder created.'],
urlparse.parse_qs(resp_url.query)['portal_status_message']) six.moves.urllib.parse.parse_qs(resp_url.query)['portal_status_message'])
self.assertIn('dummy_skin_folder', self.portal.portal_skins.objectIds()) self.assertIn('dummy_skin_folder', self.portal.portal_skins.objectIds())
skin_folders_by_skin_selection = { skin_folders_by_skin_selection = {
......
from Products.ERP5Type.tests.SecurityTestCase import SecurityTestCase from Products.ERP5Type.tests.SecurityTestCase import SecurityTestCase
from httplib import OK as HTTP_OK from six.moves.http_client import OK as HTTP_OK
class TestDiscussionThread(SecurityTestCase): class TestDiscussionThread(SecurityTestCase):
""" """
......
...@@ -28,8 +28,8 @@ ...@@ -28,8 +28,8 @@
import uuid import uuid
import mock import mock
import lxml import lxml
import urlparse import six.moves.urllib.parse
import httplib import six.moves.http_client
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.tests.utils import createZODBPythonScript from Products.ERP5Type.tests.utils import createZODBPythonScript
...@@ -328,9 +328,9 @@ class TestERP5JSGoogleLogin(GoogleLoginTestCase): ...@@ -328,9 +328,9 @@ class TestERP5JSGoogleLogin(GoogleLoginTestCase):
if img.attrib['alt'] == 'Sign in with Google' if img.attrib['alt'] == 'Sign in with Google'
] ]
self.assertIn('/ERP5Site_redirectToGoogleLoginPage', google_login_link) self.assertIn('/ERP5Site_redirectToGoogleLoginPage', google_login_link)
resp = self.publish(urlparse.urlparse(google_login_link).path) resp = self.publish(six.moves.urllib.parse.urlparse(google_login_link).path)
# this request redirects to google # this request redirects to google
self.assertEqual(resp.getStatus(), httplib.FOUND) self.assertEqual(resp.getStatus(), six.moves.http_client.FOUND)
self.assertIn('google.com', resp.getHeader('Location')) self.assertIn('google.com', resp.getHeader('Location'))
def test_logout(self): def test_logout(self):
......
...@@ -461,7 +461,7 @@ class TestSupportRequestRSSSOneEvent(SupportRequestRSSTestCase, DefaultTestRSSMi ...@@ -461,7 +461,7 @@ class TestSupportRequestRSSSOneEvent(SupportRequestRSSTestCase, DefaultTestRSSMi
"""Tests for simple cases of RSS with only one event. """Tests for simple cases of RSS with only one event.
""" """
def _checkRSS(self, response): def _checkRSS(self, response):
self.assertEqual(httplib.OK, response.getStatus()) self.assertEqual(six.moves.http_client.OK, response.getStatus())
rss = feedparser.parse(response.getBody()) rss = feedparser.parse(response.getBody())
self.assertEqual(rss['feed']['title'], "Support Requests") self.assertEqual(rss['feed']['title'], "Support Requests")
item, = rss.entries item, = rss.entries
...@@ -500,7 +500,7 @@ class TestSupportRequestRSSSOneEvent(SupportRequestRSSTestCase, DefaultTestRSSMi ...@@ -500,7 +500,7 @@ class TestSupportRequestRSSSOneEvent(SupportRequestRSSTestCase, DefaultTestRSSMi
# get rss link url # get rss link url
self.getWebSite().support_request_module.SupportRequestModule_generateRSSLinkUrl() self.getWebSite().support_request_module.SupportRequestModule_generateRSSLinkUrl()
restricted_access_url = self.portal.REQUEST.form["your_rss_url"] restricted_access_url = self.portal.REQUEST.form["your_rss_url"]
parsed_url = urlparse.urlparse(restricted_access_url) parsed_url = six.moves.urllib.parse.urlparse(restricted_access_url)
restricted_access_url = restricted_access_url.replace( restricted_access_url = restricted_access_url.replace(
'%s://%s' % (parsed_url.scheme, parsed_url.netloc), '', 1) '%s://%s' % (parsed_url.scheme, parsed_url.netloc), '', 1)
# and check it # and check it
...@@ -538,7 +538,7 @@ class TestSupportRequestRSSSMultipleEvents(SupportRequestRSSTestCase, DefaultTes ...@@ -538,7 +538,7 @@ class TestSupportRequestRSSSMultipleEvents(SupportRequestRSSTestCase, DefaultTes
self.tic() self.tic()
def _checkRSS(self, response): def _checkRSS(self, response):
self.assertEqual(httplib.OK, response.getStatus()) self.assertEqual(six.moves.http_client.OK, response.getStatus())
rss = feedparser.parse(response.getBody()) rss = feedparser.parse(response.getBody())
self.assertEqual(rss['feed']['title'], "Support Requests") self.assertEqual(rss['feed']['title'], "Support Requests")
self.assertEqual(len(rss.entries), 3) self.assertEqual(len(rss.entries), 3)
...@@ -562,7 +562,7 @@ class TestSupportRequestRSSSNonVisibleSupportRequest(SupportRequestRSSTestCase, ...@@ -562,7 +562,7 @@ class TestSupportRequestRSSSNonVisibleSupportRequest(SupportRequestRSSTestCase,
self.tic() self.tic()
def _checkRSS(self, response): def _checkRSS(self, response):
self.assertEqual(httplib.OK, response.getStatus()) self.assertEqual(six.moves.http_client.OK, response.getStatus())
rss = feedparser.parse(response.getBody()) rss = feedparser.parse(response.getBody())
item, = rss.entries item, = rss.entries
self.assertEqual(item['author'], self.user.getTitle()) self.assertEqual(item['author'], self.user.getTitle())
...@@ -605,7 +605,7 @@ class TestSupportRequestRSSSNonVisibleAttachment(SupportRequestRSSTestCase, Defa ...@@ -605,7 +605,7 @@ class TestSupportRequestRSSSNonVisibleAttachment(SupportRequestRSSTestCase, Defa
self.tic() self.tic()
def _checkRSS(self, response): def _checkRSS(self, response):
self.assertEqual(httplib.OK, response.getStatus()) self.assertEqual(six.moves.http_client.OK, response.getStatus())
rss = feedparser.parse(response.getBody()) rss = feedparser.parse(response.getBody())
item, = rss.entries item, = rss.entries
# no enclosure # no enclosure
......
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
# #
############################################################################## ##############################################################################
import urlparse import six.moves.urllib.parse
from DateTime import DateTime from DateTime import DateTime
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
...@@ -343,17 +343,17 @@ class TestPaymentTransactionGroupPaymentSelection(AccountingTestCase): ...@@ -343,17 +343,17 @@ class TestPaymentTransactionGroupPaymentSelection(AccountingTestCase):
self.tic() self.tic()
ret = ptg1.PaymentTransactionGroup_selectPaymentTransactionLineList(select_mode='stopped_or_delivered') ret = ptg1.PaymentTransactionGroup_selectPaymentTransactionLineList(select_mode='stopped_or_delivered')
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
['Payment selection in progress.']) ['Payment selection in progress.'])
self.commit() self.commit()
ret = ptg1.PaymentTransactionGroup_selectPaymentTransactionLineList(select_mode='stopped_or_delivered') ret = ptg1.PaymentTransactionGroup_selectPaymentTransactionLineList(select_mode='stopped_or_delivered')
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
['Some payments are still beeing processed in the background, please retry later']) ['Some payments are still beeing processed in the background, please retry later'])
self.commit() self.commit()
# another PTG is same, because we also want to prevent things like two users selecting # another PTG is same, because we also want to prevent things like two users selecting
# payments at the same time. # payments at the same time.
ret = ptg2.PaymentTransactionGroup_selectPaymentTransactionLineList(select_mode='stopped_or_delivered') ret = ptg2.PaymentTransactionGroup_selectPaymentTransactionLineList(select_mode='stopped_or_delivered')
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
['Some payments are still beeing processed in the background, please retry later']) ['Some payments are still beeing processed in the background, please retry later'])
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
# #
############################################################################## ##############################################################################
import urlparse import six.moves.urllib.parse
import lxml.etree import lxml.etree
from DateTime import DateTime from DateTime import DateTime
...@@ -251,7 +251,7 @@ class TestPaymentTransactionGroupPaymentSEPA(AccountingTestCase): ...@@ -251,7 +251,7 @@ class TestPaymentTransactionGroupPaymentSEPA(AccountingTestCase):
ret = ptg.PaymentTransactionGroup_generateSEPACreditTransferFile( ret = ptg.PaymentTransactionGroup_generateSEPACreditTransferFile(
version='pain.001.001.02') version='pain.001.001.02')
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
['SEPA Credit Transfer File generated.']) ['SEPA Credit Transfer File generated.'])
self.tic() self.tic()
...@@ -279,7 +279,7 @@ class TestPaymentTransactionGroupPaymentSEPA(AccountingTestCase): ...@@ -279,7 +279,7 @@ class TestPaymentTransactionGroupPaymentSEPA(AccountingTestCase):
ret = ptg.PaymentTransactionGroup_generateSEPACreditTransferFile( ret = ptg.PaymentTransactionGroup_generateSEPACreditTransferFile(
version='pain.001.001.02') version='pain.001.001.02')
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
['Some payments are still beeing processed in the background, please retry later']) ['Some payments are still beeing processed in the background, please retry later'])
self.tic() self.tic()
......
...@@ -16,7 +16,7 @@ from matplotlib import pylab ...@@ -16,7 +16,7 @@ from matplotlib import pylab
import matplotlib.image as mpimg import matplotlib.image as mpimg
import scipy.stats as stats import scipy.stats as stats
import re import re
import cPickle import six.moves.cPickle
import ocrolib import ocrolib
def getReceiptValue(self, image_data, model_name = "en-default.pyrnn"): def getReceiptValue(self, image_data, model_name = "en-default.pyrnn"):
...@@ -102,7 +102,7 @@ def getRnnModelFromDataStream(self, model_name="en-default.pyrnn"): ...@@ -102,7 +102,7 @@ def getRnnModelFromDataStream(self, model_name="en-default.pyrnn"):
WARNING: This function present a security issue and should NOT be called with WARNING: This function present a security issue and should NOT be called with
an user-defined model name (see cpickle security issue) an user-defined model name (see cpickle security issue)
""" """
network = cPickle.loads(self.data_stream_module[model_name].getData()) network = six.moves.cPickle.loads(self.data_stream_module[model_name].getData())
lnorm = getattr(network, "lnorm", None) lnorm = getattr(network, "lnorm", None)
return network, lnorm return network, lnorm
......
...@@ -27,7 +27,7 @@ try: ...@@ -27,7 +27,7 @@ try:
except ImportError: # BBB Zope2 except ImportError: # BBB Zope2
from Globals import package_home from Globals import package_home
import PIL.Image as PIL_Image import PIL.Image as PIL_Image
import thread import six.moves._thread
import random import random
import base64 import base64
from OFS.Folder import Folder from OFS.Folder import Folder
......
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
from base64 import b16encode, b16decode from base64 import b16encode, b16decode
from logging import getLogger from logging import getLogger
from urlparse import urlparse from six.moves.urllib.parse import urlparse
from lxml import etree from lxml import etree
from copy import deepcopy from copy import deepcopy
from six import string_types as basestring from six import string_types as basestring
......
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
# #
############################################################################## ##############################################################################
from HTMLParser import HTMLParser from six.moves.html_parser import HTMLParser
class HtmlParseHelper(HTMLParser): class HtmlParseHelper(HTMLParser):
""" """
Listens to all the HTMLParser methods and push results in a list of tuple. Listens to all the HTMLParser methods and push results in a list of tuple.
......
...@@ -27,11 +27,11 @@ ...@@ -27,11 +27,11 @@
import unittest import unittest
from Products.ERP5Type.tests.ERP5TypeFunctionalTestCase import ERP5TypeFunctionalTestCase from Products.ERP5Type.tests.ERP5TypeFunctionalTestCase import ERP5TypeFunctionalTestCase
from SimpleHTTPServer import SimpleHTTPRequestHandler from six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler
from threading import Thread from threading import Thread
from datetime import datetime from datetime import datetime
import SocketServer import six.moves.socketserver
import tempfile import tempfile
import shutil import shutil
import time import time
...@@ -73,7 +73,7 @@ class TestZeleniumCore(ERP5TypeFunctionalTestCase): ...@@ -73,7 +73,7 @@ class TestZeleniumCore(ERP5TypeFunctionalTestCase):
root_title = "TEST Instance Tree" root_title = "TEST Instance Tree"
def start_httpd_server(self, root_folder): def start_httpd_server(self, root_folder):
self.httpd = SocketServer.TCPServer(('localhost', 5378), CustomHTTPRequestHandler) self.httpd = six.moves.socketserver.TCPServer(('localhost', 5378), CustomHTTPRequestHandler)
self.httpd.timeout = 2 self.httpd.timeout = 2
os.chdir(root_folder) os.chdir(root_folder)
#self.httpd.serve_forever() #self.httpd.serve_forever()
......
import json import json
import re import re
from urlparse import urljoin from six.moves.urllib.parse import urljoin
if REQUEST is None: if REQUEST is None:
REQUEST = context.REQUEST REQUEST = context.REQUEST
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
import os import os
import unittest import unittest
import urlparse import six.moves.urllib.parse
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
...@@ -36,7 +36,7 @@ class TestSFTPConnection(ERP5TypeTestCase): ...@@ -36,7 +36,7 @@ class TestSFTPConnection(ERP5TypeTestCase):
if os.environ.get("testSFTPConnection_SFTP_URL"): if os.environ.get("testSFTPConnection_SFTP_URL"):
def afterSetUp(self): def afterSetUp(self):
url = os.environ["testSFTPConnection_SFTP_URL"] url = os.environ["testSFTPConnection_SFTP_URL"]
parsed_url = urlparse.urlparse(url) parsed_url = six.moves.urllib.parse.urlparse(url)
self.connection = self.portal.portal_web_services.newContent( self.connection = self.portal.portal_web_services.newContent(
portal_type='FTP Connector', portal_type='FTP Connector',
reference=self.id(), reference=self.id(),
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
############################################################################## ##############################################################################
import hashlib, httplib import hashlib, six.moves.http_client
from Products.ERP5Type.UnrestrictedMethod import super_user from Products.ERP5Type.UnrestrictedMethod import super_user
...@@ -110,6 +110,6 @@ def WebSite_viewAsWebPost(self, *args, **kwargs): ...@@ -110,6 +110,6 @@ def WebSite_viewAsWebPost(self, *args, **kwargs):
# security check should be done already. # security check should be done already.
document.publish() document.publish()
self.REQUEST.RESPONSE.setStatus(httplib.CREATED) self.REQUEST.RESPONSE.setStatus(six.moves.http_client.CREATED)
return sha512sum return sha512sum
...@@ -28,8 +28,8 @@ ...@@ -28,8 +28,8 @@
############################################################################## ##############################################################################
import httplib import six.moves.http_client
import urlparse import six.moves.urllib.parse
from unittest import expectedFailure from unittest import expectedFailure
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from erp5.component.test.ShaCacheMixin import ShaCacheMixin from erp5.component.test.ShaCacheMixin import ShaCacheMixin
...@@ -49,8 +49,8 @@ class TestShaCache(ShaCacheMixin, ERP5TypeTestCase): ...@@ -49,8 +49,8 @@ class TestShaCache(ShaCacheMixin, ERP5TypeTestCase):
""" """
Post the file Post the file
""" """
parsed = urlparse.urlparse(self.shacache_url) parsed = six.moves.urllib.parse.urlparse(self.shacache_url)
connection = httplib.HTTPConnection(parsed.hostname, parsed.port) connection = six.moves.http_client.HTTPConnection(parsed.hostname, parsed.port)
try: try:
connection.request('POST', parsed.path, self.data, self.header_dict) connection.request('POST', parsed.path, self.data, self.header_dict)
result = connection.getresponse() result = connection.getresponse()
...@@ -67,8 +67,8 @@ class TestShaCache(ShaCacheMixin, ERP5TypeTestCase): ...@@ -67,8 +67,8 @@ class TestShaCache(ShaCacheMixin, ERP5TypeTestCase):
if key is None: if key is None:
key = self.key key = self.key
parsed = urlparse.urlparse(self.shacache_url) parsed = six.moves.urllib.parse.urlparse(self.shacache_url)
connection = httplib.HTTPConnection(parsed.hostname, parsed.port) connection = six.moves.http_client.HTTPConnection(parsed.hostname, parsed.port)
try: try:
connection.request('GET', '/'.join([parsed.path, key]), None, {}) connection.request('GET', '/'.join([parsed.path, key]), None, {})
result = connection.getresponse() result = connection.getresponse()
...@@ -82,7 +82,7 @@ class TestShaCache(ShaCacheMixin, ERP5TypeTestCase): ...@@ -82,7 +82,7 @@ class TestShaCache(ShaCacheMixin, ERP5TypeTestCase):
Check if the PUT method is creating an object. Check if the PUT method is creating an object.
""" """
result, data = self.postFile() result, data = self.postFile()
self.assertEqual(result, httplib.CREATED) self.assertEqual(result, six.moves.http_client.CREATED)
self.assertEqual(data, self.key) self.assertEqual(data, self.key)
self.tic() self.tic()
...@@ -100,7 +100,7 @@ class TestShaCache(ShaCacheMixin, ERP5TypeTestCase): ...@@ -100,7 +100,7 @@ class TestShaCache(ShaCacheMixin, ERP5TypeTestCase):
Check if the file returned is the correct. Check if the file returned is the correct.
""" """
result, data = self.postFile() result, data = self.postFile()
self.assertEqual(result, httplib.CREATED) self.assertEqual(result, six.moves.http_client.CREATED)
self.assertEqual(data, self.key) self.assertEqual(data, self.key)
self.tic() self.tic()
...@@ -109,7 +109,7 @@ class TestShaCache(ShaCacheMixin, ERP5TypeTestCase): ...@@ -109,7 +109,7 @@ class TestShaCache(ShaCacheMixin, ERP5TypeTestCase):
self.assertNotEqual(None, document) self.assertNotEqual(None, document)
result, data = self.getFile() result, data = self.getFile()
self.assertEqual(result, httplib.OK) self.assertEqual(result, six.moves.http_client.OK)
self.assertEqual(data, self.data) self.assertEqual(data, self.data)
def test_put_file_twice(self): def test_put_file_twice(self):
......
...@@ -27,9 +27,9 @@ ...@@ -27,9 +27,9 @@
# #
############################################################################## ##############################################################################
import six.moves.http_client
import six.moves.urllib.parse
import hashlib import hashlib
import httplib
import urlparse
import json import json
import random import random
from base64 import b64encode from base64 import b64encode
...@@ -53,8 +53,8 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase): ...@@ -53,8 +53,8 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase):
Post the information calling the Python Script. Post the information calling the Python Script.
It simulates the real usage. It simulates the real usage.
""" """
parsed = urlparse.urlparse(self.shadir_url) parsed = six.moves.urllib.parse.urlparse(self.shadir_url)
connection = httplib.HTTPConnection(parsed.hostname, parsed.port) connection = six.moves.http_client.HTTPConnection(parsed.hostname, parsed.port)
try: try:
connection.request('PUT', '/'.join([parsed.path, key or self.key]), connection.request('PUT', '/'.join([parsed.path, key or self.key]),
data or self.data, self.header_dict) data or self.data, self.header_dict)
...@@ -62,7 +62,7 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase): ...@@ -62,7 +62,7 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase):
data = result.read() data = result.read()
finally: finally:
connection.close() connection.close()
self.assertEqual(result.status, httplib.CREATED) self.assertEqual(result.status, six.moves.http_client.CREATED)
self.assertEqual(data, '') self.assertEqual(data, '')
def getInformation(self, key=None): def getInformation(self, key=None):
...@@ -70,8 +70,8 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase): ...@@ -70,8 +70,8 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase):
Get the information calling the Python Script. Get the information calling the Python Script.
It simulates the real usage. It simulates the real usage.
""" """
parsed = urlparse.urlparse(self.shadir_url) parsed = six.moves.urllib.parse.urlparse(self.shadir_url)
connection = httplib.HTTPConnection(parsed.hostname, parsed.port) connection = six.moves.http_client.HTTPConnection(parsed.hostname, parsed.port)
try: try:
connection.request('GET', '/'.join([parsed.path, key or self.key]), connection.request('GET', '/'.join([parsed.path, key or self.key]),
self.data, self.header_dict) self.data, self.header_dict)
...@@ -126,7 +126,7 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase): ...@@ -126,7 +126,7 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase):
self.tic() self.tic()
result, data = self.getInformation() result, data = self.getInformation()
self.assertEqual(result, httplib.OK) self.assertEqual(result, six.moves.http_client.OK)
information_list = json.loads(data) information_list = json.loads(data)
...@@ -158,7 +158,7 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase): ...@@ -158,7 +158,7 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase):
q.getValidationState() for q in document_list])) q.getValidationState() for q in document_list]))
result, data = self.getInformation() result, data = self.getInformation()
self.assertEqual(result, httplib.OK) self.assertEqual(result, six.moves.http_client.OK)
information_list = json.loads(data) information_list = json.loads(data)
self.assertEqual(1, len(information_list)) self.assertEqual(1, len(information_list))
...@@ -196,7 +196,7 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase): ...@@ -196,7 +196,7 @@ class TestShaDir(ShaDirMixin, ERP5TypeTestCase):
self.tic() self.tic()
result, data = self.getInformation() result, data = self.getInformation()
self.assertEqual(result, httplib.OK) self.assertEqual(result, six.moves.http_client.OK)
information_list = json.loads(data) information_list = json.loads(data)
self.assertEqual(1, len(information_list)) self.assertEqual(1, len(information_list))
......
...@@ -27,8 +27,8 @@ ...@@ -27,8 +27,8 @@
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
import urlparse import six.moves.urllib.parse
import httplib import six.moves.http_client
import unittest import unittest
import ssl import ssl
...@@ -91,13 +91,13 @@ class TestStaticWebSiteRedirection(ERP5TypeTestCase): ...@@ -91,13 +91,13 @@ class TestStaticWebSiteRedirection(ERP5TypeTestCase):
if source_path.endswith("?"): if source_path.endswith("?"):
source_path = source_path[:-1] source_path = source_path[:-1]
api_scheme, api_netloc, api_path, _, _ = urlparse.urlsplit(absolute_url) api_scheme, api_netloc, api_path, _, _ = six.moves.urllib.parse.urlsplit(absolute_url)
redirect_url = website.getLayoutProperty("redirect_domain") redirect_url = website.getLayoutProperty("redirect_domain")
redirect_location = "/".join([redirect_url, source_path]) redirect_location = "/".join([redirect_url, source_path])
status_to_assert = httplib.MOVED_PERMANENTLY status_to_assert = six.moves.http_client.MOVED_PERMANENTLY
if use_moved_temporarily: if use_moved_temporarily:
status_to_assert = httplib.FOUND status_to_assert = six.moves.http_client.FOUND
api_netloc = '[ERP5_IPV6]:ERP5_PORT' api_netloc = '[ERP5_IPV6]:ERP5_PORT'
for url_to_check in [ for url_to_check in [
...@@ -111,12 +111,12 @@ class TestStaticWebSiteRedirection(ERP5TypeTestCase): ...@@ -111,12 +111,12 @@ class TestStaticWebSiteRedirection(ERP5TypeTestCase):
# '%s://%s/VirtualHostBase/http/example.org:1234/erp5/web_site_module/VirtualHostRoot/%s/%s' % (api_scheme, api_netloc, website.getId(), source_path) # '%s://%s/VirtualHostBase/http/example.org:1234/erp5/web_site_module/VirtualHostRoot/%s/%s' % (api_scheme, api_netloc, website.getId(), source_path)
]: ]:
scheme_to_check, netloc_to_check, _, _, _ = urlparse.urlsplit(url_to_check) scheme_to_check, netloc_to_check, _, _, _ = six.moves.urllib.parse.urlsplit(url_to_check)
if (scheme_to_check == 'https'): if (scheme_to_check == 'https'):
connection = httplib.HTTPSConnection(netloc_to_check, context=ssl._create_unverified_context(), timeout=10) connection = six.moves.http_client.HTTPSConnection(netloc_to_check, context=ssl._create_unverified_context(), timeout=10)
else: else:
connection = httplib.HTTPConnection(netloc_to_check, timeout=10) connection = six.moves.http_client.HTTPConnection(netloc_to_check, timeout=10)
connection.request( connection.request(
method="GET", method="GET",
url=url_to_check url=url_to_check
...@@ -126,7 +126,7 @@ class TestStaticWebSiteRedirection(ERP5TypeTestCase): ...@@ -126,7 +126,7 @@ class TestStaticWebSiteRedirection(ERP5TypeTestCase):
if (source_path == configuration_service_worker_url): if (source_path == configuration_service_worker_url):
# Test service worker URL # Test service worker URL
self.assertEqual(response.status, httplib.OK, '%s: %s' % (response.status, url_to_check)) self.assertEqual(response.status, six.moves.http_client.OK, '%s: %s' % (response.status, url_to_check))
self.assertEqual(response.getheader('Content-Type'), 'application/javascript') self.assertEqual(response.getheader('Content-Type'), 'application/javascript')
self.assertTrue('self.registration.unregister()' in response_body, self.assertTrue('self.registration.unregister()' in response_body,
response_body) response_body)
......
...@@ -4,7 +4,7 @@ from Products.ERP5Type import Permissions, PropertySheet ...@@ -4,7 +4,7 @@ from Products.ERP5Type import Permissions, PropertySheet
from Products.ERP5Type.XMLObject import XMLObject from Products.ERP5Type.XMLObject import XMLObject
from zLOG import LOG, WARNING from zLOG import LOG, WARNING
import random, string, hashlib, urllib2, socket import random, string, hashlib, urllib2, socket
from urlparse import urlparse from six.moves.urllib.parse import urlparse
from six import string_types as basestring from six import string_types as basestring
try: try:
import xml.etree.cElementTree as ET import xml.etree.cElementTree as ET
......
import urlparse import six.moves.urllib.parse
import unittest import unittest
from erp5.component.mixin.TestWorkflowMixin import TestWorkflowMixin from erp5.component.mixin.TestWorkflowMixin import TestWorkflowMixin
from Products.ERP5Type.Core.Workflow import ValidationFailed from Products.ERP5Type.Core.Workflow import ValidationFailed
...@@ -433,7 +433,7 @@ class TestConvertedWorkflow(TestERP5WorkflowMixin): ...@@ -433,7 +433,7 @@ class TestConvertedWorkflow(TestERP5WorkflowMixin):
self.tic() self.tic()
ret = self.workflow.Workflow_updateSecurityRoles() ret = self.workflow.Workflow_updateSecurityRoles()
self.assertEqual( self.assertEqual(
urlparse.parse_qs(urlparse.urlparse(ret).query)['portal_status_message'], six.moves.urllib.parse.parse_qs(six.moves.urllib.parse.urlparse(ret).query)['portal_status_message'],
["1 documents updated."]) ["1 documents updated."])
self.tic() self.tic()
self.assertEqual(text_document._View_Permission, ('Assignee', 'Assignor', 'Associate', 'Auditor', 'Author', 'Manager')) self.assertEqual(text_document._View_Permission, ('Assignee', 'Assignor', 'Associate', 'Auditor', 'Author', 'Manager'))
......
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
import base64 import base64
import httplib import six.moves.http_client
from unittest import expectedFailure from unittest import expectedFailure
from DateTime import DateTime from DateTime import DateTime
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
...@@ -74,7 +74,7 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase): ...@@ -74,7 +74,7 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase):
Test the external usage to POST information Test the external usage to POST information
""" """
now = DateTime() now = DateTime()
connection = httplib.HTTPConnection('%s:%s' % (self.host, self.port)) connection = six.moves.http_client.HTTPConnection('%s:%s' % (self.host, self.port))
try: try:
connection.request('POST', self.path, self.data, self.header_dict) connection.request('POST', self.path, self.data, self.header_dict)
result = connection.getresponse() result = connection.getresponse()
...@@ -83,7 +83,7 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase): ...@@ -83,7 +83,7 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase):
finally: finally:
connection.close() connection.close()
self.assertEqual(self.key, data) self.assertEqual(self.key, data)
self.assertEqual(httplib.CREATED, result.status) self.assertEqual(six.moves.http_client.CREATED, result.status)
# Check Document # Check Document
document = self.portal.portal_catalog.getResultValue(portal_type='File', document = self.portal.portal_catalog.getResultValue(portal_type='File',
...@@ -104,7 +104,7 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase): ...@@ -104,7 +104,7 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase):
if not annonymous: if not annonymous:
header_dict = self.header_dict header_dict = self.header_dict
connection = httplib.HTTPConnection('%s:%s' % (self.host, self.port)) connection = six.moves.http_client.HTTPConnection('%s:%s' % (self.host, self.port))
try: try:
connection.request('GET', '/'.join([self.path, self.key]), connection.request('GET', '/'.join([self.path, self.key]),
headers=header_dict) headers=header_dict)
...@@ -113,7 +113,7 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase): ...@@ -113,7 +113,7 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase):
finally: finally:
connection.close() connection.close()
self.assertEqual(self.data, data) self.assertEqual(self.data, data)
self.assertEqual(httplib.OK, result.status) self.assertEqual(six.moves.http_client.OK, result.status)
self.assertEqual(self.expected_content_type, self.assertEqual(self.expected_content_type,
result.getheader("content-type")) result.getheader("content-type"))
...@@ -129,7 +129,7 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase): ...@@ -129,7 +129,7 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase):
""" """
Anonymous should not be able to POST a file. Anonymous should not be able to POST a file.
""" """
connection = httplib.HTTPConnection('%s:%s' % (self.host, self.port)) connection = six.moves.http_client.HTTPConnection('%s:%s' % (self.host, self.port))
header_dict = {'Content-Type': self.content_type} header_dict = {'Content-Type': self.content_type}
try: try:
connection.request('POST', self.path, self.data, header_dict) connection.request('POST', self.path, self.data, header_dict)
...@@ -143,4 +143,4 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase): ...@@ -143,4 +143,4 @@ class TestShaCacheExternal(ShaCacheMixin, ShaSecurityMixin, ERP5TypeTestCase):
# Ref: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4 # Ref: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4
# self.assertEqual(httplib.UNAUTHORIZED, result.status) # self.assertEqual(httplib.UNAUTHORIZED, result.status)
# FORBIDDEN seems more suitable for RESTful server... # FORBIDDEN seems more suitable for RESTful server...
self.assertEqual(httplib.FORBIDDEN, result.status) self.assertEqual(six.moves.http_client.FORBIDDEN, result.status)
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
import base64 import base64
import json import json
import os import os
import httplib import six.moves.http_client
from DateTime import DateTime from DateTime import DateTime
from Products.ERP5Type.tests.ERP5TypeLiveTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeLiveTestCase import ERP5TypeTestCase
from erp5.component.test.ShaDirMixin import ShaDirMixin from erp5.component.test.ShaDirMixin import ShaDirMixin
...@@ -75,7 +75,7 @@ class TestShaDirExternal(ShaDirMixin, ShaSecurityMixin, ERP5TypeTestCase): ...@@ -75,7 +75,7 @@ class TestShaDirExternal(ShaDirMixin, ShaSecurityMixin, ERP5TypeTestCase):
Test the external usage to POST information Test the external usage to POST information
""" """
now = DateTime() now = DateTime()
connection = httplib.HTTPConnection('%s:%s' % (self.host, self.port)) connection = six.moves.http_client.HTTPConnection('%s:%s' % (self.host, self.port))
try: try:
connection.request('PUT', self.path, self.data, self.header_dict) connection.request('PUT', self.path, self.data, self.header_dict)
result = connection.getresponse() result = connection.getresponse()
...@@ -114,7 +114,7 @@ class TestShaDirExternal(ShaDirMixin, ShaSecurityMixin, ERP5TypeTestCase): ...@@ -114,7 +114,7 @@ class TestShaDirExternal(ShaDirMixin, ShaSecurityMixin, ERP5TypeTestCase):
if not annonymous: if not annonymous:
header_dict = self.header_dict header_dict = self.header_dict
connection = httplib.HTTPConnection('%s:%s' % (self.host, self.port)) connection = six.moves.http_client.HTTPConnection('%s:%s' % (self.host, self.port))
try: try:
connection.request('GET', self.path, headers=header_dict) connection.request('GET', self.path, headers=header_dict)
result = connection.getresponse() result = connection.getresponse()
...@@ -135,7 +135,7 @@ class TestShaDirExternal(ShaDirMixin, ShaSecurityMixin, ERP5TypeTestCase): ...@@ -135,7 +135,7 @@ class TestShaDirExternal(ShaDirMixin, ShaSecurityMixin, ERP5TypeTestCase):
def test_external_post_anonymous(self): def test_external_post_anonymous(self):
""" """
""" """
connection = httplib.HTTPConnection('%s:%s' % (self.host, self.port)) connection = six.moves.http_client.HTTPConnection('%s:%s' % (self.host, self.port))
header_dict = {'Content-Type': self.content_type} header_dict = {'Content-Type': self.content_type}
try: try:
connection.request('PUT', self.path, self.data, header_dict) connection.request('PUT', self.path, self.data, header_dict)
...@@ -153,7 +153,7 @@ class TestShaDirExternal(ShaDirMixin, ShaSecurityMixin, ERP5TypeTestCase): ...@@ -153,7 +153,7 @@ class TestShaDirExternal(ShaDirMixin, ShaSecurityMixin, ERP5TypeTestCase):
data[0] = json.dumps(data[0]) data[0] = json.dumps(data[0])
data = json.dumps(data) data = json.dumps(data)
connection = httplib.HTTPConnection('%s:%s' % (self.host, self.port)) connection = six.moves.http_client.HTTPConnection('%s:%s' % (self.host, self.port))
try: try:
connection.request('PUT', self.path, data, self.header_dict) connection.request('PUT', self.path, data, self.header_dict)
result = connection.getresponse() result = connection.getresponse()
......
input_file = open('big_file.log', 'r') input_file = open('big_file.log', 'r')
import httplib import six.moves.http_client
connection = httplib.HTTPConnection('192.168.242.68:12001') connection = six.moves.http_client.HTTPConnection('192.168.242.68:12001')
import base64 import base64
base64string = base64.encodestring('zope:insecure')[:-1] base64string = base64.encodestring('zope:insecure')[:-1]
......
...@@ -22,7 +22,7 @@ from urllib import splittype ...@@ -22,7 +22,7 @@ from urllib import splittype
import string import string
from urllib import FancyURLopener from urllib import FancyURLopener
from Cookie import SimpleCookie from six.moves.http_cookies import SimpleCookie
def main(): def main():
max_thread = 7 # The number of thread we want by the same time max_thread = 7 # The number of thread we want by the same time
...@@ -76,7 +76,7 @@ class URLOpener(FancyURLopener): ...@@ -76,7 +76,7 @@ class URLOpener(FancyURLopener):
def open_http(self, url, data=None): def open_http(self, url, data=None):
"""Use HTTP protocol.""" """Use HTTP protocol."""
import httplib import six.moves.http_client
user_passwd = None user_passwd = None
if type(url) is type(""): if type(url) is type(""):
host, selector = splithost(url) host, selector = splithost(url)
...@@ -104,7 +104,7 @@ class URLOpener(FancyURLopener): ...@@ -104,7 +104,7 @@ class URLOpener(FancyURLopener):
auth = base64.encodestring(user_passwd).strip() auth = base64.encodestring(user_passwd).strip()
else: else:
auth = None auth = None
h = httplib.HTTP(host) h = six.moves.http_client.HTTP(host)
if data is not None: if data is not None:
h.putrequest('POST', selector) h.putrequest('POST', selector)
h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-type', 'application/x-www-form-urlencoded')
......
...@@ -67,4 +67,5 @@ def initialize( context ): ...@@ -67,4 +67,5 @@ def initialize( context ):
# allow import of various exceptions in restricted environment # allow import of various exceptions in restricted environment
# so we can catch them in ZODB scripts and inform user nicely # so we can catch them in ZODB scripts and inform user nicely
allow_module('xmlrpclib.Fault') allow_module('xmlrpclib.Fault')
allow_module('six.moves.xmlrpc_client')
allow_module('socket.error') allow_module('socket.error')
...@@ -36,7 +36,7 @@ from AccessControl.SecurityManagement import newSecurityManager ...@@ -36,7 +36,7 @@ from AccessControl.SecurityManagement import newSecurityManager
from Acquisition import aq_base from Acquisition import aq_base
from Products.ERP5OOo.tests.utils import Validator from Products.ERP5OOo.tests.utils import Validator
from lxml import html from lxml import html
import email, urlparse, httplib import email, six.moves.urllib.parse, six.moves.http_client
from Products.Formulator.MethodField import Method from Products.Formulator.MethodField import Method
...@@ -158,9 +158,9 @@ class TestDeferredStyleBase(DeferredStyleTestCase): ...@@ -158,9 +158,9 @@ class TestDeferredStyleBase(DeferredStyleTestCase):
self.assertTrue("History%s" % extension or self.attachment_file_extension in content) self.assertTrue("History%s" % extension or self.attachment_file_extension in content)
tree = html.fromstring(content) tree = html.fromstring(content)
link, = [href for href in tree.xpath('//a/@href') if href] link, = [href for href in tree.xpath('//a/@href') if href]
relative_url =urlparse.urlparse(link) relative_url =six.moves.urllib.parse.urlparse(link)
report = self.publish(relative_url.path+"?"+relative_url.query, '%s:%s' % (self.username, self.password)) report = self.publish(relative_url.path+"?"+relative_url.query, '%s:%s' % (self.username, self.password))
self.assertEqual(httplib.OK, report.getStatus()) self.assertEqual(six.moves.http_client.OK, report.getStatus())
self.assertEqual(report.getHeader('content-type'), content_type or self.content_type) self.assertEqual(report.getHeader('content-type'), content_type or self.content_type)
def _checkDocument(self): def _checkDocument(self):
......
...@@ -49,8 +49,8 @@ import ZPublisher.HTTPRequest ...@@ -49,8 +49,8 @@ import ZPublisher.HTTPRequest
from unittest import expectedFailure from unittest import expectedFailure
import urllib import urllib
import urllib2 import urllib2
import httplib import six.moves.http_client
import urlparse import six.moves.urllib.parse
import base64 import base64
# test files' home # test files' home
...@@ -2001,7 +2001,7 @@ return result ...@@ -2001,7 +2001,7 @@ return result
reference = 'ITISAREFERENCE' reference = 'ITISAREFERENCE'
portal_url = self.portal.absolute_url() portal_url = self.portal.absolute_url()
url_split = urlparse.urlsplit(portal_url) url_split = six.moves.urllib.parse.urlsplit(portal_url)
url_dict = dict(protocol=url_split[0], url_dict = dict(protocol=url_split[0],
hostname=url_split[1]) hostname=url_split[1])
uri = '%(protocol)s://%(hostname)s' % url_dict uri = '%(protocol)s://%(hostname)s' % url_dict
...@@ -2019,7 +2019,7 @@ return result ...@@ -2019,7 +2019,7 @@ return result
# disable_cookie_login__ is required to force zope to raise Unauthorized (401) # disable_cookie_login__ is required to force zope to raise Unauthorized (401)
# then HTTPDigestAuthHandler can perform HTTP Authentication # then HTTPDigestAuthHandler can perform HTTP Authentication
response = urllib2.urlopen(request) response = urllib2.urlopen(request)
self.assertEqual(response.getcode(), httplib.OK) self.assertEqual(response.getcode(), six.moves.http_client.OK)
self.tic() self.tic()
document = self.portal.portal_catalog.getResultValue(portal_type='Spreadsheet', document = self.portal.portal_catalog.getResultValue(portal_type='Spreadsheet',
reference=reference) reference=reference)
......
...@@ -34,11 +34,11 @@ from Products.ERP5Type.tests.utils import DummyLocalizer ...@@ -34,11 +34,11 @@ from Products.ERP5Type.tests.utils import DummyLocalizer
from Products.ERP5Form.Selection import Selection from Products.ERP5Form.Selection import Selection
from Testing import ZopeTestCase from Testing import ZopeTestCase
from Products.ERP5OOo.tests.utils import Validator from Products.ERP5OOo.tests.utils import Validator
import httplib import six.moves.http_client
import lxml.html import lxml.html
import PyPDF2 import PyPDF2
HTTP_OK = httplib.OK HTTP_OK = six.moves.http_client.OK
# setting this to True allows the .publish() calls to provide tracebacks # setting this to True allows the .publish() calls to provide tracebacks
debug = False debug = False
......
...@@ -30,7 +30,7 @@ from Products.ERP5Type import WITH_LEGACY_WORKFLOW ...@@ -30,7 +30,7 @@ from Products.ERP5Type import WITH_LEGACY_WORKFLOW
from six.moves import cStringIO as StringIO from six.moves import cStringIO as StringIO
import unittest import unittest
import urllib import urllib
import httplib import six.moves.http_client
class TestUpgradeInstanceWithOldDataFs(ERP5TypeTestCase): class TestUpgradeInstanceWithOldDataFs(ERP5TypeTestCase):
...@@ -130,7 +130,7 @@ class TestUpgradeInstanceWithOldDataFs(ERP5TypeTestCase): ...@@ -130,7 +130,7 @@ class TestUpgradeInstanceWithOldDataFs(ERP5TypeTestCase):
request_method="POST", request_method="POST",
handle_errors=False handle_errors=False
) )
self.assertEqual(httplib.FOUND, ret.getStatus()) self.assertEqual(six.moves.http_client.FOUND, ret.getStatus())
alarm.Alarm_solve() alarm.Alarm_solve()
......
import sys import sys
import httplib import six.moves.http_client
if ( len(sys.argv) != 5 ): if ( len(sys.argv) != 5 ):
print("usage tinyWebClient.py host port method path") print("usage tinyWebClient.py host port method path")
...@@ -11,6 +11,6 @@ else: ...@@ -11,6 +11,6 @@ else:
info = (host, port) info = (host, port)
print("%s:%s" % info) print("%s:%s" % info)
conn = httplib.HTTPConnection("%s:%s" % info) conn = six.moves.http_client.HTTPConnection("%s:%s" % info)
conn.request(method, path) conn.request(method, path)
print(conn.getresponse().msg) print(conn.getresponse().msg)
...@@ -17,15 +17,15 @@ ...@@ -17,15 +17,15 @@
# serves files relative to the current directory. # serves files relative to the current directory.
# cgi-bin directory serves Python CGIs. # cgi-bin directory serves Python CGIs.
import BaseHTTPServer import six.moves.BaseHTTPServer
import CGIHTTPServer import six.moves.CGIHTTPServer
import time import time
import httplib import six.moves.http_client
import sys import sys
PORT = 8000 PORT = 8000
class HTTPHandler(CGIHTTPServer.CGIHTTPRequestHandler): class HTTPHandler(six.moves.CGIHTTPServer.CGIHTTPRequestHandler):
""" """
Simple Web Server that can handle query strings in a request URL and Simple Web Server that can handle query strings in a request URL and
can be stopped with a request can be stopped with a request
...@@ -47,7 +47,7 @@ class HTTPHandler(CGIHTTPServer.CGIHTTPRequestHandler): ...@@ -47,7 +47,7 @@ class HTTPHandler(CGIHTTPServer.CGIHTTPRequestHandler):
time.sleep(0.3) time.sleep(0.3)
# Carry on with the rest of the processing... # Carry on with the rest of the processing...
CGIHTTPServer.CGIHTTPRequestHandler.do_GET(self) six.moves.CGIHTTPServer.CGIHTTPRequestHandler.do_GET(self)
def do_QUIT(self): def do_QUIT(self):
self.send_response(200) self.send_response(200)
...@@ -60,7 +60,7 @@ if __name__ == '__main__': ...@@ -60,7 +60,7 @@ if __name__ == '__main__':
port = int(sys.argv[1]) port = int(sys.argv[1])
server_address = ('', port) server_address = ('', port)
httpd = BaseHTTPServer.HTTPServer(server_address, HTTPHandler) httpd = six.moves.BaseHTTPServer.HTTPServer(server_address, HTTPHandler)
print("serving at port", port) print("serving at port", port)
print("To run the entire JsUnit test suite, open") print("To run the entire JsUnit test suite, open")
......
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