2016-05-05 04:04:37 +00:00
|
|
|
import asyncio
|
|
|
|
from asyncio.subprocess import PIPE
|
|
|
|
import sys
|
|
|
|
|
2017-01-31 17:19:44 +00:00
|
|
|
from peru.async_helpers import safe_communicate
|
2016-05-05 04:04:37 +00:00
|
|
|
from shared import PeruTest, make_synchronous
|
|
|
|
|
|
|
|
|
|
|
|
class AsyncTest(PeruTest):
|
|
|
|
@make_synchronous
|
2018-10-03 19:01:08 +00:00
|
|
|
async def test_safe_communicate(self):
|
2016-05-05 04:04:37 +00:00
|
|
|
# Test safe_communicate with both empty and non-empty input.
|
2018-10-03 19:10:48 +00:00
|
|
|
cat_command = [
|
|
|
|
sys.executable, "-c",
|
|
|
|
"import sys; sys.stdout.write(sys.stdin.read())"
|
|
|
|
]
|
2016-05-05 04:04:37 +00:00
|
|
|
|
2018-10-03 19:01:08 +00:00
|
|
|
proc_empty = await asyncio.create_subprocess_exec(
|
2016-05-05 04:04:37 +00:00
|
|
|
*cat_command, stdin=PIPE, stdout=PIPE)
|
2018-10-03 19:01:08 +00:00
|
|
|
stdout, _ = await safe_communicate(proc_empty, b"")
|
2016-05-05 04:04:37 +00:00
|
|
|
self.assertEqual(stdout, b"")
|
|
|
|
|
2018-10-03 19:01:08 +00:00
|
|
|
proc_nonempty = await asyncio.create_subprocess_exec(
|
2016-05-05 04:04:37 +00:00
|
|
|
*cat_command, stdin=PIPE, stdout=PIPE)
|
2018-10-03 19:10:48 +00:00
|
|
|
stdout, _ = await safe_communicate(proc_nonempty, b"foo bar baz")
|
2016-05-05 04:04:37 +00:00
|
|
|
self.assertEqual(stdout, b"foo bar baz")
|
|
|
|
|
|
|
|
# And test a case with None input as well.
|
|
|
|
true_command = [sys.executable, "-c", ""]
|
2018-10-03 19:01:08 +00:00
|
|
|
proc_true = await asyncio.create_subprocess_exec(
|
2016-05-05 04:04:37 +00:00
|
|
|
*true_command, stdin=PIPE, stdout=PIPE)
|
2018-10-03 19:01:08 +00:00
|
|
|
stdout, _ = await safe_communicate(proc_true)
|
2016-05-05 04:04:37 +00:00
|
|
|
self.assertEqual(stdout, b"")
|