Commit d212ebb3 authored by Denis Bilenko's avatar Denis Bilenko

greentest: (some) py3k compatibility. Original patches by Damien Churchill.

- version-neutral syntax for print and exec
- version-neutral exception handling: use exc_info()
- version-neutral exception raising: use raise A("x"), not A, "x"
- use e.args[0] instead of e[0]
- use urllib.request if urllib2 unavailable
- use http.client if httplib not available
- use socketserver if SocketServer not available
- use test.support if test_support not available
parent 32677175
......@@ -24,10 +24,10 @@ def main():
start = time.time()
conn.sendall(data)
spent = time.time() - start
print "%.2f MB/s" % (length / spent / 0x100000)
print ("%.2f MB/s" % (length / spent / 0x100000))
spent_total += spent
print "~ %.2f MB/s" % (length * N / spent_total / 0x100000)
print ("~ %.2f MB/s" % (length * N / spent_total / 0x100000))
server.stop()
......
......@@ -8,4 +8,4 @@ start = time()
for _ in xrange(N):
sleep(0)
delta = time() - start
print 'sleep(0): %.1f microseconds' % (delta * 1000000.0 / N)
print ('sleep(0): %.1f microseconds' % (delta * 1000000.0 / N))
......@@ -29,13 +29,13 @@ def test(spawn, sleep, kwargs):
for _ in xrange(N):
spawn(incr, sleep, **kwargs)
delta = time() - start
print 'spawning: %.1f microseconds per greenlet' % (delta * 1000000.0 / N)
print ('spawning: %.1f microseconds per greenlet' % (delta * 1000000.0 / N))
assert counter == 0, counter
start = time()
sleep(0)
delta = time() - start
assert counter == N, (counter, N)
print 'sleep(0): %.1f microseconds per greenlet' % (delta * 1000000.0 / N)
print ('sleep(0): %.1f microseconds per greenlet' % (delta * 1000000.0 / N))
def bench_none(options):
......@@ -45,26 +45,26 @@ def bench_none(options):
incr(noop, **kwargs)
delta = time() - start
assert counter == N, (counter, N)
print '%.2f microseconds' % (delta * 1000000.0 / N)
print ('%.2f microseconds' % (delta * 1000000.0 / N))
def bench_gevent(options):
import gevent
print 'using gevent from %s' % gevent.__file__
print ('using gevent from %s' % gevent.__file__)
from gevent import spawn, sleep
test(spawn, sleep, options.kwargs)
def bench_geventraw(options):
import gevent
print 'using gevent from %s' % gevent.__file__
print ('using gevent from %s' % gevent.__file__)
from gevent import sleep, spawn_raw
test(spawn_raw, sleep, options.kwargs)
def bench_geventpool(options):
import gevent
print 'using gevent from %s' % gevent.__file__
print ('using gevent from %s' % gevent.__file__)
from gevent import sleep
from gevent.pool import Pool
p = Pool()
......@@ -72,7 +72,7 @@ def bench_geventpool(options):
start = time()
p.join()
delta = time() - start
print 'joining: %.1f microseconds per greenlet' % (delta * 1000000.0 / N)
print ('joining: %.1f microseconds per greenlet' % (delta * 1000000.0 / N))
def bench_eventlet(options):
......@@ -82,7 +82,7 @@ def bench_eventlet(options):
if options.ignore_import_errors:
return
raise
print 'using eventlet from %s' % eventlet.__file__
print ('using eventlet from %s' % eventlet.__file__)
from eventlet.api import spawn, sleep, use_hub
if options.eventlet_hub is not None:
use_hub(options.eventlet_hub)
......@@ -96,13 +96,13 @@ def bench_eventlet1(options):
if options.ignore_import_errors:
return
raise
print 'using eventlet from %s' % eventlet.__file__
print ('using eventlet from %s' % eventlet.__file__)
from eventlet.proc import spawn_greenlet as spawn
from eventlet.api import sleep, use_hub
if options.eventlet_hub:
use_hub(options.eventlet_hub)
if options.with_kwargs:
print 'eventlet.proc.spawn_greenlet does support kwargs'
print ('eventlet.proc.spawn_greenlet does support kwargs')
return
test(spawn, sleep, options.kwargs)
......@@ -114,21 +114,21 @@ def bench_all(options):
random.shuffle(names)
for func in names:
cmd = '%s %s %s --ignore-import-errors' % (sys.executable, __file__, func)
print cmd
print (cmd)
sys.stdout.flush()
time.sleep(0.01)
if os.system(cmd):
error = 1
print '%s failed' % cmd
print
print ('%s failed' % cmd)
print ('')
for func in names:
cmd = '%s %s --with-kwargs %s --ignore-import-errors' % (sys.executable, __file__, func)
print cmd
print (cmd)
sys.stdout.flush()
if os.system(cmd):
error = 1
print '%s failed' % cmd
print
print ('%s failed' % cmd)
print ('')
if error:
sys.exit(1)
......
......@@ -275,7 +275,8 @@ def test_outer_timeout_is_not_lost(self):
try:
try:
result = self.wait(timeout=1)
except gevent.Timeout, ex:
except gevent.Timeout:
ex = sys.exc_info()[1]
assert ex is timeout, (ex, timeout)
else:
raise AssertionError('must raise Timeout (returned %r)' % (result, ))
......@@ -322,7 +323,8 @@ class GenericGetTestCase(TestCase):
timeout = gevent.Timeout(0.01)
try:
self.wait(timeout=timeout)
except gevent.Timeout, ex:
except gevent.Timeout:
ex = sys.exc_info()[1]
assert ex is timeout, (ex, timeout)
delay = time.time() - start
assert 0.01 - 0.001 <= delay < 0.01 + 0.01 + 0.1, delay
......@@ -334,7 +336,8 @@ class GenericGetTestCase(TestCase):
timeout = gevent.Timeout(0.01, exception=error)
try:
self.wait(timeout=timeout)
except RuntimeError, ex:
except RuntimeError:
ex = sys.exc_info()[1]
assert ex is error, (ex, error)
delay = time.time() - start
assert 0.01 - 0.001 <= delay < 0.01 + 0.01 + 0.1, delay
......
......@@ -13,7 +13,8 @@ class Popen(subprocess.Popen):
if hasattr(subprocess.Popen, 'send_signal'):
try:
return subprocess.Popen.send_signal(self, sig)
except Exception, ex:
except Exception:
ex = sys.exc_info()[1]
sys.stderr.write('send_signal(%s, %s) failed: %s\n' % (self.pid, sig, ex))
self.external_kill(str(ex))
else:
......@@ -21,7 +22,8 @@ class Popen(subprocess.Popen):
sys.stderr.write('Sending signal %s to %s\n' % (sig, self.pid))
try:
os.kill(self.pid, sig)
except Exception, ex:
except Exception:
ex = sys.exc_info()[1]
sys.stderr.write('Error while killing %s: %s\n' % (self.pid, ex))
self.external_kill()
else:
......
......@@ -31,7 +31,7 @@ def get_switch_expected(fullname):
True
"""
if tests.match(fullname) is not None:
print fullname
print (fullname)
return False
return True
......
......@@ -101,7 +101,7 @@ class Test(unittest.TestCase):
result = []
for name in missed[:]:
if name in not_implemented:
print 'IncompleteImplWarning: gevent.%s.%s' % (self.modname, name)
print ('IncompleteImplWarning: %s.%s' % (self.modname, name))
else:
result.append(name)
missed = result
......@@ -159,8 +159,9 @@ are missing from %r:
self.check_completeness()
for path, modname in walk_modules(include_so=True):
modname = modname.replace('gevent.', '')
exec '''def test_%s(self): self._test("gevent.%s")''' % (modname, modname)
modname = modname.replace('gevent.', '').split('.')[0]
if modname not in ('http', 'httplib', 'wsgi'):
exec ('''def test_%s(self): self._test("gevent.%s")''' % (modname, modname))
del path, modname
......
......@@ -49,7 +49,8 @@ class Test(greentest.TestCase):
try:
with Timeout(DELAY) as t:
sleep(DELAY * 2)
except Timeout, ex:
except Timeout:
ex = sys.exc_info()[1]
assert ex is t, (ex, t)
else:
raise AssertionError('must raise Timeout')
......@@ -58,7 +59,8 @@ class Test(greentest.TestCase):
try:
with Timeout(DELAY, IOError("Operation takes way too long")):
sleep(DELAY * 2)
except IOError, ex:
except IOError:
ex = sys.exc_info()[1]
assert str(ex) == "Operation takes way too long", repr(ex)
# Providing classes instead of values should be possible too:
......@@ -117,7 +119,8 @@ class Test(greentest.TestCase):
with Timeout(DELAY * 2) as t2:
try:
sleep(DELAY * 3)
except Timeout, ex:
except Timeout:
ex = sys.exc_info()[1]
assert ex is t1, (ex, t1)
assert not t1.pending, t1
assert t2.pending, t2
......@@ -127,7 +130,8 @@ class Test(greentest.TestCase):
with Timeout(DELAY) as t2:
try:
sleep(DELAY * 3)
except Timeout, ex:
except Timeout:
ex = sys.exc_info()[1]
assert ex is t2, (ex, t2)
assert t1.pending, t1
assert not t2.pending, t2
......
......@@ -31,13 +31,13 @@ error = 0
if __name__ == '__main__':
for path in modules:
print path
print (path)
sys.stdout.flush()
res = system('%s %s all' % (sys.executable, path))
if res:
error = 1
print path, 'failed'
print '-----'
print ('%s %s' % (path, 'failed'))
print ('-----')
if error:
sys.exit(1)
......@@ -5,13 +5,13 @@ loop = core.loop()
signal = signal(2, sys.stderr.write, 'INTERRUPT!')
print 'must exit immediatelly...'
print ('must exit immediatelly...')
loop.run() # must exit immediatelly
print '...and once more...'
print ('...and once more...')
loop.run() # repeating does not fail
print '..done'
print ('..done')
print 'must exit after 0.5 seconds.'
print ('must exit after 0.5 seconds.')
timer = loop.timer(0.5)
timer.start(lambda: None)
loop.run()
......
......@@ -34,8 +34,8 @@ if __name__ == '__main__':
gettotalrefcount = getattr(sys, 'gettotalrefcount', None)
called[:] = []
if gettotalrefcount is not None:
print gettotalrefcount()
print (gettotalrefcount())
main()
called[:] = []
if gettotalrefcount is not None:
print gettotalrefcount()
print (gettotalrefcount())
......@@ -20,7 +20,7 @@ if __name__ == '__main__':
allowed_modules = sys.argv[1:]
sys.path.append('.')
base = os.path.dirname(gevent.__file__)
print base
print (base)
os.chdir('..')
globs = {'myfunction': myfunction, 'gevent': gevent, 'socket': socket}
......@@ -46,14 +46,14 @@ if __name__ == '__main__':
if re.search('^\s*>>> ', open(path).read(), re.M):
try:
s = doctest.DocTestSuite(m, extraglobs=globs)
print '%s (from %s): %s tests' % (m, path, len(s._tests))
print ('%s (from %s): %s tests' % (m, path, len(s._tests)))
suite.addTest(s)
modules_count += 1
tests_count += len(s._tests)
except Exception:
traceback.print_exc()
sys.stderr.write('Failed to process %s\n\n' % path)
print 'Total: %s tests in %s modules' % (tests_count, modules_count)
print ('Total: %s tests in %s modules' % (tests_count, modules_count))
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
finally:
......
import greentest
import gevent
import sys
from gevent.event import Event, AsyncResult
DELAY = 0.01
......@@ -33,7 +34,8 @@ class TestAsyncResult(greentest.TestCase):
try:
result = e.get()
log.append(('received', result))
except Exception, ex:
except Exception:
ex = sys.exc_info()[1]
log.append(('catched', ex))
gevent.spawn(waiter)
obj = Exception()
......
......@@ -3,7 +3,10 @@ import os
import glob
from os.path import join, abspath, dirname, normpath, basename
import unittest
import urllib2
try:
import urllib2
except ImportError:
from urllib import request as urllib2
import time
import signal
import re
......@@ -23,7 +26,7 @@ for example in examples:
if 'serve_forever' not in open(example).read():
simple_examples.append(example)
print '\n'.join(examples)
print ('\n'.join(examples))
def make_test(path):
......@@ -50,7 +53,7 @@ def make_test(path):
for example in simple_examples:
test = make_test(example)
globals()[test.__name__] = test
print 'Added %s' % test.__name__
print ('Added %s' % test.__name__)
del test
......@@ -75,8 +78,8 @@ class Test_httpserver(BaseTestServer):
url = self.URL + path
try:
response = urllib2.urlopen(url)
except urllib2.HTTPError, response:
pass
except urllib2.HTTPError:
response = sys.exc_info()[1]
return '%s %s' % (response.code, response.msg), response.read()
def _test_hello(self):
......
......@@ -41,7 +41,8 @@ class Test(greentest.TestCase):
raise g.exception
try:
raise
except Exception, ex:
except Exception:
ex = sys.exc_info()[1]
assert ex is error, (ex, error)
def test2(self):
......
......@@ -397,7 +397,8 @@ class TestStuff(greentest.TestCase):
b = gevent.spawn(lambda: getcurrent().throw(ExpectedError('second')))
try:
gevent.joinall([a, b], raise_error=True)
except ExpectedError, ex:
except ExpectedError:
ex = sys.exc_info()[1]
assert 'second' in str(ex), repr(str(ex))
gevent.joinall([a, b])
......
......@@ -26,6 +26,7 @@ If either operation blocked the whole script would block and timeout.
from gevent import monkey
monkey.patch_all()
import sys
import greentest
try:
import urllib2
......@@ -56,7 +57,8 @@ class TestGreenness(greentest.TestCase):
try:
urllib2.urlopen('http://127.0.0.1:%s' % port)
assert False, 'should not get there'
except urllib2.HTTPError, ex:
except urllib2.HTTPError:
ex = sys.exc_info()[1]
assert ex.code == 501, repr(ex)
server.join(0.01)
self.assertEqual(self.httpd.request_count, 1)
......
......@@ -3,6 +3,7 @@ import gevent
from gevent import http
import greentest
import os
import sys
import socket
import errno
from test__pywsgi import read_http
......@@ -46,10 +47,12 @@ class BoundTestCase(greentest.TestCase):
def check_refused(self):
try:
self.connect()
except socket.error, ex:
if ex[0] != errno.ECONNREFUSED:
except socket.error:
ex = sys.exc_info()[1]
if ex.args[0] != errno.ECONNREFUSED:
raise
except IOError, e:
except IOError:
e = sys.exc_info()[1]
print 'WARNING: instead of ECONNREFUSED got IOError: %s' % e
......@@ -176,7 +179,8 @@ class TestDetach(BoundTestCase):
try:
try:
self.urlopen()
except Exception, ex:
except Exception:
ex = sys.exc_info()[1]
assert str(ex) == 'test done', ex
finally:
self.current = None
......
......@@ -87,15 +87,15 @@ class TestSleep(greentest.GenericWaitTestCase):
from time import sleep as real_sleep
try:
real_sleep(-0.1)
except IOError, real_ex:
pass
except IOError:
real_ex = sys.exc_info()[1]
else:
# XXX real_sleep(-0.1) hangs on win32
real_ex = "[Errno 22] Invalid argument"
try:
gevent.sleep(-0.1)
except IOError, gevent_ex:
pass
except IOError:
gevent_ex = sys.exc_info()[1]
self.assertEqual(str(gevent_ex), str(real_ex))
......
......@@ -278,7 +278,8 @@ class CommonTests(TestCase):
fd.close()
finally:
timeout.cancel()
except AssertionError, ex:
except AssertionError:
ex = sys.exc_info()[1]
if ex is not exception:
raise
......@@ -294,8 +295,9 @@ class CommonTests(TestCase):
try:
result = fd.readline()
assert not result, 'The remote side is expected to close the connection, but it send %r' % (result, )
except socket.error, ex:
if ex[0] not in CONN_ABORTED_ERRORS:
except socket.error:
ex = sys.exc_info()[1]
if ex.args[0] not in CONN_ABORTED_ERRORS:
raise
def SKIP_test_006_reject_long_urls(self):
......@@ -849,7 +851,8 @@ class ChunkedInputTests(TestCase):
fd.write(req)
try:
read_http(fd, body="pong")
except AssertionError, ex:
except AssertionError:
ex = sys.exc_info()[1]
if str(ex).startswith('Unexpected code: 400'):
if not server_implements_chunked:
print 'ChunkedNotImplementedWarning'
......@@ -897,7 +900,8 @@ class Expect100ContinueTests(TestCase):
fd.write('PUT / HTTP/1.1\r\nHost: localhost\r\nContent-length: 1025\r\nExpect: 100-continue\r\n\r\n')
try:
read_http(fd, code=417, body="failure")
except AssertionError, ex:
except AssertionError:
ex = sys.exc_info()[1]
if str(ex).startswith('Unexpected code: 400'):
if not server_implements_100continue:
print '100ContinueNotImplementedWarning'
......
......@@ -3,6 +3,7 @@ from gevent import socket
import gevent
from gevent.server import StreamServer
import errno
import sys
import os
......@@ -16,7 +17,7 @@ class SimpleStreamServer(StreamServer):
try:
method, path, rest = request_line.split(' ', 3)
except Exception:
print 'Failed to parse request line: %r' % (request_line, )
print ('Failed to parse request line: %r' % (request_line, ))
raise
if path == '/ping':
client_socket.sendall('HTTP/1.0 200 OK\r\n\r\nPONG')
......@@ -51,8 +52,9 @@ class Settings:
# attempt to send anything reset the connection
try:
self.send_request()
except socket.error, ex:
if ex[0] != errno.ECONNRESET:
except socket.error:
ex = sys.exc_info()[1]
if ex.args[0] != errno.ECONNRESET:
raise
@staticmethod
......@@ -91,8 +93,9 @@ class TestCase(greentest.TestCase):
try:
conn = self.makefile()
raise AssertionError('Connection was not refused: %r' % (conn._sock, ))
except socket.error, ex:
if ex[0] not in (errno.ECONNREFUSED, errno.EADDRNOTAVAIL):
except socket.error:
ex = sys.exc_info()[1]
if ex.args[0] not in (errno.ECONNREFUSED, errno.EADDRNOTAVAIL):
raise
def assert500(self):
......@@ -140,9 +143,9 @@ class TestCase(greentest.TestCase):
def report_netstat(self, msg):
return
print msg
print (msg)
os.system('sudo netstat -anp | grep %s' % os.getpid())
print '^^^^^'
print ('^^^^^')
def init_server(self):
self.server = self.ServerSubClass(('127.0.0.1', 0))
......@@ -257,8 +260,9 @@ class TestDefaultSpawn(TestCase):
result = conn.read()
if result:
assert result.startswith('HTTP/1.0 500 Internal Server Error'), repr(result)
except socket.error, ex:
if ex[0] != errno.ECONNRESET:
except socket.error:
ex = sys.exc_info()[1]
if ex.args[0] != errno.ECONNRESET:
raise
finally:
timeout.cancel()
......
import signal
import greentest
import gevent
import sys
class Expected(Exception):
......@@ -25,14 +26,16 @@ if hasattr(signal, 'SIGALRM'):
try:
gevent.sleep(2)
raise AssertionError('must raise Expected')
except Expected, ex:
except Expected:
ex = sys.exc_info()[1]
assert str(ex) == 'TestSignal', ex
# also let's check that alarm is persistent
signal.alarm(1)
try:
gevent.sleep(2)
raise AssertionError('must raise Expected')
except Expected, ex:
except Expected:
ex = sys.exc_info()[1]
assert str(ex) == 'TestSignal', ex
finally:
sig.cancel()
......
import os
import sys
import gevent
from gevent import socket
import greentest
......@@ -145,7 +146,8 @@ class TestCreateConnection(greentest.TestCase):
del tempsock2
try:
socket.create_connection(('localhost', 4), timeout=30, source_address=('', source_port))
except socket.error, ex:
except socket.error:
ex = sys.exc_info()[1]
if 'connection refused' not in str(ex).lower():
raise
......
......@@ -41,10 +41,10 @@ def _run(function, *args):
result = function(*args)
assert not isinstance(result, Exception), repr(result)
return result
except MISMATCH_EXCEPTIONS, ex:
return ex
except (socket.error, UnicodeError), ex:
return ex
except MISMATCH_EXCEPTIONS:
return sys.exc_info()[1]
except (socket.error, UnicodeError):
return sys.exc_info()[1]
def log_fcall(function, args):
......@@ -161,7 +161,8 @@ class TestCase(greentest.TestCase):
self.assertEqual(repr(real_result), repr(gevent_result))
else:
self.assertEqual(real_result, gevent_result)
except AssertionError, ex:
except AssertionError:
ex = sys.exc_info()[1]
if good or self.assert_equal is not True:
self.warning("WARNING in %s: %s" % (self.testcasename, ex))
else:
......
......@@ -19,6 +19,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys
import greentest
from gevent.socket import socket, error
......@@ -34,8 +35,9 @@ class TestSocketErrors(greentest.TestCase):
s = socket()
try:
s.connect(('127.0.0.1', 81))
except error, ex:
assert ex[0] == ECONNREFUSED, repr(ex)
except error:
ex = sys.exc_info()[1]
assert ex.args[0] == ECONNREFUSED, repr(ex)
assert 'refused' in str(ex).lower(), str(ex)
......
......@@ -2,7 +2,10 @@
from gevent import monkey; monkey.patch_all()
import sys
import unittest
import httplib
try:
import httplib
except ImportError:
from http import client as httplib
import socket
if not hasattr(socket, 'ssl'):
......
......@@ -26,7 +26,8 @@ class Test(unittest.TestCase):
try:
result = sock.recv(1024)
raise AssertionError('Expected timeout to be raised, instead recv() returned %r' % (result, ))
except socket.error, ex:
except socket.error:
ex = sys.exc_info()[1]
self.assertEqual(ex.args, ('timed out',))
self.assertEqual(str(ex), 'timed out')
self.assertEqual(ex[0], 'timed out')
......
......@@ -20,7 +20,8 @@ class Test(greentest.TestCase):
try:
gevent.sleep(0.001)
except SystemExit, ex:
except SystemExit:
ex = sys.exc_info()[1]
assert str(ex) == MSG, repr(str(ex))
def test_keyboard_interrupt(self):
......@@ -36,7 +37,8 @@ class Test(greentest.TestCase):
try:
gevent.sleep(0.001)
except SystemError, ex:
except SystemError:
ex = sys.exc_info()[1]
assert str(ex) == MSG, repr(str(ex))
def test_exception(self):
......
import greentest
import gevent
import sys
from gevent.hub import get_hub
DELAY = 0.01
......@@ -11,14 +12,16 @@ class TestDirectRaise(greentest.TestCase):
def test_direct_raise_class(self):
try:
raise gevent.Timeout
except gevent.Timeout, t:
except gevent.Timeout:
t = sys.exc_info()[1]
assert not t.pending, repr(t)
def test_direct_raise_instance(self):
timeout = gevent.Timeout()
try:
raise timeout
except gevent.Timeout, t:
except gevent.Timeout:
t = sys.exc_info()[1]
assert timeout is t, (timeout, t)
assert not t.pending, repr(t)
......@@ -29,7 +32,8 @@ class Test(greentest.TestCase):
try:
get_hub().switch()
raise AssertionError('Must raise Timeout')
except gevent.Timeout, ex:
except gevent.Timeout:
ex = sys.exc_info()[1]
if ex is not timeout:
raise
......
......@@ -90,7 +90,7 @@ class BaseQueueTest(unittest.TestCase, BlockingTestMixin):
def simple_queue_test(self, q):
if not q.empty():
raise RuntimeError, "Call this function with an empty queue"
raise RuntimeError("Call this function with an empty queue")
# I guess we better check things actually queue correctly a little :)
q.put(111)
q.put(333)
......@@ -218,19 +218,19 @@ class FailingQueue(Queue.Queue):
def _put(self, item):
if self.fail_next_put:
self.fail_next_put = False
raise FailingQueueException, "You Lose"
raise FailingQueueException("You Lose")
return Queue.Queue._put(self, item)
def _get(self):
if self.fail_next_get:
self.fail_next_get = False
raise FailingQueueException, "You Lose"
raise FailingQueueException("You Lose")
return Queue.Queue._get(self)
class FailingQueueTest(unittest.TestCase, BlockingTestMixin):
def failing_queue_test(self, q):
if not q.empty():
raise RuntimeError, "Call this function with an empty queue"
raise RuntimeError("Call this function with an empty queue")
for i in range(QUEUE_SIZE-1):
q.put(i)
# Test a failing non-blocking put.
......
......@@ -3,12 +3,17 @@
from gevent import monkey
monkey.patch_all()
import sys
import test_support
from test_support import (verbose, verify, TESTFN, TestSkipped,
reap_children)
test_support.requires('network')
from SocketServer import *
try:
from SocketServer import *
except ImportError:
from socketserver import *
import socket
import errno
import select
......@@ -43,20 +48,29 @@ class MyMixinServer:
self.server_close()
raise
teststring = "hello world\n"
if str is unicode:
def b(s):
return s.encode('ascii')
else:
def b(s):
return s
teststring = b("hello world\n")
NL = b('\n')
def receive(sock, n, timeout=5):
r, w, x = select.select([sock], [], [], timeout)
if sock in r:
return sock.recv(n)
else:
raise RuntimeError, "timed out on %r" % (sock,)
raise RuntimeError("timed out on %r" % (sock,))
def testdgram(proto, addr):
s = socket.socket(proto, socket.SOCK_DGRAM)
s.sendto(teststring, addr)
buf = data = receive(s, 100)
while data and '\n' not in buf:
while data and NL not in buf:
data = receive(s, 100)
buf += data
verify(buf == teststring)
......@@ -67,7 +81,8 @@ def teststream(proto, addr):
s.connect(addr)
s.sendall(teststring)
buf = data = receive(s, 100)
while data and '\n' not in buf:
while data and NL not in buf:
data = receive(s, 100)
buf += data
verify(buf == teststring)
......@@ -82,7 +97,7 @@ class ServerThread(threading.Thread):
def run(self):
class svrcls(MyMixinServer, self.__svrcls):
pass
if verbose: print "thread: creating server"
if verbose: print ("thread: creating server")
svr = svrcls(self.__addr, self.__hdlrcls)
# pull the address out of the server in case it changed
# this can happen if another process is using the port
......@@ -93,9 +108,9 @@ class ServerThread(threading.Thread):
if self.__addr != svr.socket.getsockname():
raise RuntimeError('server_address was %s, expected %s' %
(self.__addr, svr.socket.getsockname()))
if verbose: print "thread: serving three times"
if verbose: print ("thread: serving three times")
svr.serve_a_few()
if verbose: print "thread: done"
if verbose: print ("thread: done")
seed = 0
def pickport():
......@@ -138,19 +153,19 @@ def testloop(proto, servers, hdlrcls, testfunc):
for svrcls in servers:
addr = pickaddr(proto)
if verbose:
print "ADDR =", addr
print "CLASS =", svrcls
print ("ADDR = %s" % (addr,))
print ("CLASS = %s" % svrcls)
t = ServerThread(addr, svrcls, hdlrcls)
if verbose: print "server created"
if verbose: print ("server created")
t.start()
if verbose: print "server running"
if verbose: print ("server running")
for i in range(NREQ):
time.sleep(DELAY)
if verbose: print "test client", i
if verbose: print ("test client %d" % i)
testfunc(proto, addr)
if verbose: print "waiting for server"
if verbose: print ("waiting for server")
t.join()
if verbose: print "done"
if verbose: print ("done")
class ForgivingTCPServer(TCPServer):
# prevent errors if another process is using the port we want
......@@ -164,7 +179,8 @@ class ForgivingTCPServer(TCPServer):
self.server_address = host, port
TCPServer.server_bind(self)
break
except socket.error, (err, msg):
except socket.error:
err, msg = sys.exc_info()[1].args
if err != errno.EADDRINUSE:
raise
print >>sys.__stderr__, \
......@@ -216,16 +232,16 @@ class Test(unittest.TestCase):
for tcpserver in tcpservers:
n = tcpserver.__name__
exec """def test_%s(self): testloop(socket.AF_INET, [%s], MyStreamHandler, teststream)""" % (n,n)
exec ("""def test_%s(self): testloop(socket.AF_INET, [%s], MyStreamHandler, teststream)""" % (n,n))
for udpserver in udpservers:
n = udpserver.__name__
exec """def test_%s(self): testloop(socket.AF_INET, [%s], MyDatagramHandler, testdgram)""" % (n,n)
exec ("""def test_%s(self): testloop(socket.AF_INET, [%s], MyDatagramHandler, testdgram)""" % (n,n))
if hasattr(socket, 'AF_UNIX'):
for streamserver in streamservers:
n = streamserver.__name__
exec """def test_%s(self): testloop(socket.AF_UNIX, [%s], MyStreamHandler, teststream)""" % (n,n)
exec ("""def test_%s(self): testloop(socket.AF_UNIX, [%s], MyStreamHandler, teststream)""" % (n,n))
def testall():
......
......@@ -61,15 +61,17 @@ class BasicTests(unittest.TestCase):
# A crude test for the legacy API
try:
ssl.sslwrap_simple(socket.socket(socket.AF_INET))
except IOError, e:
if e[0] == 32: # broken pipe when ssl_sock.do_handshake(), this test doesn't care about that
except IOError:
e = sys.exc_info()[1]
if e.args[0] == 32: # broken pipe when ssl_sock.do_handshake(), this test doesn't care about that
pass
else:
raise
try:
ssl.sslwrap_simple(socket.socket(socket.AF_INET)._sock)
except IOError, e:
if e[0] == 32: # broken pipe when ssl_sock.do_handshake(), this test doesn't care about that
except IOError:
e = sys.exc_info()[1]
if e.args[0] == 32: # broken pipe when ssl_sock.do_handshake(), this test doesn't care about that
pass
else:
raise
......@@ -94,7 +96,7 @@ class BasicTests(unittest.TestCase):
except TypeError:
pass
else:
print "didn't raise TypeError"
print ("didn't raise TypeError")
ssl.RAND_add("this is a random string", 75.0)
def test_parse_cert(self):
......@@ -161,14 +163,16 @@ class BasicTests(unittest.TestCase):
cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx")
try:
s.connect(remote)
except ssl.SSLError, ex:
except ssl.SSLError:
ex = sys.exc_info()[1]
if "No cipher can be selected" not in str(ex):
raise
def test_ciphers(self):
try:
self._test_ciphers()
except TypeError, ex:
except TypeError:
ex = sys.exc_info()[1]
if 'sslwrap() takes at most 7 arguments (8 given)' in str(ex) and sys.version_info[:2] <= (2, 6):
pass
else:
......@@ -232,7 +236,8 @@ class NetworkedTests(unittest.TestCase):
gc.collect()
try:
os.read(fd, 0)
except OSError, ex:
except OSError:
ex = sys.exc_info()[1]
if ex[0] != errno.EBADF:
raise
......@@ -249,7 +254,8 @@ class NetworkedTests(unittest.TestCase):
count += 1
s.do_handshake()
break
except ssl.SSLError, err:
except ssl.SSLError:
err = sys.exc_info()[1]
if err.args[0] == ssl.SSL_ERROR_WANT_READ:
select.select([s], [], [])
elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
......@@ -516,14 +522,16 @@ else:
def _do_ssl_handshake(self):
try:
self.socket.do_handshake()
except ssl.SSLError, err:
except ssl.SSLError:
err = sys.exc_info()[1]
if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
ssl.SSL_ERROR_WANT_WRITE):
return
elif err.args[0] == ssl.SSL_ERROR_EOF:
return self.handle_close()
raise
except socket.error, err:
except socket.error:
err = sys.exc_info()[1]
if err.args[0] == errno.ECONNABORTED:
return self.handle_close()
else:
......@@ -710,10 +718,12 @@ else:
certfile=certfile,
ssl_version=ssl.PROTOCOL_TLSv1)
s.connect((HOST, server.port))
except ssl.SSLError, x:
except ssl.SSLError:
x = sys.exc_info()[1]
if test_support.verbose:
sys.stdout.write("\nSSLError is %s\n" % x[1])
except socket.error, x:
except socket.error:
x = sys.exc_info()[1]
if test_support.verbose:
sys.stdout.write("\nsocket.error is %s\n" % x[1])
else:
......@@ -816,8 +826,9 @@ else:
except ssl.SSLError:
if expect_success:
raise
except socket.error, e:
if expect_success or e[0] != errno.ECONNRESET:
except socket.error:
e = sys.exc_info()[1]
if expect_success or e.args[0] != errno.ECONNRESET:
raise
else:
if not expect_success:
......@@ -958,7 +969,8 @@ else:
sys.stdout.write("\n")
try:
try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True)
except (ssl.SSLError, socket.error), x:
except (ssl.SSLError, socket.error):
x = sys.exc_info()[1]
# this fails on some older versions of OpenSSL (0.9.7l, for instance)
if test_support.verbose:
sys.stdout.write(
......@@ -1186,7 +1198,7 @@ else:
]
if bytearray is None:
recv_methods = recv_methods[:-2]
data_prefix = u"PREFIX_"
data_prefix = unicode("PREFIX_")
for meth_name, send_meth, expect_success, args in send_methods:
indata = data_prefix + meth_name
......@@ -1203,7 +1215,8 @@ else:
indata[:20], len(indata)
)
)
except ValueError, e:
except ValueError:
e = sys.exc_info()[1]
if expect_success:
raise test_support.TestFailed(
"Failed to send with method <<%s>>; "
......@@ -1232,7 +1245,8 @@ else:
indata[:20], len(indata)
)
)
except ValueError, e:
except ValueError:
e = sys.exc_info()[1]
if expect_success:
raise test_support.TestFailed(
"Failed to receive with method <<%s>>; "
......@@ -1285,7 +1299,8 @@ else:
# Will attempt handshake and time out
try:
ssl.wrap_socket(c)
except ssl.SSLError, ex:
except ssl.SSLError:
ex = sys.exc_info()[1]
if 'timed out' not in str(ex):
raise
finally:
......@@ -1297,7 +1312,8 @@ else:
# Will attempt handshake and time out
try:
c.connect((host, port))
except ssl.SSLError, ex:
except ssl.SSLError:
ex = sys.exc_info()[1]
if 'timed out' not in str(ex):
raise
finally:
......
......@@ -172,12 +172,13 @@ def bind_port(sock, host='', preferred_port=54321):
if port == 0:
port = sock.getsockname()[1]
return port
except socket.error, (err, msg):
except socket.error:
err = sys.exc_info()[1]
if err != errno.EADDRINUSE:
raise
print >>sys.__stderr__, \
' WARNING: failed to listen on port %d, trying another' % port
raise TestFailed, 'unable to find port to listen on'
raise TestFailed('unable to find port to listen on')
FUZZ = 1e-6
......@@ -248,10 +249,9 @@ else:
except UnicodeEncodeError:
pass
else:
print \
'WARNING: The filename %r CAN be encoded by the filesystem. ' \
'Unicode filename tests may not be effective' \
% TESTFN_UNICODE_UNENCODEABLE
sys.stderr.write('WARNING: The filename %r CAN be encoded by the filesystem. '
'Unicode filename tests may not be effective'
% TESTFN_UNICODE_UNENCODEABLE)
# Make sure we can write to TESTFN, try in /tmp if we can't
fp = None
......@@ -307,7 +307,7 @@ def vereq(a, b):
"""
if not (a == b):
raise TestFailed, "%r == %r" % (a, b)
raise TestFailed("%r == %r" % (a, b))
def sortdict(dict):
"Like repr(dict), but in sorted order."
......@@ -323,7 +323,7 @@ def check_syntax(statement):
except SyntaxError:
pass
else:
print 'Missing SyntaxError: "%s"' % statement
print ('Missing SyntaxError: "%s"' % statement)
def open_urlresource(url):
import urllib, urlparse
......@@ -390,7 +390,10 @@ _2G = 2 * _1G
class _Dummy:
def __getslice__(self, i, j):
return j
MAX_Py_ssize_t = _Dummy()[:]
try:
MAX_Py_ssize_t = _Dummy()[:]
except TypeError:
MAX_Py_ssize_t = sys.maxsize
def set_memlimit(limit):
import re
......@@ -542,7 +545,7 @@ def run_doctest(module, verbosity=None):
finally:
sys.stdout = save_stdout
if verbose:
print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t)
print ('doctest (%s) ... %d tests with zero failures' % (module.__name__, t))
return f, t
#=======================================================================
......@@ -559,13 +562,13 @@ def threading_cleanup(num_active, num_limbo):
_MAX_COUNT = 10
count = 0
while len(threading._active) != num_active and count < _MAX_COUNT:
print threading._active
print (threading._active)
count += 1
time.sleep(0.1)
count = 0
while len(threading._limbo) != num_limbo and count < _MAX_COUNT:
print threading._limbo
print (threading._limbo)
count += 1
time.sleep(0.1)
......
......@@ -24,10 +24,10 @@ def task(ident):
delay = random.random() * numtasks * 0.02
rmutex.release()
if verbose:
print 'task', ident, 'will run for', round(delay, 2), 'sec'
print ('task %s will run for %d sec' % (ident, round(delay, 2)))
time.sleep(delay)
if verbose:
print 'task', ident, 'done'
print ('task %s done' % ident)
mutex.acquire()
running = running - 1
if running == 0:
......@@ -40,7 +40,7 @@ def newtask():
mutex.acquire()
next_ident = next_ident + 1
if verbose:
print 'creating task', next_ident
print ('creating task %s' % next_ident)
thread.start_new_thread(task, (next_ident,))
running = running + 1
mutex.release()
......@@ -48,9 +48,9 @@ def newtask():
for i in range(numtasks):
newtask()
print 'waiting for all tasks to complete'
print ('waiting for all tasks to complete')
done.acquire()
print 'all tasks done'
print ('all tasks done')
class barrier:
def __init__(self, n):
......@@ -92,13 +92,13 @@ def task2(ident):
delay = random.random() * numtasks * 0.02
rmutex.release()
if verbose:
print 'task', ident, 'will run for', round(delay, 2), 'sec'
print ('task %s will run for %d sec' % (ident, round(delay, 2)))
time.sleep(delay)
if verbose:
print 'task', ident, 'entering barrier', i
print ('task %s entering barrier %s' % (ident, i))
bar.enter()
if verbose:
print 'task', ident, 'leaving barrier', i
print ('task %s leaving barrier %s' % (ident, i))
mutex.acquire()
running -= 1
# Must release mutex before releasing done, else the main thread can
......@@ -109,25 +109,25 @@ def task2(ident):
if finished:
done.release()
print '\n*** Barrier Test ***'
print ('\n*** Barrier Test ***')
if done.acquire(0):
raise ValueError, "'done' should have remained acquired"
raise ValueError("'done' should have remained acquired")
bar = barrier(numtasks)
running = numtasks
for i in range(numtasks):
thread.start_new_thread(task2, (i,))
done.acquire()
print 'all tasks done'
print ('all tasks done')
if hasattr(thread, 'stack_size'):
# not all platforms support changing thread stack size
print '\n*** Changing thread stack size ***'
print ('\n*** Changing thread stack size ***')
if thread.stack_size() != 0:
raise ValueError, "initial stack_size not 0"
raise ValueError("initial stack_size not 0")
thread.stack_size(0)
if thread.stack_size() != 0:
raise ValueError, "stack_size not reset to default"
raise ValueError("stack_size not reset to default")
from os import name as os_name
if os_name in ("nt", "os2", "posix"):
......@@ -136,10 +136,10 @@ if hasattr(thread, 'stack_size'):
try:
thread.stack_size(4096)
except ValueError:
print 'caught expected ValueError setting stack_size(4096)'
print ('caught expected ValueError setting stack_size(4096)')
except thread.error:
tss_supported = 0
print 'platform does not support changing thread stack size'
print ('platform does not support changing thread stack size')
if tss_supported:
failed = lambda s, e: s != e
......@@ -147,18 +147,18 @@ if hasattr(thread, 'stack_size'):
for tss in (262144, 0x100000, 0):
thread.stack_size(tss)
if failed(thread.stack_size(), tss):
raise ValueError, fail_msg % tss
print 'successfully set stack_size(%d)' % tss
raise ValueError(fail_msg % tss)
print ('successfully set stack_size(%d)' % tss)
for tss in (262144, 0x100000):
print 'trying stack_size = %d' % tss
print ('trying stack_size = %d' % tss)
next_ident = 0
for i in range(numtasks):
newtask()
print 'waiting for all tasks to complete'
print ('waiting for all tasks to complete')
done.acquire()
print 'all tasks done'
print ('all tasks done')
# reset stack size to default
thread.stack_size(0)
......@@ -3,7 +3,10 @@
from gevent import monkey; monkey.patch_all()
import unittest
from doctest import DocTestSuite
from test import test_support
try:
from test import test_support
except ImportError:
from test import support as test_support
import threading
import weakref
import gc
......
......@@ -51,11 +51,13 @@ import platform
try:
import sqlite3
except ImportError, ex:
except ImportError:
ex = sys.exc_info()
sys.stderr.write('Failed to import sqlite3: %s\n' % ex)
try:
import pysqlite2.dbapi2 as sqlite3
except ImportError, ex:
except ImportError:
ex = sys.exc_info()
sys.stderr.write('Failed to import pysqlite2.dbapi2: %s\n' % ex)
sqlite3 = None
......@@ -75,7 +77,8 @@ def store_record(database_path, table, dictionary, _added_colums_per_db={}):
conn.execute(sql)
conn.commit()
_added_columns.add(key)
except sqlite3.OperationalError, ex:
except sqlite3.OperationalError:
ex = sys.exc_info()
if 'duplicate column' not in str(ex).lower():
raise
sql = 'insert or replace into %s (%s) values (%s)' % (table, ', '.join(keys), ', '.join(':%s' % key for key in keys))
......@@ -83,7 +86,7 @@ def store_record(database_path, table, dictionary, _added_colums_per_db={}):
try:
cursor.execute(sql, dictionary)
except sqlite3.Error:
print 'sql=%r\ndictionary=%r' % (sql, dictionary)
print ('sql=%r\ndictionary=%r' % (sql, dictionary))
raise
conn.commit()
return cursor.lastrowid
......@@ -94,13 +97,13 @@ def delete_record(database_path, table, dictionary, _added_colums_per_db={}):
return
keys = dictionary.keys()
conn = sqlite3.connect(database_path)
print 'deleting %s from database' % (dictionary, )
print ('deleting %s from database' % (dictionary, ))
sql = 'delete from %s where %s' % (table, ' AND '.join('%s=:%s' % (key, key) for key in keys))
cursor = conn.cursor()
try:
cursor.execute(sql, dictionary)
except sqlite3.Error:
print 'sql=%r\ndictionary=%r' % (sql, dictionary)
print ('sql=%r\ndictionary=%r' % (sql, dictionary))
raise
conn.commit()
return cursor.lastrowid
......@@ -246,7 +249,7 @@ def run_subprocess(args, options):
def killer():
retcode.append('TIMEOUT')
print >> sys.stderr, 'Killing %s (%s) because of timeout' % (popen.pid, args)
sys.stderr.write('Killing %s (%s) because of timeout\n' % (popen.pid, args))
popen.kill()
timeout = Timer(options.timeout, killer)
......@@ -300,15 +303,15 @@ def spawn_subprocess(args, options, base_params):
else:
if not output_printed and options.verbosity >= -1:
sys.stdout.write(output)
print '%s failed with code %s' % (' '.join(args), retcode)
print ('%s failed with code %s' % (' '.join(args), retcode))
elif retcode == 0:
if not output_printed and options.verbosity >= 1:
sys.stdout.write(output)
if options.verbosity >= 0:
print '%s passed' % ' '.join(args)
print ('%s passed' % ' '.join(args))
success = True
else:
print '%s timed out' % ' '.join(args)
print ('%s timed out' % ' '.join(args))
if options.db:
params['output'] = output
params['retcode'] = retcode
......@@ -340,12 +343,12 @@ def spawn_subprocesses(options, args):
traceback.print_exc()
if options.db:
try:
print '-' * 80
print ('-' * 80)
if print_stats(options):
success = False
except sqlite3.OperationalError:
traceback.print_exc()
print 'To view stats again for this run, use %s --stats --runid %s --db %s' % (sys.argv[0], options.runid, options.db)
print ('To view stats again for this run, use %s --stats --runid %s --db %s' % (sys.argv[0], options.runid, options.db))
if not success:
sys.exit(1)
......@@ -415,7 +418,9 @@ def get_warning_stats(output):
counter.setdefault(warning, 0)
counter[warning] += 1
items = counter.items()
items.sort(key=lambda (a, b): -b)
def sortkey(x):
return -x[1]
items.sort(key=sortkey)
result = []
for name, count in items:
if count == 1:
......@@ -447,7 +452,9 @@ def get_traceback_stats(output, test):
counter[error] += 1
traceback_count -= 1
items = counter.items()
items.sort(key=lambda (a, b): -b)
def sortkey(x):
return -x[1]
items.sort(key=sortkey)
if traceback_count > 0:
items.append(('other traceback', traceback_count))
result = []
......@@ -473,14 +480,14 @@ def print_stats(options):
cursor = db.cursor()
if options.runid is None:
options.runid = cursor.execute('select runid from test order by started_at desc limit 1').fetchall()[0][0]
print 'Using the latest runid: %s' % options.runid
print ('Using the latest runid: %s' % options.runid)
total = len(get_testcases(cursor, options.runid))
failed, errors = get_failed_testcases(cursor, options.runid)
timedout = get_testcases(cursor, options.runid, 'TIMEOUT')
for test, output, retcode in cursor.execute('select test, output, retcode from test where runid=?', (options.runid, )):
info, skipped = get_info(output or '', test)
if info:
print '%s: %s' % (test, info)
print ('%s: %s' % (test, info))
if retcode == 'TIMEOUT':
for testcase in timedout:
if testcase.startswith(test + '.'):
......@@ -498,18 +505,18 @@ def print_stats(options):
total += 1
if failed:
failed.sort()
print 'FAILURES: '
print ('FAILURES: ')
for testcase in failed:
error = errors.get(testcase)
if error:
error = repr(error)[1:-1][:100]
print ' - %s: %s' % (testcase, error)
print (' - %s: %s' % (testcase, error))
else:
print ' - %s' % (testcase, )
print (' - %s' % (testcase, ))
if timedout:
print 'TIMEOUTS: '
print ' - ' + '\n - '.join(timedout)
print '%s testcases passed; %s failed; %s timed out' % (total, len(failed), len(timedout))
print ('TIMEOUTS: ')
print (' - ' + '\n - '.join(timedout))
print ('%s testcases passed; %s failed; %s timed out' % (total, len(failed), len(timedout)))
if failed or timedout:
return True
return False
......@@ -535,7 +542,7 @@ def main():
if options.db:
if sqlite3:
options.db = os.path.abspath(options.db)
print 'Using the database: %s' % options.db
print ('Using the database: %s' % options.db)
else:
sys.stderr.write('Cannot access the database %r: no sqlite3 module found.\n' % (options.db, ))
options.db = False
......@@ -556,7 +563,7 @@ def main():
except ImportError:
import random
options.runid = str(random.random())[2:]
print 'Generated runid: %s' % (options.runid, )
print ('Generated runid: %s' % (options.runid, ))
if options.record:
run_tests(options, args)
else:
......
......@@ -2,6 +2,7 @@ import unittest
from gevent import socket
import gevent
import errno
import sys
import os
from test__server import SimpleStreamServer
......@@ -19,8 +20,9 @@ class Test(unittest.TestCase):
try:
conn = self.makefile()
raise AssertionError('Connection was not refused: %r' % (conn._sock, ))
except socket.error, ex:
if ex[0] != errno.ECONNREFUSED:
except socket.error:
ex = sys.exc_info()[1]
if ex.args[0] != errno.ECONNREFUSED:
raise
def assertRequestSucceeded(self):
......
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