Пример #1
0
    def test_close_dont_kill_finished(self):
        @asyncio.coroutine
        def kill_running():
            create = self.loop.subprocess_exec(asyncio.SubprocessProtocol,
                                               *PROGRAM_BLOCKED)
            transport, protocol = yield from create
            proc = transport.get_extra_info('subprocess')

            # kill the process (but asyncio is not notified immediatly)
            proc.kill()
            proc.wait()

            proc.kill = mock.Mock()
            proc_returncode = proc.poll()
            transport_returncode = transport.get_returncode()
            transport.close()
            return (proc_returncode, transport_returncode, proc.kill.called)

        # Ignore "Unknown child process pid ..." log of SafeChildWatcher,
        # emitted because the test already consumes the exit status:
        # proc.wait()
        with test_utils.disable_logger():
            result = self.loop.run_until_complete(kill_running())
            test_utils.run_briefly(self.loop)

        proc_returncode, transport_return_code, killed = result

        self.assertIsNotNone(proc_returncode)
        self.assertIsNone(transport_return_code)

        # transport.close() must not kill the process if it finished, even if
        # the transport was not notified yet
        self.assertFalse(killed)
Пример #2
0
    def test_reader_callback(self):
        r, w = test_utils.socketpair()
        bytes_read = []

        def reader():
            try:
                data = r.recv(1024)
            except BlockingIOError:
                # Spurious readiness notifications are possible
                # at least on Linux -- see man select.
                return
            if data:
                bytes_read.append(data)
            else:
                self.assertTrue(self.loop.remove_reader(r.fileno()))
                r.close()

        self.loop.add_reader(r.fileno(), reader)
        self.loop.call_soon(w.send, b'abc')
        test_utils.run_briefly(self.loop)
        self.loop.call_soon(w.send, b'def')
        self.loop.call_soon(w.close)
        self.loop.call_soon(self.loop.stop)
        self.loop.run_forever()
        self.assertEqual(b''.join(bytes_read), b'abcdef')
Пример #3
0
 def test_wrap_future_cancel(self):
     f1 = concurrent.futures.Future()
     f2 = asyncio.wrap_future(f1, loop=self.loop)
     f2.cancel()
     test_utils.run_briefly(self.loop)
     self.assertTrue(f1.cancelled())
     self.assertTrue(f2.cancelled())
Пример #4
0
    def check_future_exception_never_retrieved(self, debug):
        last_ctx = None
        def handler(loop, context):
            nonlocal last_ctx
            last_ctx = context

        self.loop.set_debug(debug)
        self.loop.set_exception_handler(handler)

        def memory_error():
            try:
                raise MemoryError()
            except BaseException as exc:
                return exc
        exc = memory_error()

        future = self.create_future()
        if debug:
            source_traceback = future._source_traceback
        future.set_exception(exc)
        future = None
        support.gc_collect()
        test_utils.run_briefly(self.loop)

        self.assertIsNotNone(last_ctx)

        self.assertIs(last_ctx['exception'], exc)
        self.assertEqual(last_ctx['message'],
                         'Future exception was never retrieved')

        if debug:
            tb = last_ctx['source_traceback']
            self.assertEqual(tb[-2].name,
                             'check_future_exception_never_retrieved')
Пример #5
0
    def tearDown(self):
        # just in case if we have transport close callbacks
        test_utils.run_briefly(self.loop)

        self.loop.close()
        gc.collect()
        super().tearDown()
Пример #6
0
    def test_shield_effect(self):
        # Cancelling outer() does not affect inner().
        proof = 0
        waiter = asyncio.Future(loop=self.loop)

        @asyncio.coroutine
        def inner():
            nonlocal proof
            yield from waiter
            proof += 1

        @asyncio.coroutine
        def outer():
            nonlocal proof
            yield from asyncio.shield(inner(), loop=self.loop)
            proof += 100

        f = asyncio.async(outer(), loop=self.loop)
        test_utils.run_briefly(self.loop)
        f.cancel()
        with self.assertRaises(asyncio.CancelledError):
            self.loop.run_until_complete(f)
        waiter.set_result(None)
        test_utils.run_briefly(self.loop)
        self.assertEqual(proof, 1)
Пример #7
0
    def test_step_result_future(self):
        # If coroutine returns future, task waits on this future.

        class Fut(asyncio.Future):
            def __init__(self, *args, **kwds):
                self.cb_added = False
                super().__init__(*args, **kwds)

            def add_done_callback(self, fn):
                self.cb_added = True
                super().add_done_callback(fn)

        fut = Fut(loop=self.loop)
        result = None

        @asyncio.coroutine
        def wait_for_future():
            nonlocal result
            result = yield from fut

        t = asyncio.Task(wait_for_future(), loop=self.loop)
        test_utils.run_briefly(self.loop)
        self.assertTrue(fut.cb_added)

        res = object()
        fut.set_result(res)
        test_utils.run_briefly(self.loop)
        self.assertIs(res, result)
        self.assertTrue(t.done())
        self.assertIsNone(t.result())
Пример #8
0
    def test_close_kill_running(self):
        @asyncio.coroutine
        def kill_running():
            create = self.loop.subprocess_exec(asyncio.SubprocessProtocol,
                                               *PROGRAM_BLOCKED)
            transport, protocol = yield from create

            kill_called = False
            def kill():
                nonlocal kill_called
                kill_called = True
                orig_kill()

            proc = transport.get_extra_info('subprocess')
            orig_kill = proc.kill
            proc.kill = kill
            returncode = transport.get_returncode()
            transport.close()
            yield from transport._wait()
            return (returncode, kill_called)

        # Ignore "Close running child process: kill ..." log
        with test_utils.disable_logger():
            returncode, killed = self.loop.run_until_complete(kill_running())
        self.assertIsNone(returncode)

        # transport.close() must kill the process if it is still running
        self.assertTrue(killed)
        test_utils.run_briefly(self.loop)
Пример #9
0
    def test_close_with_waiting_buffer(self):
        self.tr._buffer = deque([(b'data',)])
        self.tr._buffer_size = 4
        self.loop.add_writer(self.sock, self.tr._write_ready)

        self.tr.close()

        self.assertEqual(1, self.loop.remove_reader_count[self.sock])
        self.assertEqual(0, self.loop.remove_writer_count[self.sock])
        self.assertEqual([(b'data',)], list(self.tr._buffer))
        self.assertEqual(4, self.tr._buffer_size)
        self.assertTrue(self.tr._closing)

        self.assertIsNotNone(self.tr._protocol)
        self.assertIsNotNone(self.tr._zmq_sock)
        self.assertIsNotNone(self.tr._loop)
        self.assertFalse(self.sock.close.called)

        test_utils.run_briefly(self.loop)

        self.assertIsNotNone(self.tr._protocol)
        self.assertIsNotNone(self.tr._zmq_sock)
        self.assertIsNotNone(self.tr._loop)
        self.assertFalse(self.sock.close.called)
        self.assertFalse(self.proto.connection_lost.called)
Пример #10
0
    def test_clear_with_waiters(self):
        ev = asyncio.Event(loop=self.loop)
        result = []

        @asyncio.coroutine
        def c1(result):
            if (yield from ev.wait()):
                result.append(1)
            return True

        t = asyncio.Task(c1(result), loop=self.loop)
        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)

        ev.set()
        ev.clear()
        self.assertFalse(ev.is_set())

        ev.set()
        ev.set()
        self.assertEqual(1, len(ev._waiters))

        test_utils.run_briefly(self.loop)
        self.assertEqual([1], result)
        self.assertEqual(0, len(ev._waiters))

        self.assertTrue(t.done())
        self.assertTrue(t.result())
Пример #11
0
    def test_yield_wait_does_not_shield_cancel(self):
        # Cancelling outer() makes wait() return early, leaves inner()
        # running.
        proof = 0
        waiter = asyncio.Future(loop=self.loop)

        @asyncio.coroutine
        def inner():
            nonlocal proof
            yield from waiter
            proof += 1

        @asyncio.coroutine
        def outer():
            nonlocal proof
            d, p = yield from asyncio.wait([inner()], loop=self.loop)
            proof += 100

        f = asyncio.async(outer(), loop=self.loop)
        test_utils.run_briefly(self.loop)
        f.cancel()
        self.assertRaises(
            asyncio.CancelledError, self.loop.run_until_complete, f)
        waiter.set_result(None)
        test_utils.run_briefly(self.loop)
        self.assertEqual(proof, 1)
