Commit f7eb6403 authored by Stefan Behnel's avatar Stefan Behnel

Add some test helper functions to create (source) files from tests.

To be used in https://github.com/cython/cython/pull/4241
parent f6c850d1
......@@ -5,6 +5,7 @@ import unittest
import shlex
import sys
import tempfile
import textwrap
from io import open
from .Compiler import Errors
......@@ -225,3 +226,31 @@ def unpack_source_tree(tree_file, workdir, cython_root):
if cur_file is not None:
cur_file.close()
return workdir, header
def write_file(file_path, content, dedent=False):
"""
Write some content (text or bytes) to the file at "file_path".
"""
mode = 'wb' if isinstance(content, bytes) else 'w'
if dedent:
content = textwrap.dedent(content)
with open(file_path, mode=mode) 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'.
"""
write_file(file_path, content, dedent=dedent)
try:
other_time = os.path.getmtime(newer_than)
except OSError:
# Support
other_time = None
while other_time is None or other_time >= os.path.getmtime(file_path):
write_file(file_path, content, dedent=dedent)
import os.path
import unittest
import tempfile
import shutil
from ..TestUtils import write_file, write_newer_file
class TestTestUtils(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self._test_path = lambda filename: os.path.join(self.temp_dir, filename)
def tearDown(self):
if self.temp_dir and os.path.isdir(self.temp_dir):
shutil.rmtree(self.temp_dir)
def _test_write_file(self, content, expected, **kwargs):
file_path = self._test_path("abcfile")
write_file(file_path, content)
assert os.path.isfile(file_path)
with open(file_path, 'rb') as f:
found = f.read()
assert found == expected, repr(found)
def test_write_file_text(self):
self._test_write_file("abcüöä", b'abc\xc3\xbc\xc3\xb6\xc3\xa4')
def test_write_file_bytes(self):
self._test_write_file(b"ab\0c", b"ab\0c")
def test_write_newer_file(self):
file_path_1 = self._test_path("abcfile1.txt")
file_path_2 = self._test_path("abcfile2.txt")
write_file(file_path_1, "abc")
assert os.path.isfile(file_path_1)
write_newer_file(file_path_2, file_path_1, "xyz")
assert os.path.isfile(file_path_2)
assert os.path.getmtime(file_path_2) > os.path.getmtime(file_path_1)
def test_write_newer_file_same(self):
file_path = self._test_path("abcfile.txt")
write_file(file_path, "abc")
mtime = os.path.getmtime(file_path)
write_newer_file(file_path, file_path, "xyz")
assert os.path.getmtime(file_path) > mtime
def test_write_newer_file_fresh(self):
file_path = self._test_path("abcfile.txt")
assert not os.path.exists(file_path)
write_newer_file(file_path, file_path, "xyz")
assert os.path.isfile(file_path)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment