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__':
......
...@@ -21,79 +21,151 @@ ...@@ -21,79 +21,151 @@
import sys import sys
import greentest import greentest
from gevent import sleep, with_timeout, Timeout, getcurrent import gevent
from gevent import proc, coros import re
from gevent import sleep, with_timeout, getcurrent
from gevent import greenlet
from gevent.event import Event, AsyncResult
from gevent.queue import Queue
DELAY = 0.01 DELAY = 0.01
class ExpectedError(Exception): class ExpectedError(Exception):
pass pass
class TestLink_Signal(greentest.TestCase):
class TestLink(greentest.TestCase):
def test_send(self):
s = proc.Source() def assertRaises(self, err, func, *args, **kwargs):
q1, q2, q3 = coros.Queue(), coros.Queue(), coros.Queue() try:
s.link_value(q1) result = func(*args, **kwargs)
self.assertRaises(Timeout, s.wait, 0) except:
assert s.wait(0, False) is None ex = sys.exc_info()[1]
assert s.wait(0.001, False) is None if ex is err:
self.assertRaises(Timeout, s.wait, 0.001) return
s.send(1) if isinstance(ex, err):
assert not q1.ready() return
assert s.wait()==1 raise
sleep(0) raise AssertionError('%s not raised, returned %r' % (err, result))
assert q1.ready()
s.link_exception(q2) def test_link_to_greenlet(self):
s.link(q3) p = gevent.spawn(lambda : 100)
assert not q2.ready() receiver = gevent.spawn(sleep, 1)
sleep(0)
assert q3.ready()
assert s.wait()==1
def test_send_exception(self):
s = proc.Source()
q1, q2, q3 = coros.Queue(), coros.Queue(), coros.Queue()
s.link_exception(q1)
s.send_exception(OSError('hello'))
sleep(0)
assert q1.ready()
s.link_value(q2)
s.link(q3)
assert not q2.ready()
sleep(0)
assert q3.ready()
self.assertRaises(OSError, q1.wait)
self.assertRaises(OSError, q3.wait)
self.assertRaises(OSError, s.wait)
class TestProc(greentest.TestCase):
def test_proc(self):
p = proc.spawn(lambda : 100)
receiver = proc.spawn(sleep, 1)
p.link(receiver) p.link(receiver)
self.assertRaises(proc.LinkedCompleted, receiver.wait) self.assertRaises(greenlet.LinkedCompleted, receiver.get)
receiver2 = proc.spawn(sleep, 1) receiver2 = gevent.spawn(sleep, 1)
p.link(receiver2) p.link(receiver2)
self.assertRaises(proc.LinkedCompleted, receiver2.wait) self.assertRaises(greenlet.LinkedCompleted, receiver2.get)
def test_link_to_event(self):
p = gevent.spawn(lambda : 100)
event = Event()
p.link(event.put)
self.assertEqual(event.get().get(), 100)
def test_event(self): for i in xrange(3):
p = proc.spawn(lambda : 100) event2 = Event()
event = coros.event() p.link(event2.put)
self.assertEqual(event2.get().get(), 100)
def test_link_to_asyncresult(self):
p = gevent.spawn(lambda : 100)
event = AsyncResult()
p.link(event) p.link(event)
self.assertEqual(event.wait(), 100) self.assertEqual(event.get(), 100)
for i in xrange(3): for i in xrange(3):
event2 = coros.event() event2 = AsyncResult()
p.link(event2) p.link(event2)
self.assertEqual(event2.wait(), 100) self.assertEqual(event2.get(), 100)
def test_current(self): def test_link_to_asyncresult_exception(self):
p = proc.spawn(lambda : 100) err = ExpectedError('test_link_to_asyncresult_exception')
p = gevent.spawn(lambda : getcurrent().throw(err))
event = AsyncResult()
p.link(event)
self.assertRaises(err, event.get)
for i in xrange(3):
event2 = AsyncResult()
p.link(event2)
self.assertRaises(err, event.get)
def test_link_to_queue(self):
p = gevent.spawn(lambda : 100)
q = Queue()
p.link(q.put)
self.assertEqual(q.get().get(), 100)
for i in xrange(3):
p.link(q.put)
self.assertEqual(q.get().get(), 100)
def test_link_to_channel(self):
p1 = gevent.spawn(lambda : 101)
p2 = gevent.spawn(lambda : 102)
p3 = gevent.spawn(lambda : 103)
q = Queue(0)
p1.link(q.put)
p2.link(q.put)
p3.link(q.put)
results = [q.get().get(), q.get().get(), q.get().get()]
assert sorted(results) == [101, 102, 103], results
def test_link_to_current(self):
p = gevent.spawn(lambda : 100)
p.link() p.link()
self.assertRaises(proc.LinkedCompleted, sleep, 0.1) self.assertRaises(greenlet.LinkedCompleted, sleep, 0.1)
self.assertRaises(greenlet.LinkedCompleted, p.link)
class TestUnlink(greentest.TestCase):
def setUp(self):
self.p = gevent.spawn(test_func)
def _test_func(self, link):
p = self.p
link(test_func)
assert len(p._links)==1, p._links
p.unlink(test_func)
assert not p._links, p._links
link(self.setUp)
assert len(p._links)==1, p._links
p.unlink(self.setUp)
assert not p._links, p._links
def test_func_link(self):
self._test_func(self.p.link)
def test_func_link_value(self):
self._test_func(self.p.link_value)
def test_func_link_exception(self):
self._test_func(self.p.link_exception)
def _test_greenlet(self, link):
p = self.p
link(getcurrent())
assert len(p._links)==1, p._links
p.unlink(getcurrent())
assert not p._links, p._links
g = gevent.Greenlet()
link(g)
assert len(p._links)==1, p._links
p.unlink(g)
assert not p._links, p._links
def test_greenlet_link(self):
self._test_greenlet(self.p.link)
def test_greenlet_link_value(self):
self._test_greenlet(self.p.link_value)
def test_greenlet_link_exception(self):
self._test_greenlet(self.p.link_exception)
class LinksTestCase(greentest.TestCase): class LinksTestCase(greentest.TestCase):
...@@ -106,18 +178,18 @@ class LinksTestCase(greentest.TestCase): ...@@ -106,18 +178,18 @@ class LinksTestCase(greentest.TestCase):
self.p.unlink() self.p.unlink()
def set_links(self, p, first_time, kill_exc_type): def set_links(self, p, first_time, kill_exc_type):
event = coros.event() event = AsyncResult()
self.link(p, event) self.link(p, event)
proc_flag = [] proc_flag = []
def receiver(): def receiver():
sleep(DELAY) sleep(DELAY)
proc_flag.append('finished') proc_flag.append('finished')
receiver = proc.spawn(receiver) receiver = gevent.spawn(receiver)
self.link(p, receiver) self.link(p, receiver)
queue = coros.Channel(1) queue = Queue(1)
self.link(p, queue) self.link(p, queue.put)
try: try:
self.link(p) self.link(p)
...@@ -131,13 +203,13 @@ class LinksTestCase(greentest.TestCase): ...@@ -131,13 +203,13 @@ class LinksTestCase(greentest.TestCase):
self.link(p, lambda *args: callback_flag.remove('initial')) self.link(p, lambda *args: callback_flag.remove('initial'))
for _ in range(10): for _ in range(10):
self.link(p, coros.event()) self.link(p, AsyncResult())
self.link(p, coros.Channel(1)) self.link(p, Queue(1).put)
return event, receiver, proc_flag, queue, callback_flag return event, receiver, proc_flag, queue, callback_flag
def set_links_timeout(self, link): def set_links_timeout(self, link):
# stuff that won't be touched # stuff that won't be touched
event = coros.event() event = AsyncResult()
link(event) link(event)
proc_finished_flag = [] proc_finished_flag = []
...@@ -145,18 +217,17 @@ class LinksTestCase(greentest.TestCase): ...@@ -145,18 +217,17 @@ class LinksTestCase(greentest.TestCase):
sleep(10) sleep(10)
proc_finished_flag.append('finished') proc_finished_flag.append('finished')
return 555 return 555
myproc = proc.spawn(myproc) myproc = gevent.spawn(myproc)
link(myproc) link(myproc)
queue = coros.Channel() queue = Queue(0)
link(queue) link(queue.put)
return event, myproc, proc_finished_flag, queue return event, myproc, proc_finished_flag, queue
def check_timed_out(self, event, myproc, proc_finished_flag, queue): def check_timed_out(self, event, myproc, proc_finished_flag, queue):
X = object() assert with_timeout(DELAY, event.get, timeout_value=X) is X, repr(event.get())
assert with_timeout(DELAY, event.wait, timeout_value=X) is X assert with_timeout(DELAY, queue.get, timeout_value=X) is X, queue.get()
assert with_timeout(DELAY, queue.wait, timeout_value=X) is X assert with_timeout(DELAY, gevent.joinall, [myproc], timeout_value=X) is X
assert with_timeout(DELAY, proc.waitall, [myproc], timeout_value=X) is X
assert proc_finished_flag == [], proc_finished_flag assert proc_finished_flag == [], proc_finished_flag
...@@ -166,11 +237,11 @@ class TestReturn_link(LinksTestCase): ...@@ -166,11 +237,11 @@ class TestReturn_link(LinksTestCase):
def test_return(self): def test_return(self):
def return25(): def return25():
return 25 return 25
p = self.p = proc.spawn(return25) p = self.p = gevent.spawn(return25)
self._test_return(p, True, 25, proc.LinkedCompleted, lambda : sleep(0)) self._test_return(p, True, 25, greenlet.LinkedCompleted, lambda : sleep(0))
# repeating the same with dead process # repeating the same with dead process
for _ in xrange(3): for _ in xrange(3):
self._test_return(p, False, 25, proc.LinkedCompleted, lambda : sleep(0)) self._test_return(p, False, 25, greenlet.LinkedCompleted, lambda : sleep(0))
def _test_return(self, p, first_time, result, kill_exc_type, action): def _test_return(self, p, first_time, result, kill_exc_type, action):
event, receiver, proc_flag, queue, callback_flag = self.set_links(p, first_time, kill_exc_type) event, receiver, proc_flag, queue, callback_flag = self.set_links(p, first_time, kill_exc_type)
...@@ -187,10 +258,10 @@ class TestReturn_link(LinksTestCase): ...@@ -187,10 +258,10 @@ class TestReturn_link(LinksTestCase):
assert not p, p assert not p, p
self.assertEqual(event.wait(), result) self.assertEqual(event.get(), result)
self.assertEqual(queue.wait(), result) self.assertEqual(queue.get().get(), result)
self.assertRaises(kill_exc_type, receiver.wait) self.assertRaises(kill_exc_type, receiver.get)
self.assertRaises(kill_exc_type, proc.waitall, [receiver]) self.assertRaises(kill_exc_type, gevent.joinall, [receiver], raise_error=True)
sleep(DELAY) sleep(DELAY)
assert not proc_flag, proc_flag assert not proc_flag, proc_flag
...@@ -198,18 +269,11 @@ class TestReturn_link(LinksTestCase): ...@@ -198,18 +269,11 @@ class TestReturn_link(LinksTestCase):
self.check_timed_out(*xxxxx) self.check_timed_out(*xxxxx)
class TestReturn_link_value(TestReturn_link): def _test_kill(self, p, first_time, kill_exc_type):
sync = False
link_method = 'link_value'
class TestRaise_link(LinksTestCase):
link_method = 'link'
def _test_raise(self, p, first_time, kill_exc_type):
event, receiver, proc_flag, queue, callback_flag = self.set_links(p, first_time, kill_exc_type) event, receiver, proc_flag, queue, callback_flag = self.set_links(p, first_time, kill_exc_type)
xxxxx = self.set_links_timeout(p.link_value) xxxxx = self.set_links_timeout(p.link_exception)
p.kill()
try: try:
sleep(DELAY) sleep(DELAY)
except kill_exc_type: except kill_exc_type:
...@@ -219,28 +283,37 @@ class TestRaise_link(LinksTestCase): ...@@ -219,28 +283,37 @@ class TestRaise_link(LinksTestCase):
assert not p, p assert not p, p
self.assertRaises(ExpectedError, event.wait) assert isinstance(event.get(), greenlet.GreenletExit), event.get()
self.assertRaises(ExpectedError, queue.wait) assert isinstance(queue.get().get(), greenlet.GreenletExit), queue.get().get()
self.assertRaises(kill_exc_type, receiver.wait) self.assertRaises(kill_exc_type, gevent.joinall, [receiver], raise_error=True)
self.assertRaises(kill_exc_type, proc.waitall, [receiver]) self.assertRaises(kill_exc_type, receiver.get)
sleep(DELAY) sleep(DELAY)
assert not proc_flag, proc_flag assert not proc_flag, proc_flag
assert not callback_flag, callback_flag assert not callback_flag, callback_flag
self.check_timed_out(*xxxxx) self.check_timed_out(*xxxxx)
def test_raise(self): def test_kill(self):
p = self.p = proc.spawn(lambda : getcurrent().throw(ExpectedError('test_raise'))) p = self.p = gevent.spawn(sleep, DELAY)
self._test_raise(p, True, proc.LinkedFailed) self._test_kill(p, True, greenlet.LinkedKilled)
# repeating the same with dead process # repeating the same with dead process
for _ in xrange(3): for _ in xrange(3):
self._test_raise(p, False, proc.LinkedFailed) self._test_kill(p, False, greenlet.LinkedKilled)
def _test_kill(self, p, first_time, kill_exc_type):
class TestReturn_link_value(TestReturn_link):
sync = False
link_method = 'link_value'
class TestRaise_link(LinksTestCase):
link_method = 'link'
def _test_raise(self, p, first_time, kill_exc_type):
event, receiver, proc_flag, queue, callback_flag = self.set_links(p, first_time, kill_exc_type) event, receiver, proc_flag, queue, callback_flag = self.set_links(p, first_time, kill_exc_type)
xxxxx = self.set_links_timeout(p.link_value) xxxxx = self.set_links_timeout(p.link_value)
p.kill()
try: try:
sleep(DELAY) sleep(DELAY)
except kill_exc_type: except kill_exc_type:
...@@ -250,69 +323,69 @@ class TestRaise_link(LinksTestCase): ...@@ -250,69 +323,69 @@ class TestRaise_link(LinksTestCase):
assert not p, p assert not p, p
self.assertRaises(proc.ProcExit, event.wait) self.assertRaises(ExpectedError, event.get)
self.assertRaises(proc.ProcExit, queue.wait) self.assertEqual(queue.get(), p)
self.assertRaises(kill_exc_type, proc.waitall, [receiver]) self.assertRaises(kill_exc_type, receiver.get)
self.assertRaises(kill_exc_type, receiver.wait) self.assertRaises(kill_exc_type, gevent.joinall, [receiver], raise_error=True)
sleep(DELAY) sleep(DELAY)
assert not proc_flag, proc_flag assert not proc_flag, proc_flag
assert not callback_flag, callback_flag assert not callback_flag, callback_flag
self.check_timed_out(*xxxxx) self.check_timed_out(*xxxxx)
def test_kill(self): def test_raise(self):
p = self.p = proc.spawn(sleep, DELAY) p = self.p = gevent.spawn(lambda : getcurrent().throw(ExpectedError('test_raise')))
self._test_kill(p, True, proc.LinkedKilled) self._test_raise(p, True, greenlet.LinkedFailed)
# repeating the same with dead process # repeating the same with dead process
for _ in xrange(3): for _ in xrange(3):
self._test_kill(p, False, proc.LinkedKilled) self._test_raise(p, False, greenlet.LinkedFailed)
class TestRaise_link_exception(TestRaise_link): class TestRaise_link_exception(TestRaise_link):
link_method = 'link_exception' link_method = 'link_exception'
#
#
class TestStuff(greentest.TestCase): class TestStuff(greentest.TestCase):
def test_wait_noerrors(self): def test_wait_noerrors(self):
x = proc.spawn(lambda : 1) x = gevent.spawn(lambda : 1)
y = proc.spawn(lambda : 2) y = gevent.spawn(lambda : 2)
z = proc.spawn(lambda : 3) z = gevent.spawn(lambda : 3)
self.assertEqual(proc.waitall([x, y, z]), [1, 2, 3]) gevent.joinall([x, y, z], raise_error=True)
e = coros.event() self.assertEqual([x.value, y.value, z.value], [1, 2, 3])
e = AsyncResult()
x.link(e) x.link(e)
self.assertEqual(e.wait(), 1) self.assertEqual(e.get(), 1)
x.unlink(e) x.unlink(e)
e = coros.event() e = AsyncResult()
x.link(e) x.link(e)
self.assertEqual(e.wait(), 1) self.assertEqual(e.get(), 1)
self.assertEqual([proc.waitall([X]) for X in [x, y, z]], [[1], [2], [3]]) #self.assertEqual([proc.waitall([X]) for X in [x, y, z]], [[1], [2], [3]])
def test_wait_error(self): def test_wait_error(self):
def x(): def x():
sleep(DELAY) sleep(DELAY)
return 1 return 1
x = proc.spawn(x) x = gevent.spawn(x)
z = proc.spawn(lambda : 3) z = gevent.spawn(lambda : 3)
y = proc.spawn(lambda : getcurrent().throw(ExpectedError('test_wait_error'))) y = gevent.spawn(lambda : getcurrent().throw(ExpectedError('test_wait_error')))
y.link(x) y.link(x)
x.link(y) x.link(y)
y.link(z) y.link(z)
z.link(y) z.link(y)
self.assertRaises(ExpectedError, proc.waitall, [x, y, z]) self.assertRaises(ExpectedError, gevent.joinall, [x, y, z], raise_error=True)
self.assertRaises(proc.LinkedFailed, proc.waitall, [x]) self.assertRaises(greenlet.LinkedFailed, gevent.joinall, [x], raise_error=True)
self.assertEqual(proc.waitall([z]), [3]) self.assertEqual(z.get(), 3)
self.assertRaises(ExpectedError, proc.waitall, [y]) self.assertRaises(ExpectedError, gevent.joinall, [y], raise_error=True)
#
def test_wait_all_exception_order(self): def test_wait_all_exception_order(self):
# if there're several exceptions raised, the earliest one must be raised by wait # if there're several exceptions raised, the earliest one must be raised by joinall
def first(): def first():
sleep(0.1) sleep(0.1)
raise ExpectedError('first') raise ExpectedError('first')
a = proc.spawn(first) a = gevent.spawn(first)
b = proc.spawn(lambda : getcurrent().throw(ExpectedError('second'))) b = gevent.spawn(lambda : getcurrent().throw(ExpectedError('second')))
try: try:
proc.waitall([a, b]) gevent.joinall([a, b], raise_error=True)
except ExpectedError, ex: except ExpectedError, ex:
assert 'second' in str(ex), repr(str(ex)) assert 'second' in str(ex), repr(str(ex))
...@@ -321,7 +394,7 @@ class TestStuff(greentest.TestCase): ...@@ -321,7 +394,7 @@ class TestStuff(greentest.TestCase):
# it should not prevent the other listeners from being called # it should not prevent the other listeners from being called
# also, all of the errors should be logged, check the output # also, all of the errors should be logged, check the output
# manually that they are # manually that they are
p = proc.spawn(lambda : 5) p = gevent.spawn(lambda : 5)
results = [] results = []
def listener1(*args): def listener1(*args):
results.append(10) results.append(10)
...@@ -337,7 +410,7 @@ class TestStuff(greentest.TestCase): ...@@ -337,7 +410,7 @@ class TestStuff(greentest.TestCase):
sleep(DELAY*10) sleep(DELAY*10)
assert results in [[10, 20], [20, 10]], results assert results in [[10, 20], [20, 10]], results
p = proc.spawn(lambda : getcurrent().throw(ExpectedError('test_multiple_listeners_error'))) p = gevent.spawn(lambda : getcurrent().throw(ExpectedError('test_multiple_listeners_error')))
results = [] results = []
p.link(listener1) p.link(listener1)
p.link(listener2) p.link(listener2)
...@@ -365,23 +438,23 @@ class TestStuff(greentest.TestCase): ...@@ -365,23 +438,23 @@ class TestStuff(greentest.TestCase):
sleep(DELAY*10) sleep(DELAY*10)
assert results == [5], results assert results == [5], results
def test_multiple_listeners_error_unlink_Proc(self): def test_multiple_listeners_error_unlink_Greenlet(self):
p = proc.spawn(lambda : 5) p = gevent.spawn(lambda : 5)
self._test_multiple_listeners_error_unlink(p) self._test_multiple_listeners_error_unlink(p)
def test_multiple_listeners_error_unlink_Source(self): def test_multiple_listeners_error_unlink_Event(self):
p = proc.Source() e = Event()
proc.spawn(p.send, 6) gevent.spawn(e.put, 6)
self._test_multiple_listeners_error_unlink(p) self._test_multiple_listeners_error_unlink(e)
def test_killing_unlinked(self): def test_killing_unlinked(self):
e = coros.event() e = AsyncResult()
def func(): def func():
try: try:
raise ExpectedError('test_killing_unlinked') raise ExpectedError('test_killing_unlinked')
except: except:
e.send_exception(*sys.exc_info()) e.put_exception(sys.exc_info()[1])
p = proc.spawn_link(func) p = gevent.spawn_link(func)
try: try:
try: try:
e.wait() e.wait()
...@@ -391,6 +464,26 @@ class TestStuff(greentest.TestCase): ...@@ -391,6 +464,26 @@ class TestStuff(greentest.TestCase):
p.unlink() # this disables LinkedCompleted that otherwise would be raised by the next line p.unlink() # this disables LinkedCompleted that otherwise would be raised by the next line
sleep(DELAY) sleep(DELAY)
def test_func(*args):
pass
class A(object):
def method(self):
pass
hexobj = re.compile('0x[0123456789abcdef]+')
class TestStr(greentest.TestCase):
def test(self):
g1 = gevent.Greenlet(test_func)
self.assertEqual(hexobj.sub('X', str(g1)), '<Greenlet at X: test_func>')
g2 = gevent.Greenlet(A().method)
self.assertEqual(hexobj.sub('X', str(g2)), '<Greenlet at X: <bound method A.method of <__main__.A object at X>>>')
X = object()
if __name__=='__main__': if __name__=='__main__':
greentest.main() greentest.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