[GME-commit] GMESRC/Tests/GPyUnit/Samples compareTo_testA_sf_model1.xme,NONE,1.1 gmeutils.py,NONE,1.1 sample_generic_test.py,NONE,1.1 sample_gme_test.py,NONE,1.1 testcase_skeleton.py,NONE,1.1

gme-commit at list.isis.vanderbilt.edu gme-commit at list.isis.vanderbilt.edu
Wed Jun 1 21:49:34 CDT 2005


Update of /project/gme-repository/GMESRC/Tests/GPyUnit/Samples
In directory escher:/tmp/cvs-serv10128/GPyUnit/Samples

Added Files:
	compareTo_testA_sf_model1.xme gmeutils.py 
	sample_generic_test.py sample_gme_test.py testcase_skeleton.py 
Log Message:
GPyUnit, unittest, samples and testcase skeleton checked-in.


CVS User: Zoltan Molnar, ISIS (zolmol)

--- NEW FILE: gmeutils.py ---
"""
Helper methods for developing Python testcases for GME
"""
import win32com.client
import os

regNodePositionStartTag = '<regnode name="PartRegs"'
regNodeEndTag = '</regnode>'
regNodeStartTag = '<regnode'

def xmeFileComp( fn1, fn2, p_skipPositionRegnodes = True, p_skipLines = range(4,5) ):
        """Compares two xme (xml) files line by line. It may disregard position information (x, y coordinates)
        of fcos in models if speficied by the 3rd parameter. It may skip the line range specified in the 4th
        parameter->default value skips the line containing the GUIDs
        
        Returns the number of different lines.
        """
        
        lineDiff = lambda o,t: (o == t and [0] or [1])[0]
        try:
                f1 = file( fn1)
        except IOError:
                print 'gmeUtils::xmeFileComp >> Could not open', fn1
                return -1

        try:
                f2 = file( fn2)
        except IOError:
                print 'gmeUtils::xmeFileComp >> Could not open', fn2
                return -1

        #if not f1 or not f2:
        #    raise 'Could not open one of the files'

        go_on = True
        nDiff = 0
        nLine = 0
        while go_on:
                s1 = f1.readline()
                s2 = f2.readline()
                nLine += 1
                if nLine not in p_skipLines:
                        if p_skipPositionRegnodes:
                            if regNodePositionStartTag in s1:
                               s1 = nextImportantLine( s1, f1 )
                            
                            if regNodePositionStartTag in s2:
                               s2 = nextImportantLine( s2, f2 )

                        nDiff += lineDiff( s1, s2)
                        
                # eof test
                go_on = len(s1) > 0 and len(s2) > 0

        f1.close()
        f2.close()
        return nDiff

def nextImportantLine( s1, f1 ):
    """Helper method of xmlFileComp. Inside <regnode> elements another <regnode>s may exist. 
    That is why if a position storing <regnode> is met, we skip all the lines till the
    enclosing tag is found (skipping over several other regnodes).
    """

    n1 = f1.readline()
    nInnerRegs = 0
    go_on_till_endtag = True
    while f1 and go_on_till_endtag:
        if regNodeEndTag in n1 and nInnerRegs <= 0:
            go_on_till_endtag = False
            break
        elif regNodeEndTag in n1:
            nInnerRegs -= 1
        elif regNodeStartTag in n1:
            nInnerRegs += 1
        else:
            pass
        n1 = f1.readline()
    s1 = f1.readline()
    return s1



def mga2xme( mganame, xmename = ''):
        """Given an mga file, it exports to xml format using the GME.Application COM object
        When the method exits the GME.Application object remains alive, so upon the next
        invokation the same object will be used. Beware if you make testcases involving
        the GME.Application object, leave the object in a state regarding that this method 
        tries to open a project.
        """
        if xmename == '':
            xmename = mganame + '.xme'

        try:
                gme = win32com.client.Dispatch("GME.Application")
        except:
                raise 'Could not create GME.Application'

        try:
                gme.OpenProject( "MGA=" + mganame )
                
                gme.ExportProject( xmename )
                gme.CloseProject(0)
                return xmename
        except:
                gme.CloseProject(0)


def findInProj( project, obj_name = "", obj_kind = ""):
        """Helper method, to find an object in the hierarchy. You may find it useful it in your testcases.
        """

        # create a filter
        filter = project.CreateFilter()
        
        # use Name filter
        filter.Name = obj_name
        filter.Kind = obj_kind

        try:
                some_fcos = list( project.AllFCOs( filter ))
                if len( some_fcos) > 0:
                        return some_fcos[0]
                else:
                        print "findInProj >> Object not found : name = '" + obj_name + "' kind = '" + obj_kind + "'"
                        assert 0
        except:
                print "findInProj >> Exception : name = '" + obj_name + "' kind = '" + obj_kind + "'"
                assert 0

        pass


--- NEW FILE: sample_gme_test.py ---
import unittest
import win32com.client
import win32ui
import pythoncom
import os
import gmeutils  # utility functions for GME testing

#####################################################
# MyFirstGMETestCase testing creation of objects
#####################################################
class MyFirstGMETestCase( unittest.TestCase ):
        """MyFirstGMETestCase tests creation of objects
        """
        
        """if you override __init__ method, call the base class's __init__ method:
        def __init__(self, methodName='runTest'):
                unittest.TestCase.__init__(self, methodName)
        """

        def setUp(self):
            """hook method, will be called before every test method
            put here the code you think is setup-like
            """
            
        def tearDown(self ):
            """hook method, will be called after each test method
            put here the common 'destructing' code if needed
            (however destructing explicitly is needed only for 
            resources like files, databases)
            """

        def runTest():
            """you may list here a sequence of test method invokations
            """
            testA()
            testB()

        def testA( self ):
            """DESCRIPTION: testing 
             CreateProject, CreateObject and finally comparing the xme output to an expected value
            the initial value of mydict
            """
            
            md = "_testA_sf_model1.mga"
            mganame = os.path.join( os.path.abspath(os.path.curdir), md)
            project = win32com.client.Dispatch("Mga.MgaProject")
            
            try:
                project.Create( "MGA=" + mganame, "SF")
            except:
                self.fail("Project Create failed")
                return
            
            terr = project.CreateTerritory( None, None, None)
            
            # 1st transaction: change project's and rootfolder's name
            trans = project.BeginTransaction( terr)

            project.Name = 'testA1_sf'

            rf = project.RootFolder
            rf.Name = 'testA1_sf'

            # commit transaction
            project.CommitTransaction()
            
            # 2nd transaction: create children
            trans = project.BeginTransaction( terr)

            metaproject = project.RootMeta
            metarootfolder = metaproject.RootFolder
            
            #metarootfolder.BeginTransaction()
            metafol = metarootfolder.LegalChildFolderByName('Folder')
            metafco1 = metarootfolder.LegalRootObjectByName('Compound')
            #metafco2 = metarootfolder.LegalRootObjectByName('InputSignal')
            meta_inp_sig = metarootfolder.DefinedFCOByName('InputSignal', 1)
            meta_out_sig = metarootfolder.DefinedFCOByName('OutputSignal', 1)
            #metarootfolder.CommitTransaction()

            newfolder = rf.CreateFolder( metafol)
            newfolder.Name = 'Folder1'
            
            newcomp1 = rf.CreateRootObject( metafco1)
            newcomp1.Name = 'Comp1'
            
            newcomp2 = newfolder.CreateRootObject( metafco1)
            newcomp2.Name = 'CompInFolder1'
            
            metarole_inp_sig = metafco1.RoleByName('InputSignals')
            metarole_out_sig = metafco1.RoleByName('OutputSignals')
            
            #newsig1 = newcomp2.CreateChildObject( metarole_inp_sig)
            #newsig1.Name = 'InSignal1'
            newcomp2.CreateChildObject( metarole_inp_sig).Name = 'InSignal1'

            #newsig2 = newcomp2.CreateChildObject( metarole_out_sig)
            #newsig2.Name = 'OutSignal1'
            newcomp2.CreateChildObject( metarole_out_sig).Name = 'OutSignal1'
            
            project.CommitTransaction()
            
            project.Save()
            project.Close(0)
            
            try:
                 xmename = gmeutils.mga2xme( mganame )
            except:
                raise 'Could not export file'

            # compare the just created file to a pre-created one: 'compareTo_testA_sf_model1.xme'
            ndiffs = gmeutils.xmeFileComp( xmename, 'compareTo_testA_sf_model1.xme')
            
            self.failIf( ndiffs == -1, 'Could not open some of the files')
            self.failIf( ndiffs > 0, str(ndiffs) + ' differencies between the two files ' + xmename + ' and ' + 'testA1_sf_model_to_compare_to.xme')
               
            pass

        def testB( self ):
            """DESCRIPTION: modifying Names inside the model created by testA
            """
            
            md = "_testA_sf_model1.mga"
            mganame = os.path.join( os.path.abspath(os.path.curdir), md)
            project = win32com.client.Dispatch("Mga.MgaProject")

            try:
            	project.Open( "MGA=" + mganame )
            except:
                self.fail('Could not open: ' + mganame)
                
            # 1st transaction
            trans = project.BeginTransaction(project.CreateTerritory( None, None, None))
            
            insig = gmeutils.findInProj( project, 'InSignal1')
            
            assert insig.Name == 'InSignal1'
            insig.Name = 'InputSign1'
            assert insig.Name == 'InputSign1'

            # commit transaction
            project.CommitTransaction()
            
            project.Save()
            project.Close(0)
           
            pass

#####################################################
# 1st option to produce testsuites
#####################################################
def suites():
    """A method named 'suites' is needed if you'd like to execute the tests with GPyunit.py
    Produces a test suite, gathering all methods in the class specified, matching the pattern specified:
    """
    suite = unittest.makeSuite(MyFirstGMETestCase,'test')
    return suite

#####################################################
# 2nd option to produce testsuites
#####################################################
def suites2():
    """Produces a test suite, adding methods one by one:
    """
    suite = unittest.TestSuite()
    suite.addTest( MyFirstGMETestCase( "testA"))
    suite.addTest( MyFirstGMETestCase( "testB"))
    return suite

########
# main
########
if __name__ == "__main__":
    """If this file is run standalone, execute the suite given back by the suites() function above
    """

    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TEST BEGINS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    
    ######## 1st option
    all = suites()
    runner = unittest.TextTestRunner()
    runner.run( all )

    ######## 2nd option
    #unittest.main(defaultTest='TestCaseX')
    
    ######## 3rd option
    #unittest.main()
--- NEW FILE: sample_generic_test.py ---
import unittest
import win32com.client
import win32ui
import pythoncom
import os

#####################################################
# class TestCaseX: contains the tests as methods
#####################################################
class TestCaseX( unittest.TestCase ):
        """TestCaseX class
        """
                
        """if you override __init__ method, call the base class's __init__ method:
        def __init__(self, methodName='runTest'):
                unittest.TestCase.__init__(self, methodName)
        """

        def setUp(self):
            """hook method, will be called before every test method
            put here the code you think is setup-like
            """
            
            # boolean class member indicating whether the setUp has been executed:
            self.inited = True
            
            # setting up a dictionary:
            self.mydict = { 'one':1, 'two':2, 'three':3}

        def tearDown(self ):
            """hook method, will be called after each test method
            put here the common 'destructing' code if needed
            (however destructing explicitly is needed only for 
            resources like files, databases)
            """

            # just to show class member accessibility:
            self.inited = False

        def runTest():
            """you may list here a sequence of test method invokations
            """
            testA()
            testB()

        def testA( self ):
            """DESCRIPTION: testing with assert, failIf, failUnless
            the initial value of mydict
            """
            
            # test if setUp really has been run
            self.failUnless( self.inited)
            
            assert self.mydict['one'] + 1 == self.mydict['two']
            self.failUnless( self.mydict['three'] - self.mydict['two'] == self.mydict['one'], 'Error in dictionary setup')
            self.failIf( self.mydict['three'] == self.mydict['two'])
            
            pass

        def testB( self ):
            """DESCRIPTION: modifying mydict and sum up the values
            """

            self.failUnless( self.inited)

            self.mydict['four'] = 4
            self.failUnless( self.mydict['four'] == 2 * self.mydict['two'])

            
            sum = 0
            for one_key in self.mydict.keys():
            	sum += self.mydict[one_key]
            
            assert sum == 10
            
            pass

#####################################################
# 1st option to produce testsuites
#####################################################
def suites():
    """A method named 'suites' is needed if you'd like to execute the tests with GPyunit.py
    Produces a test suite, gathering all methods in the class specified, matching the pattern specified:
    """
    suite = unittest.makeSuite(TestCaseX,'test')
    return suite

