def __erase(self):
        """
        Private slot to handle the erase context menu action.
        
        This method erases the collected coverage data that is
        stored in the .coverage file.
        """
        cover = coverage(data_file=self.cfn)
        cover.use_cache(True)
        cover.load()
        cover.erase()

        self.reloadButton.setEnabled(False)
        self.resultList.clear()
        self.summaryList.clear()
    def __annotate(self):
        """
        Private slot to handle the annotate context menu action.
        
        This method produce an annotated coverage file of the
        selected file.
        """
        itm = self.resultList.currentItem()
        fn = itm.text(0)

        cover = coverage(data_file=self.cfn)
        cover.use_cache(True)
        cover.exclude(self.excludeList[0])
        cover.load()
        cover.annotate([fn], None, True)
 def __erase(self):
     """
     Private slot to handle the erase context menu action.
     
     This method erases the collected coverage data that is
     stored in the .coverage file.
     """
     cover = coverage(data_file=self.cfn)
     cover.use_cache(True)
     cover.load()
     cover.erase()
     
     self.reloadButton.setEnabled(False)
     self.resultList.clear()
     self.summaryList.clear()
 def __annotate(self):
     """
     Private slot to handle the annotate context menu action.
     
     This method produce an annotated coverage file of the
     selected file.
     """
     itm = self.resultList.currentItem()
     fn = itm.text(0)
     
     cover = coverage(data_file=self.cfn)
     cover.use_cache(True)
     cover.exclude(self.excludeList[0])
     cover.load()
     cover.annotate([fn], None, True)
    def __annotateAll(self):
        """
        Private slot to handle the annotate all context menu action.
        
        This method produce an annotated coverage file of every
        file listed in the listview.
        """
        amount = self.resultList.topLevelItemCount()
        if amount == 0:
            return

        # get list of all filenames
        files = []
        for index in range(amount):
            itm = self.resultList.topLevelItem(index)
            files.append(itm.text(0))

        cover = coverage(data_file=self.cfn)
        cover.use_cache(True)
        cover.exclude(self.excludeList[0])
        cover.load()

        # now process them
        progress = E5ProgressDialog(self.tr("Annotating files..."),
                                    self.tr("Abort"), 0, len(files),
                                    self.tr("%v/%m Files"), self)
        progress.setMinimumDuration(0)
        progress.setWindowTitle(self.tr("Coverage"))
        count = 0

        for file in files:
            progress.setValue(count)
            if progress.wasCanceled():
                break
            cover.annotate([file], None)  # , True)
            count += 1

        progress.setValue(len(files))
 def __annotateAll(self):
     """
     Private slot to handle the annotate all context menu action.
     
     This method produce an annotated coverage file of every
     file listed in the listview.
     """
     amount = self.resultList.topLevelItemCount()
     if amount == 0:
         return
     
     # get list of all filenames
     files = []
     for index in range(amount):
         itm = self.resultList.topLevelItem(index)
         files.append(itm.text(0))
     
     cover = coverage(data_file=self.cfn)
     cover.use_cache(True)
     cover.exclude(self.excludeList[0])
     cover.load()
     
     # now process them
     progress = E5ProgressDialog(
         self.tr("Annotating files..."), self.tr("Abort"),
         0, len(files), self.tr("%v/%m Files"), self)
     progress.setMinimumDuration(0)
     progress.setWindowTitle(self.tr("Coverage"))
     count = 0
     
     for file in files:
         progress.setValue(count)
         if progress.wasCanceled():
             break
         cover.annotate([file], None)  # , True)
         count += 1
     
     progress.setValue(len(files))
 def on_startButton_clicked(self, failedOnly=False):
     """
     Private slot to start the test.
     
     @keyparam failedOnly flag indicating to run only failed tests (boolean)
     """
     if self.running:
         return
     
     prog = self.testsuiteComboBox.currentText()
     if not prog:
         E5MessageBox.critical(
             self,
             self.tr("Unittest"),
             self.tr("You must enter a test suite file."))
         return
     
     # prepend the selected file to the testsuite combobox
     self.insertProg(prog)
     self.sbLabel.setText(self.tr("Preparing Testsuite"))
     QApplication.processEvents()
     
     testFunctionName = self.testComboBox.currentText()
     if testFunctionName:
         self.insertTestName(testFunctionName)
     else:
         testFunctionName = "suite"
     
     # build the module name from the filename without extension
     self.testName = os.path.splitext(os.path.basename(prog))[0]
     
     if self.dbs and not self.localCheckBox.isChecked():
         # we are cooperating with the eric6 IDE
         project = e5App().getObject("Project")
         if project.isOpen() and project.isProjectSource(prog):
             mainScript = project.getMainScript(True)
             clientType = project.getProjectLanguage()
         else:
             mainScript = os.path.abspath(prog)
             flags = Utilities.extractFlagsFromFile(mainScript)
             if mainScript.endswith(
                 tuple(Preferences.getPython("PythonExtensions"))) or \
                ("FileType" in flags and
                     flags["FileType"] in ["Python", "Python2"]):
                 clientType = "Python2"
             else:
                 clientType = ""
         if failedOnly and self.__failedTests:
             failed = [t.split(".", 1)[1] for t in self.__failedTests]
         else:
             failed = []
         self.__failedTests = []
         self.dbs.remoteUTPrepare(
             prog, self.testName, testFunctionName, failed,
             self.coverageCheckBox.isChecked(), mainScript,
             self.coverageEraseCheckBox.isChecked(), clientType=clientType)
     else:
         # we are running as an application or in local mode
         sys.path = [os.path.dirname(os.path.abspath(prog))] + \
             self.savedSysPath
         
         # clean up list of imported modules to force a reimport upon
         # running the test
         if self.savedModulelist:
             for modname in list(sys.modules.keys()):
                 if modname not in self.savedModulelist:
                     # delete it
                     del(sys.modules[modname])
         self.savedModulelist = sys.modules.copy()
         
         # now try to generate the testsuite
         try:
             module = __import__(self.testName)
             try:
                 if failedOnly and self.__failedTests:
                     test = unittest.defaultTestLoader.loadTestsFromNames(
                         [t.split(".", 1)[1] for t in self.__failedTests],
                         module)
                 else:
                     test = unittest.defaultTestLoader.loadTestsFromName(
                         testFunctionName, module)
             except AttributeError:
                 test = unittest.defaultTestLoader.loadTestsFromModule(
                     module)
         except:
             exc_type, exc_value, exc_tb = sys.exc_info()
             E5MessageBox.critical(
                 self,
                 self.tr("Unittest"),
                 self.tr(
                     "<p>Unable to run test <b>{0}</b>.<br>"
                     "{1}<br>{2}</p>")
                 .format(self.testName, str(exc_type),
                         str(exc_value)))
             return
             
         # now set up the coverage stuff
         if self.coverageCheckBox.isChecked():
             if self.dbs:
                 # we are cooperating with the eric6 IDE
                 project = e5App().getObject("Project")
                 if project.isOpen() and project.isProjectSource(prog):
                     mainScript = project.getMainScript(True)
                     if not mainScript:
                         mainScript = os.path.abspath(prog)
                 else:
                     mainScript = os.path.abspath(prog)
             else:
                 mainScript = os.path.abspath(prog)
             
             from DebugClients.Python3.coverage import coverage
             cover = coverage(
                 data_file="{0}.coverage".format(
                     os.path.splitext(mainScript)[0]))
             cover.use_cache(True)
             if self.coverageEraseCheckBox.isChecked():
                 cover.erase()
         else:
             cover = None
         
         self.testResult = QtTestResult(self)
         self.totalTests = test.countTestCases()
         self.__failedTests = []
         self.__setRunningMode()
         if cover:
             cover.start()
         test.run(self.testResult)
         if cover:
             cover.stop()
             cover.save()
         self.__setStoppedMode()
         sys.path = self.savedSysPath
    def on_startButton_clicked(self, failedOnly=False):
        """
        Private slot to start the test.
        
        @keyparam failedOnly flag indicating to run only failed tests (boolean)
        """
        if self.running:
            return

        prog = self.testsuiteComboBox.currentText()
        if not prog:
            E5MessageBox.critical(self, self.tr("Unittest"),
                                  self.tr("You must enter a test suite file."))
            return

        # prepend the selected file to the testsuite combobox
        self.insertProg(prog)
        self.sbLabel.setText(self.tr("Preparing Testsuite"))
        QApplication.processEvents()

        testFunctionName = self.testComboBox.currentText()
        if testFunctionName:
            self.insertTestName(testFunctionName)
        else:
            testFunctionName = "suite"

        # build the module name from the filename without extension
        self.testName = os.path.splitext(os.path.basename(prog))[0]

        if self.dbs and not self.localCheckBox.isChecked():
            # we are cooperating with the eric6 IDE
            project = e5App().getObject("Project")
            if project.isOpen() and project.isProjectSource(prog):
                mainScript = project.getMainScript(True)
                clientType = project.getProjectLanguage()
            else:
                mainScript = os.path.abspath(prog)
                flags = Utilities.extractFlagsFromFile(mainScript)
                if mainScript.endswith(
                    tuple(Preferences.getPython("PythonExtensions"))) or \
                   ("FileType" in flags and
                        flags["FileType"] in ["Python", "Python2"]):
                    clientType = "Python2"
                else:
                    clientType = ""
            if failedOnly and self.__failedTests:
                failed = [t.split(".", 1)[1] for t in self.__failedTests]
            else:
                failed = []
            self.__failedTests = []
            self.dbs.remoteUTPrepare(prog,
                                     self.testName,
                                     testFunctionName,
                                     failed,
                                     self.coverageCheckBox.isChecked(),
                                     mainScript,
                                     self.coverageEraseCheckBox.isChecked(),
                                     clientType=clientType)
        else:
            # we are running as an application or in local mode
            sys.path = [os.path.dirname(os.path.abspath(prog))] + \
                self.savedSysPath

            # clean up list of imported modules to force a reimport upon
            # running the test
            if self.savedModulelist:
                for modname in list(sys.modules.keys()):
                    if modname not in self.savedModulelist:
                        # delete it
                        del (sys.modules[modname])
            self.savedModulelist = sys.modules.copy()

            # now try to generate the testsuite
            try:
                module = __import__(self.testName)
                try:
                    if failedOnly and self.__failedTests:
                        test = unittest.defaultTestLoader.loadTestsFromNames(
                            [t.split(".", 1)[1] for t in self.__failedTests],
                            module)
                    else:
                        test = unittest.defaultTestLoader.loadTestsFromName(
                            testFunctionName, module)
                except AttributeError:
                    test = unittest.defaultTestLoader.loadTestsFromModule(
                        module)
            except:
                exc_type, exc_value, exc_tb = sys.exc_info()
                E5MessageBox.critical(
                    self, self.tr("Unittest"),
                    self.tr("<p>Unable to run test <b>{0}</b>.<br>"
                            "{1}<br>{2}</p>").format(self.testName,
                                                     str(exc_type),
                                                     str(exc_value)))
                return

            # now set up the coverage stuff
            if self.coverageCheckBox.isChecked():
                if self.dbs:
                    # we are cooperating with the eric6 IDE
                    project = e5App().getObject("Project")
                    if project.isOpen() and project.isProjectSource(prog):
                        mainScript = project.getMainScript(True)
                        if not mainScript:
                            mainScript = os.path.abspath(prog)
                    else:
                        mainScript = os.path.abspath(prog)
                else:
                    mainScript = os.path.abspath(prog)

                from DebugClients.Python3.coverage import coverage
                cover = coverage(data_file="{0}.coverage".format(
                    os.path.splitext(mainScript)[0]))
                cover.use_cache(True)
                if self.coverageEraseCheckBox.isChecked():
                    cover.erase()
            else:
                cover = None

            self.testResult = QtTestResult(self)
            self.totalTests = test.countTestCases()
            self.__failedTests = []
            self.__setRunningMode()
            if cover:
                cover.start()
            test.run(self.testResult)
            if cover:
                cover.stop()
                cover.save()
            self.__setStoppedMode()
            sys.path = self.savedSysPath
    def start(self, cfn, fn):
        """
        Public slot to start the coverage data evaluation.
        
        @param cfn basename of the coverage file (string)
        @param fn file or list of files or directory to be checked
                (string or list of strings)
        """
        self.__cfn = cfn
        self.__fn = fn

        self.basename = os.path.splitext(cfn)[0]

        self.cfn = "{0}.coverage".format(self.basename)

        if isinstance(fn, list):
            files = fn
            self.path = os.path.dirname(cfn)
        elif os.path.isdir(fn):
            files = Utilities.direntries(fn, True, '*.py', False)
            self.path = fn
        else:
            files = [fn]
            self.path = os.path.dirname(cfn)
        files.sort()

        cover = coverage(data_file=self.cfn)
        cover.use_cache(True)
        cover.load()

        # set the exclude pattern
        self.excludeCombo.clear()
        self.excludeCombo.addItems(self.excludeList)

        self.checkProgress.setMaximum(len(files))
        QApplication.processEvents()

        total_statements = 0
        total_executed = 0
        total_exceptions = 0

        cover.exclude(self.excludeList[0])
        progress = 0

        try:
            # disable updates of the list for speed
            self.resultList.setUpdatesEnabled(False)
            self.resultList.setSortingEnabled(False)

            # now go through all the files
            for file in files:
                if self.cancelled:
                    return

                try:
                    statements, excluded, missing, readable = \
                        cover.analysis2(file)[1:]
                    readableEx = (excluded and self.__format_lines(excluded)
                                  or '')
                    n = len(statements)
                    m = n - len(missing)
                    if n > 0:
                        pc = 100.0 * m / n
                    else:
                        pc = 100.0
                    self.__createResultItem(file, str(n), str(m), pc,
                                            readableEx, readable)

                    total_statements = total_statements + n
                    total_executed = total_executed + m
                except CoverageException:
                    total_exceptions += 1

                progress += 1
                self.checkProgress.setValue(progress)
                QApplication.processEvents()
        finally:
            # reenable updates of the list
            self.resultList.setSortingEnabled(True)
            self.resultList.setUpdatesEnabled(True)
            self.checkProgress.reset()

        # show summary info
        if len(files) > 1:
            if total_statements > 0:
                pc = 100.0 * total_executed / total_statements
            else:
                pc = 100.0
            itm = QTreeWidgetItem(self.summaryList, [
                str(total_statements),
                str(total_executed), "{0:.0f}%".format(pc)
            ])
            for col in range(0, 3):
                itm.setTextAlignment(col, Qt.AlignRight)
        else:
            self.summaryGroup.hide()

        if total_exceptions:
            E5MessageBox.warning(
                self, self.tr("Parse Error"),
                self.tr(
                    """%n file(s) could not be parsed. Coverage"""
                    """ info for these is not available.""", "",
                    total_exceptions))

        self.__finish()
 def start(self, cfn, fn):
     """
     Public slot to start the coverage data evaluation.
     
     @param cfn basename of the coverage file (string)
     @param fn file or list of files or directory to be checked
             (string or list of strings)
     """
     self.__cfn = cfn
     self.__fn = fn
     
     self.basename = os.path.splitext(cfn)[0]
     
     self.cfn = "{0}.coverage".format(self.basename)
     
     if isinstance(fn, list):
         files = fn
         self.path = os.path.dirname(cfn)
     elif os.path.isdir(fn):
         files = Utilities.direntries(fn, True, '*.py', False)
         self.path = fn
     else:
         files = [fn]
         self.path = os.path.dirname(cfn)
     files.sort()
     
     cover = coverage(data_file=self.cfn)
     cover.use_cache(True)
     cover.load()
     
     # set the exclude pattern
     self.excludeCombo.clear()
     self.excludeCombo.addItems(self.excludeList)
     
     self.checkProgress.setMaximum(len(files))
     QApplication.processEvents()
     
     total_statements = 0
     total_executed = 0
     total_exceptions = 0
     
     cover.exclude(self.excludeList[0])
     progress = 0
     
     try:
         # disable updates of the list for speed
         self.resultList.setUpdatesEnabled(False)
         self.resultList.setSortingEnabled(False)
         
         # now go through all the files
         for file in files:
             if self.cancelled:
                 return
             
             try:
                 statements, excluded, missing, readable = \
                     cover.analysis2(file)[1:]
                 readableEx = (excluded and self.__format_lines(excluded)
                               or '')
                 n = len(statements)
                 m = n - len(missing)
                 if n > 0:
                     pc = 100.0 * m / n
                 else:
                     pc = 100.0
                 self.__createResultItem(
                     file, str(n), str(m), pc, readableEx, readable)
                 
                 total_statements = total_statements + n
                 total_executed = total_executed + m
             except CoverageException:
                 total_exceptions += 1
             
             progress += 1
             self.checkProgress.setValue(progress)
             QApplication.processEvents()
     finally:
         # reenable updates of the list
         self.resultList.setSortingEnabled(True)
         self.resultList.setUpdatesEnabled(True)
         self.checkProgress.reset()
     
     # show summary info
     if len(files) > 1:
         if total_statements > 0:
             pc = 100.0 * total_executed / total_statements
         else:
             pc = 100.0
         itm = QTreeWidgetItem(self.summaryList, [
             str(total_statements),
             str(total_executed),
             "{0:.0f}%".format(pc)
         ])
         for col in range(0, 3):
             itm.setTextAlignment(col, Qt.AlignRight)
     else:
         self.summaryGroup.hide()
     
     if total_exceptions:
         E5MessageBox.warning(
             self,
             self.tr("Parse Error"),
             self.tr("""%n file(s) could not be parsed. Coverage"""
                     """ info for these is not available.""", "",
                     total_exceptions))
     
     self.__finish()