コード例 #1
0
    def test_pyflakes_compliance(self):
        from pyflakes import reporter
        from pyflakes import api

        class PyflakesReporter(reporter.Reporter):
            def print_error(self, error):
                message = error.message % error.message_args
                print("{filename}: {message}".format(
                    filename=error.filename,
                    message=message,
                ))

            def __init__(self, *args, **kwargs):
                self.error = False

            def unexpectedError(self, *args, **kwargs):
                arg = args[0]
                self.print_error(arg)
                self.error = True

            def syntaxError(self, *args, **kwargs):
                arg = args[0]
                self.print_error(arg)
                self.error = True

            def flake(self, *args, **kwargs):
                arg = args[0]
                self.print_error(arg)
                self.error = True

        reporter = PyflakesReporter()
        api.checkRecursive(self.path, reporter)
        self.assertEqual(reporter.error, False)
コード例 #2
0
    def get_unused_imports(self, directory):
        file_descriptor, absolute_path = mkstemp()
        with open(absolute_path, 'w') as report_output:
            eb_reporter = pyflakes_reporter.Reporter(report_output, sys.stderr)
            pyflakes_api.checkRecursive([directory], eb_reporter)

        with open(absolute_path, 'r') as report_output:
            unused_import_lines = []
            for line in report_output.xreadlines():
                if re.match(self.UNUSED_IMPORT_RE, line.strip()):
                    unused_import_lines.append(line)

        os.close(file_descriptor)
        os.remove(absolute_path)
        return unused_import_lines
コード例 #3
0
ファイル: test_api.py プロジェクト: yamatogun/pyflakes
 def test_checkRecursive(self):
     """
     L{checkRecursive} descends into each directory, finding Python files
     and reporting problems.
     """
     tempdir = tempfile.mkdtemp()
     os.mkdir(os.path.join(tempdir, "foo"))
     file1 = os.path.join(tempdir, "foo", "bar.py")
     fd = open(file1, "wb")
     fd.write("import baz\n".encode("ascii"))
     fd.close()
     file2 = os.path.join(tempdir, "baz.py")
     fd = open(file2, "wb")
     fd.write("import contraband".encode("ascii"))
     fd.close()
     log = []
     reporter = LoggingReporter(log)
     warnings = checkRecursive([tempdir], reporter)
     self.assertEqual(warnings, 2)
     self.assertEqual(
         sorted(log),
         sorted(
             [
                 ("flake", str(UnusedImport(file1, Node(1), "baz"))),
                 ("flake", str(UnusedImport(file2, Node(1), "contraband"))),
             ]
         ),
     )
コード例 #4
0
ファイル: test_api.py プロジェクト: HeitorGonzaga/simple_list
 def test_checkRecursive(self):
     """
     L{checkRecursive} descends into each directory, finding Python files
     and reporting problems.
     """
     tempdir = tempfile.mkdtemp()
     try:
         os.mkdir(os.path.join(tempdir, 'foo'))
         file1 = os.path.join(tempdir, 'foo', 'bar.py')
         with open(file1, 'wb') as fd:
             fd.write("import baz\n".encode('ascii'))
         file2 = os.path.join(tempdir, 'baz.py')
         with open(file2, 'wb') as fd:
             fd.write("import contraband".encode('ascii'))
         log = []
         reporter = LoggingReporter(log)
         warnings = checkRecursive([tempdir], reporter)
         self.assertEqual(warnings, 2)
         self.assertEqual(
             sorted(log),
             sorted([('flake', str(UnusedImport(file1, Node(1), 'baz'))),
                     ('flake',
                      str(UnusedImport(file2, Node(1), 'contraband')))]))
     finally:
         shutil.rmtree(tempdir)
