improved unittest's create file: do not gather GB in memory before writing
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Thu, 9 Jun 2016 15:53:54 +0000 (17:53 +0200)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Wed, 15 Jun 2016 11:18:02 +0000 (13:18 +0200)
testing/__init__.py

index c616370..c538fef 100644 (file)
@@ -49,13 +49,15 @@ class BaseTest(unittest.TestCase):
         Creates a file with some gibberish inside, returning the md5sum of that
         file. File path and length are specified as function arguments.
         '''
-        f = open(path, 'w')
-        s = string.ascii_lowercase + string.digits + "\n"
-        if len(s) < length:
-            s += s*int(length/len(s))
-        data = s[:length]
-        f.write(data)
-        f.close()
+        data = string.ascii_lowercase + string.digits + "\n"
+
+        # determine how often need to repeat data and how much part of data is
+        # left in the end to fill file up to length
+        n_blocks, remainder = divmod(length, len(data))
+        with open(path, 'w') as write_handle:
+            for _ in range(n_blocks):
+                write_handle.write(data)
+            write_handle.write(data[:remainder])
         return self.md5sum(path)
 
     def md5sum(self, filename):