test_asyncore.py 25.8 KB
Newer Older
1 2 3 4 5 6 7
import asyncore
import unittest
import select
import os
import socket
import sys
import time
8
import errno
9
import struct
10
import threading
11

12
from test import support
Christian Heimes's avatar
Christian Heimes committed
13
from io import BytesIO
14

15 16 17
if support.PGO:
    raise unittest.SkipTest("test is not helpful for PGO")

18

19
TIMEOUT = 3
20 21
HAS_UNIX_SOCKETS = hasattr(socket, 'AF_UNIX')

22 23 24 25 26 27 28 29 30 31 32 33 34 35
class dummysocket:
    def __init__(self):
        self.closed = False

    def close(self):
        self.closed = True

    def fileno(self):
        return 42

class dummychannel:
    def __init__(self):
        self.socket = dummysocket()

36 37 38
    def close(self):
        self.socket.close()

39 40 41 42 43 44 45 46
class exitingdummy:
    def __init__(self):
        pass

    def handle_read_event(self):
        raise asyncore.ExitNow()

    handle_write_event = handle_read_event
47
    handle_close = handle_read_event
48 49 50 51 52 53 54 55 56 57
    handle_expt_event = handle_read_event

class crashingdummy:
    def __init__(self):
        self.error_handled = False

    def handle_read_event(self):
        raise Exception()

    handle_write_event = handle_read_event
58
    handle_close = handle_read_event
59 60 61 62 63 64
    handle_expt_event = handle_read_event

    def handle_error(self):
        self.error_handled = True

# used when testing senders; just collects what it gets until newline is sent
Christian Heimes's avatar
Christian Heimes committed
65
def capture_server(evt, buf, serv):
66
    try:
67
        serv.listen()
68 69 70 71 72
        conn, addr = serv.accept()
    except socket.timeout:
        pass
    else:
        n = 200
73 74 75
        start = time.time()
        while n > 0 and time.time() - start < 3.0:
            r, w, e = select.select([conn], [], [], 0.1)
76
            if r:
77
                n -= 1
78 79 80 81 82
                data = conn.recv(10)
                # keep everything except for the newline terminator
                buf.write(data.replace(b'\n', b''))
                if b'\n' in data:
                    break
83 84 85 86 87 88 89
            time.sleep(0.01)

        conn.close()
    finally:
        serv.close()
        evt.set()

90 91
def bind_af_aware(sock, addr):
    """Helper function to bind a socket according to its family."""
92
    if HAS_UNIX_SOCKETS and sock.family == socket.AF_UNIX:
93
        # Make sure the path doesn't exist.
94
        support.unlink(addr)
95 96 97
        support.bind_unix_socket(sock, addr)
    else:
        sock.bind(addr)
98

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

class HelperFunctionTests(unittest.TestCase):
    def test_readwriteexc(self):
        # Check exception handling behavior of read, write and _exception

        # check that ExitNow exceptions in the object handler method
        # bubbles all the way up through asyncore read/write/_exception calls
        tr1 = exitingdummy()
        self.assertRaises(asyncore.ExitNow, asyncore.read, tr1)
        self.assertRaises(asyncore.ExitNow, asyncore.write, tr1)
        self.assertRaises(asyncore.ExitNow, asyncore._exception, tr1)

        # check that an exception other than ExitNow in the object handler
        # method causes the handle_error method to get called
        tr2 = crashingdummy()
        asyncore.read(tr2)
        self.assertEqual(tr2.error_handled, True)

        tr2 = crashingdummy()
        asyncore.write(tr2)
        self.assertEqual(tr2.error_handled, True)

        tr2 = crashingdummy()
        asyncore._exception(tr2)
        self.assertEqual(tr2.error_handled, True)

