From b09a95ccc164ae7ad5c74520446a77cc313b2d3c Mon Sep 17 00:00:00 2001 From: Mike Dirolf Date: Fri, 5 Feb 2010 09:51:44 -0500 Subject: [PATCH] fix for chunk number calculation when unaligned - thanks to Daniel Lundin for the patch --- doc/contributors.rst | 1 + gridfs/grid_file.py | 2 +- test/test_grid_file.py | 21 +++++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/doc/contributors.rst b/doc/contributors.rst index f81648d85..e0b53f59b 100644 --- a/doc/contributors.rst +++ b/doc/contributors.rst @@ -18,3 +18,4 @@ The following is a list of people who have contributed to - Joshua Roesslein (joshthecoder) - Gregg Lind (gregglind) - Michael Schurter (schmichael) +- Daniel Lundin diff --git a/gridfs/grid_file.py b/gridfs/grid_file.py index 5ba81a001..0ab1631e8 100644 --- a/gridfs/grid_file.py +++ b/gridfs/grid_file.py @@ -306,7 +306,7 @@ class GridFile(object): size = remainder bytes = self.__buffer - chunk_number = math.floor(self.__position / self.__chunk_size) + chunk_number = (len(bytes) + self.__position) / self.__chunk_size while len(bytes) < size: chunk = self.__collection.chunks.find_one({"files_id": self.__id, "n": chunk_number}) diff --git a/test/test_grid_file.py b/test/test_grid_file.py index 867aa0057..ff5d510f3 100644 --- a/test/test_grid_file.py +++ b/test/test_grid_file.py @@ -406,5 +406,26 @@ class TestGridFile(unittest.TestCase): file = GridFile({"_id": "foobar", "filename": "foobar"}, self.db, "w") file.close() + def test_read_chunks_unaligned_buffer_size(self): + self.db.fs.files.remove({}) + self.db.fs.chunks.remove({}) + + in_data = "This is a text that doesn't quite fit in a single 16-byte chunk." + f = GridFile({"filename":"test", "chunkSize":16}, self.db, "w") + f.write(in_data) + f.close() + + f = GridFile({"filename":"test"}, self.db) + out_data = '' + while 1: + s = f.read(13) + if not s: + break + out_data += s + f.close() + + self.assertEqual(in_data, out_data) + + if __name__ == "__main__": unittest.main()