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