| 598 | |
| 599 | |
| 600 | class FileCreator: |
| 601 | def __init__(self): |
| 602 | self.rootdir = tempfile.mkdtemp() |
| 603 | |
| 604 | def remove_all(self): |
| 605 | if os.path.exists(self.rootdir): |
| 606 | shutil.rmtree(self.rootdir) |
| 607 | |
| 608 | def create_file( |
| 609 | self, filename, contents, mtime=None, mode='w', encoding=None |
| 610 | ): |
| 611 | """Creates a file in a tmpdir |
| 612 | |
| 613 | ``filename`` should be a relative path, e.g. "foo/bar/baz.txt" |
| 614 | It will be translated into a full path in a tmp dir. |
| 615 | |
| 616 | If the ``mtime`` argument is provided, then the file's |
| 617 | mtime will be set to the provided value (must be an epoch time). |
| 618 | Otherwise the mtime is left untouched. |
| 619 | |
| 620 | ``mode`` is the mode the file should be opened either as ``w`` or |
| 621 | `wb``. |
| 622 | |
| 623 | Returns the full path to the file. |
| 624 | |
| 625 | """ |
| 626 | full_path = os.path.join(self.rootdir, filename) |
| 627 | if not os.path.isdir(os.path.dirname(full_path)): |
| 628 | os.makedirs(os.path.dirname(full_path)) |
| 629 | with open(full_path, mode, encoding=encoding) as f: |
| 630 | f.write(contents) |
| 631 | current_time = os.path.getmtime(full_path) |
| 632 | # Subtract a few years off the last modification date. |
| 633 | os.utime(full_path, (current_time, current_time - 100000000)) |
| 634 | if mtime is not None: |
| 635 | os.utime(full_path, (mtime, mtime)) |
| 636 | return full_path |
| 637 | |
| 638 | def create_file_with_size(self, filename, filesize): |
| 639 | filename = self.create_file(filename, contents='') |
| 640 | chunksize = 8192 |
| 641 | with open(filename, 'wb') as f: |
| 642 | for i in range(int(math.ceil(filesize / float(chunksize)))): |
| 643 | f.write(b'a' * chunksize) |
| 644 | return filename |
| 645 | |
| 646 | def append_file(self, filename, contents, encoding=None): |
| 647 | """Append contents to a file |
| 648 | |
| 649 | ``filename`` should be a relative path, e.g. "foo/bar/baz.txt" |
| 650 | It will be translated into a full path in a tmp dir. |
| 651 | |
| 652 | Returns the full path to the file. |
| 653 | """ |
| 654 | full_path = os.path.join(self.rootdir, filename) |
| 655 | if not os.path.isdir(os.path.dirname(full_path)): |
| 656 | os.makedirs(os.path.dirname(full_path)) |
| 657 | with open(full_path, 'a', encoding=encoding) as f: |