Commit f59234e3 authored by Denis Bilenko's avatar Denis Bilenko

update the tests

--HG--
rename : greentest/test__proc.py => greentest/test__greenlet.py
rename : greentest/test__proc_procset.py => greentest/test__greenletset.py
rename : greentest/test__proc_pool.py => greentest/test__pool.py
parent 272bedc8
...@@ -47,7 +47,7 @@ class TestCase(unittest.TestCase): ...@@ -47,7 +47,7 @@ class TestCase(unittest.TestCase):
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'): if hasattr(gevent.core, '_event_count'):
self._event_count = (gevent.core._event_count(), gevent.core._event_count_active()) self._event_count = (gevent.core._event_count(), gevent.core._event_count_active())
hub = gevent.greenlet.get_hub() hub = gevent.hub.get_hub()
if hasattr(hub, 'switch_count'): if hasattr(hub, 'switch_count'):
self._switch_count = hub.switch_count self._switch_count = hub.switch_count
self._timer = gevent.Timeout(self.__timeout__, RuntimeError('test is taking too long')) self._timer = gevent.Timeout(self.__timeout__, RuntimeError('test is taking too long'))
...@@ -55,7 +55,7 @@ class TestCase(unittest.TestCase): ...@@ -55,7 +55,7 @@ class TestCase(unittest.TestCase):
def tearDown(self): def tearDown(self):
if hasattr(self, '_timer'): if hasattr(self, '_timer'):
self._timer.cancel() self._timer.cancel()
hub = gevent.greenlet.get_hub() hub = gevent.hub.get_hub()
if self.__switch_check__ and self._switch_count is not None and hasattr(hub, 'switch_count') and hub.switch_count <= self._switch_count: if self.__switch_check__ and self._switch_count is not None and hasattr(hub, 'switch_count') and hub.switch_count <= self._switch_count:
name = getattr(self, '_testMethodName', '') # 2.4 does not have it name = getattr(self, '_testMethodName', '') # 2.4 does not have it
sys.stderr.write('WARNING: %s.%s did not switch\n' % (type(self).__name__, name)) sys.stderr.write('WARNING: %s.%s did not switch\n' % (type(self).__name__, name))
...@@ -78,7 +78,7 @@ def find_command(command): ...@@ -78,7 +78,7 @@ def find_command(command):
main = unittest.main main = unittest.main
_original_Hub = gevent.greenlet.Hub _original_Hub = gevent.hub.Hub
class CountingHub(_original_Hub): class CountingHub(_original_Hub):
...@@ -88,4 +88,4 @@ class CountingHub(_original_Hub): ...@@ -88,4 +88,4 @@ class CountingHub(_original_Hub):
self.switch_count += 1 self.switch_count += 1
return _original_Hub.switch(self) return _original_Hub.switch(self)
gevent.greenlet.Hub = CountingHub gevent.hub.Hub = CountingHub
...@@ -65,12 +65,12 @@ class TestGreenIo(TestCase): ...@@ -65,12 +65,12 @@ class TestGreenIo(TestCase):
server = socket.tcp_listener(('0.0.0.0', 0)) server = socket.tcp_listener(('0.0.0.0', 0))
server_greenlet = gevent.spawn(accept_close_early, server) server_greenlet = gevent.spawn(accept_close_early, server)
did_it_work(server) did_it_work(server)
gevent.kill(server_greenlet, block=True) server_greenlet.kill(block=True)
server = socket.tcp_listener(('0.0.0.0', 0)) server = socket.tcp_listener(('0.0.0.0', 0))
server_greenlet = gevent.spawn(accept_close_late, server) server_greenlet = gevent.spawn(accept_close_late, server)
did_it_work(server) did_it_work(server)
gevent.kill(server_greenlet, block=True) server_greenlet.kill(block=True)
def test_del_closes_socket(self): def test_del_closes_socket(self):
......
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
import greentest import greentest
import gevent import gevent
from gevent import core, proc, greenlet from gevent import core, util, socket
DELAY = 0.1 DELAY = 0.1
...@@ -41,7 +41,7 @@ class Test(greentest.TestCase): ...@@ -41,7 +41,7 @@ class Test(greentest.TestCase):
g = gevent.spawn(test) g = gevent.spawn(test)
gevent.sleep(DELAY/2) gevent.sleep(DELAY/2)
assert state == ['start'], state assert state == ['start'], state
gevent.kill(g, block=True) g.kill(block=True)
# will not get there, unless switching is explicitly scheduled by kill # will not get there, unless switching is explicitly scheduled by kill
assert state == ['start', 'except', 'finished'], state assert state == ['start', 'except', 'finished'], state
...@@ -50,33 +50,34 @@ class Test(greentest.TestCase): ...@@ -50,33 +50,34 @@ class Test(greentest.TestCase):
return gevent.with_timeout(0.2, gevent.sleep, 2, timeout_value=1) return gevent.with_timeout(0.2, gevent.sleep, 2, timeout_value=1)
self.assertRaises(gevent.Timeout, gevent.with_timeout, 0.1, func) self.assertRaises(gevent.Timeout, gevent.with_timeout, 0.1, func)
def test_killing_just_spawned(self): def test_killing_not_yet_started(self):
def func(): def func():
pass pass
g = gevent.spawn_later(2, func) g = gevent.spawn_later(2000, func)
assert not g.dead, g assert not g.dead, g
gevent.kill(g, block=True) g.kill(block=True)
assert g.dead, g assert g.dead, g
self.assertRaises(Exception, g.get)
def test_sleep_invalid_switch(self): def test_sleep_invalid_switch(self):
p = proc.spawn(proc.wrap_errors(AssertionError, gevent.sleep), 2) p = gevent.spawn(util.wrap_errors(AssertionError, gevent.sleep), 2)
gevent.spawn(p.greenlet.switch, None) gevent.spawn(p.switch, None)
result = p.wait() result = p.get()
assert isinstance(result, AssertionError), instance assert isinstance(result, AssertionError), result
assert 'Invalid switch' in str(result), repr(str(result)) assert 'Invalid switch' in str(result), repr(str(result))
def test_wait_reader_invalid_switch(self): def test_wait_reader_invalid_switch(self):
p = proc.spawn(proc.wrap_errors(AssertionError, greenlet.wait_reader), 0) p = gevent.spawn(util.wrap_errors(AssertionError, socket.wait_reader), 0)
gevent.spawn(p.greenlet.switch, None) gevent.spawn(p.switch, None)
result = p.wait() result = p.get()
assert isinstance(result, AssertionError), instance assert isinstance(result, AssertionError), result
assert 'Invalid switch' in str(result), repr(str(result)) assert 'Invalid switch' in str(result), repr(str(result))
def test_wait_writer_invalid_switch(self): def test_wait_writer_invalid_switch(self):
p = proc.spawn(proc.wrap_errors(AssertionError, greenlet.wait_writer), 0) p = gevent.spawn(util.wrap_errors(AssertionError, socket.wait_writer), 0)
gevent.spawn(p.greenlet.switch, None) gevent.spawn(p.switch, None)
result = p.wait() result = p.get()
assert isinstance(result, AssertionError), instance assert isinstance(result, AssertionError), result
assert 'Invalid switch' in str(result), repr(str(result)) assert 'Invalid switch' in str(result), repr(str(result))
......
import greentest
import gevent
from gevent.event import AsyncResult
DELAY = 0.01
class TestLink_Signal(greentest.TestCase):
def test_put(self):
g = gevent.spawn(lambda : 1)
s1, s2, s3 = AsyncResult(), AsyncResult(), AsyncResult()
g.link(s1)
g.link_value(s2)
g.link_exception(s3)
assert s1.get() == 1
assert s2.get() == 1
assert gevent.with_timeout(DELAY, s3.get, timeout_value=X) is X
def test_put_exception(self):
g = gevent.spawn(lambda : 1/0)
s1, s2, s3 = AsyncResult(), AsyncResult(), AsyncResult()
g.link(s1)
g.link_value(s2)
g.link_exception(s3)
self.assertRaises(ZeroDivisionError, s1.get)
assert gevent.with_timeout(DELAY, s2.get, timeout_value=X) is X
self.assertRaises(ZeroDivisionError, s3.get)
X = object()
if __name__=='__main__':
greentest.main()
...@@ -17,7 +17,7 @@ class Test(greentest.TestCase): ...@@ -17,7 +17,7 @@ class Test(greentest.TestCase):
s.sendall('2+2\r\n') s.sendall('2+2\r\n')
l = f.readline() l = f.readline()
assert l.strip() == '4', repr(l) assert l.strip() == '4', repr(l)
gevent.kill(g, block=True) g.kill(block=True)
if __name__ == '__main__': if __name__ == '__main__':
......
from greentest import TestCase from greentest import TestCase
from greentest import main from greentest import main
import gevent import gevent
from gevent import coros, proc from gevent import coros
class TestQueue(TestCase): class TestQueue(TestCase):
...@@ -203,7 +203,7 @@ class TestChannel(TestCase): ...@@ -203,7 +203,7 @@ class TestChannel(TestCase):
events.append(channel.wait()) events.append(channel.wait())
events.append(channel.wait()) events.append(channel.wait())
g = proc.spawn(another_greenlet) g = gevent.spawn(another_greenlet)
events.append('sending') events.append('sending')
channel.send('hello') channel.send('hello')
...@@ -226,7 +226,7 @@ class TestChannel(TestCase): ...@@ -226,7 +226,7 @@ class TestChannel(TestCase):
channel.send('world') channel.send('world')
events.append('sent world') events.append('sent world')
g = proc.spawn(another_greenlet) g = gevent.spawn(another_greenlet)
events.append('waiting') events.append('waiting')
events.append(channel.wait()) events.append(channel.wait())
...@@ -235,7 +235,7 @@ class TestChannel(TestCase): ...@@ -235,7 +235,7 @@ class TestChannel(TestCase):
self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world'], events) self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world'], events)
gevent.sleep(0) gevent.sleep(0)
self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world', 'sent world'], events) self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world', 'sent world'], events)
g.wait(timeout=0) g.get(block=False)
if __name__=='__main__': if __name__=='__main__':
......
...@@ -22,7 +22,6 @@ ...@@ -22,7 +22,6 @@
import greentest import greentest
import gevent import gevent
from gevent import coros from gevent import coros
from greentest import TestCase
DELAY = 0.01 DELAY = 0.01
...@@ -60,7 +59,7 @@ class TestEvent(greentest.TestCase): ...@@ -60,7 +59,7 @@ class TestEvent(greentest.TestCase):
assert result is X, 'Nobody sent anything to event2 yet it received %r' % (result, ) assert result is X, 'Nobody sent anything to event2 yet it received %r' % (result, )
finally: finally:
t.cancel() t.cancel()
gevent.kill(g, block=True) g.kill(block=True)
if __name__=='__main__': if __name__=='__main__':
......
import time import time
import greentest import greentest
import gevent import gevent
from gevent import proc from gevent import pool
DELAY = 0.01 DELAY = 0.1
class Undead(object): class Undead(object):
...@@ -21,8 +21,9 @@ class Test(greentest.TestCase): ...@@ -21,8 +21,9 @@ class Test(greentest.TestCase):
def test_basic(self): def test_basic(self):
DELAY = 0.05 DELAY = 0.05
s = proc.ProcSet() s = pool.GreenletSet()
s.spawn(gevent.sleep, DELAY) s.spawn(gevent.sleep, DELAY)
assert len(s)==1, s
s.spawn(gevent.sleep, DELAY*2.) s.spawn(gevent.sleep, DELAY*2.)
assert len(s)==2, s assert len(s)==2, s
gevent.sleep(DELAY*3./2.) gevent.sleep(DELAY*3./2.)
...@@ -31,19 +32,19 @@ class Test(greentest.TestCase): ...@@ -31,19 +32,19 @@ class Test(greentest.TestCase):
assert not s, s assert not s, s
def test_waitall(self): def test_waitall(self):
s = proc.ProcSet() s = pool.GreenletSet()
s.spawn(gevent.sleep, DELAY) s.spawn(gevent.sleep, DELAY)
s.spawn(gevent.sleep, DELAY*2) s.spawn(gevent.sleep, DELAY*2)
assert len(s)==2, s assert len(s)==2, s
start = time.time() start = time.time()
s.waitall() s.joinall(raise_error=True)
delta = time.time() - start delta = time.time() - start
assert not s, s assert not s, s
assert len(s)==0, s assert len(s)==0, s
assert DELAY*2 < delta < DELAY*2.5, delta assert DELAY*2 < delta < DELAY*2.5, delta
def test_killall_wait(self): def test_killall_wait(self):
s = proc.ProcSet() s = pool.GreenletSet()
s.spawn(gevent.sleep, DELAY) s.spawn(gevent.sleep, DELAY)
s.spawn(gevent.sleep, DELAY*2) s.spawn(gevent.sleep, DELAY*2)
assert len(s)==2, s assert len(s)==2, s
...@@ -55,7 +56,7 @@ class Test(greentest.TestCase): ...@@ -55,7 +56,7 @@ class Test(greentest.TestCase):
assert delta < DELAY*0.5, delta assert delta < DELAY*0.5, delta
def test_killall_nowait(self): def test_killall_nowait(self):
s = proc.ProcSet() s = pool.GreenletSet()
s.spawn(gevent.sleep, DELAY) s.spawn(gevent.sleep, DELAY)
s.spawn(gevent.sleep, DELAY*2) s.spawn(gevent.sleep, DELAY*2)
assert len(s)==2, s assert len(s)==2, s
...@@ -68,9 +69,9 @@ class Test(greentest.TestCase): ...@@ -68,9 +69,9 @@ class Test(greentest.TestCase):
def test_kill_fires_once(self): def test_kill_fires_once(self):
u1 = Undead() u1 = Undead()
u2 = Undead() u2 = Undead()
p1 = proc.spawn(u1) p1 = gevent.spawn(u1)
p2 = proc.spawn(u2) p2 = gevent.spawn(u2)
s = proc.ProcSet([p1, p2]) s = pool.GreenletSet([p1, p2])
assert u1.shot_count == 0, u1.shot_count assert u1.shot_count == 0, u1.shot_count
s.kill(p1) s.kill(p1)
assert u1.shot_count == 0, u1.shot_count assert u1.shot_count == 0, u1.shot_count
...@@ -92,13 +93,13 @@ class Test(greentest.TestCase): ...@@ -92,13 +93,13 @@ class Test(greentest.TestCase):
assert X is gevent.with_timeout(DELAY, s.killall, block=True, timeout_value=X) assert X is gevent.with_timeout(DELAY, s.killall, block=True, timeout_value=X)
def test_killall_subclass(self): def test_killall_subclass(self):
p1 = Proc1.spawn(lambda : 1/0) p1 = GreenletSubclass.spawn(lambda : 1/0)
p2 = Proc1.spawn(lambda : gevent.sleep(10)) p2 = GreenletSubclass.spawn(lambda : gevent.sleep(10))
s = proc.ProcSet([p1, p2]) s = pool.GreenletSet([p1, p2])
s.killall(block=True) s.killall(block=True)
class Proc1(proc.Proc): class GreenletSubclass(gevent.Greenlet):
pass pass
......
...@@ -30,7 +30,7 @@ import greentest ...@@ -30,7 +30,7 @@ import greentest
from greentest import test_support from greentest import test_support
import urllib2 import urllib2
import BaseHTTPServer import BaseHTTPServer
from gevent import spawn, kill from gevent import spawn
def start_http_server(): def start_http_server():
server_address = ('', 0) server_address = ('', 0)
...@@ -51,7 +51,7 @@ class TestGreenness(greentest.TestCase): ...@@ -51,7 +51,7 @@ class TestGreenness(greentest.TestCase):
def tearDown(self): def tearDown(self):
self.httpd.server_close() self.httpd.server_close()
kill(self.gthread) self.gthread.kill(block=True)
def test_urllib2(self): def test_urllib2(self):
self.assertEqual(self.httpd.request_count, 0) self.assertEqual(self.httpd.request_count, 0)
......
...@@ -83,18 +83,18 @@ class TestShutdown(unittest.TestCase): ...@@ -83,18 +83,18 @@ class TestShutdown(unittest.TestCase):
def _shutdown(self, seconds=0, fuzzy=0.01): def _shutdown(self, seconds=0, fuzzy=0.01):
start = time.time() start = time.time()
gevent.greenlet.shutdown() gevent.hub.shutdown()
delta = time.time() - start 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): def assert_hub(self):
assert 'hub' in gevent.greenlet._threadlocal.__dict__ assert 'hub' in gevent.hub._threadlocal.__dict__
def assert_no_hub(self): def assert_no_hub(self):
assert 'hub' not in gevent.greenlet._threadlocal.__dict__ assert 'hub' not in gevent.hub._threadlocal.__dict__
def test(self): def test(self):
assert not gevent.greenlet.get_hub().dead assert not gevent.hub.get_hub().dead
self._shutdown() self._shutdown()
self.assert_no_hub() self.assert_no_hub()
......
import gevent import gevent
from gevent import proc, coros from gevent import pool
from gevent.event import Event
from greentest import TestCase, main from greentest import TestCase, main
class TestCoroutinePool(TestCase): class TestCoroutinePool(TestCase):
klass = proc.Pool klass = pool.Pool
def test_execute_async(self): def test_execute_async(self):
done = coros.event() done = Event()
def some_work(): def some_work(x):
done.send() print 'puttin'
done.put()
print 'done putting'
pool = self.klass(2) pool = self.klass(2)
pool.execute_async(some_work) pool.execute_async(some_work, 'x')
done.wait() done.get()
def test_execute(self): def test_execute(self):
value = 'return value' value = 'return value'
...@@ -19,24 +22,24 @@ class TestCoroutinePool(TestCase): ...@@ -19,24 +22,24 @@ class TestCoroutinePool(TestCase):
return value return value
pool = self.klass(2) pool = self.klass(2)
worker = pool.execute(some_work) worker = pool.execute(some_work)
self.assertEqual(value, worker.wait()) self.assertEqual(value, worker.get())
def test_multiple_coros(self): def test_multiple_coros(self):
evt = coros.event() evt = Event()
results = [] results = []
def producer(): def producer():
results.append('prod') results.append('prod')
evt.send() evt.put()
def consumer(): def consumer():
results.append('cons1') results.append('cons1')
evt.wait() evt.get()
results.append('cons2') results.append('cons2')
pool = self.klass(2) pool = self.klass(2)
done = pool.execute(consumer) done = pool.execute(consumer)
pool.execute_async(producer) pool.execute_async(producer)
done.wait() done.get()
self.assertEquals(['cons1', 'prod', 'cons2'], results) self.assertEquals(['cons1', 'prod', 'cons2'], results)
def dont_test_timer_cancel(self): def dont_test_timer_cancel(self):
...@@ -47,7 +50,7 @@ class TestCoroutinePool(TestCase): ...@@ -47,7 +50,7 @@ class TestCoroutinePool(TestCase):
gevent.timer(0, fire_timer) gevent.timer(0, fire_timer)
pool = self.klass(2) pool = self.klass(2)
worker = pool.execute(some_work) worker = pool.execute(some_work)
worker.wait() worker.get()
gevent.sleep(0) gevent.sleep(0)
self.assertEquals(timer_fired, []) self.assertEquals(timer_fired, [])
...@@ -55,18 +58,18 @@ class TestCoroutinePool(TestCase): ...@@ -55,18 +58,18 @@ class TestCoroutinePool(TestCase):
pool = self.klass(1) pool = self.klass(1)
def reenter(): def reenter():
waiter = pool.execute(lambda a: a, 'reenter') waiter = pool.execute(lambda a: a, 'reenter')
self.assertEqual('reenter', waiter.wait()) self.assertEqual('reenter', waiter.get())
outer_waiter = pool.execute(reenter) outer_waiter = pool.execute(reenter)
outer_waiter.wait() outer_waiter.get()
evt = coros.event() evt = Event()
def reenter_async(): def reenter_async():
pool.execute_async(lambda a: a, 'reenter') pool.execute_async(lambda a: a, 'reenter')
evt.send('done') evt.put('done')
pool.execute_async(reenter_async) pool.execute_async(reenter_async)
evt.wait() evt.get()
def test_stderr_raising(self): def test_stderr_raising(self):
# testing that really egregious errors in the error handling code # testing that really egregious errors in the error handling code
...@@ -85,7 +88,7 @@ class TestCoroutinePool(TestCase): ...@@ -85,7 +88,7 @@ class TestCoroutinePool(TestCase):
try: try:
sys.stderr = FakeFile() sys.stderr = FakeFile()
waiter = pool.execute(crash) waiter = pool.execute(crash)
self.assertRaises(RuntimeError, waiter.wait) self.assertRaises(RuntimeError, waiter.get)
# the pool should have something free at this point since the # the pool should have something free at this point since the
# waiter returned # waiter returned
# pool.Pool change: if an exception is raised during execution of a link, # pool.Pool change: if an exception is raised during execution of a link,
...@@ -105,7 +108,7 @@ class TestCoroutinePool(TestCase): ...@@ -105,7 +108,7 @@ class TestCoroutinePool(TestCase):
class PoolBasicTests(TestCase): class PoolBasicTests(TestCase):
klass = proc.Pool klass = pool.Pool
def test_execute_async(self): def test_execute_async(self):
p = self.klass(size=2) p = self.klass(size=2)
...@@ -115,7 +118,7 @@ class PoolBasicTests(TestCase): ...@@ -115,7 +118,7 @@ class PoolBasicTests(TestCase):
r.append(a) r.append(a)
evt = p.execute(foo, 1) evt = p.execute(foo, 1)
self.assertEqual(p.free_count(), 1) self.assertEqual(p.free_count(), 1)
evt.wait() evt.get()
self.assertEqual(r, [1]) self.assertEqual(r, [1])
gevent.sleep(0) gevent.sleep(0)
self.assertEqual(p.free_count(), 2) self.assertEqual(p.free_count(), 2)
...@@ -138,7 +141,7 @@ class PoolBasicTests(TestCase): ...@@ -138,7 +141,7 @@ class PoolBasicTests(TestCase):
def test_execute(self): def test_execute(self):
p = self.klass() p = self.klass()
evt = p.execute(lambda a: ('foo', a), 1) evt = p.execute(lambda a: ('foo', a), 1)
self.assertEqual(evt.wait(), ('foo', 1)) self.assertEqual(evt.get(), ('foo', 1))
if __name__=='__main__': if __name__=='__main__':
......
import random
from greentest import TestCase, main from greentest import TestCase, main
import gevent import gevent
from gevent import proc, coros, core from gevent import util, coros, core
from gevent import queue from gevent import queue
...@@ -23,11 +22,11 @@ class TestQueue(TestCase): ...@@ -23,11 +22,11 @@ class TestQueue(TestCase):
timer.cancel() timer.cancel()
return "OK" return "OK"
p = proc.spawn(waiter, q) p = gevent.spawn(waiter, q)
gevent.sleep(0.01) gevent.sleep(0.01)
q.put('hi2') q.put('hi2')
gevent.sleep(0.01) gevent.sleep(0.01)
assert p.wait(timeout=0)=="OK" assert p.get(timeout=0)=="OK"
def test_max_size(self): def test_max_size(self):
q = queue.Queue(2) q = queue.Queue(2)
...@@ -42,7 +41,7 @@ class TestQueue(TestCase): ...@@ -42,7 +41,7 @@ class TestQueue(TestCase):
results.append('c') results.append('c')
return "OK" return "OK"
p = proc.spawn(putter, q) p = gevent.spawn(putter, q)
gevent.sleep(0) gevent.sleep(0)
self.assertEquals(results, ['a', 'b']) self.assertEquals(results, ['a', 'b'])
self.assertEquals(q.get(), 'a') self.assertEquals(q.get(), 'a')
...@@ -50,7 +49,7 @@ class TestQueue(TestCase): ...@@ -50,7 +49,7 @@ class TestQueue(TestCase):
self.assertEquals(results, ['a', 'b', 'c']) self.assertEquals(results, ['a', 'b', 'c'])
self.assertEquals(q.get(), 'b') self.assertEquals(q.get(), 'b')
self.assertEquals(q.get(), 'c') self.assertEquals(q.get(), 'c')
assert p.wait(timeout=0)=="OK" assert p.get(timeout=0)=="OK"
def test_zero_max_size(self): def test_zero_max_size(self):
q = queue.Queue(0) q = queue.Queue(0)
...@@ -65,15 +64,15 @@ class TestQueue(TestCase): ...@@ -65,15 +64,15 @@ class TestQueue(TestCase):
e1 = coros.event() e1 = coros.event()
e2 = coros.event() e2 = coros.event()
p1 = proc.spawn(sender, e1, q) p1 = gevent.spawn(sender, e1, q)
gevent.sleep(0.001) gevent.sleep(0.001)
self.assert_(not e1.ready()) self.assert_(not e1.ready())
p2 = proc.spawn(receiver, e2, q) p2 = gevent.spawn(receiver, e2, q)
self.assertEquals(e2.wait(),'hi') self.assertEquals(e2.wait(),'hi')
self.assertEquals(e1.wait(),'done') self.assertEquals(e1.wait(),'done')
timeout = gevent.Timeout(0) timeout = gevent.Timeout(0)
try: try:
proc.waitall([p1, p2]) gevent.joinall([p1, p2])
finally: finally:
timeout.cancel() timeout.cancel()
...@@ -87,7 +86,7 @@ class TestQueue(TestCase): ...@@ -87,7 +86,7 @@ class TestQueue(TestCase):
sendings = ['1', '2', '3', '4'] sendings = ['1', '2', '3', '4']
evts = [coros.event() for x in sendings] evts = [coros.event() for x in sendings]
for i, x in enumerate(sendings): for i, x in enumerate(sendings):
gevent.spawn(waiter, q, evts[i]) # use proc and 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
...@@ -194,7 +193,7 @@ class TestChannel(TestCase): ...@@ -194,7 +193,7 @@ class TestChannel(TestCase):
events.append(channel.get()) events.append(channel.get())
events.append(channel.get()) events.append(channel.get())
g = proc.spawn(another_greenlet) g = gevent.spawn(another_greenlet)
events.append('sending') events.append('sending')
channel.put('hello') channel.put('hello')
...@@ -203,7 +202,7 @@ class TestChannel(TestCase): ...@@ -203,7 +202,7 @@ class TestChannel(TestCase):
events.append('sent world') events.append('sent world')
self.assertEqual(['sending', 'hello', 'sent hello', 'world', 'sent world'], events) self.assertEqual(['sending', 'hello', 'sent hello', 'world', 'sent world'], events)
g.wait() g.get()
def test_wait(self): def test_wait(self):
channel = queue.Queue(0) channel = queue.Queue(0)
...@@ -216,7 +215,7 @@ class TestChannel(TestCase): ...@@ -216,7 +215,7 @@ class TestChannel(TestCase):
channel.put('world') channel.put('world')
events.append('sent world') events.append('sent world')
g = proc.spawn(another_greenlet) g = gevent.spawn(another_greenlet)
events.append('waiting') events.append('waiting')
events.append(channel.get()) events.append(channel.get())
...@@ -225,7 +224,7 @@ class TestChannel(TestCase): ...@@ -225,7 +224,7 @@ class TestChannel(TestCase):
self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world'], events) self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world'], events)
gevent.sleep(0) gevent.sleep(0)
self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world', 'sent world'], events) self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world', 'sent world'], events)
g.wait() g.get()
class TestNoWait(TestCase): class TestNoWait(TestCase):
...@@ -235,8 +234,8 @@ class TestNoWait(TestCase): ...@@ -235,8 +234,8 @@ class TestNoWait(TestCase):
q = queue.Queue(1) q = queue.Queue(1)
def store_result(func, *args): def store_result(func, *args):
result.append(func(*args)) result.append(func(*args))
core.active_event(store_result, proc.wrap_errors(Exception, q.put_nowait), 2) core.active_event(store_result, util.wrap_errors(Exception, q.put_nowait), 2)
core.active_event(store_result, proc.wrap_errors(Exception, q.put_nowait), 3) core.active_event(store_result, util.wrap_errors(Exception, q.put_nowait), 3)
gevent.sleep(0) gevent.sleep(0)
assert len(result)==2, result assert len(result)==2, result
assert result[0]==None, result assert result[0]==None, result
...@@ -248,8 +247,8 @@ class TestNoWait(TestCase): ...@@ -248,8 +247,8 @@ class TestNoWait(TestCase):
q.put(4) q.put(4)
def store_result(func, *args): def store_result(func, *args):
result.append(func(*args)) result.append(func(*args))
core.active_event(store_result, proc.wrap_errors(Exception, q.get_nowait)) core.active_event(store_result, util.wrap_errors(Exception, q.get_nowait))
core.active_event(store_result, proc.wrap_errors(Exception, q.get_nowait)) core.active_event(store_result, util.wrap_errors(Exception, q.get_nowait))
gevent.sleep(0) gevent.sleep(0)
assert len(result)==2, result assert len(result)==2, result
assert result[0]==4, result assert result[0]==4, result
...@@ -259,7 +258,7 @@ class TestNoWait(TestCase): ...@@ -259,7 +258,7 @@ class TestNoWait(TestCase):
def test_get_nowait_unlock(self): def test_get_nowait_unlock(self):
result = [] result = []
q = queue.Queue(0) q = queue.Queue(0)
p = proc.spawn(q.put, 5) p = gevent.spawn(q.put, 5)
def store_result(func, *args): def store_result(func, *args):
result.append(func(*args)) result.append(func(*args))
assert q.empty(), q assert q.empty(), q
...@@ -267,7 +266,7 @@ class TestNoWait(TestCase): ...@@ -267,7 +266,7 @@ class TestNoWait(TestCase):
gevent.sleep(0) gevent.sleep(0)
assert not q.empty(), q assert not q.empty(), q
assert q.full(), q assert q.full(), q
core.active_event(store_result, proc.wrap_errors(Exception, q.get_nowait)) core.active_event(store_result, util.wrap_errors(Exception, q.get_nowait))
gevent.sleep(0) gevent.sleep(0)
assert q.empty(), q assert q.empty(), q
assert q.full(), q assert q.full(), q
...@@ -280,7 +279,7 @@ class TestNoWait(TestCase): ...@@ -280,7 +279,7 @@ class TestNoWait(TestCase):
def test_put_nowait_unlock(self): def test_put_nowait_unlock(self):
result = [] result = []
q = queue.Queue(0) q = queue.Queue(0)
p = proc.spawn(q.get) p = gevent.spawn(q.get)
def store_result(func, *args): def store_result(func, *args):
result.append(func(*args)) result.append(func(*args))
assert q.empty(), q assert q.empty(), q
...@@ -288,7 +287,7 @@ class TestNoWait(TestCase): ...@@ -288,7 +287,7 @@ class TestNoWait(TestCase):
gevent.sleep(0) gevent.sleep(0)
assert q.empty(), q assert q.empty(), q
assert not q.full(), q assert not q.full(), q
core.active_event(store_result, proc.wrap_errors(Exception, q.put_nowait), 10) core.active_event(store_result, util.wrap_errors(Exception, q.put_nowait), 10)
assert not p.ready(), p assert not p.ready(), p
gevent.sleep(0) gevent.sleep(0)
assert result == [None], result assert result == [None], result
......
...@@ -38,10 +38,17 @@ from gevent.socket import _original_socket ...@@ -38,10 +38,17 @@ from gevent.socket import _original_socket
class Socket(_original_socket): class Socket(_original_socket):
"Something we can have a weakref to" "Something we can have a weakref to"
import gevent
gevent.socket._original_socket = Socket
import socket
socket._realsocket = Socket
SOCKET_TIMEOUT = 0.1 SOCKET_TIMEOUT = 0.1
def init_server(): def init_server():
s = socket.socket(Socket()) s = socket.socket()
s.settimeout(SOCKET_TIMEOUT) s.settimeout(SOCKET_TIMEOUT)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('127.0.0.1', 0)) s.bind(('127.0.0.1', 0))
...@@ -67,7 +74,7 @@ def handle_request(s, raise_on_timeout): ...@@ -67,7 +74,7 @@ def handle_request(s, raise_on_timeout):
def make_request(port): def make_request(port):
#print 'make_request' #print 'make_request'
s = socket.socket(Socket()) s = socket.socket()
s.connect(('127.0.0.1', port)) s.connect(('127.0.0.1', port))
#print 'make_request - connected' #print 'make_request - connected'
res = s.send('hello') res = s.send('hello')
...@@ -86,7 +93,7 @@ def run_interaction(run_client): ...@@ -86,7 +93,7 @@ def run_interaction(run_client):
sleep(0.1+SOCKET_TIMEOUT) sleep(0.1+SOCKET_TIMEOUT)
#print sys.getrefcount(s.fd) #print sys.getrefcount(s.fd)
#s.close() #s.close()
return weakref.ref(s.fd) return weakref.ref(s.fd) # XXX OR _sock depending on whether monkey patching is enabled. rename GreenSocket.fd to GreenSocket._sock ?
def run_and_check(run_client): def run_and_check(run_client):
w = run_interaction(run_client=run_client) w = run_interaction(run_client=run_client)
......
import os import os
import gevent import gevent
from gevent import proc, socket, coros from gevent import socket, coros
import greentest import greentest
import time import time
...@@ -23,15 +23,15 @@ class TestTCP(greentest.TestCase): ...@@ -23,15 +23,15 @@ class TestTCP(greentest.TestCase):
(client, addr) = self.listener.accept() (client, addr) = self.listener.accept()
# start reading, then, while reading, start writing. the reader should not hang forever # 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
proc.spawn_link_exception(client.sendall, 't' * N) gevent.spawn_link_exception(client.sendall, 't' * N)
result = client.recv(1000) result = client.recv(1000)
assert result == 'hello world', result assert result == 'hello world', result
#print '%s: client' % getcurrent() #print '%s: client' % getcurrent()
server_proc = proc.spawn_link_exception(server) server_proc = gevent.spawn_link_exception(server)
client = self.create_connection() client = self.create_connection()
client_reader = proc.spawn_link_exception(client.makefile().read) client_reader = gevent.spawn_link_exception(client.makefile().read)
gevent.sleep(0.001) gevent.sleep(0.001)
client.send('hello world') client.send('hello world')
...@@ -39,9 +39,9 @@ class TestTCP(greentest.TestCase): ...@@ -39,9 +39,9 @@ class TestTCP(greentest.TestCase):
client.close() client.close()
# this tests "full duplex" bug; # this tests "full duplex" bug;
server_proc.wait() server_proc.get()
client_reader.wait() client_reader.get()
def test_recv_timeout(self): def test_recv_timeout(self):
client = self.create_connection() client = self.create_connection()
...@@ -73,14 +73,14 @@ class TestTCP(greentest.TestCase): ...@@ -73,14 +73,14 @@ class TestTCP(greentest.TestCase):
fd.write('hello\n') fd.write('hello\n')
fd.close() fd.close()
acceptor = proc.spawn(accept_once) acceptor = gevent.spawn(accept_once)
client = self.create_connection() client = self.create_connection()
fd = client.makefile() fd = client.makefile()
client.close() client.close()
assert fd.readline() == 'hello\n' assert fd.readline() == 'hello\n'
assert fd.read() == '' assert fd.read() == ''
fd.close() fd.close()
acceptor.wait() acceptor.get()
# this test was copied from api_test.py # this test was copied from api_test.py
# using kill() like that is not good, so tcp_server should return an object # using kill() like that is not good, so tcp_server should return an object
...@@ -94,13 +94,14 @@ class TestTCP(greentest.TestCase): ...@@ -94,13 +94,14 @@ class TestTCP(greentest.TestCase):
connected.append(True) connected.append(True)
conn.close() conn.close()
if len(connected) == 2: if len(connected) == 2:
gevent.kill(current, socket.error(32, 'broken pipe')) #gevent.kill(current, socket.error(32, 'broken pipe'))
gevent.core.active_event(current.throw, socket.error(32, 'broken pipe'))
g1 = proc.spawn_link_exception(self.create_connection) g1 = gevent.spawn_link_exception(self.create_connection)
g2 = proc.spawn_link_exception(self.create_connection) g2 = gevent.spawn_link_exception(self.create_connection)
socket.tcp_server(self.listener, accept_twice) socket.tcp_server(self.listener, accept_twice)
assert len(connected) == 2 assert len(connected) == 2
proc.waitall([g1, g2]) gevent.joinall([g1, g2])
class TestSSL(TestTCP): class TestSSL(TestTCP):
...@@ -121,7 +122,7 @@ class TestSSL(TestTCP): ...@@ -121,7 +122,7 @@ class TestSSL(TestTCP):
def test_recv_timeout(self): def test_recv_timeout(self):
incoming = coros.Queue() # preventing the incoming socket from being GCed before the test finished incoming = coros.Queue() # preventing the incoming socket from being GCed before the test finished
acceptor = proc.spawn_link_exception(lambda : incoming.send(self.listener.accept())) acceptor = gevent.spawn_link_exception(lambda : incoming.send(self.listener.accept()))
client = self.create_connection() client = self.create_connection()
client.settimeout(0.1) client.settimeout(0.1)
start = time.time() start = time.time()
...@@ -131,11 +132,11 @@ class TestSSL(TestTCP): ...@@ -131,11 +132,11 @@ class TestSSL(TestTCP):
assert time.time() - start >= 0.1, (time.time() - start) assert time.time() - start >= 0.1, (time.time() - start)
else: else:
raise AssertionError('socket.timeout should have been raised, instead recv returned %r' % (data, )) raise AssertionError('socket.timeout should have been raised, instead recv returned %r' % (data, ))
acceptor.wait() acceptor.get()
def test_sendall_timeout(self): def test_sendall_timeout(self):
incoming = coros.Queue() # preventing the incoming socket from being GCed before the test finished incoming = coros.Queue() # preventing the incoming socket from being GCed before the test finished
acceptor = proc.spawn_link_exception(lambda : incoming.send(self.listener.accept())) acceptor = gevent.spawn_link_exception(lambda : incoming.send(self.listener.accept()))
client = self.create_connection() client = self.create_connection()
client.settimeout(0.1) client.settimeout(0.1)
start = time.time() start = time.time()
...@@ -145,7 +146,7 @@ class TestSSL(TestTCP): ...@@ -145,7 +146,7 @@ class TestSSL(TestTCP):
assert time.time() - start >= 0.1, (time.time() - start) assert time.time() - start >= 0.1, (time.time() - start)
else: else:
raise AssertionError('socket.timeout should have been raised, instead sendall returned %r' % (result, )) raise AssertionError('socket.timeout should have been raised, instead sendall returned %r' % (result, ))
acceptor.wait() acceptor.get()
if __name__=='__main__': if __name__=='__main__':
......
...@@ -3,11 +3,10 @@ ...@@ -3,11 +3,10 @@
#from __future__ import with_statement #from __future__ import with_statement
from gevent import monkey; monkey.patch_all() from gevent import monkey; monkey.patch_all()
from gevent import queue as Queue from gevent import queue as Queue
import sys
import threading import threading
import time import time
import unittest import unittest
from test import test_support from greentest import test_support
QUEUE_SIZE = 5 QUEUE_SIZE = 5
......
...@@ -138,12 +138,12 @@ class TestHttpd(TestCase): ...@@ -138,12 +138,12 @@ class TestHttpd(TestCase):
def setUp(self): def setUp(self):
self.logfile = StringIO() self.logfile = StringIO()
self.site = Site() self.site = Site()
self.killer = gevent.spawn( self.server = gevent.spawn(
wsgi.server, wsgi.server,
socket.tcp_listener(('0.0.0.0', 12346)), self.site, max_size=128, log=self.logfile) socket.tcp_listener(('0.0.0.0', 12346)), self.site, max_size=128, log=self.logfile)
def tearDown(self): def tearDown(self):
gevent.kill(self.killer, block=True) self.server.kill(block=True)
gevent.sleep(0) # XXX kill should be enough! gevent.sleep(0) # XXX kill should be enough!
def test_001_server(self): def test_001_server(self):
...@@ -325,7 +325,7 @@ class TestHttps(TestCase): ...@@ -325,7 +325,7 @@ class TestHttps(TestCase):
result = f.read() result = f.read()
self.assertEquals(result, 'abc') self.assertEquals(result, 'abc')
finally: finally:
gevent.kill(g) g.kill() # XXX use blocking kill
def test_013_empty_return(self): def test_013_empty_return(self):
def wsgi_app(environ, start_response): def wsgi_app(environ, start_response):
...@@ -342,7 +342,7 @@ class TestHttps(TestCase): ...@@ -342,7 +342,7 @@ class TestHttps(TestCase):
result = f.read() result = f.read()
self.assertEquals(result, '') self.assertEquals(result, '')
finally: finally:
gevent.kill(g) g.kill()
class HTTPRequest(urllib2.Request): class HTTPRequest(urllib2.Request):
......
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