diff options
Diffstat (limited to 'Cython/TestUtils.py')
-rw-r--r-- | Cython/TestUtils.py | 41 |
1 files changed, 31 insertions, 10 deletions
diff --git a/Cython/TestUtils.py b/Cython/TestUtils.py index d5abacaa6..56f1dfa2e 100644 --- a/Cython/TestUtils.py +++ b/Cython/TestUtils.py @@ -228,23 +228,44 @@ def unpack_source_tree(tree_file, workdir, cython_root): return workdir, header -def write_file(file_path, content, dedent=False): - """ - Write some content (text or bytes) to the file at "file_path". +def write_file(file_path, content, dedent=False, encoding=None): + r"""Write some content (text or bytes) to the file + at `file_path` without translating `'\n'` into `os.linesep`. + + The default encoding is `'utf-8'`. """ - mode = 'wb' if isinstance(content, bytes) else 'w' + if isinstance(content, bytes): + mode = "wb" + + # binary mode doesn't take an encoding and newline arguments + newline = None + default_encoding = None + else: + mode = "w" + + # any "\n" characters written are not translated + # to the system default line separator, os.linesep + newline = "\n" + default_encoding = "utf-8" + + if encoding is None: + encoding = default_encoding + if dedent: content = textwrap.dedent(content) - with open(file_path, mode=mode) as f: + with open(file_path, mode=mode, encoding=encoding, newline=newline) as f: f.write(content) -def write_newer_file(file_path, newer_than, content, dedent=False): - """ - Write 'content' to the file 'file_path' and make sure it is newer than the file 'newer_than'. +def write_newer_file(file_path, newer_than, content, dedent=False, encoding=None): + r""" + Write `content` to the file `file_path` without translating `'\n'` + into `os.linesep` and make sure it is newer than the file `newer_than`. + + The default encoding is `'utf-8'` (same as for `write_file`). """ - write_file(file_path, content, dedent=dedent) + write_file(file_path, content, dedent=dedent, encoding=encoding) try: other_time = os.path.getmtime(newer_than) @@ -253,4 +274,4 @@ def write_newer_file(file_path, newer_than, content, dedent=False): other_time = None while other_time is None or other_time >= os.path.getmtime(file_path): - write_file(file_path, content, dedent=dedent) + write_file(file_path, content, dedent=dedent, encoding=encoding) |