2016-01-26 05:49:32 +08:00
|
|
|
import unittest
|
|
|
|
import sys
|
|
|
|
import asyncio
|
2016-01-26 07:48:12 +08:00
|
|
|
import os
|
2016-01-26 05:49:32 +08:00
|
|
|
|
|
|
|
from artiq.protocols import pipe_ipc
|
|
|
|
|
|
|
|
|
|
|
|
class IPCCase(unittest.TestCase):
|
|
|
|
def setUp(self):
|
2016-01-26 07:48:12 +08:00
|
|
|
if os.name == "nt":
|
|
|
|
self.loop = asyncio.ProactorEventLoop()
|
|
|
|
else:
|
|
|
|
self.loop = asyncio.new_event_loop()
|
2016-01-26 05:49:32 +08:00
|
|
|
asyncio.set_event_loop(self.loop)
|
|
|
|
|
|
|
|
def tearDown(self):
|
|
|
|
self.loop.close()
|
|
|
|
|
2016-01-26 07:48:12 +08:00
|
|
|
async def _coro_test(self, child_asyncio):
|
2016-01-26 05:49:32 +08:00
|
|
|
ipc = pipe_ipc.AsyncioParentComm()
|
|
|
|
await ipc.create_subprocess(sys.executable,
|
|
|
|
sys.modules[__name__].__file__,
|
2016-01-26 07:48:12 +08:00
|
|
|
str(child_asyncio),
|
2016-01-26 05:49:32 +08:00
|
|
|
ipc.get_address())
|
|
|
|
for i in range(10):
|
|
|
|
ipc.write("{}\n".format(i).encode())
|
2016-01-26 07:48:12 +08:00
|
|
|
await ipc.drain()
|
2016-01-26 05:49:32 +08:00
|
|
|
s = (await ipc.readline()).decode()
|
|
|
|
self.assertEqual(int(s), i+1)
|
|
|
|
ipc.write(b"-1\n")
|
|
|
|
await ipc.process.wait()
|
|
|
|
|
|
|
|
def test_blocking(self):
|
2016-01-26 07:48:12 +08:00
|
|
|
self.loop.run_until_complete(self._coro_test(False))
|
|
|
|
|
|
|
|
def test_asyncio(self):
|
2016-01-26 05:49:32 +08:00
|
|
|
self.loop.run_until_complete(self._coro_test(True))
|
|
|
|
|
|
|
|
|
2016-01-26 07:48:12 +08:00
|
|
|
def run_child_blocking():
|
|
|
|
child_comm = pipe_ipc.ChildComm(sys.argv[2])
|
2016-01-26 05:49:32 +08:00
|
|
|
while True:
|
|
|
|
x = int(child_comm.readline().decode())
|
|
|
|
if x < 0:
|
|
|
|
break
|
|
|
|
child_comm.write((str(x+1) + "\n").encode())
|
2016-01-26 07:48:12 +08:00
|
|
|
child_comm.close()
|
|
|
|
|
|
|
|
|
|
|
|
async def coro_child():
|
|
|
|
child_comm = pipe_ipc.AsyncioChildComm(sys.argv[2])
|
|
|
|
await child_comm.connect()
|
|
|
|
while True:
|
|
|
|
x = int((await child_comm.readline()).decode())
|
|
|
|
if x < 0:
|
|
|
|
break
|
|
|
|
child_comm.write((str(x+1) + "\n").encode())
|
|
|
|
await child_comm.drain()
|
|
|
|
child_comm.close()
|
|
|
|
|
|
|
|
|
|
|
|
def run_child_asyncio():
|
|
|
|
if os.name == "nt":
|
|
|
|
loop = asyncio.ProactorEventLoop()
|
|
|
|
asyncio.set_event_loop(loop)
|
|
|
|
else:
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
loop.run_until_complete(coro_child())
|
|
|
|
loop.close()
|
|
|
|
|
|
|
|
|
|
|
|
def run_child():
|
|
|
|
if sys.argv[1] == "True":
|
|
|
|
run_child_asyncio()
|
|
|
|
else:
|
|
|
|
run_child_blocking()
|
2016-01-26 05:49:32 +08:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
run_child()
|