#####################################################
# 2nd option to produce testsuites
#####################################################
def suites2():
    """Produces a test suite, adding methods one by one:
    """
    suite = unittest.TestSuite()
    suite.addTest( TestCaseX( "testA"))
    suite.addTest( TestCaseX( "testB"))
    return suite

#####################################################
# main
#####################################################
if __name__ == "__main__":
    """If this file is run standalone, execute the suite given back by the suites() function above
    """

    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TEST BEGINS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    
    ######## 1st option
    all = suites()
    runner = unittest.TextTestRunner()
    runner.run( all )

    ######## 2nd option
    #unittest.main(defaultTest='TestCaseX')
    
    ######## 3rd option
    #unittest.main()
--- NEW FILE: testcase_skeleton.py ---
import unittest
import win32com.client
import win32ui
import pythoncom
import os

#####################################################
# class TestCaseX: contains the tests as methods
#####################################################
class TestCaseX( unittest.TestCase ):
        """TestCaseX class
        """
                
        """if you override __init__ method, call the base class's __init__ method:
        def __init__(self, methodName='runTest'):
                unittest.TestCase.__init__(self, methodName)
        """

        def setUp(self):
            """hook method, will be called before every test method
            put here the code you think is setup-like
            """
            pass

        def tearDown(self ):
            """hook method, will be called after each test method
            put here the common 'destructing' code if needed
            (however destructing explicitly is needed only for 
            resources like files, databases)
            """
            pass

        def runTest():
            """you may list here a sequence of test method invokations
            """
            testA()
            testB()

        def testA( self ):
            """DESCRIPTION: testing with assert, failIf, failUnless
            the initial value of mydict
            """
            pass

        def testB( self ):
            """DESCRIPTION: modifying mydict and sum up the values
            """
            pass

#####################################################
# 1st option to produce testsuites
#####################################################
def suites():
    """A method named 'suites' is needed if you'd like to execute the tests with GPyunit.py
    Produces a test suite, gathering all methods in the class specified, matching the pattern specified:
    """
    suite = unittest.makeSuite(TestCaseX,'test')
    return suite

#####################################################
# 2nd option to produce testsuites
#####################################################
def suites2():
    """Produces a test suite, adding methods one by one:
    """
    suite = unittest.TestSuite()
    suite.addTest( TestCaseX( "testA"))
    suite.addTest( TestCaseX( "testB"))
    return suite

#####################################################
# main
#####################################################
if __name__ == "__main__":
    """If this file is run standalone, execute the suite given back by the suites() function above
    """

    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TEST BEGINS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    
    ######## 1st option
    all = suites()
    runner = unittest.TextTestRunner()
    runner.run( all )

    ######## 2nd option
    #unittest.main(defaultTest='TestCaseX')
    
    ######## 3rd option
    #unittest.main()
--- NEW FILE: compareTo_testA_sf_model1.xme ---
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE project SYSTEM "mga.dtd">

<project guid="{45AA99E4-95CA-4280-9472-3BDBAD6B22AF}" cdate="Fri May 27 14:58:27 2005" mdate="Fri May 27 14:58:27 2005" version="" metaguid="{9B9ABE95-DEAD-BEEF-FEED-DAD000000001}" metaversion="" metaname="SF">
	<name>testA1_sf</name>
	<comment></comment>
	<author></author>
	<folder id="id-006a-00000001" relid="0x1" childrelidcntr="0x2" kind="RootFolder">
		<name>testA1_sf</name>
		<folder id="id-006a-00000002" relid="0x1" childrelidcntr="0x1" kind="Folder">
			<name>Folder1</name>
			<model id="id-0065-00000002" kind="Compound" relid="0x1" childrelidcntr="0x2">
				<name>CompInFolder1</name>
				<atom id="id-0066-00000001" kind="InputSignal" role="InputSignals" relid="0x1">
					<name>InSignal1</name>
				</atom>
				<atom id="id-0066-00000002" kind="OutputSignal" role="OutputSignals" relid="0x2">
					<name>OutSignal1</name>
				</atom>
			</model>
		</folder>
		<model id="id-0065-00000001" kind="Compound" relid="0x2" childrelidcntr="0x0">
			<name>Comp1</name>
		</model>
	</folder>
</project>



More information about the GME-commit mailing list