"""Codenomicon specific classes.
"""

import pexpect 
import shells 
import os, sys
import unittest
import logging
from time import *

class Codenomicon(object):
    """Class encapsulating Codenomicon software. Basically wrapping the software into this class, allows
    others to use the software as an object without bothering about the exact commands. This also isolates
    Nextest from Codenomicon related changes.
    """
    def __init__(self, codyAddr, serverAddr, workDir='/tmp'):
        # Commented these lines for ticket 35958
        # to run the codenomicon for sip and h323 simultaneously.
        #if (not (os.environ.has_key('CLASSPATH') and (os.environ['CLASSPATH'].count('h323-121.jar') > 0))):
        #    raise EnvironmentError, 'CLASSPATH does not contain h323-121.jar file'

        self.localShell = shells.LocalShell()
        self.msw = shells.MswShell()
        self.workDir = workDir
        self.myAddr = codyAddr
        self.serverAddr = serverAddr
        self.results = {'verdict':'UNTESTED', 'testIndex':0}
        self.coreFiles = self.msw.getCoreFiles()
        self.log = logging.getLogger('nextestlog')
        self.logPatterns = self.localShell.compile_pattern_list([
                                    'Test case #(\d+) completed',
                                    'Reached end-of-test-cases',
                                    pexpect.EOF, 
                                    pexpect.TIMEOUT])
        self.errorPatterns = self.localShell.compile_pattern_list([
                                    pexpect.TIMEOUT,
                                    'No such file or directory',
                                    'Exception in thread',
                                    pexpect.EOF])

    def __del__(self):
        self.localShell.disconnect()
        self.msw.disconnect()

    def start(self, index='0-'):
        """Start running the codenomicon software.
        """
        # For FP 35958
	# 40168:  updated the codenomicon version to 121	
        codyToolCommand = 'java -Xmx256M -jar /home/test/codenomicon/h323-121.jar '
        codyToolCommand += '--no-gui '
        codyToolCommand += '--index %s ' % index
        codyToolCommand += '--host %s ' % self.serverAddr
        codyToolCommand += '--h323-host  %s ' % self.serverAddr
        codyToolCommand += '--local-host %s ' % self.myAddr
        codyToolCommand += '--number 6024441111 ' 
        codyToolCommand += '--log-dir %s/cody ' % self.workDir
        print 'Cody command is :%s:' % codyToolCommand
        self.log.debug('Codenomicon: start command: %s' % codyToolCommand)
        self.localShell.sendline(codyToolCommand)

        # Made the changes for ticket 35958
        #i = self.localShell.expect_list(self.errorPatterns, 2)
        #if (i != 0):
        #    warningMessage = 'h323-121.jar file is not in CLASSPATH. Following steps should be performed: ' + \
        #                     'Correct the CLASSPATH in .bashrc or .nextestrc file'
        #    raise EnvironmentError,warningMessage

    def runTillVerdict(self):
        """This call is blocking call for the calling user. The call will wait till the Cody software
        stops running which may take more than 24 hours.
        """
        while True:
            #we wait for a maximum of 60 seconds for each test to complete
            i = self.localShell.expect_list(self.logPatterns, 60)
            if i == 0:
                testCaseNumber = int(self.localShell.match.group(1))
        
                if (self.results['testIndex'] != testCaseNumber):
                    print 'Warning: Missing tests between %s and %s' % (self.results['testIndex'], testCaseNumber)
        
                self.results['testIndex'] = testCaseNumber+1
        
                print '\ttest %s completed' % testCaseNumber
                self.qmtTestEndHook(testCaseNumber)
        
            elif i == 1:
                print 'End reached:%s:' % self.localShell.match.group()
                self.results['verdict'] = 'PASS'
                break
        
            else:
                print 'EOF or timeout'
                self.results['verdict'] = 'FAIL'
                break

        return self.results


    def __del__(self):
        #destroy local shell
        pass

    def testHooks(self, testPoint):
        """Future use only.
        """
        #demux calls
        pass

    def startRunHook(self):
        """Called at the beginning of test campaign. Not used currently.
        """
        #Verify iserver is running
        if not self.msw.isServerRunning():
            raise EnvironmentError,'Server is down'

        #start sdebug 3
        self.localShell.runCommand('localShelljava GetiServerConfig mymsw LoggingConfig')

    def startTestHook(self):
        """Called at the begining of each test case run. Not used currently.
        """

    def endTestHook(self):
        """Called at the end of each test case run. Not used currently.
        """
        #where do I store the results
        if self.msw.isCoreFilePresent():
	    #copy over the file somewhere else
            self.localShell.runCommand('scp root@mymsw:/usr/local/nextone/bin/*core* ~/cody')
            self.msw.runCommand('mv /usr/local/nextone/bin/*core* /tmp')
            self.localShell.runCommand('scp root@mymsw:/var/core/*core* ~/cody')
            self.msw.runCommand('mv /var/core/*core* /tmp')

            #copy over debug buffer
            self.localShell.runCommand('scp root@mymsw: ~/cody')

        #truncate the buffer
        self.msw.runCommand('echo "" > /var/log/iserver.log')

    def IntrumentHook(self):
        """Instrumentation hook function. Used to find out health of MSW at the end of each test. 
        Not used currently.
        """
        #if iserver is not running
        #   return fail
        pass

    def IntrumentFailHook(self):
        """Instrumentation fail hook function. Used to take corrective action if instrumentation fails. 
        Not used currently.
        """
        #Restart iserver
        #If failed to restart
        #	return fail
        pass

    def qmtTestEndHook(self, testIndex):
        """Hook Function called the end of test campaign. 
        """

        self.log.info('test %s completed' % testIndex)
        coreFiles = self.msw.getCoreFiles()

        newCoreFiles = [x for x in coreFiles if x not in self.coreFiles]

        if len(newCoreFiles) == 0:
            return

        self.coreFiles.extend(newCoreFiles)

        for files in newCoreFiles:
            print 'CORE FILE for test %s' % testIndex
            self.log.critical('test %s caused core: %s' % (testIndex, files))
            self.msw.runCommand('echo "CODY TEST %s caused core %s file" > /var/log/iserver.log' % (testIndex, files))

            #copy over debug buffer
            #self.localShell.runCommand('scp root@mymsw: ~/cody')

        #truncate the buffer
        #self.msw.runCommand('echo "" > /var/log/iserver.log')


class CodyTest(unittest.TestCase):
    """
    Unittest class for testing Codenomicon class.
    """
    def test_1(self):
        """
        check runCommand()
        """
        msw = shells.MswShell()
        msw.deleteCoreFiles()

        cody = Codenomicon(
                              codyAddr='10.1.6.22',
                              serverAddr='10.2.0.40', 
                              workDir='/tmp'
                              )
        print 'existing core files: %s' % cody.coreFiles
        cody.start('0-2')
        cody.msw.runCommand('echo \'\' > %s/core.DilbaghChahal01' %cody.msw.corePath)
        cody.msw.runCommand('echo \'\' > %s/core.DilbaghChahal02' %cody.msw.corePath)
        verdict = cody.runTillVerdict()
        print verdict
        #cody = Codenomicon()
        #coreFiles = cody.msw.getCoreFiles()
        #self.assertEqual(len(coreFiles), 2)
        #cody.qmtTestEndHook(999)
        #coreFiles = cody.msw.getCoreFiles()
        #self.assertEqual(len(coreFiles), 0)
        #output = cody.localShell.runCommand('ls -1 /tmp/*core*')
        #self.assertNotEqual(output.find('999_core.DilbaghChahal01'), -1)
        #self.assertNotEqual(output.find('999_core.DilbaghChahal02'), -1)

        #cody.localShell('delete /tmp/core*')
        


if __name__ == '__main__':

    if len(sys.argv) == 1:
        unittest.main()