コード例 #5
0
ファイル: test_api.py プロジェクト: taratran/swe-project
 def test_checkRecursive(self):
     """
     L{checkRecursive} descends into each directory, finding Python files
     and reporting problems.
     """
     tempdir = tempfile.mkdtemp()
     try:
         os.mkdir(os.path.join(tempdir, "foo"))
         file1 = os.path.join(tempdir, "foo", "bar.py")
         with open(file1, "wb") as fd:
             fd.write("import baz\n".encode("ascii"))
         file2 = os.path.join(tempdir, "baz.py")
         with open(file2, "wb") as fd:
             fd.write("import contraband".encode("ascii"))
         log = []
         reporter = LoggingReporter(log)
         warnings = checkRecursive([tempdir], reporter)
         self.assertEqual(warnings, 2)
         self.assertEqual(
             sorted(log),
             sorted([
                 ("flake", str(UnusedImport(file1, Node(1), "baz"))),
                 ("flake", str(UnusedImport(file2, Node(1), "contraband"))),
             ]),
         )
     finally:
         shutil.rmtree(tempdir)
コード例 #6
0
def main():
    my_dir = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, os.path.abspath(os.path.join(my_dir, '..')))

    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('--with-pep8', action='store_true', dest='with_pep8',
                      default=True)
    parser.add_option('--with-pyflakes', action='store_true',
                      dest='with_pyflakes', default=True)
    parser.add_option('--force-all', action='store_true', dest='force_all',
                      default=False)
    parser.add_option('-v', '--verbose', action='count', dest='verbosity',
                      default=0)
    parser.add_option('-q', '--quiet', action='count', dest='quietness',
                      default=0)
    options, extra_args = parser.parse_args()
    if options.with_pep8:
        try:
            import pep8
        except ImportError:
            sys.stderr.write('# Could not find pep8 library.\n')
            sys.exit(1)

        guide_main = pep8.StyleGuide(
            ignore=[],
            paths=['subte/'],
            exclude=[],
            max_line_length=80,
        )
        guide_tests = pep8.StyleGuide(
            ignore=['E221'],
            paths=['tests/'],
            max_line_length=80,
        )
        for guide in (guide_main, guide_tests):
            report = guide.check_files()
            if report.total_errors:
                sys.exit(1)

    if options.with_pyflakes:
        try:
            import pyflakes
            assert pyflakes  # silence pyflakes
        except ImportError:
            sys.stderr.write('# Could not find pyflakes library.\n')
            sys.exit(1)

        from pyflakes import api, reporter
        warnings = api.checkRecursive(['subte', 'tests'],
                                      reporter._makeDefaultReporter())
        if warnings > 0:
            sys.exit(1)

    suite = make_suite('', tuple(extra_args), options.force_all)

    runner = TextTestRunner(verbosity=options.verbosity - options.quietness + 1)
    result = runner.run(suite)
    sys.exit(not result.wasSuccessful())
コード例 #7
0
def test_pyflakes():
    rep = reporter._makeDefaultReporter()
    base_path = os.path.dirname(os.path.dirname(__file__))
    paths = [
        os.path.join(base_path, 'src'),
        os.path.join(base_path, 'test'),
    ]
    warnings = checkRecursive(paths, rep)
    assert warnings == 0
コード例 #8
0
def test_pyflakes_conformance():
    """Test source code for PyFlakes conformance."""
    reporter = Reporter(sys.stdout, sys.stderr)
    base_path = os.path.join(os.path.dirname(__file__), '..')
    paths = [
        os.path.join(base_path, 'ros_buildfarm'),
        os.path.join(base_path, 'scripts'),
    ]
    warning_count = checkRecursive(paths, reporter)
    assert warning_count == 0, \
        'Found %d code style warnings' % warning_count
コード例 #9
0
ファイル: test_pyflakes.py プロジェクト: gdlg/ros_buildfarm
def test_pyflakes_conformance():
    """Test source code for PyFlakes conformance."""
    reporter = Reporter(sys.stdout, sys.stderr)
    base_path = os.path.join(os.path.dirname(__file__), '..')
    paths = [
        os.path.join(base_path, 'ros_buildfarm'),
        os.path.join(base_path, 'scripts'),
    ]
    warning_count = checkRecursive(paths, reporter)
    assert warning_count == 0, \
        'Found %d code style warnings' % warning_count
コード例 #10
0
    def run(self):
        # Don't import the pyflakes code until now because setup.py needs to be
        # able to install Pyflakes if its missing. This localizes the import to
        # only after the setuptools code has run and verified everything is
        # installed.
        from pyflakes import api
        from pyflakes import reporter

        # Run the Pyflakes check against our package and check its output
        val = api.checkRecursive([PACKAGE], reporter._makeDefaultReporter())
        if val > 0:
            sys.exit('ERROR: Pyflakes failed with exit code %d' % val)
コード例 #11
0
ファイル: setup.py プロジェクト: Nextdoor/zkmonitor
    def run(self):
        # Don't import the pyflakes code until now because setup.py needs to be
        # able to install Pyflakes if its missing. This localizes the import to
        # only after the setuptools code has run and verified everything is
        # installed.
        from pyflakes import api
        from pyflakes import reporter

        # Run the Pyflakes check against our package and check its output
        val = api.checkRecursive([PACKAGE], reporter._makeDefaultReporter())
        if val > 0:
            sys.exit('ERROR: Pyflakes failed with exit code %d' % val)
コード例 #12
0
ファイル: tests.py プロジェクト: nijotz/dht-experiment
    def test_pyflakes_compliance(self):
        from pyflakes import reporter
        from pyflakes import api

        class PyflakesReporter(reporter.Reporter):
            def __init__(self, *args, **kwargs):
                self.error = False

            def unexpectedError(self, *args, **kwargs):
                self.error = True

            def syntaxError(self, *args, **kwargs):
                self.error = True

            def flake(self, *args, **kwargs):
                self.error = True

        import os
        path = os.path.dirname(os.path.realpath(__file__))

        reporter = PyflakesReporter()
        api.checkRecursive([path], reporter)
        self.assertEqual(reporter.error, False)
コード例 #13
0
ファイル: setup.py プロジェクト: lbarchive/lnkckr
    def run(self):

        try:
            from pyflakes import api
            from pyflakes import reporter as modReporter
        except ImportError:
            print(
                'Cannot import pyflakes, you forgot to install?\n'
                'run `pip install pyflakes` to install.',
                file=sys.stderr)
            sys.exit(1)

        from os.path import basename

        reporter = modReporter._makeDefaultReporter()

        # monkey patch for exclusion of pathes
        api_iterSourceCode = api.iterSourceCode

        def _iterSourceCode(paths):
            for path in api_iterSourceCode(paths):
                if basename(path) not in EXCLUDE_SCRIPTS:
                    yield path

        api.iterSourceCode = _iterSourceCode

        print()
        print('Options')
        print('=======')
        print()
        print('Exclude:', EXCLUDE_SCRIPTS)

        print()
        print('Results')
        print('=======')
        print()
        warnings = api.checkRecursive(CHECK_LIST, reporter)
        print()
        print('Total warnings: %d' % warnings)
コード例 #14
0
 def test_checkRecursive(self):
     """
     L{checkRecursive} descends into each directory, finding Python files
     and reporting problems.
     """
     tempdir = tempfile.mkdtemp()
     os.mkdir(os.path.join(tempdir, 'foo'))
     file1 = os.path.join(tempdir, 'foo', 'bar.py')
     fd = open(file1, 'wb')
     fd.write("import baz\n".encode('ascii'))
     fd.close()
     file2 = os.path.join(tempdir, 'baz.py')
     fd = open(file2, 'wb')
     fd.write("import contraband".encode('ascii'))
     fd.close()
     log = []
     reporter = LoggingReporter(log)
     warnings = checkRecursive([tempdir], reporter)
     self.assertEqual(warnings, 2)
     self.assertEqual(
         sorted(log),
         sorted([('flake', str(UnusedImport(file1, 1, 'baz'))),
                 ('flake', str(UnusedImport(file2, 1, 'contraband')))]))
