From f52381655b939aacf408a665a53e8c28c2cd5965 Mon Sep 17 00:00:00 2001 From: scott Date: Thu, 4 Mar 2010 17:06:23 -0600 Subject: [PATCH] Add context manager to GreenPipe. --- eventlet/greenio.py | 6 ++++++ tests/greenio_test.py | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/eventlet/greenio.py b/eventlet/greenio.py index 06e1883..6478d22 100644 --- a/eventlet/greenio.py +++ b/eventlet/greenio.py @@ -461,6 +461,12 @@ class GreenPipe(object): def __iter__(self): return self.xreadlines() + def __enter__(self): + return self + + def __exit__(self, *exc_info): + self.close() + def xreadlines(self, size=None): if size is None: while True: diff --git a/tests/greenio_test.py b/tests/greenio_test.py index 8a654a7..3ca97de 100644 --- a/tests/greenio_test.py +++ b/tests/greenio_test.py @@ -483,6 +483,26 @@ class TestGreenIo(LimitedTestCase): gt.wait() + def test_pipe_context(self): + # ensure using a pipe as a context actually closes it. + r, w = os.pipe() + + r = os.fdopen(r) + w = os.fdopen(w, 'w') + + r = greenio.GreenPipe(r) + w = greenio.GreenPipe(w) + + with r: + pass + + assert r.closed and not w.closed + + with w as f: + assert f == w + + assert r.closed and w.closed + class TestGreenIoLong(LimitedTestCase): TEST_TIMEOUT=10 # the test here might take a while depending on the OS