summaryrefslogtreecommitdiff
path: root/tests/helpers.py
diff options
context:
space:
mode:
authorNed Batchelder <ned@nedbatchelder.com>2021-03-21 17:05:35 -0400
committerNed Batchelder <ned@nedbatchelder.com>2021-03-22 07:04:13 -0400
commite613a75b7c20bec00b4564f2d87812a8fd7b8e11 (patch)
tree24c2655f09046d226551255301e9d7bba42afc17 /tests/helpers.py
parent34660a217c70b810f7ec5630963f8c37e7a208dc (diff)
downloadpython-coveragepy-git-e613a75b7c20bec00b4564f2d87812a8fd7b8e11.tar.gz
refactor: make_file can be used as a function
Diffstat (limited to 'tests/helpers.py')
-rw-r--r--tests/helpers.py42
1 files changed, 42 insertions, 0 deletions
diff --git a/tests/helpers.py b/tests/helpers.py
index d4dd33ea..c916c8a2 100644
--- a/tests/helpers.py
+++ b/tests/helpers.py
@@ -7,9 +7,11 @@ import collections
import contextlib
import glob
import os
+import os.path
import re
import subprocess
import sys
+import textwrap
import mock
@@ -51,6 +53,46 @@ def run_command(cmd):
return status, output
+def make_file(filename, text="", bytes=b"", newline=None):
+ """Create a file for testing.
+
+ `filename` is the relative path to the file, including directories if
+ desired, which will be created if need be.
+
+ `text` is the content to create in the file, a native string (bytes in
+ Python 2, unicode in Python 3), or `bytes` are the bytes to write.
+
+ If `newline` is provided, it is a string that will be used as the line
+ endings in the created file, otherwise the line endings are as provided
+ in `text`.
+
+ Returns `filename`.
+
+ """
+ # pylint: disable=redefined-builtin # bytes
+ if bytes:
+ data = bytes
+ else:
+ text = textwrap.dedent(text)
+ if newline:
+ text = text.replace("\n", newline)
+ if env.PY3:
+ data = text.encode('utf8')
+ else:
+ data = text
+
+ # Make sure the directories are available.
+ dirs, _ = os.path.split(filename)
+ if dirs and not os.path.exists(dirs):
+ os.makedirs(dirs)
+
+ # Create the file.
+ with open(filename, 'wb') as f:
+ f.write(data)
+
+ return filename
+
+
class CheckUniqueFilenames(object):
"""Asserts the uniqueness of file names passed to a function."""
def __init__(self, wrapped):