89f13eb9cfbd2c20d9d03fee6660aa746470bd60
"""Codenomicon specific classes.
"""

import pexpect 
import shells 
import os, sys
import unittest
import logging
from time import *

class Codenomicon(object):
    """Class encapsulating Codenomicon software. Basically wrapping the software into this class, allows
    others to use the software as an object without bothering about the exact commands. This also isolates
    Nextest from Codenomicon related changes.
    """
    def __init__(self, codyAddr, serverAddr, workDir='/tmp'):
        # Commented these lines for ticket 35958
        # to run the codenomicon for sip and h323 simultaneously.
        #if (not (os.environ.has_key('CLASSPATH') and (os.environ['CLASSPATH'].count('h323-121.jar') > 0))):
        #    raise EnvironmentError, 'CLASSPATH does not contain h323-121.jar file'

        self.localShell = shells.LocalShell()
        self.msw = shells.MswShell()
        self.workDir = workDir
        self.myAddr = codyAddr
        self.serverAddr = serverAddr
        self.results = {'verdict':'UNTESTED', 'testIndex':0}
        self.coreFiles = self.msw.getCoreFiles()
        self.log = logging.getLogger('nextestlog')
        self.logPatterns = self.localShell.compile_pattern_list([
                                    'Test case #(\d+) completed',
                                    'Reached end-of-test-cases',
                                    pexpect.EOF, 
                                    pexpect.TIMEOUT])
        self.errorPatterns = self.localShell.compile_pattern_list([
                                    pexpect.TIMEOUT,
                                    'No such file or directory',
                                    'Exception in thread',
                                    pexpect.EOF])

    def __del__(self):
        self.localShell.disconnect()
        self.msw.disconnect()

    def start(self, index='0-'):
        """Start running the codenomicon software.
        """
        # For FP 35958
	# 40168:  updated the codenomicon version to 121	
        codyToolCommand = 'java -Xmx256M -jar /home/test/codenomicon/h323-121.jar '
        codyToolCommand += '--no-gui '
        codyToolCommand += '--index %s ' % index
        codyToolCommand += '--host %s ' % self.serverAddr
        codyToolCommand += '--h323-host  %s ' % self.serverAddr
        codyToolCommand += '--local-host %s ' % self.myAddr
        codyToolCommand += '--number 6024441111 ' 
        codyToolCommand += '--log-dir %s/cody ' % self.workDir
        print 'Cody command is :%s:' % codyToolCommand
        self.log.debug('Codenomicon: start command: %s' % codyToolCommand)
        self.localShell.sendline(codyToolCommand)

        # Made the changes for ticket 35958
        #i = self.localShell.expect_list(self.errorPatterns, 2)
        #if (i != 0):
        #    warningMessage = 'h323-121.jar file is not in CLASSPATH. Following steps should be performed: ' + \
        #                     'Correct the CLASSPATH in .bashrc or .nextestrc file'
        #    raise EnvironmentError,warningMessage

    def runTillVerdict(self):
        """This call is blocking call for the calling user. The call will wait till the Cody software
        stops running which may take more than 24 hours.
        """
        while True:
            #we wait for a maximum of 60 seconds for each test to complete
            i = self.localShell.expect_list(self.logPatterns, 60)
            if i == 0:
                testCaseNumber = int(self.localShell.match.group(1))
        
                if (self.results['testIndex'] != testCaseNumber):
                    print 'Warning: Missing tests between %s and %s' % (self.results['testIndex'], testCaseNumber)
        
                self.results['testIndex'] = testCaseNumber+1
        
                print '\ttest %s completed' % testCaseNumber
                self.qmtTestEndHook(testCaseNumber)
        
            elif i == 1:
                print 'End reached:%s:' % self.localShell.match.group()
                self.results['verdict'] = 'PASS'
                break
        
            else:
                print 'EOF or timeout'
                self.results['verdict'] = 'FAIL'
                break

        return self.results


    def __del__(self):
        #destroy local shell
        pass

    def testHooks(self, testPoint):
        """Future use only.
        """
        #demux calls
        pass

    def startRunHook(self):
        """Called at the beginning of test campaign. Not used currently.
        """
        #Verify iserver is running
        if not self.msw.isServerRunning():
            raise EnvironmentError,'Server is down'

        #start sdebug 3
        self.localShell.runCommand('localShelljava GetiServerConfig mymsw LoggingConfig')

    def startTestHook(self):
        """Called at the begining of each test case run. Not used currently.
        """

    def endTestHook(self):
        """Called at the end of each test case run. Not used currently.
        """
        #where do I store the results
        if self.msw.isCoreFilePresent():
	    #copy over the file somewhere else
            self.localShell.runCommand('scp root@mymsw:/usr/local/nextone/bin/*core* ~/cody')
            self.msw.runCommand('mv /usr/local/nextone/bin/*core* /tmp')
            self.localShell.runCommand('scp root@mymsw:/var/core/*core* ~/cody')
            self.msw.runCommand('mv /var/core/*core* /tmp')

            #copy over debug buffer
            self.localShell.runCommand('scp root@mymsw: ~/cody')

        #truncate the buffer
        self.msw.runCommand('echo "" > /var/log/iserver.log')

    def IntrumentHook(self):
        """Instrumentation hook function. Used to find out health of MSW at the end of each test. 
        Not used currently.
        """
        #if iserver is not running
        #   return fail
        pass

    def IntrumentFailHook(self):
        """Instrumentation fail hook function. Used to take corrective action if instrumentation fails. 
        Not used currently.
        """
        #Restart iserver
        #If failed to restart
        #	return fail
        pass

    def qmtTestEndHook(self, testIndex):
        """Hook Function called the end of test campaign. 
        """

        self.log.info('test %s completed' % testIndex)
        coreFiles = self.msw.getCoreFiles()

        newCoreFiles = [x for x in coreFiles if x not in self.coreFiles]

        if len(newCoreFiles) == 0:
            return

        self.coreFiles.extend(newCoreFiles)

        for files in newCoreFiles:
            print 'CORE FILE for test %s' % testIndex
            self.log.critical('test %s caused core: %s' % (testIndex, files))
            self.msw.runCommand('echo "CODY TEST %s caused core %s file" > /var/log/iserver.log' % (testIndex, files))

            #copy over debug buffer
            #self.localShell.runCommand('scp root@mymsw: ~/cody')

        #truncate the buffer
        #self.msw.runCommand('echo "" > /var/log/iserver.log')


