pax_global_header00006660000000000000000000000064133336156160014521gustar00rootroot0000000000000052 comment=fb74f6d8bde58bc2ed67b425f4d61a6af54746b7 aiofiles-0.4.0/000077500000000000000000000000001333361561600133155ustar00rootroot00000000000000aiofiles-0.4.0/.gitignore000066400000000000000000000013441333361561600153070ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ pyvenv/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ # IDEA IDE files .idea/ *.imlaiofiles-0.4.0/.travis.yml000066400000000000000000000006341333361561600154310ustar00rootroot00000000000000language: python cache: pip matrix: include: - python: "3.5" env: TOXENV=py35 - python: "3.6" env: TOXENV=py36 - python: "pypy3" env: TOXENV=pypy3 - python: "3.7" env: TOXENV=py37 dist: xenial sudo: true before_install: - pip install codecov install: - pip install tox script: - tox -e $TOXENV after_success: - tox -e coverage-report - codecov aiofiles-0.4.0/LICENSE000066400000000000000000000260751333361561600143340ustar00rootroot00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. aiofiles-0.4.0/MANIFEST.in000066400000000000000000000000201333361561600150430ustar00rootroot00000000000000include LICENSE aiofiles-0.4.0/README.rst000066400000000000000000000074371333361561600150170ustar00rootroot00000000000000aiofiles: file support for asyncio ================================== .. image:: https://img.shields.io/pypi/v/aiofiles.svg :target: https://pypi.python.org/pypi/aiofiles .. image:: https://travis-ci.org/Tinche/aiofiles.svg?branch=master :target: https://travis-ci.org/Tinche/aiofiles .. image:: https://codecov.io/gh/Tinche/aiofiles/branch/master/graph/badge.svg :target: https://codecov.io/gh/Tinche/aiofiles **aiofiles** is an Apache2 licensed library, written in Python, for handling local disk files in asyncio applications. Ordinary local file IO is blocking, and cannot easily and portably made asynchronous. This means doing file IO may interfere with asyncio applications, which shouldn't block the executing thread. aiofiles helps with this by introducing asynchronous versions of files that support delegating operations to a separate thread pool. .. code-block:: python async with aiofiles.open('filename', mode='r') as f: contents = await f.read() print(contents) 'My file contents' Asynchronous iteration is also supported. .. code-block:: python async with aiofiles.open('filename') as f: async for line in f: ... Features -------- - a file API very similar to Python's standard, blocking API - support for buffered and unbuffered binary files, and buffered text files - support for ``async``/``await`` (:PEP:`492`) constructs Installation ------------ To install aiofiles, simply: .. code-block:: bash $ pip install aiofiles Usage ----- Files are opened using the ``aiofiles.open()`` coroutine, which in addition to mirroring the builtin ``open`` accepts optional ``loop`` and ``executor`` arguments. If ``loop`` is absent, the default loop will be used, as per the set asyncio policy. If ``executor`` is not specified, the default event loop executor will be used. In case of success, an asynchronous file object is returned with an API identical to an ordinary file, except the following methods are coroutines and delegate to an executor: * ``close`` * ``flush`` * ``isatty`` * ``read`` * ``readall`` * ``read1`` * ``readinto`` * ``readline`` * ``readlines`` * ``seek`` * ``seekable`` * ``tell`` * ``truncate`` * ``writable`` * ``write`` * ``writelines`` In case of failure, one of the usual exceptions will be raised. The ``aiofiles.os`` module contains executor-enabled coroutine versions of several useful ``os`` functions that deal with files: * ``stat`` * ``sendfile`` Writing tests for aiofiles ~~~~~~~~~~~~~~~~~~~~~~~~~~ Real file IO can be mocked by patching ``aiofiles.threadpool.sync_open`` as desired. The return type also needs to be registered with the ``aiofiles.threadpool.wrap`` dispatcher: .. code-block:: python aiofiles.threadpool.wrap.register(mock.MagicMock)( lambda *args, **kwargs: threadpool.AsyncBufferedIOBase(*args, **kwargs)) async def test_stuff(): data = 'data' mock_file = mock.MagicMock() with mock.patch('aiofiles.threadpool.sync_open', return_value=mock_file) as mock_open: async with aiofiles.open('filename', 'w') as f: await f.write(data) mock_file.write.assert_called_once_with(data) History ~~~~~~~ 0.4.0 (2018-08-11) `````````````````` - Python 3.7 support. - Removed Python 3.3/3.4 support. If you use these versions, stick to aiofiles 0.3.x. 0.3.2 (2017-09-23) `````````````````` - The LICENSE is now included in the sdist. `#31 `_ 0.3.1 (2017-03-10) `````````````````` - Introduced a changelog. - ``aiofiles.os.sendfile`` will now work if the standard ``os`` module contains a ``sendfile`` function. Contributing ~~~~~~~~~~~~ Contributions are very welcome. Tests can be run with ``tox``, please ensure the coverage at least stays the same before you submit a pull request. aiofiles-0.4.0/aiofiles/000077500000000000000000000000001333361561600151105ustar00rootroot00000000000000aiofiles-0.4.0/aiofiles/__init__.py000066400000000000000000000001731333361561600172220ustar00rootroot00000000000000"""Utilities for asyncio-friendly file handling.""" from .threadpool import open __version__ = "0.4.0" __all__ = (open,) aiofiles-0.4.0/aiofiles/base.py000066400000000000000000000041111333361561600163710ustar00rootroot00000000000000"""Various base classes.""" import asyncio from collections.abc import Coroutine class AsyncBase: def __init__(self, file, loop, executor): self._file = file self._loop = loop self._executor = executor def __aiter__(self): """We are our own iterator.""" return self @asyncio.coroutine def __anext__(self): """Simulate normal file iteration.""" line = yield from self.readline() if line: return line else: raise StopAsyncIteration class _ContextManager(Coroutine): __slots__ = ('_coro', '_obj') def __init__(self, coro): self._coro = coro self._obj = None def send(self, value): return self._coro.send(value) def throw(self, typ, val=None, tb=None): if val is None: return self._coro.throw(typ) elif tb is None: return self._coro.throw(typ, val) else: return self._coro.throw(typ, val, tb) def close(self): return self._coro.close() @property def gi_frame(self): return self._coro.gi_frame @property def gi_running(self): return self._coro.gi_running @property def gi_code(self): return self._coro.gi_code def __next__(self): return self.send(None) @asyncio.coroutine def __iter__(self): resp = yield from self._coro return resp def __await__(self): resp = yield from self._coro return resp @asyncio.coroutine def __anext__(self): resp = yield from self._coro return resp @asyncio.coroutine def __aenter__(self): self._obj = yield from self._coro return self._obj @asyncio.coroutine def __aexit__(self, exc_type, exc, tb): self._obj.close() self._obj = None class AiofilesContextManager(_ContextManager): """An adjusted async context manager for aiofiles.""" @asyncio.coroutine def __aexit__(self, exc_type, exc_val, exc_tb): yield from self._obj.close() self._obj = None aiofiles-0.4.0/aiofiles/os.py000066400000000000000000000010021333361561600160740ustar00rootroot00000000000000"""Async executor versions of file functions from the os module.""" import asyncio from functools import partial, wraps import os def wrap(func): @asyncio.coroutine @wraps(func) def run(*args, loop=None, executor=None, **kwargs): if loop is None: loop = asyncio.get_event_loop() pfunc = partial(func, *args, **kwargs) return loop.run_in_executor(executor, pfunc) return run stat = wrap(os.stat) if hasattr(os, "sendfile"): sendfile = wrap(os.sendfile) aiofiles-0.4.0/aiofiles/threadpool/000077500000000000000000000000001333361561600172515ustar00rootroot00000000000000aiofiles-0.4.0/aiofiles/threadpool/__init__.py000066400000000000000000000041401333361561600213610ustar00rootroot00000000000000"""Handle files using a thread pool executor.""" import asyncio from io import (FileIO, TextIOBase, BufferedReader, BufferedWriter, BufferedRandom) from functools import partial, singledispatch from .binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO from .text import AsyncTextIOWrapper from ..base import AiofilesContextManager sync_open = open __all__ = ('open', ) def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, *, loop=None, executor=None): return AiofilesContextManager(_open(file, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, closefd=closefd, opener=opener, loop=loop, executor=executor)) @asyncio.coroutine def _open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, *, loop=None, executor=None): """Open an asyncio file.""" if loop is None: loop = asyncio.get_event_loop() cb = partial(sync_open, file, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, closefd=closefd, opener=opener) f = yield from loop.run_in_executor(executor, cb) return wrap(f, loop=loop, executor=executor) @singledispatch def wrap(file, *, loop=None, executor=None): raise TypeError('Unsupported io type: {}.'.format(file)) @wrap.register(TextIOBase) def _(file, *, loop=None, executor=None): return AsyncTextIOWrapper(file, loop=loop, executor=executor) @wrap.register(BufferedWriter) def _(file, *, loop=None, executor=None): return AsyncBufferedIOBase(file, loop=loop, executor=executor) @wrap.register(BufferedReader) @wrap.register(BufferedRandom) def _(file, *, loop=None, executor=None): return AsyncBufferedReader(file, loop=loop, executor=executor) @wrap.register(FileIO) def _(file, *, loop=None, executor=None): return AsyncFileIO(file, loop, executor) aiofiles-0.4.0/aiofiles/threadpool/binary.py000066400000000000000000000021161333361561600211070ustar00rootroot00000000000000from ..base import AsyncBase from .utils import (delegate_to_executor, proxy_property_directly, proxy_method_directly) @delegate_to_executor('close', 'flush', 'isatty', 'read', 'read1', 'readinto', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines') @proxy_method_directly('detach', 'fileno', 'readable') @proxy_property_directly('closed', 'raw') class AsyncBufferedIOBase(AsyncBase): """The asyncio executor version of io.BufferedWriter.""" @delegate_to_executor('peek') class AsyncBufferedReader(AsyncBufferedIOBase): """The asyncio executor version of io.BufferedReader and Random.""" @delegate_to_executor('close', 'flush', 'isatty', 'read', 'readall', 'readinto', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines') @proxy_method_directly('fileno', 'readable') @proxy_property_directly('closed') class AsyncFileIO(AsyncBase): """The asyncio executor version of io.FileIO.""" aiofiles-0.4.0/aiofiles/threadpool/text.py000066400000000000000000000011651333361561600206120ustar00rootroot00000000000000from .utils import (delegate_to_executor, proxy_property_directly, proxy_method_directly) from ..base import AsyncBase @delegate_to_executor('close', 'flush', 'isatty', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'write', 'writable', 'writelines') @proxy_method_directly('detach', 'fileno', 'readable') @proxy_property_directly('buffer', 'closed', 'encoding', 'errors', 'line_buffering', 'newlines') class AsyncTextIOWrapper(AsyncBase): """The asyncio executor version of io.TextIOWrapper.""" aiofiles-0.4.0/aiofiles/threadpool/utils.py000066400000000000000000000023621333361561600207660ustar00rootroot00000000000000import asyncio import functools def delegate_to_executor(*attrs): def cls_builder(cls): for attr_name in attrs: setattr(cls, attr_name, _make_delegate_method(attr_name)) return cls return cls_builder def proxy_method_directly(*attrs): def cls_builder(cls): for attr_name in attrs: setattr(cls, attr_name, _make_proxy_method(attr_name)) return cls return cls_builder def proxy_property_directly(*attrs): def cls_builder(cls): for attr_name in attrs: setattr(cls, attr_name, _make_proxy_property(attr_name)) return cls return cls_builder def _make_delegate_method(attr_name): @asyncio.coroutine def method(self, *args, **kwargs): cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs) return (yield from self._loop.run_in_executor(self._executor, cb)) return method def _make_proxy_method(attr_name): def method(self, *args, **kwargs): return getattr(self._file, attr_name)(*args, **kwargs) return method def _make_proxy_property(attr_name): def proxy_property(self): return getattr(self._file, attr_name) return property(proxy_property) aiofiles-0.4.0/setup.py000066400000000000000000000023601333361561600150300ustar00rootroot00000000000000import codecs import os import re from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() def read(*parts): here = os.path.abspath(os.path.dirname(__file__)) return codecs.open(os.path.join(here, *parts), 'r').read() def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") setup( name='aiofiles', version=find_version('aiofiles', '__init__.py'), packages=find_packages(), url='https://github.com/Tinche/aiofiles', license='Apache 2.0', author='Tin Tvrtkovic', author_email='tinchester@gmail.com', description='File support for asyncio.', long_description=readme, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: System :: Filesystems", ] ) aiofiles-0.4.0/test_requirements.txt000066400000000000000000000001061333361561600176350ustar00rootroot00000000000000coverage==4.5.1 pytest-asyncio==0.9.0 pytest==3.7.1 pytest-cov==2.5.1 aiofiles-0.4.0/tests/000077500000000000000000000000001333361561600144575ustar00rootroot00000000000000aiofiles-0.4.0/tests/conftest.py000066400000000000000000000002641333361561600166600ustar00rootroot00000000000000import sys collect_ignore = [] if sys.version_info[:2] < (3, 5): collect_ignore.append("threadpool/test_text_35.py") collect_ignore.append("threadpool/test_binary_35.py") aiofiles-0.4.0/tests/resources/000077500000000000000000000000001333361561600164715ustar00rootroot00000000000000aiofiles-0.4.0/tests/resources/multiline_file.txt000066400000000000000000000000331333361561600222270ustar00rootroot00000000000000line 1 line 2 line 3 line 4aiofiles-0.4.0/tests/resources/test_file1.txt000066400000000000000000000000121333361561600212620ustar00rootroot000000000000000123456789aiofiles-0.4.0/tests/test_os.py000066400000000000000000000047411333361561600165170ustar00rootroot00000000000000"""Tests for asyncio's os module.""" import aiofiles.os import asyncio from os.path import join, dirname import pytest import platform @asyncio.coroutine @pytest.mark.asyncio def test_stat(): """Test the stat call.""" filename = join(dirname(__file__), 'resources', 'test_file1.txt') stat_res = yield from aiofiles.os.stat(filename) assert stat_res.st_size == 10 @asyncio.coroutine @pytest.mark.skipif('2.4' < platform.release() < '2.6.33', reason = "sendfile() syscall doesn't allow file->file") @pytest.mark.asyncio def test_sendfile_file(tmpdir): """Test the sendfile functionality, file-to-file.""" filename = join(dirname(__file__), 'resources', 'test_file1.txt') tmp_filename = tmpdir.join('tmp.bin') with open(filename) as f: contents = f.read() input_file = yield from aiofiles.open(filename) output_file = yield from aiofiles.open(str(tmp_filename), mode='w+') size = (yield from aiofiles.os.stat(filename)).st_size input_fd = input_file.fileno() output_fd = output_file.fileno() yield from aiofiles.os.sendfile(output_fd, input_fd, 0, size) yield from output_file.seek(0) actual_contents = yield from output_file.read() actual_size = (yield from aiofiles.os.stat(str(tmp_filename))).st_size assert contents == actual_contents assert size == actual_size @asyncio.coroutine @pytest.mark.asyncio def test_sendfile_socket(unused_tcp_port): """Test the sendfile functionality, file-to-socket.""" filename = join(dirname(__file__), 'resources', 'test_file1.txt') with open(filename, mode='rb') as f: contents = f.read() @asyncio.coroutine def serve_file(_, writer): out_fd = writer.transport.get_extra_info('socket').fileno() size = (yield from aiofiles.os.stat(filename)).st_size in_file = yield from aiofiles.open(filename) try: in_fd = in_file.fileno() yield from aiofiles.os.sendfile(out_fd, in_fd, 0, size) finally: yield from in_file.close() yield from writer.drain() writer.close() server = yield from asyncio.start_server(serve_file, port=unused_tcp_port) reader, writer = yield from asyncio.open_connection('127.0.0.1', unused_tcp_port) actual_contents = yield from reader.read() writer.close() assert contents == actual_contents server.close() yield from server.wait_closed() aiofiles-0.4.0/tests/test_simple.py000066400000000000000000000044571333361561600173730ustar00rootroot00000000000000"""Simple tests verifying basic functionality.""" import asyncio from aiofiles import threadpool import pytest @asyncio.coroutine @pytest.mark.asyncio def test_serve_small_bin_file_sync(event_loop, tmpdir, unused_tcp_port): """Fire up a small simple file server, and fetch a file. The file is read into memory synchronously, so this test doesn't actually test anything except the general test concept. """ # First we'll write a small file. filename = 'test.bin' file_content = b'0123456789' file = tmpdir.join(filename) file.write_binary(file_content) @asyncio.coroutine def serve_file(reader, writer): full_filename = str(file) with open(full_filename, 'rb') as f: writer.write(f.read()) writer.close() server = yield from asyncio.start_server(serve_file, port=unused_tcp_port, loop=event_loop) reader, _ = yield from asyncio.open_connection(host='localhost', port=unused_tcp_port, loop=event_loop) payload = yield from reader.read() assert payload == file_content server.close() yield from server.wait_closed() @asyncio.coroutine @pytest.mark.asyncio def test_serve_small_bin_file(event_loop, tmpdir, unused_tcp_port): """Fire up a small simple file server, and fetch a file.""" # First we'll write a small file. filename = 'test.bin' file_content = b'0123456789' file = tmpdir.join(filename) file.write_binary(file_content) @asyncio.coroutine def serve_file(reader, writer): full_filename = str(file) f = yield from threadpool.open(full_filename, mode='rb') writer.write((yield from f.read())) yield from f.close() writer.close() server = yield from asyncio.start_server(serve_file, port=unused_tcp_port, loop=event_loop) reader, _ = yield from asyncio.open_connection(host='localhost', port=unused_tcp_port, loop=event_loop) payload = yield from reader.read() assert payload == file_content server.close() yield from server.wait_closed() aiofiles-0.4.0/tests/threadpool/000077500000000000000000000000001333361561600166205ustar00rootroot00000000000000aiofiles-0.4.0/tests/threadpool/test_binary.py000066400000000000000000000222151333361561600215170ustar00rootroot00000000000000"""PEP 0492/Python 3.5+ tests for binary files.""" import io from os.path import dirname, join from aiofiles.threadpool import open as aioopen import pytest @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['rb', 'rb+', 'ab+']) @pytest.mark.parametrize('buffering', [-1, 0]) async def test_simple_iteration(mode, buffering): """Test iterating over lines from a file.""" filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') async with aioopen(filename, mode=mode, buffering=buffering) as file: # Append mode needs us to seek. await file.seek(0) counter = 1 # The old iteration pattern: while True: line = await file.readline() if not line: break assert line.strip() == b'line ' + str(counter).encode() counter += 1 counter = 1 await file.seek(0) # The new iteration pattern: async for line in file: assert line.strip() == b'line ' + str(counter).encode() counter += 1 assert file.closed @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['rb', 'rb+', 'ab+']) @pytest.mark.parametrize('buffering', [-1, 0]) async def test_simple_readlines(mode, buffering): """Test the readlines functionality.""" filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') with open(filename, mode='rb') as f: expected = f.readlines() async with aioopen(str(filename), mode=mode) as file: # Append mode needs us to seek. await file.seek(0) actual = await file.readlines() assert actual == expected @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['rb+', 'wb', 'ab']) @pytest.mark.parametrize('buffering', [-1, 0]) async def test_simple_flush(mode, buffering, tmpdir): """Test flushing to a file.""" filename = 'file.bin' full_file = tmpdir.join(filename) if 'r' in mode: full_file.ensure() # Read modes want it to already exist. async with aioopen(str(full_file), mode=mode, buffering=buffering) as file: await file.write(b'0') # Shouldn't flush. if buffering == -1: assert b'' == full_file.read_binary() else: assert b'0' == full_file.read_binary() await file.flush() assert b'0' == full_file.read_binary() @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['rb+', 'wb+', 'ab+']) async def test_simple_peek(mode, tmpdir): """Test flushing to a file.""" filename = 'file.bin' full_file = tmpdir.join(filename) full_file.write_binary(b'0123456789') async with aioopen(str(full_file), mode=mode) as file: if 'a' in mode: await file.seek(0) # Rewind for append modes. peeked = await file.peek(1) # Technically it's OK for the peek to return less bytes than requested. if peeked: assert peeked.startswith(b'0') read = await file.read(1) assert peeked.startswith(read) @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['rb', 'rb+', 'ab+']) @pytest.mark.parametrize('buffering', [-1, 0]) async def test_simple_read(mode, buffering): """Just read some bytes from a test file.""" filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') async with aioopen(filename, mode=mode, buffering=buffering) as file: await file.seek(0) # Needed for the append mode. actual = await file.read() assert b'' == (await file.read()) assert actual == open(filename, mode='rb').read() @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['rb', 'rb+', 'ab+']) @pytest.mark.parametrize('buffering', [-1, 0]) async def test_staggered_read(mode, buffering): """Read bytes repeatedly.""" filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') async with aioopen(filename, mode=mode, buffering=buffering) as file: await file.seek(0) # Needed for the append mode. actual = [] while True: byte = await file.read(1) if byte: actual.append(byte) else: break assert b'' == (await file.read()) expected = [] with open(filename, mode='rb') as f: while True: byte = f.read(1) if byte: expected.append(byte) else: break assert actual == expected @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['rb', 'rb+', 'ab+']) @pytest.mark.parametrize('buffering', [-1, 0]) async def test_simple_seek(mode, buffering, tmpdir): """Test seeking and then reading.""" filename = 'bigfile.bin' content = b'0123456789' * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write_binary(content) async with aioopen(str(full_file), mode=mode, buffering=buffering) as file: await file.seek(4) assert b'4' == (await file.read(1)) @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['wb', 'rb', 'rb+', 'wb+', 'ab', 'ab+']) @pytest.mark.parametrize('buffering', [-1, 0]) async def test_simple_close_ctx_mgr(mode, buffering, tmpdir): """Open a file, read a byte, and close it.""" filename = 'bigfile.bin' content = b'0' * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write_binary(content) async with aioopen(str(full_file), mode=mode, buffering=buffering) as file: assert not file.closed assert not file._file.closed assert file.closed assert file._file.closed @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['wb', 'rb', 'rb+', 'wb+', 'ab', 'ab+']) @pytest.mark.parametrize('buffering', [-1, 0]) async def test_simple_close_ctx_mgr(mode, buffering, tmpdir): """Open a file, read a byte, and close it.""" filename = 'bigfile.bin' content = b'0' * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write_binary(content) file = await aioopen(str(full_file), mode=mode, buffering=buffering) assert not file.closed assert not file._file.closed await file.close() assert file.closed assert file._file.closed @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['rb', 'rb+', 'ab+']) @pytest.mark.parametrize('buffering', [-1, 0]) async def test_simple_readinto(mode, buffering): """Test the readinto functionality.""" filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') async with aioopen(filename, mode=mode, buffering=buffering) as file: await file.seek(0) # Needed for the append mode. array = bytearray(4) bytes_read = await file.readinto(array) assert bytes_read == 4 assert array == open(filename, mode='rb').read(4) @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['rb+', 'wb', 'ab+']) @pytest.mark.parametrize('buffering', [-1, 0]) async def test_simple_truncate(mode, buffering, tmpdir): """Test truncating files.""" filename = 'bigfile.bin' content = b'0123456789' * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write_binary(content) async with aioopen(str(full_file), mode=mode, buffering=buffering) as file: # The append modes want us to seek first. await file.seek(0) if 'w' in mode: # We've just erased the entire file. await file.write(content) await file.flush() await file.seek(0) await file.truncate() assert b'' == full_file.read_binary() @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['wb', 'rb+', 'wb+', 'ab', 'ab+']) @pytest.mark.parametrize('buffering', [-1, 0]) async def test_simple_write(mode, buffering, tmpdir): """Test writing into a file.""" filename = 'bigfile.bin' content = b'0' * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) if 'r' in mode: full_file.ensure() # Read modes want it to already exist. async with aioopen(str(full_file), mode=mode, buffering=buffering) as file: bytes_written = await file.write(content) assert bytes_written == len(content) assert content == full_file.read_binary() @pytest.mark.asyncio async def test_simple_detach(tmpdir): """Test detaching for buffered streams.""" filename = 'file.bin' full_file = tmpdir.join(filename) full_file.write_binary(b'0123456789') with pytest.raises(ValueError): async with aioopen(str(full_file), mode='rb') as file: raw_file = file.detach() assert raw_file with pytest.raises(ValueError): await file.read() assert b'0123456789' == raw_file.read(10) @pytest.mark.asyncio async def test_simple_readall(tmpdir): """Test the readall function by reading a large file in. Only RawIOBase supports readall(). """ filename = 'bigfile.bin' content = b'0' * 4 * io.DEFAULT_BUFFER_SIZE # Hopefully several reads. sync_file = tmpdir.join(filename) sync_file.write_binary(content) file = await aioopen(str(sync_file), mode='rb', buffering=0) actual = await file.readall() assert actual == content await file.close() assert file.closed aiofiles-0.4.0/tests/threadpool/test_concurrency.py000066400000000000000000000044271333361561600225720ustar00rootroot00000000000000"""Test concurrency properties of the implementation.""" from os.path import dirname from os.path import join import time import asyncio import pytest import aiofiles.threadpool @asyncio.coroutine @pytest.mark.asyncio def test_slow_file(monkeypatch, unused_tcp_port): """Monkey patch open and file.read(), and assert the loop still works.""" filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') with open(filename, mode='rb') as f: contents = f.read() def new_open(*args, **kwargs): time.sleep(1) return open(*args, **kwargs) monkeypatch.setattr(aiofiles.threadpool, 'sync_open', value=new_open) @asyncio.coroutine def serve_file(_, writer): file = yield from aiofiles.threadpool.open(filename, mode='rb') try: while True: data = yield from file.read(1) if not data: break writer.write(data) yield from writer.drain() yield from writer.drain() finally: writer.close() yield from file.close() @asyncio.coroutine def return_one(_, writer): writer.write(b'1') yield from writer.drain() writer.close() counter = 0 @asyncio.coroutine def spam_client(): nonlocal counter while True: r, w = yield from asyncio.open_connection('127.0.0.1', port=30001) assert (yield from r.read()) == b'1' counter += 1 w.close() yield from asyncio.sleep(0.01) file_server = yield from asyncio.start_server(serve_file, port=unused_tcp_port) spam_server = yield from asyncio.start_server(return_one, port=30001) spam_task = asyncio.ensure_future(spam_client()) reader, writer = yield from asyncio.open_connection('127.0.0.1', port=unused_tcp_port) actual_contents = yield from reader.read() writer.close() yield from asyncio.sleep(0) file_server.close() spam_server.close() yield from file_server.wait_closed() yield from spam_server.wait_closed() spam_task.cancel() assert actual_contents == contents assert counter > 40 aiofiles-0.4.0/tests/threadpool/test_open.py000066400000000000000000000013101333361561600211650ustar00rootroot00000000000000"""Test the open functionality.""" from aiofiles.threadpool import open as aioopen, wrap import pytest @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['r', 'rb']) def test_file_not_found(mode): filename = 'non_existent' try: open(filename, mode=mode) except Exception as e: expected = e assert expected try: yield from aioopen(filename, mode=mode) except Exception as e: actual = e assert actual assert actual.errno == expected.errno assert str(actual) == str(expected) def test_unsupported_wrap(): """A type error should be raised when wrapping something unsupported.""" with pytest.raises(TypeError): wrap(int)aiofiles-0.4.0/tests/threadpool/test_text.py000066400000000000000000000161131333361561600212170ustar00rootroot00000000000000"""PEP 0492/Python 3.5+ tests for text files.""" import io from os.path import dirname, join from aiofiles.threadpool import open as aioopen import pytest @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['r', 'r+', 'a+']) async def test_simple_iteration(mode): """Test iterating over lines from a file.""" filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') async with aioopen(filename, mode=mode) as file: # Append mode needs us to seek. await file.seek(0) counter = 1 # The old iteration pattern: while True: line = await file.readline() if not line: break assert line.strip() == 'line ' + str(counter) counter += 1 await file.seek(0) counter = 1 # The new iteration pattern: async for line in file: assert line.strip() == 'line ' + str(counter) counter += 1 assert file.closed @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['r', 'r+', 'a+']) async def test_simple_readlines(mode): """Test the readlines functionality.""" filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') with open(filename, mode='r') as f: expected = f.readlines() async with aioopen(filename, mode=mode) as file: # Append mode needs us to seek. await file.seek(0) actual = await file.readlines() assert file.closed assert actual == expected @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['r+', 'w', 'a']) async def test_simple_flush(mode, tmpdir): """Test flushing to a file.""" filename = 'file.bin' full_file = tmpdir.join(filename) if 'r' in mode: full_file.ensure() # Read modes want it to already exist. async with aioopen(str(full_file), mode=mode) as file: await file.write('0') # Shouldn't flush. assert '' == full_file.read_text(encoding='utf8') await file.flush() assert '0' == full_file.read_text(encoding='utf8') assert file.closed @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['r', 'r+', 'a+']) async def test_simple_read(mode): """Just read some bytes from a test file.""" filename = join(dirname(__file__), '..', 'resources', 'test_file1.txt') async with aioopen(filename, mode=mode) as file: await file.seek(0) # Needed for the append mode. actual = await file.read() assert '' == (await file.read()) assert actual == open(filename, mode='r').read() assert file.closed @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['w', 'a']) async def test_simple_read_fail(mode, tmpdir): """Try reading some bytes and fail.""" filename = 'bigfile.bin' content = '0123456789' * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write(content) with pytest.raises(ValueError): async with aioopen(str(full_file), mode=mode) as file: await file.seek(0) # Needed for the append mode. await file.read() assert file.closed @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['r', 'r+', 'a+']) async def test_staggered_read(mode): """Read bytes repeatedly.""" filename = join(dirname(__file__), '..', 'resources', 'test_file1.txt') async with aioopen(filename, mode=mode) as file: await file.seek(0) # Needed for the append mode. actual = [] while True: char = await file.read(1) if char: actual.append(char) else: break assert '' == (await file.read()) expected = [] with open(filename, mode='r') as f: while True: char = f.read(1) if char: expected.append(char) else: break assert actual == expected assert file.closed @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['r', 'r+', 'a+']) async def test_simple_seek(mode, tmpdir): """Test seeking and then reading.""" filename = 'bigfile.bin' content = '0123456789' * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write(content) async with aioopen(str(full_file), mode=mode) as file: await file.seek(4) assert '4' == (await file.read(1)) assert file.closed @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['w', 'r', 'r+', 'w+', 'a', 'a+']) async def test_simple_close(mode, tmpdir): """Open a file, read a byte, and close it.""" filename = 'bigfile.bin' content = '0' * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write(content) async with aioopen(str(full_file), mode=mode) as file: assert not file.closed assert not file._file.closed assert file.closed assert file._file.closed @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['r+', 'w', 'a+']) async def test_simple_truncate(mode, tmpdir): """Test truncating files.""" filename = 'bigfile.bin' content = '0123456789' * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) full_file.write(content) async with aioopen(str(full_file), mode=mode) as file: # The append modes want us to seek first. await file.seek(0) if 'w' in mode: # We've just erased the entire file. await file.write(content) await file.flush() await file.seek(0) await file.truncate() assert '' == full_file.read() @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['w', 'r+', 'w+', 'a', 'a+']) async def test_simple_write(mode, tmpdir): """Test writing into a file.""" filename = 'bigfile.bin' content = '0' * 4 * io.DEFAULT_BUFFER_SIZE full_file = tmpdir.join(filename) if 'r' in mode: full_file.ensure() # Read modes want it to already exist. async with aioopen(str(full_file), mode=mode) as file: bytes_written = await file.write(content) assert bytes_written == len(content) assert content == full_file.read() assert file.closed @pytest.mark.asyncio async def test_simple_detach(tmpdir): """Test detaching for buffered streams.""" filename = 'file.bin' full_file = tmpdir.join(filename) full_file.write('0123456789') with pytest.raises(ValueError): # Close will error out. async with aioopen(str(full_file), mode='r') as file: raw_file = file.detach() assert raw_file with pytest.raises(ValueError): await file.read() assert b'0123456789' == raw_file.read(10) @pytest.mark.asyncio @pytest.mark.parametrize('mode', ['r', 'r+', 'a+']) async def test_simple_iteration_ctx_mgr(mode): """Test iterating over lines from a file.""" filename = join(dirname(__file__), '..', 'resources', 'multiline_file.txt') async with aioopen(filename, mode=mode) as file: assert not file.closed await file.seek(0) counter = 1 async for line in file: assert line.strip() == 'line ' + str(counter) counter += 1 assert file.closed aiofiles-0.4.0/tox.ini000066400000000000000000000004121333361561600146250ustar00rootroot00000000000000[tox] envlist = py35, py36, py37, pypy3 [testenv] deps = pip >= 6 -rtest_requirements.txt commands = py.test --cov aiofiles changedir = tests [testenv:coverage-report] deps = coverage skip_install = true commands = coverage combine coverage report