125 126 127 128 129
    # asyncore.readwrite uses constants in the select module that
    # are not present in Windows systems (see this thread:
    # http://mail.python.org/pipermail/python-list/2001-October/109973.html)
    # These constants should be present as long as poll is available

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    @unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required')
    def test_readwrite(self):
        # Check that correct methods are called by readwrite()

        attributes = ('read', 'expt', 'write', 'closed', 'error_handled')

        expected = (
            (select.POLLIN, 'read'),
            (select.POLLPRI, 'expt'),
            (select.POLLOUT, 'write'),
            (select.POLLERR, 'closed'),
            (select.POLLHUP, 'closed'),
            (select.POLLNVAL, 'closed'),
            )

        class testobj:
            def __init__(self):
                self.read = False
                self.write = False
                self.closed = False
                self.expt = False
                self.error_handled = False

            def handle_read_event(self):
                self.read = True

            def handle_write_event(self):
                self.write = True

            def handle_close(self):
                self.closed = True

            def handle_expt_event(self):
                self.expt = True

            def handle_error(self):
                self.error_handled = True

        for flag, expectedattr in expected:
            tobj = testobj()
            self.assertEqual(getattr(tobj, expectedattr), False)
            asyncore.readwrite(tobj, flag)

            # Only the attribute modified by the routine we expect to be
            # called should be True.
            for attr in attributes:
                self.assertEqual(getattr(tobj, attr), attr==expectedattr)

            # check that ExitNow exceptions in the object handler method
            # bubbles all the way up through asyncore readwrite call
            tr1 = exitingdummy()
            self.assertRaises(asyncore.ExitNow, asyncore.readwrite, tr1, flag)

            # check that an exception other than ExitNow in the object handler
            # method causes the handle_error method to get called
            tr2 = crashingdummy()
            self.assertEqual(tr2.error_handled, False)
            asyncore.readwrite(tr2, flag)
            self.assertEqual(tr2.error_handled, True)
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

    def test_closeall(self):
        self.closeall_check(False)

    def test_closeall_default(self):
        self.closeall_check(True)

    def closeall_check(self, usedefault):
        # Check that close_all() closes everything in a given map

        l = []
        testmap = {}
        for i in range(10):
            c = dummychannel()
            l.append(c)
            self.assertEqual(c.socket.closed, False)
            testmap[i] = c

        if usedefault:
            socketmap = asyncore.socket_map
            try:
                asyncore.socket_map = testmap
                asyncore.close_all()
            finally:
                testmap, asyncore.socket_map = asyncore.socket_map, socketmap
        else:
            asyncore.close_all(testmap)

        self.assertEqual(len(testmap), 0)

        for c in l:
            self.assertEqual(c.socket.closed, True)

    def test_compact_traceback(self):
        try:
            raise Exception("I don't like spam!")
        except:
            real_t, real_v, real_tb = sys.exc_info()
            r = asyncore.compact_traceback()
        else:
            self.fail("Expected exception")

        (f, function, line), t, v, info = r
        self.assertEqual(os.path.split(f)[-1], 'test_asyncore.py')
        self.assertEqual(function, 'test_compact_traceback')
        self.assertEqual(t, real_t)
        self.assertEqual(v, real_v)
        self.assertEqual(info, '[%s|%s|%s]' % (f, function, line))


