import unittest
import os
import shutil
import difflib


class StringAssertionError(AssertionError):

    def __str__(self):
        response = ["Strings not equal, diff follows\n"]
        text1, text2, comment = self.args
        if comment:
            response.append(comment)
        lines1 = text1.split("\n")
        lines2 = text2.split("\n")
        response.extend(difflib.ndiff(lines1, lines2))
        return "\n".join(response)

class TestCase(unittest.TestCase):
    def createFile(self, path, size):
        str = 'x' * size
        open(path, 'w').write(str)

    def assertStringsEqual(self, text1, text2, comment = None):
        """Compares two string. If they are not equal, prints a unified diff"""
        if text1 == text2:
            return
        self.fail(StringAssertionError(text1, text2, comment))

    def assertStringsEqualExceptWhiteChars(self, str1, str2):
        arr1 = str1.split("\n")
        arr2 = str2.split("\n")
        for i in range(len(arr1)):
            arr1[i] = arr1[i].strip()
        for i in range(len(arr2)):
            arr2[i] = arr2[i].strip()
        buffer1 = os.linesep.join(arr1)
        buffer2 = os.linesep.join(arr2)
        self.assertStringsEqual(buffer1, buffer2)

    def assertListsEqual(self, list1, list2, comment = None):
        """Compares two lists. TODO: Print the diff in a readable way"""
        if list1 == list2:
            return
        print "List 1: ", repr(list1)
        print "List 2: ", repr(list2)
        self.fail("Lists are not equal")

    def assertFileExists(self, path):
        self.failIf(not os.path.exists(path), 'File %s does not exist' % path)

    def assertFileNotExists(self, path):
        self.failIf(os.path.exists(path), 'File %s exists' % path)

    def assertFileContains(self, path, content, comment = None,):
        if os.path.exists(path):
            fileContent = file(path, 'r').read()
            self.assertStringsEqual(fileContent, content)
        else:
            self.fail('File %s does not exist' % path)

    def assertFileContainsXML(self, path, content, comment = None,):
        if os.path.exists(path):
            fileContent = file(path, 'r').read()
            self.assertStringsEqualExceptWhiteChars(fileContent, content)
        else:
            self.fail('File %s does not exist' % path)

    def rmtree(self, dirname):
        if dirname and os.path.isdir(dirname):
            shutil.rmtree(dirname)

    def rmfile(self, filename):
        if filename and os.path.isfile(filename):
            os.remove(filename)

    def backupFile(self, filename):
        if filename and os.path.isfile(filename):
            newname = filename + '.dsbak'
            shutil.copyfile(filename, newname)

    def restoreFile(self, filename):
        if filename:
            newname = filename + '.dsbak'
            if os.path.isfile(newname):
                shutil.copyfile (newname, filename)
