Exemplo n.º 1
0
    async def open_file(cls, *args, **kwargs):
        file_path = args[0]
        rest = args[1:]

        if isinstance(file_path, IOBase):
            return trio.wrap_file(file_path)

        return await trio.open_file(file_path, *rest, **kwargs)
Exemplo n.º 2
0
    async def open(self, *args, **kwargs):
        """Open the file pointed to by the path, like the :func:`trio.open_file`
        function does.

        """

        func = partial(self._wrapped.open, *args, **kwargs)
        value = await trio.to_thread.run_sync(func)
        return trio.wrap_file(value)
Exemplo n.º 3
0
def test_wrap_non_iobase():
    class FakeFile:
        def close(self):  # pragma: no cover
            pass

        def write(self):  # pragma: no cover
            pass

    wrapped = FakeFile()
    assert not isinstance(wrapped, io.IOBase)

    async_file = trio.wrap_file(wrapped)
    assert isinstance(async_file, AsyncIOWrapper)

    del FakeFile.write

    with pytest.raises(TypeError):
        trio.wrap_file(FakeFile())
Exemplo n.º 4
0
    async def open(self, *args, **kwargs):
        """Open the file pointed to by the path, like the :func:`trio.open_file`
        function does.

        """

        func = partial(self._wrapped.open, *args, **kwargs)
        value = await trio.run_sync_in_worker_thread(func)
        return trio.wrap_file(value)
Exemplo n.º 5
0
async def test_detach_rewraps_asynciobase():
    raw = io.BytesIO()
    buffered = io.BufferedReader(raw)

    async_file = trio.wrap_file(buffered)

    detached = await async_file.detach()

    assert isinstance(detached, AsyncIOWrapper)
    assert detached.wrapped is raw
Exemplo n.º 6
0
async def test_async_iter():
    async_file = trio.wrap_file(io.StringIO('test\nfoo\nbar'))
    expected = list(async_file.wrapped)
    result = []
    async_file.wrapped.seek(0)

    async for line in async_file:
        result.append(line)

    assert result == expected
Exemplo n.º 7
0
def test_unsupported_not_forwarded():
    class FakeFile(io.RawIOBase):
        def unsupported_attr(self):  # pragma: no cover
            pass

    async_file = trio.wrap_file(FakeFile())

    assert hasattr(async_file.wrapped, 'unsupported_attr')

    with pytest.raises(AttributeError):
        getattr(async_file, 'unsupported_attr')
Exemplo n.º 8
0
async def parent():
    async with trio.open_nursery() as nursery:
        serial_port = serial.Serial("/dev/serial0", 9600, timeout=5.0)
        serial_io = io.TextIOWrapper(
            io.BufferedRWPair(serial_port, serial_port))
        a_serial = trio.wrap_file(serial_port)

        print("Starting print loop")
        nursery.start_soon(aprint_loop)
        print("Starting GPS async serial loop")
        a_serial.flushInput()
        nursery.start_soon(agps_loop, a_serial)
    print("This should never be reached...")
Exemplo n.º 9
0
    async def test_upload_trio_wrapped_files(self):
        """Uploading a file wrapped via 'trio.wrap_file()' should be possible"""
        with open(__file__, mode="rb") as f:
            data = f.read()
            content_length = len(data)

        headers = {
            "Content-Length": str(content_length),
        }
        url = "%s/echo" % self.base_url

        with PoolManager(backend="trio") as http:
            with open(__file__, mode="rb") as f:
                f = trio.wrap_file(f)
                resp = await http.urlopen("PUT", url, headers=headers, body=f)
                assert resp.status == 200
                assert resp.data == data
Exemplo n.º 10
0
    def __init__(self, port, nursery, data=None, notification_callbacks=None, error_callbacks=None):
        super().__init__(nursery, notification_callbacks, error_callbacks)
        if port is None:
            raise ValueError('port cannot be None')
        try:
            self._connection = serial.Serial(port, 9600, timeout=5.0)
            self._a_connection = trio.wrap_file(self._connection)
            self._data = data if data is not None else {'latitude': None, 'longitude': None, 'altitude': None,
                                                        'num_satellites': None}
        except serial.SerialException:
            print("ERROR initializing GPS module")
            raise

        self.location = None  # type: Union[pynmea2.GGA, None]
        self.visible_satellites = []  # type: List[SatelliteMeasurement]

        self._new_satellites = []  # New list of satellites being constructed (multiple NMEA sentences are required)
        self._is_running = False
Exemplo n.º 11
0
def test_wrap_invalid():
    with pytest.raises(TypeError):
        trio.wrap_file(str())
Exemplo n.º 12
0
def async_file(wrapped):
    return trio.wrap_file(wrapped)
Exemplo n.º 13
0
async def write_data(stream: INetStream) -> None:
    async_f = trio.wrap_file(sys.stdin)
    while True:
        line = await async_f.readline()
        await stream.write(line.encode())
Exemplo n.º 14
0
async def make_named_tempfile(*args: typing.Any, **kwargs: typing.Any) \
      -> 'trio._file_io.AsyncIOWrapper':
    return typing.cast(
        'trio._file_io.AsyncIOWrapper',
        trio.wrap_file(await run_blocking_nointr(tempfile.NamedTemporaryFile,
                                                 *args, **kwargs)))
Exemplo n.º 15
0
 async def open(self, *args, **kwargs):
     func = partial(self._wrapped.open, *args, **kwargs)
     value = await trio.run_in_worker_thread(func)
     return trio.wrap_file(value)