示例#1
0
async def test_run_until_first_complete():
    task1_finished = anyio.Event()
    task2_finished = anyio.Event()

    async def task1():
        task1_finished.set()

    async def task2():
        await task1_finished.wait()
        await anyio.sleep(0)  # pragma: nocover
        task2_finished.set()  # pragma: nocover

    await run_until_first_complete((task1, {}), (task2, {}))
    assert task1_finished.is_set()
    assert not task2_finished.is_set()
示例#2
0
async def test_streaming_response_stops_if_receiving_http_disconnect():
    streamed = 0

    disconnected = anyio.Event()

    async def receive_disconnect():
        await disconnected.wait()
        return {"type": "http.disconnect"}

    async def send(message):
        nonlocal streamed
        if message["type"] == "http.response.body":
            streamed += len(message.get("body", b""))
            # Simulate disconnection after download has started
            if streamed >= 16:
                disconnected.set()

    async def stream_indefinitely():
        while True:
            # Need a sleep for the event loop to switch to another task
            await anyio.sleep(0)
            yield b"chunk "

    response = StreamingResponse(content=stream_indefinitely())

    with anyio.move_on_after(1) as cancel_scope:
        await response({}, receive_disconnect, send)
    assert not cancel_scope.cancel_called, "Content streaming should stop itself."
示例#3
0
async def test_await_stop_event(tmp_path: Path, write_soon):
    sleep(0.05)
    write_soon(tmp_path / 'foo.txt')
    stop_event = anyio.Event()
    async for changes in awatch(tmp_path, debounce=50, step=10, watch_filter=None, stop_event=stop_event):
        assert changes == {(Change.added, str((tmp_path / 'foo.txt')))}
        stop_event.set()
示例#4
0
    def __new__(cls, service, id):  # pylint: disable=redefined-builtin
        family_id, code, chksum = split_id(id)

        cls = dev_classes.get(family_id)  # pylint: disable=self-cls-assignment
        if cls is None:

            class cls(Device):  # pylint: disable=function-redefined
                family = family_id

            cls.__name__ = "Device_%02x" % (family_id, )
            dev_classes[family_id] = cls

        self = object.__new__(cls)

        self.id = id.upper()
        self.family = family_id
        self.code = code
        self.chksum = chksum

        self.service = service
        self.bus = None

        self._unseen = 0
        self._events = []
        self._wait_bus = anyio.Event()
        self._poll = {}  # name > poll task scopes
        self._intervals = {}
        self._task_lock = anyio.Lock()

        return self
示例#5
0
    async def _run_one(self, val: ValueEvent):
        try:
            async with anyio.create_task_group() as tg:
                self._current_tg = tg
                self.stream = await anyio.connect_tcp(self.host, self.port)

                ml, self.requests = deque(self.requests), deque()
                try:
                    self._msg_proto = MessageProtocol(self, is_server=False)

                    e_w = anyio.Event()
                    e_r = anyio.Event()
                    tg.spawn(self._writer, e_w)
                    tg.spawn(self._reader, e_r)
                    await e_r.wait()
                    await e_w.wait()

                    # re-send messages, but skip those that have been cancelled
                    while ml:
                        msg = ml.popleft()
                        if not msg.cancelled:
                            try:
                                await self._wqueue_w.send(msg)
                            except BaseException:
                                ml.appendleft(msg)

                except BaseException:
                    self.requests = ml
                    raise

                await self.chat(NOPMsg())

                if self._scan_args is not None:
                    tg.spawn(partial(self.start_scan, **self._scan_args))
                if val is not None:
                    val.set(None)
                self._backoff = 0.1
                pass  # wait for tasks
            pass  # exited tasks

        finally:
            self._current_tg = None
            if self.stream is not None:
                with anyio.CancelScope(shield=True):
                    await self.stream.aclose()
                self.stream = None
示例#6
0
文件: queue.py 项目: lewoudar/scalpel
 def put_nowait(self, item: Any) -> None:
     logger.debug('trying to add %s to queue', item)
     self._send_channel.send_nowait(item)
     self._tasks_in_progress += 1
     logger.debug('number of tasks in progress is now: %s',
                  self._tasks_in_progress)
     if self._finished.is_set():
         self._finished = anyio.Event()
示例#7
0
    async def continue_parsing(self):
        if self.parsing_paused_event:
            # join waiting for the current parse results
            return await self.parsing_paused_event.wait()
        self.parsing_paused_event = anyio.Event()

        chunk = await anext(self.input)
        for args in self.parser.feed(chunk):
            self._process_parsed(*args)

        self.parsing_paused_event.set()
        self.parsing_paused_event = None
