#!/usr/bin/python # Copyright (c) 2005 by Mark T. Holder, Florida State University. (see end of file) from PIPRes.util.io import * from cStringIO import StringIO import unittest, sys from PIPRes.testing import silentAssertRaises class FakeLogger: def __init__(self): self.message = '' def error(self, m): self.message = m def __eq__(self, other): return self.message == other def __str__(self): return self.message def appendIterable(iterable): return [i for i in iterable] class IOUtilTest(unittest.TestCase): def testOpenInPathAndCall(self): def appendIterable(iterable): return [i for i in iterable] def appendIterableOptArg(iterable, arg = None): a = [i for i in iterable] if arg is not None: a.append(arg) return a try: path = expandPath(os.path.join('$PIPRES_ROOT', 'test', 'files', 'simple_taxa_block.nex')) f = open(path, 'rU') allLines = [i for i in f] except : print >>sys.stderr, 'could not open', path , 'using standard python routines. testOpenPathAndCall ommitted.' return self.assertEqual(allLines, openInPathAndCall(path, appendIterable)) self.assertEqual(allLines, openInPathAndCall(path, appendIterableOptArg)) allLines.append(1) self.assertEqual(allLines, openInPathAndCall(path, appendIterableOptArg, 1)) silentAssertRaises(self, FileNotFoundError, openInPathAndCall, os.path.join('..', 'files', 'bogus'), appendIterable) def testWriteWrapped(self): s = '123457890abcdefghijklmnopqrstuvwxyz' self.assertEqual(writeWrapped(StringIO(), s, 5).getvalue(), '''12345 7890a bcdef ghijk lmnop qrstu vwxyz''') self.assertEqual(writeWrapped(StringIO(), s, 5, firstOffset=1).getvalue(), '''1234 57890 abcde fghij klmno pqrst uvwxy z''') self.assertEqual(writeWrapped(StringIO(), s, 6, leftMargin='x', firstOffset=2).getvalue(), '''1234 x57890 xabcde xfghij xklmno xpqrst xuvwxy xz''') self.assertEqual(writeWrapped(StringIO(), s, 6, leftMargin=' ').getvalue(), '''123457 89 0a bc de fg hi jk lm no pq rs tu vw xy z''') self.assertEqual(writeWrapped(StringIO(), s, 5, noCountLeftMargin=' ', firstOffset=1).getvalue(), '''1234 57890 abcde fghij klmno pqrst uvwxy z''') def testOpenOutPathAndCall(self): def writeStuffToFile(fout, b, e): for i in range(b, e): fout.write('%d\n' % i) return 32 path = 'temp_junk' self.assertEqual(32, openOutPathAndCall(path, writeStuffToFile, 2, 20)) self.assertEqual([str(i)+'\n' for i in range(2,20)], openInPathAndCall(path, appendIterable)) self.assertEqual(32, openOutPathAndCall(path, writeStuffToFile, 31, 40)) self.assertEqual([str(i)+'\n' for i in range(31,40)], openInPathAndCall(path, appendIterable)) silentAssertRaises(self, IOError, openOutPathAndCall, os.path.join('..'), writeStuffToFile, 31, 40) class BogusError: pass def writeStuffToFileAndRaise(fout, b, e): for i in range(b, e): fout.write('%d\n' % i) raise BogusError try : openOutPathAndCall(path, writeStuffToFileAndRaise, 1, 10) except BogusError: pass try : openAppendPathAndCall(path, writeStuffToFileAndRaise, 10, 20) except BogusError : pass self.assertEqual([str(i)+'\n' for i in range(1,20)], openInPathAndCall(path, appendIterable)) def testLogExcep(self): fl = FakeLogger() try: raise ValueError, 'test Exception message' except: logException(fl) m = str(fl) pathRE = re.compile(r'\"(.*)(?=test_io\.py\")') #depending on where we invoke this test script we get a different path before test_io.py. this re pattern strips the path m = pathRE.sub('"', m) self.assertEqual(True, m.startswith('''Traceback (most recent call last): File "test_io.py", line ''')) self.assertEqual(True, m.endswith('''in testLogExcep raise ValueError, 'test Exception message' ValueError: test Exception message ''')) def testPrependNumberToRename(self): import shutil testFilesDir = os.path.expandvars(os.path.join('$PIPRES_ROOT','test', 'files')) for n in range(20): p = os.path.join(testFilesDir, '%dexampleRegistry.xml' % n) if os.path.exists(p): os.remove(p) fileToBackup = os.path.expandvars(os.path.join('$PIPRES_ROOT','test', 'files', 'exampleRegistry.xml')) backup = os.path.expandvars(os.path.join('$PIPRES_ROOT','test', 'files', 'backup_exampleRegistry.xml')) shutil.copy2(fileToBackup, backup) fileToBackupPattern = os.path.expandvars(os.path.join('$PIPRES_ROOT','test', 'files', '%dexampleRegistry.xml')) try: self.assertEqual(prependNumberToRename(fileToBackup), fileToBackupPattern % 0) silentAssertRaises(self, IOError, prependNumberToRename,fileToBackup) finally: shutil.copy2(backup, fileToBackup) if __name__ == '__main__': unittest.main()