import unittest from util import bulk_replace, UtilException class UtilTestCases(unittest.TestCase): def setUp(self): self.filepath = 'test_text' self.pattern = 'foo' self.replace_with = 'bar' def test_same_patterns(self): try: bulk_replace(filepath=self.filepath, pattern=self.pattern, replace_with='foo') except UtilException as e: self.assertEqual(e.__str__(), 'pattern and replace_with can not be same') def test_line(self): try: bulk_replace(filepath=self.filepath, pattern=self.pattern, replace_with=self.replace_with, line=999) except UtilException as e: self.assertEqual(e.__str__(), 'line not found') try: bulk_replace(filepath=self.filepath, pattern=self.pattern, replace_with=self.replace_with, line=-1) except UtilException as e: self.assertEqual(e.__str__(), 'line index should be gte 1') def test_replace_one_line(self): bulk_replace(filepath=self.filepath, pattern=self.pattern, replace_with=self.replace_with, line=1) file = open(self.filepath, 'r') line = file.readlines() file.close() self.assertEqual(line[0].strip('\n'), self.replace_with) # switch it back bulk_replace(filepath=self.filepath, pattern=self.replace_with, replace_with=self.pattern, line=1) def test_replace_all(self): file = open(self.filepath, 'r') old = file.readlines() file.close() bulk_replace(filepath=self.filepath, pattern=self.pattern, replace_with=self.replace_with) file = open(self.filepath, 'r') lines = file.readlines() self.assertTrue(self.pattern not in lines) # switch it back file = open(self.filepath, 'w') file.writelines(old) file.close() if __name__ == '__main__': unittest.main()