示例#8
0
async def test_fail_after_after_cancellation() -> None:
    event = anyio.Event()
    async with anyio.create_task_group() as tg:
        tg.cancel_scope.cancel()
        await event.wait()

    block_complete = False
    with pytest.raises(TimeoutError):
        with fail_after(0.1):
            await anyio.sleep(0.5)
            block_complete = True

    assert not block_complete
示例#9
0
 def __init__(
     self,
     pub_cancel: abc.Publication[GoalID],
     goal_id: GoalID,
 ) -> None:
     self._pub_cancel = pub_cancel
     self._goal_id = goal_id
     self._sm = CommStateMachine(goal_id)
     self._terminated = anyio.Event()
     self._result: Optional[abc.ResultT] = None
     (
         self._feedback_send_stream,
         self._feedback_receive_stream,
     ) = anyio.create_memory_object_stream(float("inf"), abc.FeedbackT)
示例#10
0
async def test_bestow(library):
    task = None
    task_started = anyio.Event()
    portal_installed = anyio.Event()

    async def task_fn():
        nonlocal task
        task = greenback._impl.current_task()
        task_started.set()
        await portal_installed.wait()
        await_(anyio.sleep(0))

    async with anyio.create_task_group() as tg:
        tg.start_soon(task_fn)
        await task_started.wait()
        assert not has_portal(task)
        greenback.bestow_portal(task)
        assert has_portal(task)
        greenback.bestow_portal(task)
        portal_installed.set()

    with pytest.raises(RuntimeError):
        await_(anyio.sleep(0))
示例#11
0
文件: _queue.py 项目: smurfix/util-py
    async def next_seq(self):
        """
        Returns the next seq num for sending.

        May need to delay until an ack is received.
        """
        async with self._send_lock:
            self._n_sent += 1
            res = self._n_sent
            if self._delay is None and self._n_sent - self._n_ack >= self.len:
                logger.debug("%s: wait: %d/%d", self._info, self._n_sent, self._n_ack)
                self._delay = anyio.Event()
            if self._delay is not None:
                await self._delay.wait()
            return res
示例#12
0
    async def changes(self, since=None, continuous=False):
        """"Like CouchDB's _changes with style=all_docs"""

        while True:
            # send (new) changes to the caller
            async for change in self._changes(since):
                since = change.seq
                yield change

            if not continuous:
                # stop immediately.
                break
            # wait for new changes to come available, then loop
            if not hasattr(self, '_update_event'):
                self._update_event = anyio.Event()
            await self._update_event.wait()
示例#13
0
async def test_shielded_cancel_sleep_time() -> None:
    """Test that cancelling a shielded tasks spends more time sleeping than cancelling."""
    event = anyio.Event()
    hang_time = 0.2

    async def set_event() -> None:
        await sleep(hang_time)
        event.set()

    async def never_cancel_task() -> None:
        with CancelScope(shield=True):
            await sleep(0.2)
            await event.wait()

    async with create_task_group() as tg:
        tg.start_soon(set_event)

        async with create_task_group() as tg:
            tg.start_soon(never_cancel_task)
            tg.cancel_scope.cancel()
            process_time = time.process_time()

        assert (time.process_time() - process_time) < hang_time
示例#14
0
 def __init__(self, *, size, frame_rate, draw_fn):
     """
     :param size: sequence of width, height
     :param frame_rate: rate of draw calls when the view is active
     :param draw_fn: draw function called each frame when the view is active
     """
     self.width, self.height = size
     self._draw_fn = draw_fn
     self._frame_rate = frame_rate
     self._peers = set()
     self._hasPeers = anyio.Event()
     # NOTE: empty string is used to force a batching boundary
     self._sendQueue = []
     self._receiveQueue = []  # oldest to newest
     self._shapeState = _ShapeState.NONE
     self._images = []
     self._is_draw_context = False
     self.frameCount = 0
     self.mousePressed = False
     self.mouseX = 0
     self.mouseY = 0
     self.keyPressed = False
     self.key = ''
     self.inputEvents = []
