Ejemplo n.º 1
0
    def __init__(self, path, templateFilter, outputPath, reports, jUnitPackagePrefix):

        sys.setrecursionlimit(10000)

        self.caduceusPath = CaduceusHelper.getPackagePath()
        
        self.path = os.path.abspath(path)
        self.rootPath = self.path
        if templateFilter:
            print("Filtering templates using '%s'" % templateFilter)
            self._templateFilter = re.compile(templateFilter)
        else:
            self._templateFilter = None
            
        self.outputPath = os.path.abspath(outputPath)
        self._reports = reports
        self._jUnitPackagePrefix = jUnitPackagePrefix
        
        self.results = CaduceusResults()
        
        os.environ["CADUCEUS_OUTPUT"] = self.outputPath
        os.environ["CADUCEUS_SRC"] = self.rootPath
Ejemplo n.º 2
0
class CaduceusGenerator:
    REPORT_HTML = 0
    REPORT_JUNIT = 1
    
    def __init__(self, path, templateFilter, outputPath, reports, jUnitPackagePrefix):

        sys.setrecursionlimit(10000)

        self.caduceusPath = CaduceusHelper.getPackagePath()
        
        self.path = os.path.abspath(path)
        self.rootPath = self.path
        if templateFilter:
            print("Filtering templates using '%s'" % templateFilter)
            self._templateFilter = re.compile(templateFilter)
        else:
            self._templateFilter = None
            
        self.outputPath = os.path.abspath(outputPath)
        self._reports = reports
        self._jUnitPackagePrefix = jUnitPackagePrefix
        
        self.results = CaduceusResults()
        
        os.environ["CADUCEUS_OUTPUT"] = self.outputPath
        os.environ["CADUCEUS_SRC"] = self.rootPath

    def run(self):
        
        if os.path.isfile(self.path):
            print("Output must be a directory !")
            #path, filename = os.path.split(self.path)
            #self._processFile(path, filename, self.outputPath)
            return
        
        if os.path.isdir(self.path):
            self._processDirectory(self.path, self.outputPath)
            
            # copy css file to output path
            CaduceusHelper.copyResource(self.caduceusPath, self.outputPath, "caduceus.css")
            
        # Print statistics
        print("Assertions: %d" % self.results.getAssertionCount())
        print("Success: %d" % self.results.getAssertionTypeCount(CaduceusTemplateResults.SUCCESS))
        print("Failures: %d" % self.results.getAssertionTypeCount(CaduceusTemplateResults.FAILURE))
        print("Errors: %d" % self.results.getAssertionTypeCount(CaduceusTemplateResults.ERROR))
        
        # Generate execution report
        if self._reports[self.REPORT_HTML]:
            report = ReportHtml(self.results, self.outputPath, self.caduceusPath)
            report.generate()
        
        if self._reports[self.REPORT_JUNIT]:
            report = ReportJUnit(self.results, self.outputPath, self.caduceusPath, self._jUnitPackagePrefix)
            report.generate()
        return self.results.failures == 0 and self.results.errors == 0
            
    def _processDirectory(self, path, outPath):
        print("  Processing path %s..." % path)
        entries = os.listdir(path)
        for entry in entries:
            entryFullPath = os.path.join(path, entry)
            
            if os.path.isfile(entryFullPath):
                self._processFile(path, entry, outPath)
            elif os.path.isdir(entryFullPath) and (entry != ".svn"):
                self._processDirectory(entryFullPath, os.path.join(outPath, entry))
            else:
                print("Not handling %s" % entryFullPath)
                
                
    def _processFile(self, filePath, fileName, outFilePath):
        inputFullPath = os.path.join(filePath, fileName)
        inputBasenamePath, ext = os.path.splitext(inputFullPath)
        outputFullPath = os.path.join(outFilePath, fileName)
        
        if ext == ".html":
            if self.allowedTemplateFile(filePath, fileName):
                print("  Processing file %s..." % inputFullPath)
            
                template = CaduceusTemplateParser.parseTemplateFile(inputFullPath, self.rootPath, self.caduceusPath)	
                if template:
                    CaduceusHelper.ensurePathExists(outFilePath)
                    
                    outputFile = open(outputFullPath, 'w')
                    try:
                        # Load controller for file
                        dictGlob = {}
                        dictLoc = {}
                        
                        try:
                            controllerName, _ext = os.path.splitext(fileName)
                            controllerName = controllerName + "Test"
                            
                            sys.path.append(os.path.dirname(inputFullPath))
                            #exec ("from %s import %s" % (controllerName, controllerName)) in dictGlob, dictLoc
                            exec ("from %s import %s" % (controllerName, controllerName), dictGlob, dictLoc)
                            
                            # We must copy local dictionnary into global, to allow some symbols resolution
                            dictGlob.update(dictLoc)
                            
                            # Instanciate a controller in parsing context 
                            #exec ("__caduceus_controler__ = %s()" % controllerName) in dictGlob, dictLoc
                            exec ("__caduceus_controler__ = %s()" % controllerName, dictGlob, dictLoc)
                            os.environ["CADUCEUS_TEMPLATE_PATH"] = inputFullPath
                                                        
                            # Bind all controller public methods as global methods 
                            for key in dir(dictLoc[controllerName]):
                                if key[0] != "_":
                                    proc = eval("__caduceus_controler__.%s" % key, dictGlob, dictLoc)
                                    dictLoc[key] = proc
                        except IOError:
                            print("Warning: No controller file for '%s'" % inputFullPath)
                        except ImportError:
                            print("Warning: No controller file for '%s'" % inputFullPath)
                            import traceback
                            traceback.print_exc()
                            
                        # Render template using context
                        tmplResults = CaduceusTemplateResults(outputFullPath)
                        result = template.render(dictGlob, dictLoc, tmplResults)
                        self.results.addTemplateResult(tmplResults)
                        
                        outputFile.write(result)
                    finally:
                        outputFile.close()

        elif ext not in [".py", ".pyc"]:
            # File may be stylesheet, javasript or other resource
            # copy as it
            print("  Copy file %s..." % inputFullPath)
            
            CaduceusHelper.ensurePathExists(outFilePath)		
            shutil.copyfile(inputFullPath, outputFullPath)

    def allowedTemplateFile(self, filePath, fileName):
        inputFullPath = os.path.join(filePath, fileName)
        if fileName[0] == "_":
            print("  Skipping partial %s" % inputFullPath)
            return False
        
        if self._templateFilter:
            if not self._templateFilter.match(inputFullPath):
                print("  Skipping filtered template %s" % inputFullPath)
                return False
        
        return True

    @staticmethod
    def main():
        from optparse import OptionParser
    
        parser = OptionParser()
        parser.add_option("-o", "--output", dest="outputPath", help="Output path", metavar="OUTPUT", default="")
        parser.add_option("-s", "--src", dest="srcPath", help="Base directory", metavar="INPUT", default=None)
        parser.add_option("-r", "--report-html", action="store_true", dest="reportHtml", help="Generate HTML report", default=True)
        parser.add_option("-q", "--no-report-html", action="store_false", dest="reportHtml", help="Do not generate HTML report")
        parser.add_option("-j", "--junit", action="store_true", dest="reportJUnit", help="Generate JUnit report", default=False)
        parser.add_option("-p", "--junit-package-prefix", dest="jUnitPackagePrefix", help="JUnit report package prefix", default="")
        parser.add_option("", "--filter", dest="templateFilter", help="regexp to filter templates", default="")
    
        (options, args) = parser.parse_args()
        
        if options.srcPath and options.outputPath:
            caduceus = CaduceusGenerator(options.srcPath,
                                options.templateFilter,
                                options.outputPath,
                                [options.reportHtml, options.reportJUnit],
                                options.jUnitPackagePrefix)
            sys.exit([1, 0][caduceus.run()])
        else:
            parser.print_help()