Skip to content

Commit

Permalink
Refs #11418. Added testhelper for temporary files
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Wedel committed Mar 24, 2015
1 parent 474548a commit 5f1af07
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
Expand Up @@ -5,6 +5,7 @@
set ( PY_FILES
__init__.py
algorithm_decorator.py
tempfile_wrapper.py
)

# Copy python files to output directory
Expand Down
@@ -0,0 +1,46 @@
from tempfile import NamedTemporaryFile
import os


class TemporaryFileHelper(object):
"""Helper class for temporary files in unit tests
This class is a small helper for using temporary files for unit test. On instantiation, a temporary file will be
created (using NamedTemporaryFile from the tempfile module). If the string argument to the constructor is not empty,
its content will be written to that file. The getName()-method provides the name of the temporary file, which can
for example be passed to an algorithm that expects a FileProperty. On destruction of the TemporaryFileHelper object,
the temporary file is removed automatically using os.unlink().
Usage:
emptyFileHelper = TemporaryFileHelper()
fh = open(emptyFileHelper.getName(), 'r+')
fh.write("Something or other\n")
fh.close()
filledFileHelper = TemporaryFileHelper("Something or other\n")
other = open(filledFileHelper.getName(), 'r')
for line in other:
print line
other.close()
del emptyFileHelper
del filledFileHelper
"""
tempFile = None

def __init__(self, fileContent=""):
self.tempFile = NamedTemporaryFile('r+', delete=False)

if fileContent:
self._setFileContent(fileContent)

def __del__(self):
os.unlink(self.tempFile.name)

def getName(self):
return self.tempFile.name

def _setFileContent(self, content):
fileHandle = open(self.getName(), 'r+')
fileHandle.write(content)
fileHandle.close()

0 comments on commit 5f1af07

Please sign in to comment.