Пример #12
0
 def test_tb_logger_exception_unretrieved(self, m_log):
     fut = asyncio.Future(loop=self.loop)
     fut.set_exception(RuntimeError("boom"))
     del fut
     test_utils.run_briefly(self.loop)
     support.gc_collect()
     self.assertTrue(m_log.error.called)
Пример #13
0
    def test_baseexception_during_cancel(self):

        def gen():
            when = yield
            self.assertAlmostEqual(10.0, when)
            yield 0

        loop = test_utils.TestLoop(gen)
        self.addCleanup(loop.close)

        @asyncio.coroutine
        def sleeper():
            yield from asyncio.sleep(10, loop=loop)

        base_exc = BaseException()

        @asyncio.coroutine
        def notmutch():
            try:
                yield from sleeper()
            except asyncio.CancelledError:
                raise base_exc

        task = asyncio.Task(notmutch(), loop=loop)
        test_utils.run_briefly(loop)

        task.cancel()
        self.assertFalse(task.done())

        self.assertRaises(BaseException, test_utils.run_briefly, loop)

        self.assertTrue(task.done())
        self.assertFalse(task.cancelled())
        self.assertIs(task.exception(), base_exc)
Пример #14
0
 def test_shield_cancel(self):
     inner = asyncio.Future(loop=self.loop)
     outer = asyncio.shield(inner)
     test_utils.run_briefly(self.loop)
     inner.cancel()
     test_utils.run_briefly(self.loop)
     self.assertTrue(outer.cancelled())
Пример #15
0
    def test_sleep_cancel(self):

        def gen():
            when = yield
            self.assertAlmostEqual(10.0, when)
            yield 0

        loop = test_utils.TestLoop(gen)
        self.addCleanup(loop.close)

        t = asyncio.Task(asyncio.sleep(10.0, 'yeah', loop=loop),
                         loop=loop)

        handle = None
        orig_call_later = loop.call_later

        def call_later(self, delay, callback, *args):
            nonlocal handle
            handle = orig_call_later(self, delay, callback, *args)
            return handle

        loop.call_later = call_later
        test_utils.run_briefly(loop)

        self.assertFalse(handle._cancelled)

        t.cancel()
        test_utils.run_briefly(loop)
        self.assertTrue(handle._cancelled)
Пример #16
0
    def test_cancellation_broadcast(self):
        # Cancelling outer() cancels all children.
        proof = 0
        waiter = asyncio.Future(loop=self.one_loop)

        @asyncio.coroutine
        def inner():
            nonlocal proof
            yield from waiter
            proof += 1

        child1 = asyncio.async(inner(), loop=self.one_loop)
        child2 = asyncio.async(inner(), loop=self.one_loop)
        gatherer = None

        @asyncio.coroutine
        def outer():
            nonlocal proof, gatherer
            gatherer = asyncio.gather(child1, child2, loop=self.one_loop)
            yield from gatherer
            proof += 100

        f = asyncio.async(outer(), loop=self.one_loop)
        test_utils.run_briefly(self.one_loop)
        self.assertTrue(f.cancel())
        with self.assertRaises(asyncio.CancelledError):
            self.one_loop.run_until_complete(f)
        self.assertFalse(gatherer.cancel())
        self.assertTrue(waiter.cancelled())
        self.assertTrue(child1.cancelled())
        self.assertTrue(child2.cancelled())
        test_utils.run_briefly(self.one_loop)
        self.assertEqual(proof, 0)
Пример #17
0
 def test_eof_received_waiter(self):
     waiter = asyncio.Future(loop=self.loop)
     ssl_proto = self.ssl_protocol(waiter)
     self.connection_made(ssl_proto)
     ssl_proto.eof_received()
     test_utils.run_briefly(self.loop)
     self.assertIsInstance(waiter.exception(), ConnectionResetError)
Пример #18
0
 def test_ctor_with_waiter(self):
     fut = asyncio.Future(loop=self.loop)
     tr = unix_events._UnixWritePipeTransport(
         self.loop, self.pipe, self.protocol, fut)
     self.loop.assert_reader(5, tr._read_ready)
     test_utils.run_briefly(self.loop)
     self.assertEqual(None, fut.result())
