import os, string, cStringIO, tempfile

class TestRun:

    def __init__(self, name, options, args, expectedOut=None,
                 validationFunc=None, input=None, outFile=None):
        self.name = name
        self.options = options
        self.args = args
        self.expectedOut = expectedOut
        self.validationFunc = validationFunc
        self.input = input
        self.outFile = outFile
        

    def test(self, tester, commandName):

        cmd = "%s " % commandName
        for name,value in self.options.items():
            cmd = cmd + "--%s" % name
            if value:
                cmd = cmd + "=%s " % value
            else:
                cmd = cmd + " "

        cmd = reduce(lambda a, b: a + ' "%s"' % b, self.args, cmd)

        tester.startGroup(self.name)
        tester.startTest(cmd)
        fn = None
        outName = None
        import tempfile
        if self.input:
            fn = tempfile.mktemp()
            f = open(fn,'w')
            f.write(self.input)
            f.close()
            cmd = cmd + ' < "%s"' % fn

        outName = tempfile.mktemp()
        cmd = cmd + ' > "%s"' % outName
        os.system(cmd)
        if self.outFile:
            out = open(self.outFile).read()
            os.unlink(self.outFile)
        else:
            out = open(outName).read()
        os.unlink(outName)
        if fn:
            os.unlink(fn)

        if out and not self.expectedOut:
            tester.warning("Unexpected output: %s" % out)
        elif not out and self.expectedOut:
            tester.error("Missing Expected output: %s" % self.expectedOut)
        elif out:
            tester.compare(self.expectedOut,out,diff=1)
        elif self.validationFunc and not self.validationFunc(tester):
            tester.error("Validation Failed")

        tester.testDone()
        return tester.groupDone()

class Test:

    def __init__(self,commandName,runs):
        self.commandName = commandName
        self.runs = runs



    def test(self,tester):
        tester.startGroup("Test Command Line %s" % self.commandName)

        runs = self.runs[:]

        for run in runs:
            run.test(tester,self.commandName)


        tester.groupDone()
    
