Commit 158fd479 authored by Denis Bilenko's avatar Denis Bilenko

greentest: pep8

parent e8994144
......@@ -13,9 +13,9 @@ def main():
server = StreamServer(("127.0.0.1", 0), recvall)
server.start()
length = 50*0x100000
length = 50 * 0x100000
data = "x" * length
spent_total = 0
N = 10
......@@ -31,6 +31,5 @@ def main():
server.stop()
if __name__=="__main__":
if __name__ == "__main__":
main()
......@@ -3,9 +3,9 @@ from gevent import sleep
N = 10000
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)
......@@ -6,6 +6,7 @@ import random
import traceback
from time import time
def init():
global N, counter
N = 10000
......@@ -13,26 +14,30 @@ def init():
init()
def incr(sleep, **kwargs):
global counter
counter += 1
sleep(0)
def noop(p):
pass
def test(spawn, sleep, kwargs):
start = time()
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):
kwargs = options.kwargs
......@@ -41,7 +46,8 @@ 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
......@@ -49,12 +55,14 @@ def bench_gevent(options):
from gevent import spawn, sleep
test(spawn, sleep, options.kwargs)
def bench_geventraw(options):
import gevent
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__
......@@ -65,7 +73,8 @@ 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):
try:
......@@ -80,6 +89,7 @@ def bench_eventlet(options):
use_hub(options.eventlet_hub)
test(spawn, sleep, options.kwargs)
def bench_eventlet1(options):
try:
import eventlet
......@@ -97,6 +107,7 @@ def bench_eventlet1(options):
return
test(spawn, sleep, options.kwargs)
def bench_all(options):
import time
error = 0
......@@ -122,16 +133,19 @@ def bench_all(options):
if error:
sys.exit(1)
def all():
result = [x for x in globals() if x.startswith('bench_') and x!='bench_all']
result.sort(key = lambda x: globals()[x].func_code.co_firstlineno)
result = [x for x in globals() if x.startswith('bench_') and x != 'bench_all']
result.sort(key=lambda x: globals()[x].func_code.co_firstlineno)
result = [x.replace('bench_', '') for x in result]
return result
def all_functions():
return [globals()['bench_%s' % x] for x in all()]
if __name__=='__main__':
if __name__ == '__main__':
USAGE = 'USAGE: python %s [--with-kwargs] [--eventlet-hub HUB] %s' % (sys.argv[0], '|'.join(all()))
if not sys.argv[1:]:
sys.exit(USAGE)
......@@ -154,4 +168,3 @@ if __name__=='__main__':
sys.exit(USAGE)
function = globals()['bench_' + args[0]]
function(options)
......@@ -44,7 +44,7 @@ class TestCase(unittest.TestCase):
_switch_count = None
def setUp(self):
gevent.sleep(0) # switch at least once to setup signal handlers
gevent.sleep(0) # switch at least once to setup signal handlers
if hasattr(gevent.core, '_event_count'):
self._event_count = (gevent.core._event_count(), gevent.core._event_count_active())
hub = gevent.hub.get_hub()
......@@ -154,7 +154,7 @@ class TestCase(unittest.TestCase):
def extract_re(self, regex, **kwargs):
assert self.stderr is not None
m = re.search(regex, self.stderr, re.DOTALL|re.M)
m = re.search(regex, self.stderr, re.DOTALL | re.M)
if m is None:
raise AssertionError('%r did not match:\n%r' % (regex, self.stderr))
for key, expected_value in kwargs.items():
......@@ -168,13 +168,13 @@ class TestCase(unittest.TestCase):
if DEBUG:
ate = '\n#ATE#: ' + self.stderr[m.start(0):m.end(0)].replace('\n', '\n#ATE#: ') + '\n'
sys.__stderr__.write(ate)
self.stderr = self.stderr[:m.start(0)] + self.stderr[m.end(0)+1:]
self.stderr = self.stderr[:m.start(0)] + self.stderr[m.end(0) + 1:]
main = unittest.main
_original_Hub = gevent.hub.Hub
class CountingHub(_original_Hub):
switch_count = 0
......@@ -273,4 +273,3 @@ def walk_modules(basedir=None, modpath=None):
if not fn.endswith('.py') or fn in ['__init__.py', 'core.py']:
continue
yield path, modpath + fn[:-3]
......@@ -10,18 +10,19 @@ missing_modules = {
'test_httpservers': ['2.4', '2.5'],
'test_ftplib': ['2.4', '2.5'],
'test_wsgiref': ['2.4'],
'test_socket_ssl': ['2.6', '2.7']
}
'test_socket_ssl': ['2.6', '2.7']}
class ContainsAll(object):
def __contains__(self, item):
return True
def patch_all(timeout=None):
from gevent import monkey
monkey.patch_all(aggressive=True)
import unittest, greentest
import unittest
import greentest
unittest.TestCase = greentest.TestCase
if timeout is not None:
unittest.TestCase.__timeout__ = timeout
......@@ -45,7 +46,7 @@ def prepare_stdlib_test(filename):
# XXX importing just to find where it resides; need a function that just returns the path
package = __import__('test.%s' % name)
except:
if version in missing_modules.get(name, []):
if version in missing_modules.get(name, []):
sys.exit(0)
raise
......
......@@ -4,6 +4,7 @@ import subprocess
import signal
from subprocess import *
class Popen(subprocess.Popen):
def send_signal(self, sig):
......@@ -46,4 +47,3 @@ class Popen(subprocess.Popen):
os.system('taskkill /f /pid %s' % self.pid)
else:
sys.stderr.write('Cannot kill on this platform. Please kill %s\n' % self.pid)
......@@ -25,8 +25,7 @@ disabled_tests = [
# this test seems to have a bug which makes it fail with error: (107, 'Transport endpoint is not connected')
# (they create TCP socket, not UDP)
'test_socket.UDPTimeoutTest.testUDPTimeout'
]
'test_socket.UDPTimeoutTest.testUDPTimeout']
if sys.version_info[:2] < (2, 7):
# On Python 2.6, this test fails even without monkey patching
......@@ -43,4 +42,3 @@ def disable_tests_in_the_source(source, name):
source, n = re.subn(testcase, 'XXX' + testcase, source)
print >> sys.stderr, 'Removed %s (%d)' % (testcase, n)
return source
......@@ -25,10 +25,12 @@ from gevent import core, util, socket
DELAY = 0.1
class Test(greentest.TestCase):
def test_killing_dormant(self):
state = []
def test():
try:
state.append('start')
......@@ -38,8 +40,9 @@ class Test(greentest.TestCase):
# catching GreenletExit
pass
state.append('finished')
g = gevent.spawn(test)
gevent.sleep(DELAY/2)
gevent.sleep(DELAY / 2)
assert state == ['start'], state
g.kill(block=True)
# will not get there, unless switching is explicitly scheduled by kill
......@@ -99,6 +102,5 @@ class TestTimers(greentest.TestCase):
assert self.lst == [], self.lst
if __name__=='__main__':
if __name__ == '__main__':
greentest.main()
......@@ -27,26 +27,28 @@ import time
from gevent import sleep, Timeout
DELAY = 0.04
class Error(Exception):
pass
class Test(greentest.TestCase):
def test_api(self):
# Nothing happens if with-block finishes before the timeout expires
t = Timeout(DELAY*2)
t = Timeout(DELAY * 2)
assert not t.pending, repr(t)
with t:
assert t.pending, repr(t)
sleep(DELAY)
# check if timer was actually cancelled
assert not t.pending, repr(t)
sleep(DELAY*2)
sleep(DELAY * 2)
# An exception will be raised if it's not
try:
with Timeout(DELAY) as t:
sleep(DELAY*2)
sleep(DELAY * 2)
except Timeout, ex:
assert ex is t, (ex, t)
else:
......@@ -55,23 +57,23 @@ class Test(greentest.TestCase):
# You can customize the exception raised:
try:
with Timeout(DELAY, IOError("Operation takes way too long")):
sleep(DELAY*2)
sleep(DELAY * 2)
except IOError, ex:
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:
try:
with Timeout(DELAY, ValueError):
sleep(DELAY*2)
sleep(DELAY * 2)
except ValueError:
pass
try:
1/0
1 / 0
except:
try:
with Timeout(DELAY, sys.exc_info()[0]):
sleep(DELAY*2)
sleep(DELAY * 2)
raise AssertionError('should not get there')
raise AssertionError('should not get there')
except ZeroDivisionError:
......@@ -82,15 +84,15 @@ class Test(greentest.TestCase):
# It's possible to cancel the timer inside the block:
with Timeout(DELAY) as timer:
timer.cancel()
sleep(DELAY*2)
sleep(DELAY * 2)
# To silent the exception before exiting the block, pass False as second parameter.
XDELAY=0.1
XDELAY = 0.1
start = time.time()
with Timeout(XDELAY, False):
sleep(XDELAY*2)
delta = (time.time()-start)
assert delta<XDELAY*2, delta
sleep(XDELAY * 2)
delta = (time.time() - start)
assert delta < XDELAY * 2, delta
# passing None as seconds disables the timer
with Timeout(None):
......@@ -100,31 +102,31 @@ class Test(greentest.TestCase):
def test_ref(self):
err = Error()
err_ref = weakref.ref(err)
with Timeout(DELAY*2, err):
with Timeout(DELAY * 2, err):
sleep(DELAY)
del err
assert not err_ref(), repr(err_ref())
def test_nested_timeout(self):
with Timeout(DELAY, False):
with Timeout(DELAY*2, False):
sleep(DELAY*3)
with Timeout(DELAY * 2, False):
sleep(DELAY * 3)
raise AssertionError('should not get there')
with Timeout(DELAY) as t1:
with Timeout(DELAY*2) as t2:
with Timeout(DELAY * 2) as t2:
try:
sleep(DELAY*3)
sleep(DELAY * 3)
except Timeout, ex:
assert ex is t1, (ex, t1)
assert not t1.pending, t1
assert t2.pending, t2
assert not t2.pending, t2
with Timeout(DELAY*2) as t1:
with Timeout(DELAY * 2) as t1:
with Timeout(DELAY) as t2:
try:
sleep(DELAY*3)
sleep(DELAY * 3)
except Timeout, ex:
assert ex is t2, (ex, t2)
assert t1.pending, t1
......@@ -132,6 +134,5 @@ class Test(greentest.TestCase):
assert not t1.pending, t1
if __name__=='__main__':
if __name__ == '__main__':
greentest.main()
......@@ -19,12 +19,14 @@ class Test(greentest.TestCase):
def test(self):
server = backdoor.BackdoorServer(('127.0.0.1', 0))
server.start()
def connect():
conn = socket.create_connection(('127.0.0.1', server.server_port))
read_until(conn, '>>> ')
conn.sendall('2+2\r\n')
line = conn.makefile().readline()
assert line.strip() == '4', repr(line)
jobs = [gevent.spawn(connect) for _ in xrange(10)]
gevent.joinall(jobs)
server.kill()
......
......@@ -3,6 +3,7 @@ import glob
import mysubprocess as subprocess
import time
def system(command):
p = subprocess.Popen(command, shell=True)
try:
......@@ -40,4 +41,3 @@ if __name__ == '__main__':
if error:
sys.exit(1)
......@@ -2,6 +2,7 @@ import gevent
called = []
def f():
called.append(1)
......
......@@ -39,4 +39,3 @@ class TestSwitch(greentest.TestCase):
if __name__ == '__main__':
greentest.main()
......@@ -10,6 +10,7 @@ from greentest import walk_modules
# Ignore tracebacks: ZeroDivisionError
def myfunction(*args, **kwargs):
pass
......
......@@ -4,21 +4,25 @@ from gevent.event import Event, AsyncResult
DELAY = 0.01
class TestEventWait(greentest.GenericWaitTestCase):
def wait(self, timeout):
Event().wait(timeout=timeout)
class TestAsyncResultWait(greentest.GenericWaitTestCase):
def wait(self, timeout):
AsyncResult().wait(timeout=timeout)
class TestAsyncResultGet(greentest.GenericGetTestCase):
def wait(self, timeout):
AsyncResult().get(timeout=timeout)
class TestAsyncResult(greentest.TestCase):
def test_set_exc(self):
......@@ -41,7 +45,7 @@ class TestAsyncResult(greentest.TestCase):
event1 = AsyncResult()
event2 = AsyncResult()
g = gevent.spawn_later(DELAY/2.0, event1.set, 'hello event1')
g = gevent.spawn_later(DELAY / 2.0, event1.set, 'hello event1')
t = gevent.Timeout.start_new(0, ValueError('interrupted'))
try:
try:
......@@ -58,7 +62,7 @@ class TestAsyncResult(greentest.TestCase):
class TestAsync_ResultAsLinkTarget(greentest.TestCase):
def test_set(self):
g = gevent.spawn(lambda : 1)
g = gevent.spawn(lambda: 1)
s1, s2, s3 = AsyncResult(), AsyncResult(), AsyncResult()
g.link(s1)
g.link_value(s2)
......@@ -92,14 +96,16 @@ class TestEvent_SetThenClear(greentest.TestCase):
for t in waiters:
t.join()
class TestEvent_SetThenClear100(TestEvent_SetThenClear):
N = 100
class TestEvent_SetThenClear1000(TestEvent_SetThenClear):
N = 1000
X = object()
if __name__=='__main__':
if __name__ == '__main__':
greentest.main()
......@@ -25,13 +25,14 @@ for example in examples:
print '\n'.join(examples)
def make_test(path):
if ' ' in path:
path = '"%s"' % path
class TestExample(unittest.TestCase):
def test(self):
exe = sys.executable
if ' ' in exe:
......@@ -82,7 +83,7 @@ class Test_httpserver(BaseTestServer):
status, data = self.read('/')
self.assertEqual(status, '200 OK')
self.assertEqual(data, "<b>hello world</b>")
def _test_not_found(self):
status, data = self.read('/xxx')
self.assertEqual(status, '404 Not Found')
......
......@@ -4,12 +4,14 @@ import greentest
sys.exc_clear()
class ExpectedError(Exception):
pass
expected_error = ExpectedError('expected exception in hello')
def hello():
assert sys.exc_info() == (None, None, None), sys.exc_info()
raise expected_error
......
......@@ -21,8 +21,11 @@ from greentest import TestCase, main
import gevent
from gevent import socket
class TestGreenIo(TestCase):
def test_close_with_makefile(self):
def accept_close_early(listener):
# verify that the makefile and the socket are truly independent
# by closing the socket prior to using the made file
......@@ -72,9 +75,9 @@ class TestGreenIo(TestCase):
did_it_work(server)
server_greenlet.kill(block=True)
def test_del_closes_socket(self):
timer = gevent.Timeout.start_new(0.5)
def accept_once(listener):
# delete/overwrite the original conn
# object, only keeping the file object around
......@@ -88,6 +91,7 @@ class TestGreenIo(TestCase):
assert r is None, r
finally:
listener.close()
server = socket.tcp_listener(('0.0.0.0', 0))
killer = gevent.spawn(accept_once, server)
client = socket.create_connection(('127.0.0.1', server.getsockname()[1]))
......
This diff is collapsed.
......@@ -5,6 +5,7 @@ from gevent import pool
DELAY = 0.1
class Undead(object):
def __init__(self):
......@@ -17,60 +18,62 @@ class Undead(object):
except:
self.shot_count += 1
class Test(greentest.TestCase):
def test_basic(self):
DELAY = 0.05
s = pool.GreenletSet()
s.spawn(gevent.sleep, DELAY)
assert len(s)==1, s
s.spawn(gevent.sleep, DELAY*2.)
assert len(s)==2, s
gevent.sleep(DELAY*3./2.)
assert len(s)==1, s
assert len(s) == 1, s
s.spawn(gevent.sleep, DELAY * 2.)
assert len(s) == 2, s
gevent.sleep(DELAY * 3. / 2.)
assert len(s) == 1, s
gevent.sleep(DELAY)
assert not s, s
def test_waitall(self):
s = pool.GreenletSet()
s.spawn(gevent.sleep, DELAY)
s.spawn(gevent.sleep, DELAY*2)
assert len(s)==2, s
s.spawn(gevent.sleep, DELAY * 2)
assert len(s) == 2, s
start = time.time()
s.join(raise_error=True)
delta = time.time() - start
assert not s, s
assert len(s)==0, s
assert DELAY*1.9 <= delta <= DELAY*2.5, (delta, DELAY)
assert len(s) == 0, s
assert DELAY * 1.9 <= delta <= DELAY * 2.5, (delta, DELAY)
def test_kill_block(self):
s = pool.GreenletSet()
s.spawn(gevent.sleep, DELAY)
s.spawn(gevent.sleep, DELAY*2)
assert len(s)==2, s
s.spawn(gevent.sleep, DELAY * 2)
assert len(s) == 2, s
start = time.time()
s.kill(block=True)
assert not s, s
assert len(s)==0, s
assert len(s) == 0, s
delta = time.time() - start
assert delta < DELAY*0.8, delta
assert delta < DELAY * 0.8, delta
def test_kill_noblock(self):
s = pool.GreenletSet()
s.spawn(gevent.sleep, DELAY)
s.spawn(gevent.sleep, DELAY*2)
assert len(s)==2, s
s.spawn(gevent.sleep, DELAY * 2)
assert len(s) == 2, s
s.kill(block=False)
assert len(s)==2, s
assert len(s) == 2, s
gevent.sleep(0)
assert not s, s
assert len(s)==0, s
assert len(s) == 0, s
def test_kill_fires_once(self):
u1 = Undead()
u2 = Undead()
p1 = gevent.spawn(u1)
p2 = gevent.spawn(u2)
def check(count1, count2):
assert p1, p1
assert p2, p2
......@@ -78,6 +81,7 @@ class Test(greentest.TestCase):
assert not p2.dead, p2
self.assertEqual(u1.shot_count, count1)
self.assertEqual(u2.shot_count, count2)
gevent.sleep(0.01)
s = pool.GreenletSet([p1, p2])
assert len(s) == 2, s
......@@ -103,8 +107,8 @@ class Test(greentest.TestCase):
check(1, 1)
def test_killall_subclass(self):
p1 = GreenletSubclass.spawn(lambda : 1/0)
p2 = GreenletSubclass.spawn(lambda : gevent.sleep(10))
p1 = GreenletSubclass.spawn(lambda: 1 / 0)
p2 = GreenletSubclass.spawn(lambda: gevent.sleep(10))
s = pool.GreenletSet([p1, p2])
s.kill(block=True)
......@@ -113,6 +117,5 @@ class GreenletSubclass(gevent.Greenlet):
pass
if __name__=='__main__':
if __name__ == '__main__':
greentest.main()
......@@ -32,6 +32,7 @@ import urllib2
import BaseHTTPServer
from gevent import spawn
def start_http_server():
server_address = ('', 0)
BaseHTTPServer.BaseHTTPRequestHandler.protocol_version = "HTTP/1.0"
......@@ -39,11 +40,14 @@ def start_http_server():
#sa = httpd.socket.getsockname()[1]
#print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.request_count = 0
def serve():
httpd.handle_request()
httpd.request_count += 1
return spawn(serve), httpd
class TestGreenness(greentest.TestCase):
def setUp(self):
......@@ -60,7 +64,7 @@ class TestGreenness(greentest.TestCase):
urllib2.urlopen('http://127.0.0.1:%s' % port)
assert False, 'should not get there'
except urllib2.HTTPError, ex:
assert ex.code == 501, `ex`
assert ex.code == 501, repr(ex)
self.assertEqual(self.httpd.request_count, 1)
if __name__ == '__main__':
......
......@@ -29,7 +29,7 @@ class BoundTestCase(greentest.TestCase):
self.check_refused()
def print_netstat(self, comment=''):
cmd ='sudo netstat -anp | grep %s' % self.server.server_port
cmd = 'sudo netstat -anp | grep %s' % self.server.server_port
print cmd, ' # %s' % comment
os.system(cmd)
......@@ -222,4 +222,3 @@ class TestDetach(BoundTestCase):
if __name__ == '__main__':
greentest.main()
......@@ -38,7 +38,7 @@ class TestScheduleCall(greentest.TestCase):
def test_global(self):
lst = [1]
gevent.spawn(core.timer, DELAY, lst.pop)
gevent.sleep(DELAY*2)
gevent.sleep(DELAY * 2)
assert lst == [], lst
......@@ -63,7 +63,7 @@ class TestExceptionInMainloop(greentest.TestCase):
gevent.sleep(DELAY)
delay = time.time() - start
assert delay >= DELAY*0.9, 'sleep returned after %s seconds (was scheduled for %s)' % (delay, DELAY)
assert delay >= DELAY * 0.9, 'sleep returned after %s seconds (was scheduled for %s)' % (delay, DELAY)
def fail():
raise greentest.ExpectedException('TestExceptionInMainloop.test_sleep/fail')
......@@ -74,7 +74,7 @@ class TestExceptionInMainloop(greentest.TestCase):
gevent.sleep(DELAY)
delay = time.time() - start
assert delay >= DELAY*0.9, 'sleep returned after %s seconds (was scheduled for %s)' % (delay, DELAY)
assert delay >= DELAY * 0.9, 'sleep returned after %s seconds (was scheduled for %s)' % (delay, DELAY)
class TestShutdown(unittest.TestCase):
......@@ -85,7 +85,7 @@ class TestShutdown(unittest.TestCase):
start = time.time()
gevent.hub.shutdown()
delta = time.time() - start
assert seconds - fuzzy < delta < seconds + fuzzy, (seconds-fuzzy, delta, seconds+fuzzy)
assert seconds - fuzzy < delta < seconds + fuzzy, (seconds - fuzzy, delta, seconds + fuzzy)
def assert_hub(self):
assert 'hub' in gevent.hub._threadlocal.__dict__
......@@ -109,7 +109,7 @@ class TestShutdown(unittest.TestCase):
gevent.sleep(0)
self.assert_hub()
gevent.core.timer(0.1, lambda : None)
gevent.core.timer(0.1, lambda: None)
self.assert_hub()
self._shutdown(seconds=0.1)
self.assert_no_hub()
......@@ -146,6 +146,7 @@ class Expected(Exception):
if hasattr(signal, 'SIGALRM'):
class TestSignal(greentest.TestCase):
__timeout__ = 2
......@@ -193,6 +194,5 @@ class TestWaiter(greentest.GenericWaitTestCase):
assert str(waiter).startswith('<Waiter greenlet=<Greenlet at '), str(waiter)
if __name__=='__main__':
if __name__ == '__main__':
greentest.main()
......@@ -2,6 +2,7 @@ from gevent.util import lazy_property
calc = []
class A(object):
@lazy_property
......
......@@ -9,4 +9,3 @@ import threading
assert 'built-in' not in repr(thread.start_new_thread), repr(thread.start_new_thread)
assert 'built-in' not in repr(threading._start_new_thread), repr(threading._start_new_thread)
assert 'built-in' not in repr(threading._sleep), repr(threading._sleep)
......@@ -10,16 +10,20 @@ class TestCoroutinePool(greentest.TestCase):
def test_apply_async(self):
done = Event()
def some_work(x):
done.set()
pool = self.klass(2)
pool.apply_async(some_work, ('x', ))
done.wait()
def test_apply(self):
value = 'return value'
def some_work():
return value
pool = self.klass(2)
result = pool.apply(some_work)
self.assertEqual(value, result)
......@@ -27,6 +31,7 @@ class TestCoroutinePool(greentest.TestCase):
def test_multiple_coros(self):
evt = Event()
results = []
def producer():
results.append('prod')
evt.set()
......@@ -44,10 +49,13 @@ class TestCoroutinePool(greentest.TestCase):
def dont_test_timer_cancel(self):
timer_fired = []
def fire_timer():
timer_fired.append(True)
def some_work():
gevent.timer(0, fire_timer)
pool = self.klass(2)
pool.apply(some_work)
gevent.sleep(0)
......@@ -55,6 +63,7 @@ class TestCoroutinePool(greentest.TestCase):
def test_reentrant(self):
pool = self.klass(1)
def reenter():
result = pool.apply(lambda a: a, ('reenter', ))
self.assertEqual('reenter', result)
......@@ -62,6 +71,7 @@ class TestCoroutinePool(greentest.TestCase):
pool.apply(reenter)
evt = Event()
def reenter_async():
pool.apply_async(lambda a: a, ('reenter', ))
evt.set()
......@@ -75,8 +85,10 @@ class TestCoroutinePool(greentest.TestCase):
# any members
import sys
pool = self.klass(size=1)
def crash(*args, **kw):
raise RuntimeError("Whoa")
class FakeFile(object):
write = crash
......@@ -113,9 +125,8 @@ class PoolBasicTests(greentest.TestCase):
p = self.klass(size=2)
self.assertEqual(p.free_count(), 2)
r = []
def foo(a):
r.append(a)
first = p.spawn(foo, 1)
first = p.spawn(r.append, 1)
self.assertEqual(p.free_count(), 1)
first.get()
self.assertEqual(r, [1])
......@@ -124,18 +135,18 @@ class PoolBasicTests(greentest.TestCase):
#Once the pool is exhausted, calling an execute forces a yield.
p.apply_async(foo, (2, ))
p.apply_async(r.append, (2, ))
self.assertEqual(1, p.free_count())
self.assertEqual(r, [1])
p.apply_async(foo, (3, ))
p.apply_async(r.append, (3, ))
self.assertEqual(0, p.free_count())
self.assertEqual(r, [1])
p.apply_async(foo, (4, ))
p.apply_async(r.append, (4, ))
self.assertEqual(r, [1])
gevent.sleep(0.01)
self.assertEqual(r, [1,2,3,4])
self.assertEqual(r, [1, 2, 3, 4])
def test_execute(self):
p = self.klass()
......@@ -145,6 +156,7 @@ class PoolBasicTests(greentest.TestCase):
#
# tests from standard library test/test_multiprocessing.py
class TimingWrapper(object):
def __init__(self, func):
......@@ -161,10 +173,11 @@ class TimingWrapper(object):
def sqr(x, wait=0.0):
gevent.sleep(wait)
return x*x
return x * x
TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.082, 0.035, 0.14
class TestPool(greentest.TestCase):
size = 1
......@@ -177,12 +190,12 @@ class TestPool(greentest.TestCase):
def test_apply(self):
papply = self.pool.apply
self.assertEqual(papply(sqr, (5,)), sqr(5))
self.assertEqual(papply(sqr, (), {'x':3}), sqr(x=3))
self.assertEqual(papply(sqr, (), {'x': 3}), sqr(x=3))
def test_map(self):
pmap = self.pool.map
self.assertEqual(pmap(sqr, range(10)), map(sqr, range(10)))
self.assertEqual(pmap(sqr, range(100)), map(sqr, range(100)))
self.assertEqual(pmap(sqr, range(100)), map(sqr, range(100)))
def test_async(self):
res = self.pool.apply_async(sqr, (7, TIMEOUT1,))
......@@ -196,7 +209,7 @@ class TestPool(greentest.TestCase):
get = TimingWrapper(res.get)
self.assertEqual(get(), 49)
self.assertAlmostEqual(get.elapsed, TIMEOUT1, 1)
gevent.sleep(0) # let's the callback run
gevent.sleep(0) # let's the callback run
assert result == [49], result
def test_async_timeout(self):
......@@ -211,12 +224,12 @@ class TestPool(greentest.TestCase):
it = self.pool.imap(sqr, range(10))
for i in range(10):
self.assertEqual(it.next(), i*i)
self.assertEqual(it.next(), i * i)
self.assertRaises(StopIteration, it.next)
it = self.pool.imap(sqr, range(1000))
for i in range(1000):
self.assertEqual(it.next(), i*i)
self.assertEqual(it.next(), i * i)
self.assertRaises(StopIteration, it.next)
def test_imap_unordered(self):
......@@ -236,12 +249,15 @@ class TestPool(greentest.TestCase):
class TestPool2(TestPool):
size = 2
class TestPool3(TestPool):
size = 3
class TestPool10(TestPool):
size = 10
class TestPoolUnlimit(TestPool):
size = None
......@@ -270,12 +286,11 @@ class TestSpawn(greentest.TestCase):
self.assertEqual(len(p), 0)
p.spawn(gevent.sleep, 0.1)
self.assertEqual(len(p), 1)
p.spawn(gevent.sleep, 0.1) # this spawn blocks until the old one finishes
p.spawn(gevent.sleep, 0.1) # this spawn blocks until the old one finishes
self.assertEqual(len(p), 1)
gevent.sleep(0.19)
self.assertEqual(len(p), 0)
if __name__=='__main__':
if __name__ == '__main__':
greentest.main()
......@@ -28,6 +28,7 @@ import sys
try:
from wsgiref.validate import validator
except ImportError:
def validator(app):
return app
......@@ -201,6 +202,7 @@ def makefile(self, mode='r', bufsize=-1):
socket.socket.makefile = makefile
class TestCase(greentest.TestCase):
def get_wsgi_module(self):
......@@ -500,7 +502,7 @@ class TestUseWrite(TestCase):
response.assertHeader('Transfer-Encoding', 'chunked')
assert response.chunks == [self.body, self.body, self.end], response.chunks
else:
response.assertHeader('Content-Length', str(5+5+3))
response.assertHeader('Content-Length', str(5 + 5 + 3))
class HttpsTestCase(TestCase):
......@@ -637,10 +639,10 @@ class TestEmptyYield(TestCase):
fd = self.connect().makefile(bufsize=1)
fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n')
st, h, body = read_http(fd)
assert body==""
assert body == ""
garbage = fd.read()
self.assert_(garbage=="", "got garbage: %r" % garbage)
self.assert_(garbage == "", "got garbage: %r" % garbage)
class TestEmptyWrite(TestEmptyYield):
......@@ -679,7 +681,7 @@ class HTTPRequest(urllib2.Request):
def __init__(self, url, method="GET", data=None, headers={},
origin_req_host=None, unverifiable=False):
urllib2.Request.__init__(self,url,data,headers,origin_req_host,unverifiable)
urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)
self.url = url
self.method = method
......@@ -722,7 +724,7 @@ class ChunkedInputTests(TestCase):
return b
def body(self, dirt=None):
return self.chunk_encode(["this", " is ", "chunked", "\nline", " 2", "\n", "line3", ""], dirt=dirt)
return self.chunk_encode(["this", " is ", "chunked", "\nline", " 2", "\n", "line3", ""], dirt=dirt)
def ping(self, fd):
fd.write("GET /ping HTTP/1.1\r\n\r\n")
......@@ -806,6 +808,7 @@ class ChunkedInputTests(TestCase):
class Expect100ContinueTests(TestCase):
validator = None
def application(self, environ, start_response):
if int(environ['CONTENT_LENGTH']) > 1024:
start_response('417 Expectation Failed', [('Content-Length', '7'), ('Content-Type', 'text/plain')])
......@@ -828,7 +831,6 @@ class Expect100ContinueTests(TestCase):
return
raise
fd.write('PUT / HTTP/1.1\r\nHost: localhost\r\nContent-length: 7\r\nExpect: 100-continue\r\n\r\ntesting')
read_http(fd, code=100)
read_http(fd, body="testing")
......
......@@ -15,6 +15,7 @@ class TestQueue(TestCase):
def test_send_last(self):
q = queue.Queue()
def waiter(q):
timer = gevent.Timeout.start_new(0.1)
try:
......@@ -27,7 +28,7 @@ class TestQueue(TestCase):
gevent.sleep(0.01)
q.put('hi2')
gevent.sleep(0.01)
assert p.get(timeout=0)=="OK"
assert p.get(timeout=0) == "OK"
def test_max_size(self):
q = queue.Queue(2)
......@@ -50,10 +51,11 @@ class TestQueue(TestCase):
self.assertEquals(results, ['a', 'b', 'c'])
self.assertEquals(q.get(), 'b')
self.assertEquals(q.get(), 'c')
assert p.get(timeout=0)=="OK"
assert p.get(timeout=0) == "OK"
def test_zero_max_size(self):
q = queue.Queue(0)
def sender(evt, q):
q.put('hi')
evt.set('done')
......@@ -69,8 +71,8 @@ class TestQueue(TestCase):
gevent.sleep(0.001)
self.assert_(not e1.ready())
p2 = gevent.spawn(receiver, e2, q)
self.assertEquals(e2.get(),'hi')
self.assertEquals(e1.get(),'done')
self.assertEquals(e2.get(), 'hi')
self.assertEquals(e1.get(), 'done')
timeout = gevent.Timeout.start_new(0)
try:
gevent.joinall([p1, p2])
......@@ -87,11 +89,12 @@ class TestQueue(TestCase):
sendings = ['1', '2', '3', '4']
evts = [AsyncResult() for x in sendings]
for i, x in enumerate(sendings):
gevent.spawn(waiter, q, evts[i]) # use waitall for them
gevent.spawn(waiter, q, evts[i]) # use waitall for them
gevent.sleep(0.01) # get 'em all waiting
gevent.sleep(0.01) # get 'em all waiting
results = set()
def collect_pending_results():
for i, e in enumerate(evts):
timer = gevent.Timeout.start_new(0.001)
......@@ -138,8 +141,10 @@ class TestQueue(TestCase):
self.assertEquals(q.get(), 'sent')
def test_two_waiters_one_dies(self):
def waiter(q, evt):
evt.set(q.get())
def do_receive(q, evt):
timeout = gevent.Timeout.start_new(0, RuntimeError())
try:
......@@ -243,26 +248,30 @@ class TestNoWait(TestCase):
def test_put_nowait_simple(self):
result = []
q = queue.Queue(1)
def store_result(func, *args):
result.append(func(*args))
core.active_event(store_result, util.wrap_errors(Exception, q.put_nowait), 2)
core.active_event(store_result, util.wrap_errors(Exception, q.put_nowait), 3)
gevent.sleep(0)
assert len(result)==2, result
assert result[0]==None, result
assert len(result) == 2, result
assert result[0] == None, result
assert isinstance(result[1], queue.Full), result
def test_get_nowait_simple(self):
result = []
q = queue.Queue(1)
q.put(4)
def store_result(func, *args):
result.append(func(*args))
core.active_event(store_result, util.wrap_errors(Exception, q.get_nowait))
core.active_event(store_result, util.wrap_errors(Exception, q.get_nowait))
gevent.sleep(0)
assert len(result)==2, result
assert result[0]==4, result
assert len(result) == 2, result
assert result[0] == 4, result
assert isinstance(result[1], queue.Empty), result
# get_nowait must work from the mainloop
......@@ -270,8 +279,10 @@ class TestNoWait(TestCase):
result = []
q = queue.Queue(0)
p = gevent.spawn(q.put, 5)
def store_result(func, *args):
result.append(func(*args))
assert q.empty(), q
assert q.full(), q
gevent.sleep(0)
......@@ -291,8 +302,10 @@ class TestNoWait(TestCase):
result = []
q = queue.Queue(0)
p = gevent.spawn(q.get)
def store_result(func, *args):
result.append(func(*args))
assert q.empty(), q
assert q.full(), q
gevent.sleep(0)
......@@ -307,5 +320,5 @@ class TestNoWait(TestCase):
assert q.empty(), q
if __name__=='__main__':
if __name__ == '__main__':
main()
......@@ -23,6 +23,8 @@
are not leaked by the hub.
"""
from _socket import socket
class Socket(socket):
"Something we can have a weakref to"
......@@ -42,9 +44,9 @@ import gc
import socket
socket._realsocket = Socket
SOCKET_TIMEOUT = 0.1
def init_server():
s = socket.socket()
s.settimeout(SOCKET_TIMEOUT)
......@@ -53,6 +55,7 @@ def init_server():
s.listen(5)
return s
def handle_request(s, raise_on_timeout):
try:
conn, address = s.accept()
......@@ -63,13 +66,14 @@ def handle_request(s, raise_on_timeout):
return
#print 'handle_request - accepted'
res = conn.recv(100)
assert res == 'hello', `res`
assert res == 'hello', repr(res)
#print 'handle_request - recvd %r' % res
res = conn.send('bye')
#print 'handle_request - sent %r' % res
#print 'handle_request - conn refcount: %s' % sys.getrefcount(conn)
#conn.close()
def make_request(port):
#print 'make_request'
s = socket.socket()
......@@ -78,21 +82,23 @@ def make_request(port):
res = s.send('hello')
#print 'make_request - sent %s' % res
res = s.recv(100)
assert res == 'bye', `res`
assert res == 'bye', repr(res)
#print 'make_request - recvd %r' % res
#s.close()
def run_interaction(run_client):
s = init_server()
start_new_thread(handle_request, (s, run_client))
if run_client:
port = s.getsockname()[1]
start_new_thread(make_request, (port, ))
sleep(0.1+SOCKET_TIMEOUT)
sleep(0.1 + SOCKET_TIMEOUT)
#print sys.getrefcount(s._sock)
#s.close()
return weakref.ref(s._sock)
def run_and_check(run_client):
w = run_interaction(run_client=run_client)
if w():
......@@ -103,6 +109,7 @@ def run_and_check(run_client):
print '-', pformat(y)
raise AssertionError('server should be dead by now')
class test(greentest.TestCase):
def test_clean_exit(self):
......@@ -113,6 +120,6 @@ class test(greentest.TestCase):
run_and_check(False)
run_and_check(False)
if __name__=='__main__':
greentest.main()
if __name__ == '__main__':
greentest.main()
......@@ -16,5 +16,5 @@ class TestSelectTypes(greentest.TestCase):
select.select([1L], [], [], 0.001)
if __name__=='__main__':
if __name__ == '__main__':
greentest.main()
import greentest
from gevent.coros import Semaphore
class TestTimeoutAcquire(greentest.TestCase):
# issue 39
......@@ -10,5 +11,5 @@ class TestTimeoutAcquire(greentest.TestCase):
assert result is False, repr(result)
if __name__=='__main__':
if __name__ == '__main__':
greentest.main()
......@@ -155,7 +155,7 @@ class TestCase(greentest.TestCase):
def _test_invalid_callback(self):
self.hook_stderr()
self.server = self.ServerClass(('127.0.0.1', 0), lambda : None)
self.server = self.ServerClass(('127.0.0.1', 0), lambda: None)
self.server.start()
self.assert500()
self.assert_stderr_traceback('TypeError')
......@@ -189,7 +189,7 @@ class TestDefaultSpawn(TestCase):
self.report_netstat('after start_accepting')
self.assertRequestSucceeded()
else:
self.assertRaises(Exception, self.server.start) # XXX which exception exactly?
self.assertRaises(Exception, self.server.start) # XXX which exception exactly?
self.stop_server()
self.report_netstat('after stop')
......@@ -334,7 +334,6 @@ class TestNoneSpawn(TestCase):
self.assert_mainloop_assertion(self.invalid_callback_message)
class ExpectedError(Exception):
pass
......@@ -363,4 +362,3 @@ class TestSSLSocketNotAllowed(TestCase):
if __name__ == '__main__':
greentest.main()
......@@ -14,6 +14,7 @@ Content-length: 31
Service Temporarily Unavailable'''.replace('\n', '\r\n')
class SimpleHTTPServer(http.HTTPServer):
def handle(self, request):
......@@ -60,4 +61,3 @@ test__server.Settings = Settings
if __name__ == '__main__':
unittest.main()
......@@ -62,4 +62,3 @@ del TestNoneSpawn
if __name__ == '__main__':
unittest.main()
......@@ -45,4 +45,3 @@ TestDefaultSpawn.invalid_callback_message = msg
if __name__ == '__main__':
unittest.main()
......@@ -39,7 +39,7 @@ class TestTCP(greentest.TestCase):
def server():
(client, addr) = self.listener.accept()
# start reading, then, while reading, start writing. the reader should not hang forever
N = 100000 # must be a big enough number so that sendall calls trampoline
N = 100000 # must be a big enough number so that sendall calls trampoline
sender = gevent.spawn_link_exception(client.sendall, 't' * N)
result = client.recv(1000)
assert result == 'hello world', result
......@@ -137,7 +137,6 @@ if hasattr(socket, 'ssl'):
def create_connection(self):
return socket.ssl(socket.create_connection(('127.0.0.1', self.listener.getsockname()[1])))
def ssl_listener(address, private_key, certificate):
import _socket
r = _socket.socket()
......@@ -166,5 +165,5 @@ class TestCreateConnection(greentest.TestCase):
raise
if __name__=='__main__':
if __name__ == '__main__':
greentest.main()
......@@ -4,6 +4,7 @@ import greentest
# XXX also test: send, sendall, recvfrom, recvfrom_into, sendto
class Test(greentest.TestCase):
def setUp(self):
......
......@@ -7,8 +7,7 @@ from gevent.socket import *
ACCEPTED_GAIERROR_MISMATCH = {
"gaierror(-5, 'No address associated with hostname')": "DNSError(3, 'name does not exist')"
}
"gaierror(-5, 'No address associated with hostname')": "DNSError(3, 'name does not exist')"}
assert gaierror is real_socket.gaierror
assert error is real_socket.error
......@@ -52,7 +51,6 @@ class TestCase(greentest.TestCase):
(AF_UNSPEC, SOCK_STREAM, 6),
(AF_INET, SOCK_DGRAM, 17)]
def _test_getaddrinfo(self, hostname):
for port in self.PORTS:
for args in self.getaddrinfo_args:
......@@ -80,7 +78,7 @@ class TestCase(greentest.TestCase):
if isinstance(a, Exception) and isinstance(b, Exception):
if repr(a) == repr(b):
return True
if ACCEPTED_GAIERROR_MISMATCH.get(repr(a), repr(b))==repr(b):
if ACCEPTED_GAIERROR_MISMATCH.get(repr(a), repr(b)) == repr(b):
return True
def checkEqual(self, a, b):
......@@ -154,4 +152,3 @@ class TestRemote(TestCase):
if __name__ == '__main__':
greentest.main()
......@@ -27,6 +27,7 @@ try:
except ImportError:
from errno import ECONNREFUSED
class TestSocketErrors(greentest.TestCase):
def test_connection_refused(self):
......@@ -38,6 +39,5 @@ class TestSocketErrors(greentest.TestCase):
assert 'refused' in str(ex).lower(), str(ex)
if __name__=='__main__':
if __name__ == '__main__':
greentest.main()
......@@ -8,6 +8,7 @@ import socket
if not hasattr(socket, 'ssl'):
sys.exit(0)
class AmazonHTTPSTests(unittest.TestCase):
def test_amazon_response(self):
......@@ -26,4 +27,3 @@ class AmazonHTTPSTests(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
......@@ -2,6 +2,7 @@ import gevent
from gevent import socket
import unittest
class Test(unittest.TestCase):
def setUp(self):
......
......@@ -4,9 +4,9 @@ import threading
localdata = threading.local()
localdata.x = "hello"
assert localdata.x == 'hello'
success = []
def func():
try:
localdata.x
......
......@@ -20,17 +20,17 @@ class TestDirectRaise(greentest.TestCase):
assert timeout is t, (timeout, t)
assert not t.pending, repr(t)
class Test(greentest.TestCase):
def test_with_timeout(self):
self.assertRaises(gevent.Timeout, gevent.with_timeout, DELAY, gevent.sleep, DELAY*2)
self.assertRaises(gevent.Timeout, gevent.with_timeout, DELAY, gevent.sleep, DELAY * 2)
X = object()
r = gevent.with_timeout(DELAY, gevent.sleep, DELAY*2, timeout_value=X)
r = gevent.with_timeout(DELAY, gevent.sleep, DELAY * 2, timeout_value=X)
assert r is X, (r, X)
r = gevent.with_timeout(DELAY*2, gevent.sleep, DELAY, timeout_value=X)
r = gevent.with_timeout(DELAY * 2, gevent.sleep, DELAY, timeout_value=X)
assert r is None, r
if __name__=='__main__':
if __name__ == '__main__':
greentest.main()
import glob, os
import os
import glob
for filename in glob.glob('test_patched_*.py'):
cmd = 'cp patched_test.py %s' % filename
print cmd
......
......@@ -66,4 +66,3 @@ class Test(unittest.TestCase):
if __name__ == '__main__':
unittest.main()
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