os/mm/mmtestenv/mmtesttools/Build/buildutils/testMbcUtils.py
changeset 0 bde4ae8d615e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/os/mm/mmtestenv/mmtesttools/Build/buildutils/testMbcUtils.py	Fri Jun 15 03:10:57 2012 +0200
     1.3 @@ -0,0 +1,350 @@
     1.4 +# Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
     1.5 +# All rights reserved.
     1.6 +# This component and the accompanying materials are made available
     1.7 +# under the terms of "Eclipse Public License v1.0"
     1.8 +# which accompanies this distribution, and is available
     1.9 +# at the URL "http://www.eclipse.org/legal/epl-v10.html".
    1.10 +#
    1.11 +# Initial Contributors:
    1.12 +# Nokia Corporation - initial contribution.
    1.13 +#
    1.14 +# Contributors:
    1.15 +#
    1.16 +# Description:
    1.17 +# Test code for MbcUtils
    1.18 +#
    1.19 +
    1.20 +from MbcUtils import *
    1.21 +import testDataMbcUtils as testdata
    1.22 +import unittest
    1.23 +import tempfile
    1.24 +import StringIO
    1.25 +
    1.26 +class TestParent(unittest.TestCase):
    1.27 +    """Potential parent test"""
    1.28 +
    1.29 +    def TempFile(self, str):
    1.30 +        """Create a temp file. Write given string and return filename.
    1.31 +        Note caller is responsible for deleting the file"""
    1.32 +        tfile = tempfile.mkstemp()
    1.33 +        file = os.fdopen(tfile[0],"w")
    1.34 +        print >> file, str
    1.35 +        file.close() # close the file - we just want the filename then
    1.36 +        return tfile[1] # return filename. Note client expected to delete
    1.37 +
    1.38 +    def fixupDirsInExpectedList(self, expectedToFixUp):
    1.39 +        """Convert relative filenames to absolute.
    1.40 +        The returned list returns absolute filenames. Need to convert relelative
    1.41 +        names to absolute so can easily compare."""
    1.42 +
    1.43 +        for tupEle in expectedToFixUp:
    1.44 +            mbcFile = tupEle[0]
    1.45 +            baseDir = os.path.dirname(mbcFile)
    1.46 +            for i in range(1,3):
    1.47 +                # tupEle[1] is list of required folders
    1.48 +                # tupEle[2] is list of optional folders
    1.49 +                for j in range(0, len(tupEle[i])):
    1.50 +                    absDir = os.path.abspath(os.path.join(baseDir, tupEle[i][j]))
    1.51 +                    tupEle[i][j] = absDir
    1.52 +            # tupEle[3] is list of tuples of dir and command
    1.53 +            for j in range(0, len(tupEle[3])):
    1.54 +                # note need to tuple to list and back to do this
    1.55 +                lst = list(tupEle[3][j])
    1.56 +                absDir = os.path.abspath(os.path.join(baseDir, lst[0]))
    1.57 +                lst[0] = absDir
    1.58 +                tupEle[3][j] = tuple(lst)
    1.59 +        return expectedToFixUp
    1.60 +
    1.61 +class SimpleTest(TestParent):
    1.62 +    """Open and return basic case"""
    1.63 +
    1.64 +    def __init__(self, sample, expected):
    1.65 +        super(SimpleTest,self).__init__()
    1.66 +        self.sample = sample
    1.67 +        self.expected = expected
    1.68 +        self.tfileName = None
    1.69 +
    1.70 +    def fixExpected(self, fname):
    1.71 +        """change the filename slot in self.expected"""
    1.72 +        # expected is a tuple. Need to convert to list and back.
    1.73 +        # then turn into a single element list so can run through
    1.74 +        # fixupDirsInExpectedList()
    1.75 +        tempList = list(self.expected)
    1.76 +        tempList[0] = fname
    1.77 +        newTuple = tuple(tempList)
    1.78 +        fixedList = self.fixupDirsInExpectedList([newTuple])
    1.79 +        self.expected = fixedList[0]
    1.80 +
    1.81 +    def runTest(self):
    1.82 +        """SimpleTest.runTest
    1.83 +
    1.84 +        Create temp file with known content. Run parser and compare result
    1.85 +        """
    1.86 +        self.tfileName = self.TempFile(self.sample)
    1.87 +        parser = MbcParser(self.tfileName)
    1.88 +        parser.execute()
    1.89 +        self.fixExpected(self.tfileName)
    1.90 +        result = parser()
    1.91 +        self.assertEquals(result, self.expected,
    1.92 +                        "Result(%s) not same as Expected(%s)"%(result,self.expected))
    1.93 +
    1.94 +    def tearDown(self):
    1.95 +        if self.tfileName:
    1.96 +            os.unlink(self.tfileName)
    1.97 +
    1.98 +class BadDataTest(SimpleTest):
    1.99 +    """Bad data so should get an exception"""
   1.100 +
   1.101 +    def __init__(self, sample, testName):
   1.102 +        super(BadDataTest,self).__init__(sample, [])
   1.103 +        self.__testName = testName
   1.104 +
   1.105 +    def runTest(self):
   1.106 +        """BadDataTest.runTest
   1.107 +
   1.108 +        Use SimpleTest.runTest. Should throw an exception"""
   1.109 +        self.assertRaises(InvalidInput, SimpleTest.runTest, self)
   1.110 +
   1.111 +    def shortDescription(self):
   1.112 +		"One line description - additionally giving test name"
   1.113 +		parentStr = super(BadDataTest, self).shortDescription()
   1.114 +		return  "%s-%s" % (parentStr, self.__testName)
   1.115 +
   1.116 +class ListTest(TestParent):
   1.117 +    """Open and return basic case, but with list input"""
   1.118 +
   1.119 +    def __init__(self, samples, expected, secondStageExpected=None, filenameToLookFor=None):
   1.120 +        super(ListTest,self).__init__()
   1.121 +        self.samples = samples
   1.122 +        self.expected = expected
   1.123 +        self.secondStageExpected = secondStageExpected
   1.124 +        self.filenameToLookFor = filenameToLookFor
   1.125 +        self.tfileNames = []
   1.126 +
   1.127 +    def fixExpected(self, indx, fname):
   1.128 +        """change the filename slot in self.expected"""
   1.129 +        # expected is a tuple. Need to convert to list and back
   1.130 +        tempList = list(self.expected[indx])
   1.131 +        tempList[0] = fname
   1.132 +        self.expected[indx] = tuple(tempList)
   1.133 +
   1.134 +    def runTest(self):
   1.135 +        """ListTest.runTest
   1.136 +
   1.137 +        Create temp files with known content, one per list element. Run parser and compare result
   1.138 +        """
   1.139 +        for indx in range(0, len(self.samples)):
   1.140 +            tfileName = self.TempFile(self.samples[indx])
   1.141 +            self.tfileNames.append(tfileName)
   1.142 +            self.fixExpected(indx, tfileName)
   1.143 +        self.expected = self.fixupDirsInExpectedList(self.expected)
   1.144 +        parser = MbcParser(self.tfileNames)
   1.145 +        parser.execute()
   1.146 +        result = parser()
   1.147 +        self.assertEquals(result, self.expected,
   1.148 +                        "Result(%s) not same as Expected(%s)"%(result,self.expected))
   1.149 +        if self.secondStageExpected:
   1.150 +            getFolderList = GetFolderList(result)
   1.151 +            getFolderList.execute()
   1.152 +            folderList = getFolderList()
   1.153 +            self.assertEquals(folderList, self.secondStageExpected,
   1.154 +                       "Result2(%s) not same as Expected2(%s)"%(folderList,self.secondStageExpected))
   1.155 +
   1.156 +    def tearDown(self):
   1.157 +        if self.tfileNames:
   1.158 +            for fname in self.tfileNames:
   1.159 +                os.unlink(fname)
   1.160 +
   1.161 +class FolderListUnitTest(TestParent):
   1.162 +    """Test GetFolderList with on-the-fly generated data.
   1.163 +
   1.164 +    Create a list on fly with folder of one temp file and a non-existant one. Treatement of second
   1.165 +    is optional."""
   1.166 +
   1.167 +    def __init__(self, fussyOnNonExist):
   1.168 +        super(FolderListUnitTest,self).__init__()
   1.169 +        self.__fussyOnNonExist = fussyOnNonExist
   1.170 +        self.__tempFile = None
   1.171 +
   1.172 +    def shortDescription(self):
   1.173 +		"""One line description - additionally giving option"""
   1.174 +		parentStr = super(FolderListUnitTest, self).shortDescription()
   1.175 +		return  "%s-%s" % (parentStr, str(self.__fussyOnNonExist))
   1.176 +
   1.177 +    def __realTest(self):
   1.178 +        "real test run - separate so can be trapped if required"
   1.179 +
   1.180 +        self.__tempFile = tempfile.NamedTemporaryFile() # used to create list and check
   1.181 +
   1.182 +        (input,tempFileName,expected) = self.__createDataLists()
   1.183 +        getFolderList = GetFolderList(input, nameToCheck=tempFileName)
   1.184 +        getFolderList.execute()
   1.185 +        result = getFolderList()
   1.186 +        self.assertEquals(result, expected,
   1.187 +                "Result2(%s) not same as Expected2(%s)(filename=%s)"%(result,expected,tempFileName))
   1.188 +
   1.189 +    def runTest(self):
   1.190 +        "FolderListUnitTest.runTest"
   1.191 +        if not self.__fussyOnNonExist:
   1.192 +            self.__realTest()
   1.193 +        else:
   1.194 +            # should fail
   1.195 +            self.assertRaises(MissingFile, self.__realTest)
   1.196 +
   1.197 +    def tearDown(self):
   1.198 +        "Stop using temp file, so will be deleted"
   1.199 +        self.__tempFile = None
   1.200 +
   1.201 +    def __createDataLists(self):
   1.202 +        """Create input and output for test run as lists.
   1.203 +
   1.204 +        input will be one element with <tempdir> and second with "nonexistant",
   1.205 +        but which element is used depends on fussyOnNonExist"""
   1.206 +        input = []
   1.207 +        tempFileName = None
   1.208 +        expected = []
   1.209 +
   1.210 +        (tempDir,tempFileName) = os.path.split(self.__tempFile.name) # the dir and name of the temporary file we are using
   1.211 +        input += [("f1", [tempDir], [], [])] # the existing file
   1.212 +        expected += [(True, tempDir, 'From f1')]
   1.213 +        if self.__fussyOnNonExist:
   1.214 +            input += [("f2", ["nonexistant"], [], [])]
   1.215 +        else:
   1.216 +            input += [("f2", [], ["nonexistant"], [])]
   1.217 +        expected += [(True, None, 'Skip "nonexistant" from f2')] # always return the non-fussy version, as with fussy we expect exception raised
   1.218 +
   1.219 +        return (input,tempFileName,expected)
   1.220 +
   1.221 +class FolderListIntTest(TestParent):
   1.222 +    """Integration test combining MbcParser and FolderList
   1.223 +
   1.224 +    Create a temporary folder. Add the following contents:
   1.225 +
   1.226 +    x/bld.inf
   1.227 +    y/bld.inf
   1.228 +    z/bld.inf
   1.229 +    mbc containing "./x, ./y, [optional] ./z"
   1.230 +
   1.231 +    z/bld.inf and y.bld are optional
   1.232 +        option="x" no z or y. Should raise exception.
   1.233 +        option="xy" no z but y. Should get list of ../x and ../y
   1.234 +        option="xz" no y but z. Should raise exception.
   1.235 +        option="xyz" both y and z. Should get list of ../x, ../y and ../z
   1.236 +
   1.237 +    """
   1.238 +
   1.239 +    def __init__(self, option):
   1.240 +        super(FolderListIntTest,self).__init__()
   1.241 +        self.__option = option
   1.242 +        self.__testDir = None
   1.243 +        self.__testDirs = [] # list of dirs we create, so we can delete them
   1.244 +        self.__testFiles = [] # list of files we create, so we can delete them
   1.245 +        self.__fullMbcFileName = None
   1.246 +        self.__expectedResult = []
   1.247 +
   1.248 +    def shortDescription(self):
   1.249 +        "One line description - additionally giving option"
   1.250 +        parentStr = super(FolderListIntTest, self).shortDescription()
   1.251 +        return  "%s-%s" % (parentStr, str(self.__option))
   1.252 +
   1.253 +    def tearDown(self):
   1.254 +        for fle in self.__testFiles:
   1.255 +            try:
   1.256 +                os.unlink(fle)
   1.257 +            except:
   1.258 +                pass # ignore any error. assume means we didn't create the file in the end
   1.259 +        # delete folders in reverse, so child directories deleted after parent
   1.260 +        for dir in self.__testDirs[len(self.__testDirs)-1::-1]:
   1.261 +            try:
   1.262 +                os.rmdir(dir)
   1.263 +            except:
   1.264 +                pass # ignore any error. assume means we didn't create the file in the end
   1.265 +
   1.266 +    def runTest(self):
   1.267 +        "FolderListIntTest.runTest"
   1.268 +        self.__setup()
   1.269 +        if "y" in self.__option:
   1.270 +            self.__realTest()
   1.271 +        else:
   1.272 +            # expected to raise exception as y/bld.inf does not exist
   1.273 +            self.assertRaises(MissingFile, self.__realTest)
   1.274 +
   1.275 +    def __realTest(self):
   1.276 +        parser = MbcParser(self.__fullMbcFileName)
   1.277 +        parser.execute()
   1.278 +        folderList = GetFolderList(parser())
   1.279 +        folderList.execute()
   1.280 +        result = folderList()
   1.281 +        self.assertEquals(result, self.__expectedResult,
   1.282 +            "Result (%s) not that expected (%s)" % (str(result), str(self.__expectedResult)))
   1.283 +
   1.284 +    def __setup(self):
   1.285 +        self.__testDir = tempfile.mkdtemp() # __testDir is name of temp folder
   1.286 +        self.__testDirs.append(self.__testDir)
   1.287 +        self.__fullMbcFileName = os.path.join(self.__testDir, "test.mbc")
   1.288 +
   1.289 +        for name in ["x","y","z"]:
   1.290 +            fullpath = os.path.join(self.__testDir, name)
   1.291 +            if name in self.__option:
   1.292 +                os.mkdir(fullpath)
   1.293 +                self.__testDirs.append(fullpath)
   1.294 +                filepath = os.path.join(fullpath, "bld.inf")
   1.295 +                fileToWrite = file(filepath, "w")
   1.296 +                self.__testFiles.append(filepath)
   1.297 +                print >>fileToWrite, "//generated" # 9.5 syntax
   1.298 +                fileToWrite.close()
   1.299 +                expected = (True, fullpath, "From %s" % self.__fullMbcFileName)
   1.300 +                self.__expectedResult.append(expected)
   1.301 +            else:
   1.302 +                expected = (True, None, """Skip "%s" from %s""" % (fullpath, self.__fullMbcFileName))
   1.303 +                self.__expectedResult.append(expected)
   1.304 +        mbcFile = file(self.__fullMbcFileName, "w")
   1.305 +        self.__testFiles.append(self.__fullMbcFileName)
   1.306 +        print >>mbcFile, testdata.intTestMbcFile
   1.307 +        mbcFile.close()
   1.308 +
   1.309 +class ConfigFileUnitTest(unittest.TestCase):
   1.310 +    """ConfigFile UnitTest"""
   1.311 +
   1.312 +    def __init__(self, inputData, expected):
   1.313 +        super(ConfigFileUnitTest,self).__init__()
   1.314 +        self.__inputData = inputData
   1.315 +        self.__expected = expected
   1.316 +
   1.317 +    def runTest(self):
   1.318 +        """ConfigFileUnitTest.runTest
   1.319 +
   1.320 +        Take dummy folder list and generate XML file. Output goes to string. Compare with expected
   1.321 +        """
   1.322 +
   1.323 +        outputStream = StringIO.StringIO()
   1.324 +        generator = ConfigFileGenerator(self.__inputData, outputStream)
   1.325 +        generator.write()
   1.326 +        outputString = outputStream.getvalue()
   1.327 +##        print ("output=%s" % str(outputString))
   1.328 +##        print ("expected=%s" % str(self.__expected))
   1.329 +        self.assertEquals(outputString, self.__expected,
   1.330 +                "Generated output (%s) not same as expected (%s)" % (outputString, self.__expected))
   1.331 +
   1.332 +def suite():
   1.333 +    """TestSuite"""
   1.334 +
   1.335 +    tests = [
   1.336 +        SimpleTest(testdata.import1, testdata.result1),
   1.337 +        ListTest(testdata.import2, testdata.result2),
   1.338 +        BadDataTest(testdata.badImport1, "bad1"),
   1.339 +        BadDataTest(testdata.badImport2, "bad2"),
   1.340 +        FolderListUnitTest(False),
   1.341 +        FolderListUnitTest(True),
   1.342 +        FolderListIntTest("x"),
   1.343 +        FolderListIntTest("xy"),
   1.344 +        FolderListIntTest("xz"),
   1.345 +        FolderListIntTest("xyz"),
   1.346 +        ConfigFileUnitTest(testdata.testFolderList1, testdata.testXmlFile1),
   1.347 +        ]
   1.348 +
   1.349 +    return unittest.TestSuite(tests)
   1.350 +
   1.351 +
   1.352 +if __name__ == "__main__":
   1.353 +    unittest.TextTestRunner(verbosity=2).run(suite())