Пример #19
0
 def test_get_with_waiting_putters(self):
     q = asyncio.Queue(loop=self.loop, maxsize=1)
     asyncio.Task(q.put('a'), loop=self.loop)
     asyncio.Task(q.put('b'), loop=self.loop)
     test_utils.run_briefly(self.loop)
     self.assertEqual(self.loop.run_until_complete(q.get()), 'a')
     self.assertEqual(self.loop.run_until_complete(q.get()), 'b')
Пример #20
0
    def test_write_pipe_disconnect_on_close(self):
        proto = None
        transport = None

        def factory():
            nonlocal proto
            proto = MyWritePipeProto(loop=self.loop)
            return proto

        rpipe, wpipe = os.pipe()
        pipeobj = io.open(wpipe, 'wb', 1024)

        @tasks.coroutine
        def connect():
            nonlocal transport
            t, p = yield from self.loop.connect_write_pipe(factory,
                                                           pipeobj)
            self.assertIs(p, proto)
            self.assertIs(t, proto.transport)
            self.assertEqual('CONNECTED', proto.state)
            transport = t

        self.loop.run_until_complete(connect())
        self.assertEqual('CONNECTED', proto.state)

        transport.write(b'1')
        test_utils.run_briefly(self.loop)
        data = os.read(rpipe, 1024)
        self.assertEqual(b'1', data)

        os.close(rpipe)

        self.loop.run_until_complete(proto.done)
        self.assertEqual('CLOSED', proto.state)
Пример #21
0
    def test_yield_future_passes_cancel(self):
        # Cancelling outer() cancels inner() cancels waiter.
        proof = 0
        waiter = asyncio.Future(loop=self.loop)

        @asyncio.coroutine
        def inner():
            nonlocal proof
            try:
                yield from waiter
            except asyncio.CancelledError:
                proof += 1
                raise
            else:
                self.fail('got past sleep() in inner()')

        @asyncio.coroutine
        def outer():
            nonlocal proof
            try:
                yield from inner()
            except asyncio.CancelledError:
                proof += 100  # Expect this path.
            else:
                proof += 10

        f = asyncio.async(outer(), loop=self.loop)
        test_utils.run_briefly(self.loop)
        f.cancel()
        self.loop.run_until_complete(f)
        self.assertEqual(proof, 101)
        self.assertTrue(waiter.cancelled())
Пример #22
0
    def check_future_exception_never_retrieved(self, debug, m_log):
        self.loop.set_debug(debug)

        def memory_error():
            try:
                raise MemoryError()
            except BaseException as exc:
                return exc
        exc = memory_error()

        future = self._new_future(loop=self.loop)
        future.set_exception(exc)
        future = None
        test_utils.run_briefly(self.loop)
        support.gc_collect()

        if sys.version_info >= (3, 4):
            regex = r'^Future exception was never retrieved\n'
            exc_info = (type(exc), exc, exc.__traceback__)
            m_log.error.assert_called_once_with(mock.ANY, exc_info=exc_info)
        else:
            regex = r'^Future/Task exception was never retrieved\n'
            m_log.error.assert_called_once_with(mock.ANY, exc_info=False)
        message = m_log.error.call_args[0][0]
        self.assertRegex(message, re.compile(regex, re.DOTALL))
Пример #23
0
 def test_ctor(self):
     fut = asyncio.Future(loop=self.loop)
     tr = self.socket_transport(waiter=fut)
     test_utils.run_briefly(self.loop)
     self.assertIsNone(fut.result())
     self.protocol.connection_made(tr)
     self.proactor.recv.assert_called_with(self.sock, 4096)
Пример #24
0
 def test_future_wrap_future_cancel(self):
     from uvloop.loop import _wrap_future
     f1 = concurrent.futures.Future()
     f2 = _wrap_future(f1, loop=self.loop)
     f2.cancel()
     test_utils.run_briefly(self.loop)
     self.assertTrue(f1.cancelled())
     self.assertTrue(f2.cancelled())
Пример #25
0
 def when_I_consume_a_message(self):
     self.result = []
     consumer = self.loop.run_until_complete(self.queue.consume(self.result.append, exclusive=True))
     for retry in range(10):
         test_utils.run_briefly(self.loop)
         if self.result:
             break
     consumer.cancel()