class DispatcherTests(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        asyncore.close_all()

    def test_basic(self):
        d = asyncore.dispatcher()
        self.assertEqual(d.readable(), True)
        self.assertEqual(d.writable(), True)

    def test_repr(self):
        d = asyncore.dispatcher()
        self.assertEqual(repr(d), '<asyncore.dispatcher at %#x>' % id(d))

    def test_log(self):
        d = asyncore.dispatcher()

        # capture output of dispatcher.log() (to stderr)
        l1 = "Lovely spam! Wonderful spam!"
        l2 = "I don't like spam!"
261
        with support.captured_stderr() as stderr:
262 263 264
            d.log(l1)
            d.log(l2)

265
        lines = stderr.getvalue().splitlines()
266
        self.assertEqual(lines, ['log: %s' % l1, 'log: %s' % l2])
267 268 269 270 271 272 273 274

    def test_log_info(self):
        d = asyncore.dispatcher()

        # capture output of dispatcher.log_info() (to stdout via print)
        l1 = "Have you got anything without spam?"
        l2 = "Why can't she have egg bacon spam and sausage?"
        l3 = "THAT'S got spam in it!"
275
        with support.captured_stdout() as stdout:
276 277 278 279
            d.log_info(l1, 'EGGS')
            d.log_info(l2)
            d.log_info(l3, 'SPAM')

280
        lines = stdout.getvalue().splitlines()
281
        expected = ['EGGS: %s' % l1, 'info: %s' % l2, 'SPAM: %s' % l3]
282
        self.assertEqual(lines, expected)
283 284 285

    def test_unhandled(self):
        d = asyncore.dispatcher()
286
        d.ignore_log_types = ()
287 288

        # capture output of dispatcher.log_info() (to stdout via print)
289
        with support.captured_stdout() as stdout:
290 291 292 293 294
            d.handle_expt()
            d.handle_read()
            d.handle_write()
            d.handle_connect()

295
        lines = stdout.getvalue().splitlines()
296
        expected = ['warning: unhandled incoming priority event',
297 298
                    'warning: unhandled read event',
                    'warning: unhandled write event',
299
                    'warning: unhandled connect event']
300
        self.assertEqual(lines, expected)
301

302 303 304 305 306 307
    def test_strerror(self):
        # refers to bug #8573
        err = asyncore._strerror(errno.EPERM)
        if hasattr(os, 'strerror'):
            self.assertEqual(err, os.strerror(errno.EPERM))
        err = asyncore._strerror(-1)
308
        self.assertTrue(err != "")
309

310 311 312 313 314 315 316 317 318

class dispatcherwithsend_noread(asyncore.dispatcher_with_send):
    def readable(self):
        return False

    def handle_connect(self):
        pass


319
class DispatcherWithSendTests(unittest.TestCase):
320 321 322 323 324 325
    def setUp(self):
        pass

    def tearDown(self):
        asyncore.close_all()

326
    @support.reap_threads
327
    def test_send(self):
328
        evt = threading.Event()
329
        sock = socket.socket()
330 331
        sock.settimeout(3)
        port = support.bind_port(sock)
332

Christian Heimes's avatar
Christian Heimes committed
333
        cap = BytesIO()
334 335 336 337 338 339 340
        args = (evt, cap, sock)
        t = threading.Thread(target=capture_server, args=args)
        t.start()
        try:
            # wait a little longer for the server to initialize (it sometimes
            # refuses connections on slow machines without this wait)
            time.sleep(0.2)
341

342 343
            data = b"Suppose there isn't a 16-ton weight?"
            d = dispatcherwithsend_noread()
344
            d.create_socket()
345
            d.connect((support.HOST, port))
346

347 348
            # give time for socket to connect
            time.sleep(0.1)
349

350 351 352
            d.send(data)
            d.send(data)
            d.send(b'\n')
353

354 355 356 357
            n = 1000
            while d.out_buffer and n > 0:
                asyncore.poll()
                n -= 1
358

359
            evt.wait()
360

361 362
            self.assertEqual(cap.getvalue(), data*2)
        finally:
363
            support.join_thread(t, timeout=TIMEOUT)
364

365

366 367 368 369 370
@unittest.skipUnless(hasattr(asyncore, 'file_wrapper'),
                     'asyncore.file_wrapper required')
class FileWrapperTest(unittest.TestCase):
    def setUp(self):
        self.d = b"It's not dead, it's sleeping!"
371
        with open(support.TESTFN, 'wb') as file:
372
            file.write(self.d)
373 374

    def tearDown(self):
375
        support.unlink(support.TESTFN)
376 377

    def test_recv(self):
378
        fd = os.open(support.TESTFN, os.O_RDONLY)
379 380 381 382 383 384 385 386 387 388 389 390 391
        w = asyncore.file_wrapper(fd)
        os.close(fd)

        self.assertNotEqual(w.fd, fd)
        self.assertNotEqual(w.fileno(), fd)
        self.assertEqual(w.recv(13), b"It's not dead")
        self.assertEqual(w.read(6), b", it's")
        w.close()
        self.assertRaises(OSError, w.read, 1)

    def test_send(self):
        d1 = b"Come again?"
        d2 = b"I want to buy some cheese."
392
        fd = os.open(support.TESTFN, os.O_WRONLY | os.O_APPEND)
393 394 395 396 397 398
        w = asyncore.file_wrapper(fd)
        os.close(fd)

        w.write(d1)
        w.send(d2)
        w.close()
399
        with open(support.TESTFN, 'rb') as file:
400
            self.assertEqual(file.read(), self.d + d1 + d2)
401

402 403 404
    @unittest.skipUnless(hasattr(asyncore, 'file_dispatcher'),
                         'asyncore.file_dispatcher required')
    def test_dispatcher(self):
405
        fd = os.open(support.TESTFN, os.O_RDONLY)
406 407 408 409 410 411 412 413 414
        data = []
        class FileDispatcher(asyncore.file_dispatcher):
            def handle_read(self):
                data.append(self.recv(29))
        s = FileDispatcher(fd)
        os.close(fd)
        asyncore.loop(timeout=0.01, use_poll=True, count=2)
        self.assertEqual(b"".join(data), self.d)

415 416 417 418
    def test_resource_warning(self):
        # Issue #11453
        fd = os.open(support.TESTFN, os.O_RDONLY)
        f = asyncore.file_wrapper(fd)
419 420

        os.close(fd)
421 422 423 424 425 426 427
        with support.check_warnings(('', ResourceWarning)):
            f = None
            support.gc_collect()

    def test_close_twice(self):
        fd = os.open(support.TESTFN, os.O_RDONLY)
        f = asyncore.file_wrapper(fd)
428 429
        os.close(fd)

430 431 432 433
        os.close(f.fd)  # file_wrapper dupped fd
        with self.assertRaises(OSError):
            f.close()

434 435 436 437
        self.assertEqual(f.fd, -1)
        # calling close twice should not fail
        f.close()

438

439 440 441 442 443 444 445 446 447
class BaseTestHandler(asyncore.dispatcher):

    def __init__(self, sock=None):
        asyncore.dispatcher.__init__(self, sock)
        self.flag = False

    def handle_accept(self):
        raise Exception("handle_accept not supposed to be called")

448 449 450
    def handle_accepted(self):
        raise Exception("handle_accepted not supposed to be called")

451 452 453 454 455 456 457 458 459 460 461 462 463
    def handle_connect(self):
        raise Exception("handle_connect not supposed to be called")

    def handle_expt(self):
        raise Exception("handle_expt not supposed to be called")

    def handle_close(self):
        raise Exception("handle_close not supposed to be called")

    def handle_error(self):
        raise


464
class BaseServer(asyncore.dispatcher):
465 466 467 468
    """A server which listens on an address and dispatches the
    connection to a handler.
    """

469
    def __init__(self, family, addr, handler=BaseTestHandler):
470
        asyncore.dispatcher.__init__(self)
471
        self.create_socket(family)
472
        self.set_reuse_addr()
473
        bind_af_aware(self.socket, addr)
474 475 476 477 478
        self.listen(5)
        self.handler = handler

    @property
    def address(self):
479
        return self.socket.getsockname()
480

481
    def handle_accepted(self, sock, addr):
482 483 484 485 486 487 488 489
        self.handler(sock)

    def handle_error(self):
        raise


class BaseClient(BaseTestHandler):

490
    def __init__(self, family, address):
491
        BaseTestHandler.__init__(self)
492
        self.create_socket(family)
493 494 495 496 497 498
        self.connect(address)

    def handle_connect(self):
        pass


499
class BaseTestAPI:
500 501

    def tearDown(self):
502
        asyncore.close_all(ignore_all=True)
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

    def loop_waiting_for_flag(self, instance, timeout=5):
        timeout = float(timeout) / 100
        count = 100
        while asyncore.socket_map and count > 0:
            asyncore.loop(timeout=0.01, count=1, use_poll=self.use_poll)
            if instance.flag:
                return
            count -= 1
            time.sleep(timeout)
        self.fail("flag not set")

    def test_handle_connect(self):
        # make sure handle_connect is called on connect()

        class TestClient(BaseClient):
            def handle_connect(self):
                self.flag = True

522 523
        server = BaseServer(self.family, self.addr)
        client = TestClient(self.family, server.address)
524 525 526 527 528 529 530
        self.loop_waiting_for_flag(client)

    def test_handle_accept(self):
        # make sure handle_accept() is called when a client connects

        class TestListener(BaseTestHandler):

531
            def __init__(self, family, addr):
532
                BaseTestHandler.__init__(self)
533 534
                self.create_socket(family)
                bind_af_aware(self.socket, addr)
535
                self.listen(5)
536
                self.address = self.socket.getsockname()
537 538 539 540

            def handle_accept(self):
                self.flag = True

541 542
        server = TestListener(self.family, self.addr)
        client = BaseClient(self.family, server.address)
543 544
        self.loop_waiting_for_flag(server)

545 546 547 548 549
    def test_handle_accepted(self):
        # make sure handle_accepted() is called when a client connects

        class TestListener(BaseTestHandler):

550
            def __init__(self, family, addr):
551
                BaseTestHandler.__init__(self)
552 553
                self.create_socket(family)
                bind_af_aware(self.socket, addr)
554
                self.listen(5)
555
                self.address = self.socket.getsockname()
556 557 558 559 560

            def handle_accept(self):
                asyncore.dispatcher.handle_accept(self)

            def handle_accepted(self, sock, addr):
Benjamin Peterson's avatar
Benjamin Peterson committed
561
                sock.close()
562 563
                self.flag = True

564 565
        server = TestListener(self.family, self.addr)
        client = BaseClient(self.family, server.address)
566 567 568
        self.loop_waiting_for_flag(server)


569 570 571 572 573 574 575 576 577 578 579 580
    def test_handle_read(self):
        # make sure handle_read is called on data received

        class TestClient(BaseClient):
            def handle_read(self):
                self.flag = True

        class TestHandler(BaseTestHandler):
            def __init__(self, conn):
                BaseTestHandler.__init__(self, conn)
                self.send(b'x' * 1024)

581 582
        server = BaseServer(self.family, self.addr, TestHandler)
        client = TestClient(self.family, server.address)
583 584 585 586 587 588 589 590 591
        self.loop_waiting_for_flag(client)

    def test_handle_write(self):
        # make sure handle_write is called

        class TestClient(BaseClient):
            def handle_write(self):
                self.flag = True

592 593
        server = BaseServer(self.family, self.addr)
        client = TestClient(self.family, server.address)
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
        self.loop_waiting_for_flag(client)

    def test_handle_close(self):
        # make sure handle_close is called when the other end closes
        # the connection

        class TestClient(BaseClient):

            def handle_read(self):
                # in order to make handle_close be called we are supposed
                # to make at least one recv() call
                self.recv(1024)

            def handle_close(self):
                self.flag = True
                self.close()

        class TestHandler(BaseTestHandler):
            def __init__(self, conn):
                BaseTestHandler.__init__(self, conn)
                self.close()

616 617
        server = BaseServer(self.family, self.addr, TestHandler)
        client = TestClient(self.family, server.address)
618 619
        self.loop_waiting_for_flag(client)

620 621 622 623 624 625 626 627 628 629 630 631 632
    def test_handle_close_after_conn_broken(self):
        # Check that ECONNRESET/EPIPE is correctly handled (issues #5661 and
        # #11265).

        data = b'\0' * 128

        class TestClient(BaseClient):

            def handle_write(self):
                self.send(data)

            def handle_close(self):
                self.flag = True
633 634 635 636
                self.close()

            def handle_expt(self):
                self.flag = True
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
                self.close()

        class TestHandler(BaseTestHandler):

            def handle_read(self):
                self.recv(len(data))
                self.close()

            def writable(self):
                return False

        server = BaseServer(self.family, self.addr, TestHandler)
        client = TestClient(self.family, server.address)
        self.loop_waiting_for_flag(client)

652 653 654 655 656 657
    @unittest.skipIf(sys.platform.startswith("sunos"),
                     "OOB support is broken on Solaris")
    def test_handle_expt(self):
        # Make sure handle_expt is called on OOB data received.
        # Note: this might fail on some platforms as OOB data is
        # tenuously supported and rarely used.
658
        if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX:
659
            self.skipTest("Not applicable to AF_UNIX sockets.")
660

661 662 663
        if sys.platform == "darwin" and self.use_poll:
            self.skipTest("poll may fail on macOS; see issue #28087")

664 665
        class TestClient(BaseClient):
            def handle_expt(self):
666
                self.socket.recv(1024, socket.MSG_OOB)
667 668 669 670 671 672 673
                self.flag = True

        class TestHandler(BaseTestHandler):
            def __init__(self, conn):
                BaseTestHandler.__init__(self, conn)
                self.socket.send(bytes(chr(244), 'latin-1'), socket.MSG_OOB)

674 675
        server = BaseServer(self.family, self.addr, TestHandler)
        client = TestClient(self.family, server.address)
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
        self.loop_waiting_for_flag(client)

    def test_handle_error(self):

        class TestClient(BaseClient):
            def handle_write(self):
                1.0 / 0
            def handle_error(self):
                self.flag = True
                try:
                    raise
                except ZeroDivisionError:
                    pass
                else:
                    raise Exception("exception not raised")

692 693
        server = BaseServer(self.family, self.addr)
        client = TestClient(self.family, server.address)
694 695 696
        self.loop_waiting_for_flag(client)

    def test_connection_attributes(self):
697 698
        server = BaseServer(self.family, self.addr)
        client = BaseClient(self.family, server.address)
699 700 701 702

        # we start disconnected
        self.assertFalse(server.connected)
        self.assertTrue(server.accepting)
703 704
        # this can't be taken for granted across all platforms
        #self.assertFalse(client.connected)
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
        self.assertFalse(client.accepting)

        # execute some loops so that client connects to server
        asyncore.loop(timeout=0.01, use_poll=self.use_poll, count=100)
        self.assertFalse(server.connected)
        self.assertTrue(server.accepting)
        self.assertTrue(client.connected)
        self.assertFalse(client.accepting)

        # disconnect the client
        client.close()
        self.assertFalse(server.connected)
        self.assertTrue(server.accepting)
        self.assertFalse(client.connected)
        self.assertFalse(client.accepting)

        # stop serving
        server.close()
        self.assertFalse(server.connected)
        self.assertFalse(server.accepting)

    def test_create_socket(self):
        s = asyncore.dispatcher()
728
        s.create_socket(self.family)
729
        self.assertEqual(s.socket.type, socket.SOCK_STREAM)
730
        self.assertEqual(s.socket.family, self.family)
731 732
        self.assertEqual(s.socket.gettimeout(), 0)
        self.assertFalse(s.socket.get_inheritable())
733 734

    def test_bind(self):
735
        if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX:
736
            self.skipTest("Not applicable to AF_UNIX sockets.")
737
        s1 = asyncore.dispatcher()
738 739
        s1.create_socket(self.family)
        s1.bind(self.addr)
740 741 742 743
        s1.listen(5)
        port = s1.socket.getsockname()[1]

        s2 = asyncore.dispatcher()
744
        s2.create_socket(self.family)
745
        # EADDRINUSE indicates the socket was correctly bound
746
        self.assertRaises(OSError, s2.bind, (self.addr[0], port))
747 748

    def test_set_reuse_addr(self):
749
        if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX:
750
            self.skipTest("Not applicable to AF_UNIX sockets.")
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767

        with socket.socket(self.family) as sock:
            try:
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            except OSError:
                unittest.skip("SO_REUSEADDR not supported on this platform")
            else:
                # if SO_REUSEADDR succeeded for sock we expect asyncore
                # to do the same
                s = asyncore.dispatcher(socket.socket(self.family))
                self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET,
                                                     socket.SO_REUSEADDR))
                s.socket.close()
                s.create_socket(self.family)
                s.set_reuse_addr()
                self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET,
                                                     socket.SO_REUSEADDR))
