From 8098845c0eced98feae50d3f0fd8bdadeea30771 Mon Sep 17 00:00:00 2001 From: Mike Dirolf Date: Fri, 20 Aug 2010 11:26:36 -0400 Subject: [PATCH] add readline to GridOut PYTHON-157 --- gridfs/grid_file.py | 16 ++++++++++++++++ test/test_grid_file.py | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/gridfs/grid_file.py b/gridfs/grid_file.py index 53c8d1331..8ef50c4eb 100644 --- a/gridfs/grid_file.py +++ b/gridfs/grid_file.py @@ -390,6 +390,22 @@ class GridOut(object): self.__buffer = data[size:] return to_return + def readline(self, size=-1): + """Read one line or up to `size` bytes from the file. + + :Parameters: + - `size` (optional): the maximum number of bytes to read + + .. versionadded:: 1.8.1+ + """ + bytes = "" + while len(bytes) != size: + byte = self.read(1) + bytes += byte + if byte == "" or byte =="\n": + break + return bytes + def tell(self): """Return the current position of this file. """ diff --git a/test/test_grid_file.py b/test/test_grid_file.py index 4446c1e26..aae27630c 100644 --- a/test/test_grid_file.py +++ b/test/test_grid_file.py @@ -367,6 +367,24 @@ class TestGridFile(unittest.TestCase): self.assertEqual("d", g.read(2)) self.assertEqual("", g.read(2)) + def test_readline(self): + f = GridIn(self.db.fs, chunkSize=5) + f.write("""Hello world, +How are you? +Hope all is well. +Bye""") + f.close() + + g = GridOut(self.db.fs, f._id) + self.assertEqual("H", g.read(1)) + self.assertEqual("ello world,\n", g.readline()) + self.assertEqual("How a", g.readline(5)) + self.assertEqual("", g.readline(0)) + self.assertEqual("re you?\n", g.readline()) + self.assertEqual("Hope all is well.\n", g.readline(1000)) + self.assertEqual("Bye", g.readline()) + self.assertEqual("", g.readline()) + def test_iterator(self): f = GridIn(self.db.fs) f.close()