Create a temporary file, optionally writing contents to it
(self, filename, contents=b'', mode='wb', encoding=None)
| 220 | # file creation functions |
| 221 | # |
| 222 | def write_file(self, filename, contents=b'', mode='wb', encoding=None): |
| 223 | """Create a temporary file, optionally writing contents to it""" |
| 224 | if not encoding and mode == 'w': |
| 225 | encoding = 'utf-8' |
| 226 | if not os.path.isabs(filename): |
| 227 | filename = os.path.join(self.tempdir, filename) |
| 228 | with open(extended_path(filename), mode, encoding=encoding) as f: |
| 229 | f.write(contents) |
| 230 | assert (os.path.exists(extended_path(filename))) |
| 231 | with open(extended_path(filename), 'rb' if 'b' in mode else 'r', encoding=encoding if 'b' not in mode else None) as f: |
| 232 | written_contents = f.read() |
| 233 | expected = contents if 'b' in mode else contents.encode( |
| 234 | encoding) if encoding else contents |
| 235 | actual = written_contents if 'b' in mode else written_contents.encode( |
| 236 | encoding) if encoding else written_contents |
| 237 | assert actual == expected, f"File contents mismatch: expected {expected!r}, got {actual!r}" |
| 238 | return filename |
| 239 | |
| 240 | def mkdir(self, dirname): |
| 241 | """Create a directory with a given name |