# Path: peru/async_helpers.py
# async def safe_communicate(process, input=None):
#     '''Asyncio's communicate method has a bug where `communicate(input=b"")` is
#     treated the same as `communicate(). That means that child processes can
#     hang waiting for input, when their stdin should be closed. See
#     https://bugs.python.org/issue26848. The issue is fixed upstream in
#     https://github.com/python/asyncio/commit/915b6eaa30e1e3744e6f8223f996e197c1c9b91d,
#     but we will probably always need this workaround for old versions.'''
#     if input is not None and len(input) == 0:
#         process.stdin.close()
#         return (await process.communicate())
#     else:
#         return (await process.communicate(input))


import asyncio
import sys
from asyncio.subprocess import PIPE
from peru.async_helpers import safe_communicate
from shared import PeruTest, make_synchronous



class AsyncTest(PeruTest):
    @make_synchronous
    async def test_safe_communicate(self):
        # Test safe_communicate with both empty and non-empty input.
        cat_command = [
            sys.executable, "-c",
            "import sys; sys.stdout.write(sys.stdin.read())"
        ]

        proc_empty = await asyncio.create_subprocess_exec(
            *cat_command, stdin=PIPE, stdout=PIPE)

# Path: peru/async_helpers.py
# async def safe_communicate(process, input=None):
#     '''Asyncio's communicate method has a bug where `communicate(input=b"")` is
#     treated the same as `communicate(). That means that child processes can
#     hang waiting for input, when their stdin should be closed. See
#     https://bugs.python.org/issue26848. The issue is fixed upstream in
#     https://github.com/python/asyncio/commit/915b6eaa30e1e3744e6f8223f996e197c1c9b91d,
#     but we will probably always need this workaround for old versions.'''
#     if input is not None and len(input) == 0:
#         process.stdin.close()
#         return (await process.communicate())
#     else:
#         return (await process.communicate(input))


# Path: tests/test_async.py
import asyncio
import sys
from asyncio.subprocess import PIPE
from peru.async_helpers import safe_communicate
from shared import PeruTest, make_synchronous




class AsyncTest(PeruTest):
    @make_synchronous
    async def test_safe_communicate(self):
        # Test safe_communicate with both empty and non-empty input.
        cat_command = [
            sys.executable, "-c",
            "import sys; sys.stdout.write(sys.stdin.read())"
        ]

        proc_empty = await asyncio.create_subprocess_exec(
            *cat_command, stdin=PIPE, stdout=PIPE)

        stdout, _ = await safe_communicate(proc_empty, b"")