11 from test
import test_support
12 from test
.test_support
import TESTFN
, run_unittest
, unlink
13 from StringIO
import StringIO
20 HOST
= test_support
.HOST
34 self
.socket
= dummysocket()
43 def handle_read_event(self
):
44 raise asyncore
.ExitNow()
46 handle_write_event
= handle_read_event
47 handle_close
= handle_read_event
48 handle_expt_event
= handle_read_event
52 self
.error_handled
= False
54 def handle_read_event(self
):
57 handle_write_event
= handle_read_event
58 handle_close
= handle_read_event
59 handle_expt_event
= handle_read_event
61 def handle_error(self
):
62 self
.error_handled
= True
64 # used when testing senders; just collects what it gets until newline is sent
65 def capture_server(evt
, buf
, serv
):
68 conn
, addr
= serv
.accept()
69 except socket
.timeout
:
74 r
, w
, e
= select
.select([conn
], [], [])
77 # keep everything except for the newline terminator
78 buf
.write(data
.replace('\n', ''))
90 class HelperFunctionTests(unittest
.TestCase
):
91 def test_readwriteexc(self
):
92 # Check exception handling behavior of read, write and _exception
94 # check that ExitNow exceptions in the object handler method
95 # bubbles all the way up through asyncore read/write/_exception calls
97 self
.assertRaises(asyncore
.ExitNow
, asyncore
.read
, tr1
)
98 self
.assertRaises(asyncore
.ExitNow
, asyncore
.write
, tr1
)
99 self
.assertRaises(asyncore
.ExitNow
, asyncore
._exception
, tr1
)
101 # check that an exception other than ExitNow in the object handler
102 # method causes the handle_error method to get called
103 tr2
= crashingdummy()
105 self
.assertEqual(tr2
.error_handled
, True)
107 tr2
= crashingdummy()
109 self
.assertEqual(tr2
.error_handled
, True)
111 tr2
= crashingdummy()
112 asyncore
._exception
(tr2
)
113 self
.assertEqual(tr2
.error_handled
, True)
115 # asyncore.readwrite uses constants in the select module that
116 # are not present in Windows systems (see this thread:
117 # http://mail.python.org/pipermail/python-list/2001-October/109973.html)
118 # These constants should be present as long as poll is available
120 if hasattr(select
, 'poll'):
121 def test_readwrite(self
):
122 # Check that correct methods are called by readwrite()
124 attributes
= ('read', 'expt', 'write', 'closed', 'error_handled')
127 (select
.POLLIN
, 'read'),
128 (select
.POLLPRI
, 'expt'),
129 (select
.POLLOUT
, 'write'),
130 (select
.POLLERR
, 'closed'),
131 (select
.POLLHUP
, 'closed'),
132 (select
.POLLNVAL
, 'closed'),
141 self
.error_handled
= False
143 def handle_read_event(self
):
146 def handle_write_event(self
):
149 def handle_close(self
):
152 def handle_expt_event(self
):
155 def handle_error(self
):
156 self
.error_handled
= True
158 for flag
, expectedattr
in expected
:
160 self
.assertEqual(getattr(tobj
, expectedattr
), False)
161 asyncore
.readwrite(tobj
, flag
)
163 # Only the attribute modified by the routine we expect to be
164 # called should be True.
165 for attr
in attributes
:
166 self
.assertEqual(getattr(tobj
, attr
), attr
==expectedattr
)
168 # check that ExitNow exceptions in the object handler method
169 # bubbles all the way up through asyncore readwrite call
171 self
.assertRaises(asyncore
.ExitNow
, asyncore
.readwrite
, tr1
, flag
)
173 # check that an exception other than ExitNow in the object handler
174 # method causes the handle_error method to get called
175 tr2
= crashingdummy()
176 self
.assertEqual(tr2
.error_handled
, False)
177 asyncore
.readwrite(tr2
, flag
)
178 self
.assertEqual(tr2
.error_handled
, True)
180 def test_closeall(self
):
181 self
.closeall_check(False)
183 def test_closeall_default(self
):
184 self
.closeall_check(True)
186 def closeall_check(self
, usedefault
):
187 # Check that close_all() closes everything in a given map
194 self
.assertEqual(c
.socket
.closed
, False)
198 socketmap
= asyncore
.socket_map
200 asyncore
.socket_map
= testmap
203 testmap
, asyncore
.socket_map
= asyncore
.socket_map
, socketmap
205 asyncore
.close_all(testmap
)
207 self
.assertEqual(len(testmap
), 0)
210 self
.assertEqual(c
.socket
.closed
, True)
212 def test_compact_traceback(self
):
214 raise Exception("I don't like spam!")
216 real_t
, real_v
, real_tb
= sys
.exc_info()
217 r
= asyncore
.compact_traceback()
219 self
.fail("Expected exception")
221 (f
, function
, line
), t
, v
, info
= r
222 self
.assertEqual(os
.path
.split(f
)[-1], 'test_asyncore.py')
223 self
.assertEqual(function
, 'test_compact_traceback')
224 self
.assertEqual(t
, real_t
)
225 self
.assertEqual(v
, real_v
)
226 self
.assertEqual(info
, '[%s|%s|%s]' % (f
, function
, line
))
229 class DispatcherTests(unittest
.TestCase
):
236 def test_basic(self
):
237 d
= asyncore
.dispatcher()
238 self
.assertEqual(d
.readable(), True)
239 self
.assertEqual(d
.writable(), True)
242 d
= asyncore
.dispatcher()
243 self
.assertEqual(repr(d
), '<asyncore.dispatcher at %#x>' % id(d
))
246 d
= asyncore
.dispatcher()
248 # capture output of dispatcher.log() (to stderr)
251 l1
= "Lovely spam! Wonderful spam!"
252 l2
= "I don't like spam!"
260 lines
= fp
.getvalue().splitlines()
261 self
.assertEquals(lines
, ['log: %s' % l1
, 'log: %s' % l2
])
263 def test_log_info(self
):
264 d
= asyncore
.dispatcher()
266 # capture output of dispatcher.log_info() (to stdout via print)
269 l1
= "Have you got anything without spam?"
270 l2
= "Why can't she have egg bacon spam and sausage?"
271 l3
= "THAT'S got spam in it!"
274 d
.log_info(l1
, 'EGGS')
276 d
.log_info(l3
, 'SPAM')
280 lines
= fp
.getvalue().splitlines()
281 expected
= ['EGGS: %s' % l1
, 'info: %s' % l2
, 'SPAM: %s' % l3
]
283 self
.assertEquals(lines
, expected
)
285 def test_unhandled(self
):
286 d
= asyncore
.dispatcher()
287 d
.ignore_log_types
= ()
289 # capture output of dispatcher.log_info() (to stdout via print)
302 lines
= fp
.getvalue().splitlines()
303 expected
= ['warning: unhandled incoming priority event',
304 'warning: unhandled read event',
305 'warning: unhandled write event',
306 'warning: unhandled connect event',
307 'warning: unhandled accept event']
308 self
.assertEquals(lines
, expected
)
310 def test_issue_8594(self
):
311 # XXX - this test is supposed to be removed in next major Python
313 d
= asyncore
.dispatcher(socket
.socket())
314 # make sure the error message no longer refers to the socket
315 # object but the dispatcher instance instead
316 self
.assertRaisesRegexp(AttributeError, 'dispatcher instance',
318 # cheap inheritance with the underlying socket is supposed
319 # to still work but a DeprecationWarning is expected
320 with warnings
.catch_warnings(record
=True) as w
:
321 warnings
.simplefilter("always")
323 self
.assertEqual(family
, socket
.AF_INET
)
324 self
.assertTrue(len(w
) == 1)
325 self
.assertTrue(issubclass(w
[0].category
, DeprecationWarning))
327 def test_strerror(self
):
328 # refers to bug #8573
329 err
= asyncore
._strerror
(errno
.EPERM
)
330 if hasattr(os
, 'strerror'):
331 self
.assertEqual(err
, os
.strerror(errno
.EPERM
))
332 err
= asyncore
._strerror
(-1)
333 self
.assertTrue("unknown error" in err
.lower())
336 class dispatcherwithsend_noread(asyncore
.dispatcher_with_send
):
340 def handle_connect(self
):
343 class DispatcherWithSendTests(unittest
.TestCase
):
352 @unittest.skipUnless(threading
, 'Threading required for this test.')
353 @test_support.reap_threads
355 evt
= threading
.Event()
356 sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
358 port
= test_support
.bind_port(sock
)
361 args
= (evt
, cap
, sock
)
362 t
= threading
.Thread(target
=capture_server
, args
=args
)
365 # wait a little longer for the server to initialize (it sometimes
366 # refuses connections on slow machines without this wait)
369 data
= "Suppose there isn't a 16-ton weight?"
370 d
= dispatcherwithsend_noread()
371 d
.create_socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
372 d
.connect((HOST
, port
))
374 # give time for socket to connect
382 while d
.out_buffer
and n
> 0:
388 self
.assertEqual(cap
.getvalue(), data
*2)
393 class DispatcherWithSendTests_UsePoll(DispatcherWithSendTests
):
396 if hasattr(asyncore
, 'file_wrapper'):
397 class FileWrapperTest(unittest
.TestCase
):
399 self
.d
= "It's not dead, it's sleeping!"
400 file(TESTFN
, 'w').write(self
.d
)
406 fd
= os
.open(TESTFN
, os
.O_RDONLY
)
407 w
= asyncore
.file_wrapper(fd
)
410 self
.assertNotEqual(w
.fd
, fd
)
411 self
.assertNotEqual(w
.fileno(), fd
)
412 self
.assertEqual(w
.recv(13), "It's not dead")
413 self
.assertEqual(w
.read(6), ", it's")
415 self
.assertRaises(OSError, w
.read
, 1)
419 d2
= "I want to buy some cheese."
420 fd
= os
.open(TESTFN
, os
.O_WRONLY | os
.O_APPEND
)
421 w
= asyncore
.file_wrapper(fd
)
427 self
.assertEqual(file(TESTFN
).read(), self
.d
+ d1
+ d2
)
430 class BaseTestHandler(asyncore
.dispatcher
):
432 def __init__(self
, sock
=None):
433 asyncore
.dispatcher
.__init
__(self
, sock
)
436 def handle_accept(self
):
437 raise Exception("handle_accept not supposed to be called")
439 def handle_connect(self
):
440 raise Exception("handle_connect not supposed to be called")
442 def handle_expt(self
):
443 raise Exception("handle_expt not supposed to be called")
445 def handle_close(self
):
446 raise Exception("handle_close not supposed to be called")
448 def handle_error(self
):
452 class TCPServer(asyncore
.dispatcher
):
453 """A server which listens on an address and dispatches the
454 connection to a handler.
457 def __init__(self
, handler
=BaseTestHandler
, host
=HOST
, port
=0):
458 asyncore
.dispatcher
.__init
__(self
)
459 self
.create_socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
460 self
.set_reuse_addr()
461 self
.bind((host
, port
))
463 self
.handler
= handler
467 return self
.socket
.getsockname()[:2]
469 def handle_accept(self
):
470 sock
, addr
= self
.accept()
473 def handle_error(self
):
477 class BaseClient(BaseTestHandler
):
479 def __init__(self
, address
):
480 BaseTestHandler
.__init
__(self
)
481 self
.create_socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
482 self
.connect(address
)
484 def handle_connect(self
):
488 class BaseTestAPI(unittest
.TestCase
):
493 def loop_waiting_for_flag(self
, instance
, timeout
=5):
494 timeout
= float(timeout
) / 100
496 while asyncore
.socket_map
and count
> 0:
497 asyncore
.loop(timeout
=0.01, count
=1, use_poll
=self
.use_poll
)
502 self
.fail("flag not set")
504 def test_handle_connect(self
):
505 # make sure handle_connect is called on connect()
507 class TestClient(BaseClient
):
508 def handle_connect(self
):
512 client
= TestClient(server
.address
)
513 self
.loop_waiting_for_flag(client
)
515 def test_handle_accept(self
):
516 # make sure handle_accept() is called when a client connects
518 class TestListener(BaseTestHandler
):
521 BaseTestHandler
.__init
__(self
)
522 self
.create_socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
525 self
.address
= self
.socket
.getsockname()[:2]
527 def handle_accept(self
):
530 server
= TestListener()
531 client
= BaseClient(server
.address
)
532 self
.loop_waiting_for_flag(server
)
534 def test_handle_read(self
):
535 # make sure handle_read is called on data received
537 class TestClient(BaseClient
):
538 def handle_read(self
):
541 class TestHandler(BaseTestHandler
):
542 def __init__(self
, conn
):
543 BaseTestHandler
.__init
__(self
, conn
)
544 self
.send('x' * 1024)
546 server
= TCPServer(TestHandler
)
547 client
= TestClient(server
.address
)
548 self
.loop_waiting_for_flag(client
)
550 def test_handle_write(self
):
551 # make sure handle_write is called
553 class TestClient(BaseClient
):
554 def handle_write(self
):
558 client
= TestClient(server
.address
)
559 self
.loop_waiting_for_flag(client
)
561 def test_handle_close(self
):
562 # make sure handle_close is called when the other end closes
565 class TestClient(BaseClient
):
567 def handle_read(self
):
568 # in order to make handle_close be called we are supposed
569 # to make at least one recv() call
572 def handle_close(self
):
576 class TestHandler(BaseTestHandler
):
577 def __init__(self
, conn
):
578 BaseTestHandler
.__init
__(self
, conn
)
581 server
= TCPServer(TestHandler
)
582 client
= TestClient(server
.address
)
583 self
.loop_waiting_for_flag(client
)
585 @unittest.skipIf(sys
.platform
.startswith("sunos"),
586 "OOB support is broken on Solaris")
587 def test_handle_expt(self
):
588 # Make sure handle_expt is called on OOB data received.
589 # Note: this might fail on some platforms as OOB data is
590 # tenuously supported and rarely used.
592 class TestClient(BaseClient
):
593 def handle_expt(self
):
596 class TestHandler(BaseTestHandler
):
597 def __init__(self
, conn
):
598 BaseTestHandler
.__init
__(self
, conn
)
599 self
.socket
.send(chr(244), socket
.MSG_OOB
)
601 server
= TCPServer(TestHandler
)
602 client
= TestClient(server
.address
)
603 self
.loop_waiting_for_flag(client
)
605 def test_handle_error(self
):
607 class TestClient(BaseClient
):
608 def handle_write(self
):
610 def handle_error(self
):
614 except ZeroDivisionError:
617 raise Exception("exception not raised")
620 client
= TestClient(server
.address
)
621 self
.loop_waiting_for_flag(client
)
623 def test_connection_attributes(self
):
625 client
= BaseClient(server
.address
)
627 # we start disconnected
628 self
.assertFalse(server
.connected
)
629 self
.assertTrue(server
.accepting
)
630 # this can't be taken for granted across all platforms
631 #self.assertFalse(client.connected)
632 self
.assertFalse(client
.accepting
)
634 # execute some loops so that client connects to server
635 asyncore
.loop(timeout
=0.01, use_poll
=self
.use_poll
, count
=100)
636 self
.assertFalse(server
.connected
)
637 self
.assertTrue(server
.accepting
)
638 self
.assertTrue(client
.connected
)
639 self
.assertFalse(client
.accepting
)
641 # disconnect the client
643 self
.assertFalse(server
.connected
)
644 self
.assertTrue(server
.accepting
)
645 self
.assertFalse(client
.connected
)
646 self
.assertFalse(client
.accepting
)
650 self
.assertFalse(server
.connected
)
651 self
.assertFalse(server
.accepting
)
653 def test_create_socket(self
):
654 s
= asyncore
.dispatcher()
655 s
.create_socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
656 self
.assertEqual(s
.socket
.family
, socket
.AF_INET
)
657 self
.assertEqual(s
.socket
.type, socket
.SOCK_STREAM
)
660 s1
= asyncore
.dispatcher()
661 s1
.create_socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
664 port
= s1
.socket
.getsockname()[1]
666 s2
= asyncore
.dispatcher()
667 s2
.create_socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
668 # EADDRINUSE indicates the socket was correctly bound
669 self
.assertRaises(socket
.error
, s2
.bind
, (HOST
, port
))
671 def test_set_reuse_addr(self
):
672 sock
= socket
.socket()
674 sock
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_REUSEADDR
, 1)
676 unittest
.skip("SO_REUSEADDR not supported on this platform")
678 # if SO_REUSEADDR succeeded for sock we expect asyncore
680 s
= asyncore
.dispatcher(socket
.socket())
681 self
.assertFalse(s
.socket
.getsockopt(socket
.SOL_SOCKET
,
682 socket
.SO_REUSEADDR
))
683 s
.create_socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
685 self
.assertTrue(s
.socket
.getsockopt(socket
.SOL_SOCKET
,
686 socket
.SO_REUSEADDR
))
691 class TestAPI_UseSelect(BaseTestAPI
):
694 class TestAPI_UsePoll(BaseTestAPI
):
699 tests
= [HelperFunctionTests
, DispatcherTests
, DispatcherWithSendTests
,
700 DispatcherWithSendTests_UsePoll
, TestAPI_UseSelect
]
701 if hasattr(asyncore
, 'file_wrapper'):
702 tests
.append(FileWrapperTest
)
703 if hasattr(select
, 'poll'):
704 tests
.append(TestAPI_UsePoll
)
708 if __name__
== "__main__":