示例#15
0
	async def request(self, protocol, method, body, noresponse=False):
		if self.closed:
			raise RuntimeError("RMC connection is closed")
		
		call_id = self.call_id
		self.call_id = (self.call_id + 1) & 0xFFFFFFFF
		
		if not noresponse:
			event = anyio.Event()
			self.requests[call_id] = event
		
		message = RMCMessage.request(self.settings, protocol, method, call_id, body)
		await self.client.send(message.encode())
		
		if not noresponse:
			await event.wait()
			
			if self.closed:
				raise RuntimeError("RMC connection is closed")
			
			message = self.responses.pop(call_id)
			if message.error != -1:
				raise common.RMCError(message.error)
			return message.body
示例#16
0
文件: main.py 项目: sthagen/watchgod
        # cleanup by awaiting the (now complete) stop_soon_task
        await stop_soon_task

    asyncio.run(main())
    ```
    """
    if raise_interrupt is not None:
        warnings.warn(
            'raise_interrupt is deprecated, KeyboardInterrupt will cause this coroutine to be cancelled and then '
            'be raised by the top level asyncio.run call or equivalent, and should be caught there. See #136.',
            DeprecationWarning,
        )

    if stop_event is None:
        stop_event_: 'AnyEvent' = anyio.Event()
    else:
        stop_event_ = stop_event

    force_polling = _default_force_pulling(force_polling)
    with RustNotify([str(p) for p in paths], debug, force_polling, poll_delay_ms) as watcher:
        timeout = _calc_async_timeout(rust_timeout)
        CancelledError = anyio.get_cancelled_exc_class()

        while True:
            async with anyio.create_task_group() as tg:
                try:
                    raw_changes = await anyio.to_thread.run_sync(watcher.watch, debounce, step, timeout, stop_event_)
                except (CancelledError, KeyboardInterrupt):
                    stop_event_.set()
                    # suppressing KeyboardInterrupt wouldn't stop it getting raised by the top level asyncio.run call
示例#17
0
async def server(  # pylint: disable=dangerous-default-value  # intentional
        tree={},
        options={},
        events=None,
        polling=False,
        scan=None,
        initial_scan=True,
        **kw):
    """
    This is a mock 1wire server+client.

    The context manager returns the client.

    ``tree`` and ``opotions`` are used as in `some_server`, ``polling``,
    ``scan`` and ``initial_scan`` are used to set up the client, other
    keyword arguments are forwarded to the client constructor.
    """
    PORT = (os.getpid() % 9999) + 40000
    async with OWFS(**kw) as ow:
        async with anyio.create_task_group() as tg:
            s = None
            try:
                listener = await anyio.create_tcp_listener(
                    local_host="127.0.0.1", local_port=PORT, reuse_port=True)

                async def may_close():
                    try:
                        await listener.serve(
                            partial(some_server, tree, options))
                    except (anyio.ClosedResourceError,
                            anyio.BrokenResourceError):
                        pass
                    except trio.MultiError as exc:
                        exc = exc.filter(
                            lambda x: None
                            if isinstance(x, trio.Cancelled) else x, exc)
                        if not isinstance(exc, (anyio.ClosedResourceError,
                                                anyio.BrokenResourceError)):
                            raise
                    except BaseException as exc:
                        import pdb
                        pdb.set_trace()
                        raise

                if events is not None:
                    evt = anyio.Event()
                    tg.spawn(events, ow, evt)
                    await evt.wait()
                addr = listener.extra(
                    anyio.abc.SocketAttribute.raw_socket).getsockname()
                tg.spawn(may_close)

                s = await ow.add_server(*addr,
                                        polling=polling,
                                        scan=scan,
                                        initial_scan=initial_scan)
                ow.test_server = s
                yield ow
            finally:
                ow.test_server = None
                await listener.aclose()
                with anyio.CancelScope(shield=True):
                    if s is not None:
                        await s.drop()
                    await ow.push_event(None)
                    await anyio.sleep(0.1)
                tg.cancel_scope.cancel()
示例#18
0
 def _handleClose(self, peer):
     self._peers.remove(peer)
     if not self._peers:
         self._hasPeers = anyio.Event()
示例#19
0
 async def delocate(self, bus):
     """The device is no longer located here."""
     if self.bus is bus:
         self._wait_bus = anyio.Event()
         await self._delocate()
示例#20
0
 def __init__(self) -> None:
     self._event = anyio.Event()
示例#21
0
    def __init__(self, group):
        self.group = group

        self.handle = itertools.count()
        self.event = anyio.Event()
        self.events = {}
示例#22
0
 async def process(self):
     while True:
         timeout = self.process_timers()
         with anyio.move_on_after(timeout):
             await self.event.wait()
             self.event = anyio.Event()