buildframework/helium/tools/common/python/scripts/scripttests/test_filter_metadatalog.py
changeset 628 7c4a911dc066
parent 588 c7c26511138f
child 629 541af5ee3ed9
equal deleted inserted replaced
588:c7c26511138f 628:7c4a911dc066
     1 #============================================================================ 
       
     2 #Name        : test_filter_metadatalog.py 
       
     3 #Part of     : Helium 
       
     4 
       
     5 #Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
       
     6 #All rights reserved.
       
     7 #This component and the accompanying materials are made available
       
     8 #under the terms of the License "Eclipse Public License v1.0"
       
     9 #which accompanies this distribution, and is available
       
    10 #at the URL "http://www.eclipse.org/legal/epl-v10.html".
       
    11 #
       
    12 #Initial Contributors:
       
    13 #Nokia Corporation - initial contribution.
       
    14 #
       
    15 #Contributors:
       
    16 #
       
    17 #Description:
       
    18 #===============================================================================
       
    19 
       
    20 """ Test cases for filter meta data logs.
       
    21 
       
    22 """
       
    23 
       
    24 # pylint: disable-msg=E1101
       
    25 
       
    26 import logging
       
    27 import os
       
    28 import sys
       
    29 import time
       
    30 import mocker
       
    31 import re
       
    32 import tempfile
       
    33 import shutil
       
    34 
       
    35 _logger = logging.getLogger('test.test_filter_metadatalog')
       
    36 logging.basicConfig(level=logging.DEBUG)
       
    37 
       
    38 TEMP_PATH = tempfile.mkdtemp()
       
    39 #NOTE: THE COMMENTED OUT CODE IS REQUIRED WHEN RUNNING THIS TEST USING THE PT TARGET
       
    40 #WITH THE COMMENTED OUT CODE IT DOES NOT WORK IN THE FULL UNITTEST TARGET DUE TO RAPTOR.PY
       
    41 #FILE BEING CALLED WITHOUT ALL THE ENVIRONMENT VARIABLES SET WHEN RUN SINGLY AND THEY ARE SET WHEN
       
    42 #RUN AS PART OF THE UNITTEST TARGET.
       
    43 
       
    44 PYTHON_FILE_NAME = os.path.join(TEMP_PATH, 'raptor.py')
       
    45 FILTER_FILE_NAME = os.path.join(TEMP_PATH, 'filter_interface.py')
       
    46 
       
    47 sys.path = [TEMP_PATH] + sys.path
       
    48 
       
    49 def setup_module():
       
    50     """ Setup for test_filter_metadata """
       
    51     #in order to allow the filter_metadata.py file to compile we need to create a dummy 
       
    52     #raptor.py file as this is part of SBS and not present here, the classes and objects 
       
    53     #it uses from raptor.py file are created in this file, the same goes for the file filter_interface.py
       
    54     #does not exist so create empty python.py file
       
    55     f_handle = open(PYTHON_FILE_NAME, "w")
       
    56     f_handle.write("class testRaptor():\n")
       
    57     f_handle.write("    def testRaptorFunc(self):\n")
       
    58     f_handle.write("        return True \n")
       
    59     f_handle.close()
       
    60     #does not exist so create empty python.py file
       
    61     f_handle = open(FILTER_FILE_NAME, "w")
       
    62     f_handle.write("class Filter():\n")
       
    63     f_handle.write("    def testFilterFunc(self):\n")
       
    64     f_handle.write("        return True \n")
       
    65     f_handle.close()
       
    66 
       
    67 
       
    68 def teardown_module():
       
    69     """ Teardown test_filter_metadata. """
       
    70     print("teardown called")
       
    71     if os.path.exists(TEMP_PATH):
       
    72         shutil.rmtree(TEMP_PATH)
       
    73 
       
    74 # regex for "bare" drive letters  
       
    75 DRIVERE = re.compile('^[A-Za-z]:$')
       
    76 
       
    77 # are we on windows, and if so what is the current drive letter
       
    78 ISWIN = sys.platform.lower().startswith("win")
       
    79 if ISWIN:
       
    80     DRIVE = re.match('^([A-Za-z]:)', os.getcwd()).group(0)
       
    81 
       
    82 # Base class
       
    83 class Path(object):
       
    84     """This class represents a file path.                                      
       
    85                                                                                
       
    86     A generic path object supports operations without needing to know          
       
    87     about Windows and Linux differences. The standard str() function can       
       
    88     obtain a string version of the path in Local format for use by             
       
    89     platform-specific functions (file opening for example).                    
       
    90                                                                                
       
    91     We use forward slashes as path separators (even on Windows).               
       
    92                                                                                
       
    93     For example,                                                               
       
    94                                                                                
       
    95       path1 = generic_path.Path("/foo")                                        
       
    96       path2 = generic_path.Path("bar", "bing.bang")                            
       
    97                                                                                
       
    98       print str(path1.Append(path2))                                           
       
    99                                                                                
       
   100     Prints /foo/bar/bing.bang   on Linux                                       
       
   101     Prints c:/foo/bar/bing.bang   on Windows (if c is the current drive)       
       
   102     """                                                                        
       
   103 
       
   104     def __init__(self, *arguments):
       
   105         """construct a path from a list of path elements"""
       
   106         
       
   107         if len(arguments) == 0:
       
   108             self.path = ""
       
   109             return
       
   110         
       
   111         list = []
       
   112         for i, arg in enumerate(arguments):
       
   113             if ISWIN:
       
   114                 if i == 0:
       
   115                     # If the first element starts with \ or / then we will
       
   116                     # add the current drive letter to make a fully absolute path
       
   117                     if arg.startswith("\\\\"):
       
   118                         list.append(arg) # A UNC path - don't mess with it
       
   119                     elif arg.startswith("\\") or arg.startswith("/"):
       
   120                         list.append(DRIVE + arg)
       
   121                     # If the first element is a bare drive then dress it with a \
       
   122                     # temporarily otherwise "join" will not work properly.
       
   123                     elif DRIVERE.match(arg):
       
   124                         list.append(arg + "\\")
       
   125                     # nothing special about the first element
       
   126                     else:
       
   127                         list.append(arg)
       
   128                 else:
       
   129                     if arg.startswith("\\\\"):
       
   130                         raise ValueError("non-initial path components must not start with \\\\ : %s" % arg)
       
   131                     else:
       
   132                         list.append(arg)
       
   133                 if ";" in arg:
       
   134                     raise ValueError("An individual windows Path may not contain ';' : %s" % arg)
       
   135             else:
       
   136                 list.append(arg)
       
   137       
       
   138         self.path = os.path.join(*list)
       
   139         
       
   140         # normalise to avoid nastiness with dots and multiple separators
       
   141         # but do not normalise "" as it will become "."
       
   142         if self.path != "":
       
   143             self.path = os.path.normpath(self.path)
       
   144         
       
   145         # always use forward slashes as separators
       
   146         self.path = self.path.replace("\\", "/")
       
   147         
       
   148         # remove trailing slashes unless we are just /
       
   149         if self.path != "/":
       
   150             self.path = self.path.rstrip("/")
       
   151 
       
   152     def Dir(self):
       
   153         "return an object for the directory part of this path"
       
   154         if DRIVERE.match(self.path):
       
   155             return Path(self.path)
       
   156         else:
       
   157             return Path(os.path.dirname(self.path))
       
   158     def __str__(self):
       
   159         return self.path
       
   160 
       
   161 
       
   162 class Raptor(object):
       
   163     """An instance of a running Raptor program.
       
   164 
       
   165     When operated from the command-line there is a single Raptor object
       
   166     created by the Main function. When operated by an IDE several Raptor
       
   167     objects may be created and operated at the same time."""
       
   168 
       
   169     def defaultSetUp(self):
       
   170         """ setup some variables for use by the unit under test """
       
   171         self.logFile = None #self.mocker.proxy(generic_path.Join)
       
   172         self.summary = True
       
   173         # things to initialise
       
   174         self.starttime = time.time()
       
   175         self.timestring = time.strftime("%Y-%m-%d-%H-%M-%S")
       
   176         self.logFileName = Path(os.path.join(TEMP_PATH, 'makefile_2009-11-12-12-32-34.log'))
       
   177 
       
   178 class FilterMetaDataLogTest(mocker.MockerTestCase):
       
   179     """ Tests the filter_metadataLog wrapper to the SBS plugin. 
       
   180     The plugin uses the SBS API of open, write, summary and close. """
       
   181 
       
   182 #    def test_a_setupOK(self):       #need to call it this to get it executed in the right order (alphabetical)
       
   183 #        """test_a_setupOK: tests that we have imported the correct files and that they are present 
       
   184 #        before importing the file to be tested and having it fail due to missing files"""
       
   185 #        print("got to test-a-setup ")
       
   186 #        import filter_metadatalog
       
   187 #        print("got passed import filter file to test-a-setup ")
       
   188 #        #setup an instance of the class and test it exists OK
       
   189 #        obj = filter_metadatalog.raptor.testRaptor()
       
   190 #        result = obj.testRaptorFunc()
       
   191 #        assert result == True
       
   192 #        obj = filter_metadatalog.filter_interface.Filter()
       
   193 #        result = obj.testFilterFunc()
       
   194 #        assert result == True
       
   195 
       
   196     def test_openWriteSummaryCloseInvalidData(self):
       
   197         """test_openWriteSummaryCloseInvalidData: test the opening writing, summary and 
       
   198         closing of the log file with invalid data."""
       
   199         import filter_metadatalog
       
   200         obj = self.mocker.patch(filter_metadatalog.SBSScanlogMetadata)
       
   201         obj.initialize(mocker.ANY)
       
   202         self.mocker.result(False)
       
   203         self.mocker.replay()
       
   204         
       
   205         raptor_instance = Raptor()
       
   206         raptor_instance.defaultSetUp()
       
   207         raptor_instance.logFileName = Path("..")
       
   208         filter_mLog = filter_metadatalog.FilterMetadataLog()
       
   209         result = filter_mLog.open(raptor_instance)
       
   210         assert result == False
       
   211         result = filter_mLog.close()
       
   212         assert result == False
       
   213 
       
   214     def test_openValidData_default(self):
       
   215         """test_openValidData_default: test the opening of the log file with valid data."""
       
   216         import filter_metadatalog
       
   217         obj = self.mocker.patch(filter_metadatalog.SBSScanlogMetadata)
       
   218         obj.initialize(mocker.ANY)
       
   219         self.mocker.result(True)
       
   220         self.mocker.replay()
       
   221         
       
   222         raptor_instance = Raptor()
       
   223         raptor_instance.defaultSetUp()
       
   224         filter_mLog = filter_metadatalog.FilterMetadataLog()
       
   225         result = filter_mLog.open(raptor_instance)
       
   226         assert result == True
       
   227 
       
   228     def test_openValidData_empty(self):
       
   229         """test_openValidData_empty: test the opening of the log file with valid data."""
       
   230         import filter_metadatalog
       
   231         obj = self.mocker.patch(filter_metadatalog.SBSScanlogMetadata)
       
   232         obj.initialize(mocker.ANY)
       
   233         self.mocker.result(True)
       
   234         self.mocker.replay()
       
   235         
       
   236         raptor_instance = Raptor()
       
   237         raptor_instance.defaultSetUp()
       
   238         raptor_instance.logFileName = Path("")
       
   239         filter_mLog = filter_metadatalog.FilterMetadataLog()
       
   240         result = filter_mLog.open(raptor_instance)
       
   241         assert result == True
       
   242 
       
   243     def test_openValidData_stdout(self):
       
   244         """test_openValidData_stdout: test the opening of the log file with valid data."""
       
   245         import filter_metadatalog
       
   246         obj = self.mocker.patch(filter_metadatalog.SBSScanlogMetadata)
       
   247         obj.initialize(mocker.ANY)
       
   248         self.mocker.count(0, 0)
       
   249         self.mocker.replay()
       
   250         
       
   251         raptor_instance = Raptor()
       
   252         raptor_instance.defaultSetUp()
       
   253         raptor_instance.logFileName = None
       
   254         filter_mLog = filter_metadatalog.FilterMetadataLog()
       
   255         result = filter_mLog.open(raptor_instance)
       
   256         assert result == True
       
   257