Пример #26
0
    def test_fatal_error_2(self):
        tr = self.socket_transport()
        tr._buffer = [b'data']
        tr._force_close(None)

        test_utils.run_briefly(self.loop)
        self.protocol.connection_lost.assert_called_with(None)
        self.assertEqual(None, tr._buffer)
Пример #27
0
    def test_fatal_error_2(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._buffer = [b"data"]
        tr._force_close(None)

        test_utils.run_briefly(self.loop)
        self.protocol.connection_lost.assert_called_with(None)
        self.assertEqual(None, tr._buffer)
Пример #28
0
 def _basetest_open_connection_error(self, open_connection_fut):
     reader, writer = self.loop.run_until_complete(open_connection_fut)
     writer._protocol.connection_lost(ZeroDivisionError())
     f = reader.read()
     with self.assertRaises(ZeroDivisionError):
         self.loop.run_until_complete(f)
     writer.close()
     test_utils.run_briefly(self.loop)
Пример #29
0
 def test_shield_exception(self):
     inner = asyncio.Future(loop=self.loop)
     outer = asyncio.shield(inner)
     test_utils.run_briefly(self.loop)
     exc = RuntimeError('expected')
     inner.set_exception(exc)
     test_utils.run_briefly(self.loop)
     self.assertIs(outer.exception(), exc)
Пример #30
0
 def test_wrap_future_cancel2(self):
     f1 = concurrent.futures.Future()
     f2 = asyncio.wrap_future(f1, loop=self.loop)
     f1.set_result(42)
     f2.cancel()
     test_utils.run_briefly(self.loop)
     self.assertFalse(f1.cancelled())
     self.assertEqual(f1.result(), 42)
     self.assertTrue(f2.cancelled())
Пример #31
0
    def test_wait(self):
        cond = locks.Condition(loop=self.loop)
        result = []

        @tasks.coroutine
        def c1(result):
            yield from cond.acquire()
            if (yield from cond.wait()):
                result.append(1)
            return True

        @tasks.coroutine
        def c2(result):
            yield from cond.acquire()
            if (yield from cond.wait()):
                result.append(2)
            return True

        @tasks.coroutine
        def c3(result):
            yield from cond.acquire()
            if (yield from cond.wait()):
                result.append(3)
            return True

        t1 = tasks.Task(c1(result), loop=self.loop)
        t2 = tasks.Task(c2(result), loop=self.loop)
        t3 = tasks.Task(c3(result), loop=self.loop)

        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)
        self.assertFalse(cond.locked())

        self.assertTrue(self.loop.run_until_complete(cond.acquire()))
        cond.notify()
        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)
        self.assertTrue(cond.locked())

        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1], result)
        self.assertTrue(cond.locked())

        cond.notify(2)
        test_utils.run_briefly(self.loop)
        self.assertEqual([1], result)
        self.assertTrue(cond.locked())

        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1, 2], result)
        self.assertTrue(cond.locked())

        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1, 2, 3], result)
        self.assertTrue(cond.locked())

        self.assertTrue(t1.done())
        self.assertTrue(t1.result())
        self.assertTrue(t2.done())
        self.assertTrue(t2.result())
        self.assertTrue(t3.done())
        self.assertTrue(t3.result())
