Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refs #11418. Added testhelper for temporary files
- Loading branch information
Michael Wedel
committed
Mar 24, 2015
1 parent
474548a
commit 5f1af07
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
Code/Mantid/Framework/PythonInterface/test/testhelpers/tempfile_wrapper.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |