| 189 | |
| 190 | |
| 191 | class FileCreator: |
| 192 | def __init__(self): |
| 193 | self.rootdir = tempfile.mkdtemp() |
| 194 | |
| 195 | def remove_all(self): |
| 196 | shutil.rmtree(self.rootdir) |
| 197 | |
| 198 | def create_file(self, filename, contents, mode='w'): |
| 199 | """Creates a file in a tmpdir |
| 200 | ``filename`` should be a relative path, e.g. "foo/bar/baz.txt" |
| 201 | It will be translated into a full path in a tmp dir. |
| 202 | ``mode`` is the mode the file should be opened either as ``w`` or |
| 203 | `wb``. |
| 204 | Returns the full path to the file. |
| 205 | """ |
| 206 | full_path = os.path.join(self.rootdir, filename) |
| 207 | if not os.path.isdir(os.path.dirname(full_path)): |
| 208 | os.makedirs(os.path.dirname(full_path)) |
| 209 | with open(full_path, mode) as f: |
| 210 | f.write(contents) |
| 211 | return full_path |
| 212 | |
| 213 | def create_file_with_size(self, filename, filesize): |
| 214 | filename = self.create_file(filename, contents='') |
| 215 | chunksize = 8192 |
| 216 | with open(filename, 'wb') as f: |
| 217 | for i in range(int(math.ceil(filesize / float(chunksize)))): |
| 218 | f.write(b'a' * chunksize) |
| 219 | return filename |
| 220 | |
| 221 | def append_file(self, filename, contents): |
| 222 | """Append contents to a file |
| 223 | ``filename`` should be a relative path, e.g. "foo/bar/baz.txt" |
| 224 | It will be translated into a full path in a tmp dir. |
| 225 | Returns the full path to the file. |
| 226 | """ |
| 227 | full_path = os.path.join(self.rootdir, filename) |
| 228 | if not os.path.isdir(os.path.dirname(full_path)): |
| 229 | os.makedirs(os.path.dirname(full_path)) |
| 230 | with open(full_path, 'a') as f: |
| 231 | f.write(contents) |
| 232 | return full_path |
| 233 | |
| 234 | def full_path(self, filename): |
| 235 | """Translate relative path to full path in temp dir. |
| 236 | f.full_path('foo/bar.txt') -> /tmp/asdfasd/foo/bar.txt |
| 237 | """ |
| 238 | return os.path.join(self.rootdir, filename) |
| 239 | |
| 240 | |
| 241 | class RecordingOSUtils(OSUtils): |