Пример #32
0
    def tearDown(self):
        # just in case if we have transport close callbacks
        test_utils.run_briefly(self.loop)

        self.loop.close()
        gc.collect()
    def check_future_exception_never_retrieved(self, debug, m_log):
        self.loop.set_debug(debug)

        def memory_error():
            try:
                raise MemoryError()
            except BaseException as exc:
                return exc
        exc = memory_error()

        future = asyncio.Future(loop=self.loop)
        if debug:
            source_traceback = future._source_traceback
        future.set_exception(exc)
        future = None
        test_utils.run_briefly(self.loop)
        support.gc_collect()

        if sys.version_info >= (3, 4):
            if debug:
                frame = source_traceback[-1]
                regex = (r'^Future exception was never retrieved\n'
                         r'future: <Future finished exception=MemoryError\(\) '
                             r'created at {filename}:{lineno}>\n'
                         r'source_traceback: Object '
                            r'created at \(most recent call last\):\n'
                         r'  File'
                         r'.*\n'
                         r'  File "{filename}", line {lineno}, '
                            r'in check_future_exception_never_retrieved\n'
                         r'    future = asyncio\.Future\(loop=self\.loop\)$'
                         ).format(filename=re.escape(frame[0]),
                                  lineno=frame[1])
            else:
                regex = (r'^Future exception was never retrieved\n'
                         r'future: '
                            r'<Future finished exception=MemoryError\(\)>$'
                         )
            exc_info = (type(exc), exc, exc.__traceback__)
            m_log.error.assert_called_once_with(mock.ANY, exc_info=exc_info)
        else:
            if debug:
                frame = source_traceback[-1]
                regex = (r'^Future/Task exception was never retrieved\n'
                         r'Future/Task created at \(most recent call last\):\n'
                         r'  File'
                         r'.*\n'
                         r'  File "{filename}", line {lineno}, '
                            r'in check_future_exception_never_retrieved\n'
                         r'    future = asyncio\.Future\(loop=self\.loop\)\n'
                         r'Traceback \(most recent call last\):\n'
                         r'.*\n'
                         r'MemoryError$'
                         ).format(filename=re.escape(frame[0]),
                                  lineno=frame[1])
            else:
                regex = (r'^Future/Task exception was never retrieved\n'
                         r'Traceback \(most recent call last\):\n'
                         r'.*\n'
                         r'MemoryError$'
                         )
            m_log.error.assert_called_once_with(mock.ANY, exc_info=False)
        message = m_log.error.call_args[0][0]
        self.assertRegex(message, re.compile(regex, re.DOTALL))
Пример #34
0
 def test_close_write_fut(self):
     tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
     tr._write_fut = unittest.mock.Mock()
     tr.close()
     test_utils.run_briefly(self.loop)
     self.assertFalse(self.protocol.connection_lost.called)
Пример #35
0
    def test_acquire(self):
        sem = asyncio.Semaphore(3, loop=self.loop)
        result = []

        self.assertTrue(self.loop.run_until_complete(sem.acquire()))
        self.assertTrue(self.loop.run_until_complete(sem.acquire()))
        self.assertFalse(sem.locked())

        @asyncio.coroutine
        def c1(result):
            yield from sem.acquire()
            result.append(1)
            return True

        @asyncio.coroutine
        def c2(result):
            yield from sem.acquire()
            result.append(2)
            return True

        @asyncio.coroutine
        def c3(result):
            yield from sem.acquire()
            result.append(3)
            return True

        @asyncio.coroutine
        def c4(result):
            yield from sem.acquire()
            result.append(4)
            return True

        t1 = asyncio.Task(c1(result), loop=self.loop)
        t2 = asyncio.Task(c2(result), loop=self.loop)
        t3 = asyncio.Task(c3(result), loop=self.loop)

        test_utils.run_briefly(self.loop)
        self.assertEqual([1], result)
        self.assertTrue(sem.locked())
        self.assertEqual(2, len(sem._waiters))
        self.assertEqual(0, sem._value)

        t4 = asyncio.Task(c4(result), loop=self.loop)

        sem.release()
        sem.release()
        self.assertEqual(2, sem._value)

        test_utils.run_briefly(self.loop)
        self.assertEqual(0, sem._value)
        self.assertEqual(3, len(result))
        self.assertTrue(sem.locked())
        self.assertEqual(1, len(sem._waiters))
        self.assertEqual(0, sem._value)

        self.assertTrue(t1.done())
        self.assertTrue(t1.result())
        race_tasks = [t2, t3, t4]
        done_tasks = [t for t in race_tasks if t.done() and t.result()]
        self.assertTrue(2, len(done_tasks))

        # cleanup locked semaphore
        sem.release()
        self.loop.run_until_complete(asyncio.gather(*race_tasks))