コード例 #15
0
ファイル: py_reports.py プロジェクト: geomf/omf-fork
            className = "error"
        elif msg_id in self.warningCodes:
            className = "warning"
        elif msg_id in self.infoCodes:
            className = "info"

        self.str += '<tr class="'+className+'"><td>'+ str(module_path) + "</td><td>" + str(line_no) + "</td><td>" + str(column_no) + "</td><td>" + str(msg) + "</td></tr>"

    def _display(self, layout):
        pass

    def flake(self, message):
        self.str += "<tr><td>"+ str(message.filename) + "</td><td>" + str(message.lineno) + "</td><td>" + str(message.col) + "</td><td>" + str(message.message % message.message_args) + "</td></tr>"

    def get_template(self):
        self.str += "</tbody>{% endblock %}"
        return self.str

    def save_report(self, file_name):
        template = self.env.from_string(self.get_template())
        with open(file_name, "w") as text_file:
            text_file.write(template.render())

if __name__ == "__main__":
    dirs = ['./../omf/']
    reporter = CollectionReporter()
    pylint.Run(dirs, reporter=reporter, exit=False)
    reporter.save_report("./pylint_report.html")
    reporter_pyflakes = CollectionReporter()
    warnings = pyflakes.checkRecursive(dirs, reporter_pyflakes)
    reporter_pyflakes.save_report("./pyflakes_report.html")
コード例 #16
0
def main():
    my_dir = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, os.path.abspath(os.path.join(my_dir, '..')))

    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('--with-pep8',
                      action='store_true',
                      dest='with_pep8',
                      default=True)
    parser.add_option('--with-pyflakes',
                      action='store_true',
                      dest='with_pyflakes',
                      default=True)
    parser.add_option('--force-all',
                      action='store_true',
                      dest='force_all',
                      default=False)
    parser.add_option('-v',
                      '--verbose',
                      action='count',
                      dest='verbosity',
                      default=0)
    parser.add_option('-q',
                      '--quiet',
                      action='count',
                      dest='quietness',
                      default=0)
    options, extra_args = parser.parse_args()
    has_pep8 = False
    try:
        import pep8
        has_pep8 = True
    except ImportError:
        if options.with_pep8:
            sys.stderr.write('# Could not find pep8 library.')
            sys.exit(1)

    if has_pep8:
        guide_main = pep8.StyleGuide(
            ignore=['E402'],
            paths=['asyncflux/'],
            exclude=[],
            max_line_length=80,
        )
        guide_tests = pep8.StyleGuide(
            ignore=['E221'],
            paths=['tests/'],
            max_line_length=80,
        )
        for guide in (guide_main, guide_tests):
            report = guide.check_files()
            if report.total_errors:
                sys.exit(1)

    if options.with_pyflakes:
        try:
            import pyflakes
            assert pyflakes  # silence pyflakes
        except ImportError:
            sys.stderr.write('# Could not find pyflakes library.\n')
            sys.exit(1)

        from pyflakes import api, reporter
        warnings = api.checkRecursive(['asyncflux', 'tests'],
                                      reporter._makeDefaultReporter())
        if warnings > 0:
            sys.exit(1)

    suite = make_suite('', tuple(extra_args), options.force_all)

    runner = TextTestRunner(verbosity=options.verbosity - options.quietness +
                            1)
    result = runner.run(suite)
    sys.exit(not result.wasSuccessful())
コード例 #17
0
"""
コード例 #18
0
 def test_pyflakes(self):
     rep = Reporter(sys.stdout, sys.stderr)
     error_count = checkRecursive(CHECK_DIRECTORYS, rep)
     self.assertEqual(error_count, 0, 'PyFlakes errors: %d' % error_count)
コード例 #19
0
ファイル: pep_checker.py プロジェクト: brandsimon/pandas_diff
 def test_pyflakes(self):
     rep = reporter._makeDefaultReporter()
     error_count = checkRecursive(CHECK_DIRECTORYS, rep)
     self.assertEqual(error_count, 0, 'PyFlakes errors: %d' % error_count)