768

769 770 771
    @support.reap_threads
    def test_quick_connect(self):
        # see: http://bugs.python.org/issue10340
772 773 774 775
        if self.family not in (socket.AF_INET, getattr(socket, "AF_INET6", object())):
            self.skipTest("test specific to AF_INET and AF_INET6")

        server = BaseServer(self.family, self.addr)
776
        # run the thread 500 ms: the socket should be connected in 200 ms
777
        t = threading.Thread(target=lambda: asyncore.loop(timeout=0.1,
778
                                                          count=5))
779 780 781 782 783 784 785 786 787 788 789 790
        t.start()
        try:
            with socket.socket(self.family, socket.SOCK_STREAM) as s:
                s.settimeout(.2)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
                             struct.pack('ii', 1, 0))

                try:
                    s.connect(server.address)
                except OSError:
                    pass
        finally:
791
            support.join_thread(t, timeout=TIMEOUT)
792

793 794
class TestAPI_UseIPv4Sockets(BaseTestAPI):
    family = socket.AF_INET
795
    addr = (support.HOST, 0)
796 797 798 799

@unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 support required')
class TestAPI_UseIPv6Sockets(BaseTestAPI):
    family = socket.AF_INET6
800
    addr = (support.HOSTv6, 0)
801

802
@unittest.skipUnless(HAS_UNIX_SOCKETS, 'Unix sockets required')
803
class TestAPI_UseUnixSockets(BaseTestAPI):
804 805
    if HAS_UNIX_SOCKETS:
        family = socket.AF_UNIX
806 807 808
    addr = support.TESTFN

    def tearDown(self):
809
        support.unlink(self.addr)
810 811
        BaseTestAPI.tearDown(self)

812
class TestAPI_UseIPv4Select(TestAPI_UseIPv4Sockets, unittest.TestCase):
813 814
    use_poll = False

815
@unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required')
816
class TestAPI_UseIPv4Poll(TestAPI_UseIPv4Sockets, unittest.TestCase):
817 818
    use_poll = True

819
class TestAPI_UseIPv6Select(TestAPI_UseIPv6Sockets, unittest.TestCase):
820 821 822
    use_poll = False

@unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required')
823
class TestAPI_UseIPv6Poll(TestAPI_UseIPv6Sockets, unittest.TestCase):
824
    use_poll = True
825

826
class TestAPI_UseUnixSocketsSelect(TestAPI_UseUnixSockets, unittest.TestCase):
827 828 829
    use_poll = False

@unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required')
830
class TestAPI_UseUnixSocketsPoll(TestAPI_UseUnixSockets, unittest.TestCase):
831 832
    use_poll = True

833
if __name__ == "__main__":
834
    unittest.main()