Пример #36
0
    def test_acquire(self):
        sem = asyncio.Semaphore(3, loop=self.loop)
        result = []

        self.assertTrue(self.loop.run_until_complete(sem.acquire()))
        self.assertTrue(self.loop.run_until_complete(sem.acquire()))
        self.assertFalse(sem.locked())

        @asyncio.coroutine
        def c1(result):
            yield from sem.acquire()
            result.append(1)
            return True

        @asyncio.coroutine
        def c2(result):
            yield from sem.acquire()
            result.append(2)
            return True

        @asyncio.coroutine
        def c3(result):
            yield from sem.acquire()
            result.append(3)
            return True

        @asyncio.coroutine
        def c4(result):
            yield from sem.acquire()
            result.append(4)
            return True

        t1 = asyncio.Task(c1(result), loop=self.loop)
        t2 = asyncio.Task(c2(result), loop=self.loop)
        t3 = asyncio.Task(c3(result), loop=self.loop)

        test_utils.run_briefly(self.loop)
        self.assertEqual([1], result)
        self.assertTrue(sem.locked())
        self.assertEqual(2, len(sem._waiters))
        self.assertEqual(0, sem._value)

        t4 = asyncio.Task(c4(result), loop=self.loop)

        sem.release()
        sem.release()
        self.assertEqual(2, sem._value)

        test_utils.run_briefly(self.loop)
        self.assertEqual(0, sem._value)
        self.assertEqual([1, 2, 3], result)
        self.assertTrue(sem.locked())
        self.assertEqual(1, len(sem._waiters))
        self.assertEqual(0, sem._value)

        self.assertTrue(t1.done())
        self.assertTrue(t1.result())
        self.assertTrue(t2.done())
        self.assertTrue(t2.result())
        self.assertTrue(t3.done())
        self.assertTrue(t3.result())
        self.assertFalse(t4.done())

        # cleanup locked semaphore
        sem.release()
        self.loop.run_until_complete(t4)
Пример #37
0
    def test_wait(self):
        cond = asyncio.Condition(loop=self.loop)
        result = []

        async def c1(result):
            await cond.acquire()
            if await cond.wait():
                result.append(1)
            return True

        async def c2(result):
            await cond.acquire()
            if await cond.wait():
                result.append(2)
            return True

        async def c3(result):
            await cond.acquire()
            if await cond.wait():
                result.append(3)
            return True

        t1 = asyncio.Task(c1(result), loop=self.loop)
        t2 = asyncio.Task(c2(result), loop=self.loop)
        t3 = asyncio.Task(c3(result), loop=self.loop)

        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)
        self.assertFalse(cond.locked())

        self.assertTrue(self.loop.run_until_complete(cond.acquire()))
        cond.notify()
        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)
        self.assertTrue(cond.locked())

        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1], result)
        self.assertTrue(cond.locked())

        cond.notify(2)
        test_utils.run_briefly(self.loop)
        self.assertEqual([1], result)
        self.assertTrue(cond.locked())

        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1, 2], result)
        self.assertTrue(cond.locked())

        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1, 2, 3], result)
        self.assertTrue(cond.locked())

        self.assertTrue(t1.done())
        self.assertTrue(t1.result())
        self.assertTrue(t2.done())
        self.assertTrue(t2.result())
        self.assertTrue(t3.done())
        self.assertTrue(t3.result())
Пример #38
0
 def test_put_with_waiting_getters(self):
     q = asyncio.Queue(loop=self.loop)
     t = asyncio.Task(q.get(), loop=self.loop)
     test_utils.run_briefly(self.loop)
     self.loop.run_until_complete(q.put('a'))
     self.assertEqual(self.loop.run_until_complete(t), 'a')
Пример #39
0
 def test_tb_logger_exception_unretrieved(self, m_log):
     fut = asyncio.Future(loop=self.loop)
     fut.set_exception(RuntimeError('boom'))
     del fut
     test_utils.run_briefly(self.loop)
     self.assertTrue(m_log.error.called)
Пример #40
0
 def run_briefly(self):
     test_utils.run_briefly(self.loop)
Пример #41
0
 def test_close_write_fut(self):
     tr = self.socket_transport()
     tr._write_fut = mock.Mock()
     tr.close()
     test_utils.run_briefly(self.loop)
     self.assertFalse(self.protocol.connection_lost.called)
Пример #42
0
 def test_close_buffer(self):
     tr = self.socket_transport()
     tr._buffer = [b'data']
     tr.close()
     test_utils.run_briefly(self.loop)
     self.assertFalse(self.protocol.connection_lost.called)
Пример #43
0
 def test_force_close_idempotent(self):
     tr = self.socket_transport()
     tr._closing = True
     tr._force_close(None)
     test_utils.run_briefly(self.loop)
     self.assertFalse(self.protocol.connection_lost.called)