class CodyTest(unittest.TestCase):
    """
    Unittest class for testing Codenomicon class.
    """
    def test_1(self):
        """
        check runCommand()
        """
        msw = shells.MswShell()
        msw.deleteCoreFiles()

        cody = Codenomicon(
                              codyAddr='10.1.6.22',
                              serverAddr='10.2.0.40', 
                              workDir='/tmp'
                              )
        print 'existing core files: %s' % cody.coreFiles
        cody.start('0-2')
        cody.msw.runCommand('echo \'\' > %s/core.DilbaghChahal01' %cody.msw.corePath)
        cody.msw.runCommand('echo \'\' > %s/core.DilbaghChahal02' %cody.msw.corePath)
        verdict = cody.runTillVerdict()
        print verdict
        #cody = Codenomicon()
        #coreFiles = cody.msw.getCoreFiles()
        #self.assertEqual(len(coreFiles), 2)
        #cody.qmtTestEndHook(999)
        #coreFiles = cody.msw.getCoreFiles()
        #self.assertEqual(len(coreFiles), 0)
        #output = cody.localShell.runCommand('ls -1 /tmp/*core*')
        #self.assertNotEqual(output.find('999_core.DilbaghChahal01'), -1)
        #self.assertNotEqual(output.find('999_core.DilbaghChahal02'), -1)

        #cody.localShell('delete /tmp/core*')
        


if __name__ == '__main__':

    if len(sys.argv) == 1:
        unittest.main()


